agentd 0.1.2

Agent daemon for secure capability execution with pluggable isolation backends
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
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
/*!
# Oracle System - AI-Powered Planning

The Oracle system provides sophisticated AI-driven planning capabilities with:

- **Deep Research Assistant**: Systematic codebase investigation and analysis
- **Planning Committee**: Multi-agent consensus building for robust plans
- **Decision Confidence**: Quantified confidence metrics for plan quality
- **Context Management**: Isolated conversation contexts for complex reasoning

## Architecture

```text
┌─────────────────────────────────────────────────────────────────┐
│                        Oracle System                           │
├─────────────────────────────────────────────────────────────────┤
│  Goal Analysis Engine                                          │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐           │
│  │  Context    │  │ Constraint  │  │  Success    │           │
│  │ Extraction  │  │  Analysis   │  │  Criteria   │           │
│  └─────────────┘  └─────────────┘  └─────────────┘           │
├─────────────────────────────────────────────────────────────────┤
│  Deep Research Assistant                                       │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐           │
│  │ Codebase    │  │  Pattern    │  │  Risk       │           │
│  │ Analysis    │  │ Detection   │  │ Assessment  │           │
│  └─────────────┘  └─────────────┘  └─────────────┘           │
├─────────────────────────────────────────────────────────────────┤
│  Planning Committee (Multi-Agent Consensus)                   │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐           │
│  │Architecture │  │  Security   │  │Performance  │           │
│  │ Specialist  │  │ Specialist  │  │ Specialist  │           │
│  └─────────────┘  └─────────────┘  └─────────────┘           │
│  ┌─────────────┐  ┌─────────────┐                            │
│  │    QA       │  │  Consensus  │                            │
│  │ Specialist  │  │   Builder   │                            │
│  └─────────────┘  └─────────────┘                            │
├─────────────────────────────────────────────────────────────────┤
│  Plan Generation & Validation                                 │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐           │
│  │    Step     │  │ Capability  │  │  Resource   │           │
│  │ Sequencing  │  │   Mapping   │  │ Estimation  │           │
│  └─────────────┘  └─────────────┘  └─────────────┘           │
└─────────────────────────────────────────────────────────────────┘
```

## Usage

```text
let oracle = Oracle::new(&ai_config).await?;
let goal = Goal::new("Optimize database performance");
let decision = oracle.plan_execution(&goal).await?;

match decision.confidence {
    c if c > 0.8 => println!("High confidence plan: {}", decision.plan.summary),
    c if c > 0.5 => println!("Medium confidence plan: {}", decision.plan.summary),
    _ => println!("Low confidence - consider manual intervention"),
}
```
*/

use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::RwLock;
use tracing::{debug, error, info, warn};
use uuid::Uuid;

use crate::planner::executor_adapter::ExecutionResult;
use crate::planner::{AiConfig, Goal};

/// Location (relative to the executor workdir) where transient plan artifacts are written.
/// Stored under `target/` so they stay ephemeral and out of version control.
const PLAN_OUTPUT_DIR: &str = "target/smith-plans";

/// Oracle system for AI-powered planning
#[derive(Clone)]
pub struct Oracle {
    config: AiConfig,
    research_assistant: Arc<DeepResearchAssistant>,
    planning_committee: Arc<PlanningCommittee>,
    conversation_cache: Arc<RwLock<HashMap<String, ConversationContext>>>,
    decision_history: Arc<RwLock<Vec<OracleDecision>>>,
}

/// Deep research assistant for systematic analysis
#[derive(Clone)]
pub struct DeepResearchAssistant {
    config: AiConfig,
    research_cache: Arc<RwLock<HashMap<String, ResearchResult>>>,
}

/// Planning committee for multi-agent consensus
#[derive(Clone)]
pub struct PlanningCommittee {
    config: AiConfig,
    specialists: Vec<SpecialistAgent>,
    consensus_threshold: f32,
}

/// Specialist agent types
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum SpecialistType {
    Architecture,
    Security,
    Performance,
    QualityAssurance,
}

/// Specialist agent
#[derive(Debug, Clone)]
pub struct SpecialistAgent {
    pub agent_type: SpecialistType,
    pub expertise_areas: Vec<String>,
    pub conversation_context: Option<String>,
}

/// Oracle decision result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OracleDecision {
    pub decision_id: Uuid,
    pub goal_id: Uuid,
    pub plan: ExecutionPlan,
    pub confidence: f32,
    pub reasoning: String,
    pub research_findings: Option<ResearchResult>,
    pub committee_consensus: Option<PlanningConsensus>,
    pub alternative_plans: Vec<ExecutionPlan>,
    pub risk_assessment: RiskAssessment,
    pub created_at: chrono::DateTime<chrono::Utc>,
}

/// Execution plan structure
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExecutionPlan {
    pub plan_id: Uuid,
    pub summary: String,
    pub steps: Vec<PlanStep>,
    pub estimated_duration_minutes: u32,
    pub resource_requirements: ResourceRequirements,
    pub dependencies: Vec<String>,
    pub rollback_plan: Option<RollbackPlan>,
}

/// Individual plan step
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PlanStep {
    pub step_id: Uuid,
    pub sequence: u32,
    pub description: String,
    pub capability: String,
    pub parameters: HashMap<String, serde_json::Value>,
    pub expected_duration_minutes: u32,
    pub success_criteria: Vec<String>,
    pub failure_recovery: Option<String>,
    pub parallel_group: Option<String>,
}

/// Resource requirements for plan
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResourceRequirements {
    pub cpu_cores: f32,
    pub memory_mb: u64,
    pub disk_mb: u64,
    pub network_bandwidth_mbps: f32,
    pub external_services: Vec<String>,
}

/// Rollback plan for failure recovery
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RollbackPlan {
    pub steps: Vec<PlanStep>,
    pub trigger_conditions: Vec<String>,
    pub estimated_duration_minutes: u32,
}

/// Deep research result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResearchResult {
    pub research_id: Uuid,
    pub goal_analysis: GoalAnalysis,
    pub codebase_analysis: Option<CodebaseAnalysis>,
    pub pattern_analysis: PatternAnalysis,
    pub risk_findings: Vec<RiskFinding>,
    pub recommendations: Vec<String>,
    pub confidence: f32,
    pub research_duration_minutes: u32,
}

/// Goal analysis results
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GoalAnalysis {
    pub complexity_score: f32,
    pub feasibility_score: f32,
    pub clarity_score: f32,
    pub scope_estimate: ScopeEstimate,
    pub success_probability: f32,
}

/// Scope estimation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ScopeEstimate {
    pub small: bool,
    pub medium: bool,
    pub large: bool,
    pub estimated_effort_hours: f32,
    pub confidence_interval: (f32, f32),
}

/// Codebase analysis results
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CodebaseAnalysis {
    pub relevant_files: Vec<String>,
    pub architectural_patterns: Vec<String>,
    pub technology_stack: Vec<String>,
    pub complexity_metrics: ComplexityMetrics,
    pub test_coverage: Option<f32>,
}

/// Code complexity metrics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ComplexityMetrics {
    pub cyclomatic_complexity: f32,
    pub cognitive_complexity: f32,
    pub technical_debt_ratio: f32,
    pub maintainability_index: f32,
}

/// Pattern analysis results
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PatternAnalysis {
    pub design_patterns: Vec<String>,
    pub antipatterns: Vec<String>,
    pub best_practices: Vec<String>,
    pub improvement_opportunities: Vec<String>,
}

/// Risk finding
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RiskFinding {
    pub risk_type: RiskType,
    pub severity: RiskSeverity,
    pub description: String,
    pub mitigation: String,
    pub probability: f32,
}

/// Risk types
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum RiskType {
    Security,
    Performance,
    Reliability,
    Maintainability,
    Compliance,
    Technical,
}

/// Risk severity levels
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum RiskSeverity {
    Low,
    Medium,
    High,
    Critical,
}

/// Planning committee consensus
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PlanningConsensus {
    pub consensus_id: Uuid,
    pub specialist_opinions: HashMap<SpecialistType, SpecialistOpinion>,
    pub overall_confidence: f32,
    pub consensus_reached: bool,
    pub conflicting_recommendations: Vec<String>,
    pub final_recommendation: String,
}

/// Individual specialist opinion
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SpecialistOpinion {
    pub specialist_type: SpecialistType,
    pub confidence: f32,
    pub recommendation: String,
    pub concerns: Vec<String>,
    pub approval: bool,
    pub suggested_modifications: Vec<String>,
}

/// Risk assessment
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RiskAssessment {
    pub overall_risk_score: f32,
    pub risk_categories: HashMap<RiskType, f32>,
    pub mitigation_strategies: Vec<String>,
    pub acceptable_risk_level: bool,
}

/// Conversation context for AI interactions
#[derive(Debug, Clone)]
struct ConversationContext {
    messages: Vec<ConversationMessage>,
    context_id: String,
    created_at: chrono::DateTime<chrono::Utc>,
    last_used: chrono::DateTime<chrono::Utc>,
}

/// Conversation message
#[derive(Debug, Clone)]
struct ConversationMessage {
    role: String,
    content: String,
    timestamp: chrono::DateTime<chrono::Utc>,
}

/// Result evaluation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResultEvaluation {
    pub success: bool,
    pub confidence: f32,
    pub summary: String,
    pub goal_achievement_score: f32,
    pub improvement_possible: bool,
    pub recommendations: Vec<String>,
}

impl Oracle {
    /// Create new oracle system
    pub async fn new(config: &AiConfig) -> Result<Self> {
        info!("Initializing Oracle system");

        let research_assistant = Arc::new(DeepResearchAssistant::new(config.clone()).await?);
        let planning_committee = Arc::new(PlanningCommittee::new(config.clone()).await?);
        let conversation_cache = Arc::new(RwLock::new(HashMap::new()));
        let decision_history = Arc::new(RwLock::new(Vec::new()));

        info!("Oracle system initialized successfully");

        Ok(Self {
            config: config.clone(),
            research_assistant,
            planning_committee,
            conversation_cache,
            decision_history,
        })
    }

    /// Plan execution for goal
    pub async fn plan_execution(&self, goal: &Goal) -> Result<OracleDecision> {
        info!(goal_id = %goal.id, "Starting execution planning for goal");

        let start_time = std::time::Instant::now();

        // Step 1: Conduct deep research
        let research_result = self.research_assistant.conduct_research(goal).await?;
        debug!(
            goal_id = %goal.id,
            confidence = research_result.confidence,
            "Research completed"
        );

        // Step 2: Generate initial plan based on research
        let initial_plan = self.generate_initial_plan(goal, &research_result).await?;

        // Step 3: Get planning committee consensus
        let consensus = self
            .planning_committee
            .build_consensus(&initial_plan, goal)
            .await?;
        debug!(
            goal_id = %goal.id,
            consensus_reached = consensus.consensus_reached,
            overall_confidence = consensus.overall_confidence,
            "Planning committee consensus completed"
        );

        // Step 4: Refine plan based on consensus
        let final_plan = self
            .refine_plan_with_consensus(&initial_plan, &consensus)
            .await?;

        // Step 5: Assess risks
        let risk_assessment = self
            .assess_plan_risks(&final_plan, &research_result)
            .await?;

        // Step 6: Calculate overall confidence
        let overall_confidence =
            self.calculate_decision_confidence(&research_result, &consensus, &risk_assessment);

        // Step 7: Generate alternative plans
        let alternative_plans = self
            .generate_alternative_plans(goal, &research_result, 2)
            .await?;

        // Create oracle decision
        let decision = OracleDecision {
            decision_id: Uuid::new_v4(),
            goal_id: goal.id,
            plan: final_plan,
            confidence: overall_confidence,
            reasoning: self
                .generate_decision_reasoning(&research_result, &consensus)
                .await?,
            research_findings: Some(research_result),
            committee_consensus: Some(consensus),
            alternative_plans,
            risk_assessment,
            created_at: chrono::Utc::now(),
        };

        // Store decision in history
        self.decision_history.write().await.push(decision.clone());

        let elapsed = start_time.elapsed();
        info!(
            goal_id = %goal.id,
            decision_id = %decision.decision_id,
            confidence = decision.confidence,
            planning_duration_ms = elapsed.as_millis(),
            "Execution planning completed"
        );

        Ok(decision)
    }

    /// Evaluate execution results
    pub async fn evaluate_results(
        &self,
        goal: &Goal,
        execution_results: &[ExecutionResult],
    ) -> Result<ResultEvaluation> {
        info!(goal_id = %goal.id, "Evaluating execution results");

        // Analyze results against success criteria
        let success_score = self
            .calculate_success_score(goal, execution_results)
            .await?;

        // Check if goal was achieved
        let goal_achieved = success_score >= 0.8; // 80% threshold

        // Determine if improvement is possible
        let improvement_possible = self
            .assess_improvement_potential(goal, execution_results)
            .await?;

        // Generate recommendations
        let recommendations = self
            .generate_improvement_recommendations(goal, execution_results)
            .await?;

        // Calculate confidence in evaluation
        let confidence = self.calculate_evaluation_confidence(execution_results);

        let evaluation = ResultEvaluation {
            success: goal_achieved,
            confidence,
            summary: self
                .generate_evaluation_summary(goal, execution_results, goal_achieved)
                .await?,
            goal_achievement_score: success_score,
            improvement_possible,
            recommendations,
        };

        info!(
            goal_id = %goal.id,
            success = goal_achieved,
            score = success_score,
            confidence = confidence,
            "Result evaluation completed"
        );

        Ok(evaluation)
    }

    /// Generate initial execution plan
    async fn generate_initial_plan(
        &self,
        goal: &Goal,
        research: &ResearchResult,
    ) -> Result<ExecutionPlan> {
        debug!(goal_id = %goal.id, "Generating initial execution plan");

        // For this implementation, we'll create a structured plan
        // In a real system, this would use AI to generate the plan
        let plan_steps = self.create_plan_steps(goal, research).await?;
        let resource_requirements = self.estimate_resources(&plan_steps).await?;
        let estimated_duration = plan_steps.iter().map(|s| s.expected_duration_minutes).sum();

        Ok(ExecutionPlan {
            plan_id: Uuid::new_v4(),
            summary: format!("Execution plan for: {}", goal.description),
            steps: plan_steps,
            estimated_duration_minutes: estimated_duration,
            resource_requirements,
            dependencies: research.recommendations.clone(),
            rollback_plan: self.create_rollback_plan().await?,
        })
    }

    /// Create plan steps based on goal and research
    async fn create_plan_steps(
        &self,
        goal: &Goal,
        research: &ResearchResult,
    ) -> Result<Vec<PlanStep>> {
        // This is a simplified implementation
        // In practice, this would use sophisticated AI planning
        let mut steps = Vec::new();

        // Determine candidate files to inspect
        let target_files: Vec<String> = goal
            .metadata
            .get("target_files")
            .map(|value| {
                value
                    .split(',')
                    .filter_map(|entry| {
                        let trimmed = entry.trim();
                        if trimmed.is_empty() {
                            None
                        } else {
                            Some(trimmed.to_string())
                        }
                    })
                    .collect()
            })
            .filter(|list: &Vec<String>| !list.is_empty())
            .unwrap_or_else(|| vec!["README.md".to_string()]);

        let mut analysis_params = HashMap::new();
        analysis_params.insert("target_files".to_string(), serde_json::json!(target_files));

        // Analysis step executed by the new analysis runner
        steps.push(PlanStep {
            step_id: Uuid::new_v4(),
            sequence: 1,
            description: "Analyze current state and requirements".to_string(),
            capability: "analysis.system.v1".to_string(),
            parameters: analysis_params,
            expected_duration_minutes: 5,
            success_criteria: vec!["Analysis report generated".to_string()],
            failure_recovery: Some("Retry analysis with different approach".to_string()),
            parallel_group: None,
        });

        // Implementation step writes a structured plan document to disk
        let implementation_doc = format!(
            "# Execution Plan for {}\n\n## Recommended Actions\n{}\n\n## Research Highlights\nConfidence: {:.2}\nResearch Duration: {} minutes\n",
            goal.description,
            research
                .recommendations
                .iter()
                .map(|rec| format!("- {}", rec))
                .collect::<Vec<_>>()
                .join("\n"),
            research.confidence,
            research.research_duration_minutes
        );

        let mut implementation_params = HashMap::new();
        implementation_params.insert(
            "operations".to_string(),
            serde_json::json!([
                {
                    "path": format!(
                        "{}/{}_plan.md",
                        PLAN_OUTPUT_DIR,
                        goal.id
                    ),
                    "content": implementation_doc,
                    "mode": "overwrite"
                }
            ]),
        );
        implementation_params.insert(
            "instructions".to_string(),
            serde_json::json!(format!(
                "Apply the recommended solution for '{}', ensuring artifacts and documentation are up to date.",
                goal.description
            )),
        );

        steps.push(PlanStep {
            step_id: Uuid::new_v4(),
            sequence: 2,
            description: "Execute implementation plan".to_string(),
            capability: "implementation.execute.v1".to_string(),
            parameters: implementation_params,
            expected_duration_minutes: 15,
            success_criteria: vec!["Plan artifacts produced".to_string()],
            failure_recovery: Some(
                "Review implementation output and retry with adjustments".to_string(),
            ),
            parallel_group: None,
        });

        let mut validation_params = HashMap::new();
        validation_params.insert(
            "command".to_string(),
            serde_json::json!(["cargo", "check", "--workspace"]),
        );
        validation_params.insert("working_dir".to_string(), serde_json::json!("."));
        validation_params.insert("timeout_ms".to_string(), serde_json::json!(180_000));

        steps.push(PlanStep {
            step_id: Uuid::new_v4(),
            sequence: 3,
            description: "Validate implementation through automated checks".to_string(),
            capability: "validation.test.v1".to_string(),
            parameters: validation_params,
            expected_duration_minutes: 5,
            success_criteria: vec!["Validation command exits successfully".to_string()],
            failure_recovery: Some("Address failures and rerun validation".to_string()),
            parallel_group: None,
        });

        Ok(steps)
    }

    /// Estimate resource requirements
    async fn estimate_resources(&self, steps: &[PlanStep]) -> Result<ResourceRequirements> {
        // Simple resource estimation based on step complexity
        let total_duration: u32 = steps.iter().map(|s| s.expected_duration_minutes).sum();

        Ok(ResourceRequirements {
            cpu_cores: (total_duration as f32 / 30.0).max(1.0), // 1 core per 30 minutes
            memory_mb: 512 + (total_duration as u64 * 10),      // Base + duration factor
            disk_mb: 1024,                                      // Standard disk allocation
            network_bandwidth_mbps: 10.0,                       // Standard bandwidth
            external_services: vec!["smith-executor".to_string()],
        })
    }

    /// Create rollback plan
    async fn create_rollback_plan(&self) -> Result<Option<RollbackPlan>> {
        Ok(Some(RollbackPlan {
            steps: vec![PlanStep {
                step_id: Uuid::new_v4(),
                sequence: 1,
                description: "Restore previous state".to_string(),
                capability: "rollback.restore.v1".to_string(),
                parameters: HashMap::new(),
                expected_duration_minutes: 5,
                success_criteria: vec!["State restored".to_string()],
                failure_recovery: None,
                parallel_group: None,
            }],
            trigger_conditions: vec![
                "Implementation failure".to_string(),
                "Validation failure".to_string(),
                "Critical error detected".to_string(),
            ],
            estimated_duration_minutes: 5,
        }))
    }

    /// Refine plan based on committee consensus
    async fn refine_plan_with_consensus(
        &self,
        plan: &ExecutionPlan,
        consensus: &PlanningConsensus,
    ) -> Result<ExecutionPlan> {
        let mut refined_plan = plan.clone();

        // Apply consensus modifications
        for opinion in consensus.specialist_opinions.values() {
            for modification in &opinion.suggested_modifications {
                debug!(modification = %modification, "Applying consensus modification");
                // In practice, this would parse and apply specific modifications
                // For now, we'll add them as metadata
            }
        }

        // Adjust confidence-based parameters
        if consensus.overall_confidence < 0.5 {
            // Add extra validation steps for low confidence plans
            refined_plan.steps.push(PlanStep {
                step_id: Uuid::new_v4(),
                sequence: refined_plan.steps.len() as u32 + 1,
                description: "Additional validation due to low confidence".to_string(),
                capability: "validation.extended.v1".to_string(),
                parameters: HashMap::new(),
                expected_duration_minutes: 10,
                success_criteria: vec!["Extended validation passed".to_string()],
                failure_recovery: Some("Escalate to manual review".to_string()),
                parallel_group: None,
            });
        }

        Ok(refined_plan)
    }

    /// Assess plan risks
    async fn assess_plan_risks(
        &self,
        plan: &ExecutionPlan,
        research: &ResearchResult,
    ) -> Result<RiskAssessment> {
        let mut risk_categories = HashMap::new();

        // Calculate risk scores based on plan complexity and research findings
        let complexity_risk = research.goal_analysis.complexity_score * 0.6;
        let feasibility_risk = (1.0 - research.goal_analysis.feasibility_score) * 0.8;

        risk_categories.insert(RiskType::Technical, complexity_risk);
        risk_categories.insert(RiskType::Reliability, feasibility_risk);

        // Add risks from research findings
        for finding in &research.risk_findings {
            let current = risk_categories.get(&finding.risk_type).unwrap_or(&0.0);
            risk_categories.insert(
                finding.risk_type.clone(),
                (*current + finding.probability * 0.5).min(1.0),
            );
        }

        let overall_risk = risk_categories.values().sum::<f32>() / risk_categories.len() as f32;

        Ok(RiskAssessment {
            overall_risk_score: overall_risk,
            risk_categories,
            mitigation_strategies: vec![
                "Implement rollback procedures".to_string(),
                "Add monitoring and alerting".to_string(),
                "Use incremental deployment".to_string(),
            ],
            acceptable_risk_level: overall_risk < 0.7,
        })
    }

    /// Calculate decision confidence
    fn calculate_decision_confidence(
        &self,
        research: &ResearchResult,
        consensus: &PlanningConsensus,
        risk_assessment: &RiskAssessment,
    ) -> f32 {
        let research_weight = 0.4;
        let consensus_weight = 0.4;
        let risk_weight = 0.2;

        let risk_confidence = 1.0 - risk_assessment.overall_risk_score;

        (research.confidence * research_weight
            + consensus.overall_confidence * consensus_weight
            + risk_confidence * risk_weight)
            .min(1.0)
            .max(0.0)
    }

    /// Generate decision reasoning
    async fn generate_decision_reasoning(
        &self,
        research: &ResearchResult,
        consensus: &PlanningConsensus,
    ) -> Result<String> {
        let mut reasoning = String::new();

        reasoning.push_str(&format!(
            "Decision based on research (confidence: {:.2}) and committee consensus (confidence: {:.2}). ",
            research.confidence, consensus.overall_confidence
        ));

        if consensus.consensus_reached {
            reasoning.push_str("Planning committee reached consensus. ");
        } else {
            reasoning.push_str("Planning committee had conflicting views. ");
        }

        reasoning.push_str(&format!(
            "Goal feasibility score: {:.2}, complexity score: {:.2}.",
            research.goal_analysis.feasibility_score, research.goal_analysis.complexity_score
        ));

        Ok(reasoning)
    }

    /// Generate alternative plans
    async fn generate_alternative_plans(
        &self,
        goal: &Goal,
        research: &ResearchResult,
        count: usize,
    ) -> Result<Vec<ExecutionPlan>> {
        let mut alternatives = Vec::new();

        for i in 0..count {
            // Create simplified alternative
            let alternative = ExecutionPlan {
                plan_id: Uuid::new_v4(),
                summary: format!("Alternative plan {} for: {}", i + 1, goal.description),
                steps: vec![PlanStep {
                    step_id: Uuid::new_v4(),
                    sequence: 1,
                    description: format!("Alternative approach {}", i + 1),
                    capability: "alternative.execute.v1".to_string(),
                    parameters: HashMap::new(),
                    expected_duration_minutes: 20,
                    success_criteria: goal.success_criteria.clone(),
                    failure_recovery: None,
                    parallel_group: None,
                }],
                estimated_duration_minutes: 20,
                resource_requirements: ResourceRequirements {
                    cpu_cores: 1.0,
                    memory_mb: 256,
                    disk_mb: 512,
                    network_bandwidth_mbps: 5.0,
                    external_services: vec![],
                },
                dependencies: vec![],
                rollback_plan: None,
            };
            alternatives.push(alternative);
        }

        Ok(alternatives)
    }

    /// Calculate success score
    async fn calculate_success_score(
        &self,
        goal: &Goal,
        results: &[ExecutionResult],
    ) -> Result<f32> {
        if results.is_empty() {
            return Ok(0.0);
        }

        let success_count = results.iter().filter(|r| r.success).count();
        let total_count = results.len();

        Ok(success_count as f32 / total_count as f32)
    }

    /// Assess improvement potential
    async fn assess_improvement_potential(
        &self,
        _goal: &Goal,
        results: &[ExecutionResult],
    ) -> Result<bool> {
        // Check if there are any failed results that could be retried
        Ok(results.iter().any(|r| !r.success && r.retryable))
    }

    /// Generate improvement recommendations
    async fn generate_improvement_recommendations(
        &self,
        _goal: &Goal,
        results: &[ExecutionResult],
    ) -> Result<Vec<String>> {
        let mut recommendations = Vec::new();

        // Analyze failed results
        for result in results.iter().filter(|r| !r.success) {
            recommendations.push(format!("Address failure: {}", result.error_message));
        }

        // General recommendations
        if results.iter().any(|r| r.execution_time_ms > 60000) {
            recommendations
                .push("Consider optimizing performance for long-running operations".to_string());
        }

        if recommendations.is_empty() {
            recommendations.push("No specific improvements identified".to_string());
        }

        Ok(recommendations)
    }

    /// Calculate evaluation confidence
    fn calculate_evaluation_confidence(&self, results: &[ExecutionResult]) -> f32 {
        if results.is_empty() {
            return 0.0;
        }

        // Confidence based on result completeness and clarity
        let complete_results = results.iter().filter(|r| !r.output.is_empty()).count();
        complete_results as f32 / results.len() as f32
    }

    /// Generate evaluation summary
    async fn generate_evaluation_summary(
        &self,
        goal: &Goal,
        results: &[ExecutionResult],
        success: bool,
    ) -> Result<String> {
        let total_results = results.len();
        let successful_results = results.iter().filter(|r| r.success).count();

        if success {
            Ok(format!(
                "Goal '{}' achieved successfully. {} of {} operations completed successfully.",
                goal.description, successful_results, total_results
            ))
        } else {
            Ok(format!(
                "Goal '{}' not fully achieved. {} of {} operations completed successfully. Review failed operations for improvement opportunities.",
                goal.description, successful_results, total_results
            ))
        }
    }

    /// Get decision history
    pub async fn get_decision_history(&self) -> Vec<OracleDecision> {
        self.decision_history.read().await.clone()
    }

    /// Export oracle metrics
    pub async fn export_metrics(&self) -> OracleMetrics {
        let history = self.decision_history.read().await;

        let total_decisions = history.len();
        let high_confidence = history.iter().filter(|d| d.confidence > 0.8).count();
        let medium_confidence = history
            .iter()
            .filter(|d| d.confidence > 0.5 && d.confidence <= 0.8)
            .count();
        let low_confidence = history.iter().filter(|d| d.confidence <= 0.5).count();

        let avg_confidence = if total_decisions > 0 {
            history.iter().map(|d| d.confidence).sum::<f32>() / total_decisions as f32
        } else {
            0.0
        };

        OracleMetrics {
            total_decisions,
            high_confidence_decisions: high_confidence,
            medium_confidence_decisions: medium_confidence,
            low_confidence_decisions: low_confidence,
            average_confidence: avg_confidence,
            research_cache_size: self.research_assistant.get_cache_size().await,
        }
    }
}

/// Oracle metrics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OracleMetrics {
    pub total_decisions: usize,
    pub high_confidence_decisions: usize,
    pub medium_confidence_decisions: usize,
    pub low_confidence_decisions: usize,
    pub average_confidence: f32,
    pub research_cache_size: usize,
}

impl DeepResearchAssistant {
    /// Create new research assistant
    pub async fn new(config: AiConfig) -> Result<Self> {
        Ok(Self {
            config,
            research_cache: Arc::new(RwLock::new(HashMap::new())),
        })
    }

    /// Conduct research for goal
    pub async fn conduct_research(&self, goal: &Goal) -> Result<ResearchResult> {
        info!(goal_id = %goal.id, "Conducting deep research");

        let start_time = std::time::Instant::now();

        // Analyze goal
        let goal_analysis = self.analyze_goal(goal).await?;

        // Analyze codebase (if applicable)
        let codebase_analysis = self.analyze_codebase(goal).await?;

        // Detect patterns
        let pattern_analysis = self.analyze_patterns(goal).await?;

        // Assess risks
        let risk_findings = self.assess_risks(goal, &goal_analysis).await?;

        // Generate recommendations
        let recommendations = self.generate_recommendations(goal, &goal_analysis).await?;

        // Calculate confidence
        let confidence = self.calculate_research_confidence(&goal_analysis, &risk_findings);

        let duration = start_time.elapsed();

        let result = ResearchResult {
            research_id: Uuid::new_v4(),
            goal_analysis,
            codebase_analysis,
            pattern_analysis,
            risk_findings,
            recommendations,
            confidence,
            research_duration_minutes: duration.as_secs() as u32 / 60,
        };

        // Cache result
        let cache_key = format!("goal_{}", goal.id);
        self.research_cache
            .write()
            .await
            .insert(cache_key, result.clone());

        info!(
            goal_id = %goal.id,
            confidence = confidence,
            duration_ms = duration.as_millis(),
            "Research completed"
        );

        Ok(result)
    }

    /// Analyze goal complexity and feasibility
    async fn analyze_goal(&self, goal: &Goal) -> Result<GoalAnalysis> {
        // Simplified goal analysis
        let description_length = goal.description.len();
        let constraint_count = goal.constraints.len();
        let success_criteria_count = goal.success_criteria.len();

        let complexity_score =
            ((description_length as f32 / 100.0) + (constraint_count as f32 * 0.2)).min(1.0);

        let clarity_score = if success_criteria_count > 0 { 0.8 } else { 0.4 };
        let feasibility_score = 1.0 - (complexity_score * 0.5);

        Ok(GoalAnalysis {
            complexity_score,
            feasibility_score,
            clarity_score,
            scope_estimate: ScopeEstimate {
                small: complexity_score < 0.3,
                medium: complexity_score >= 0.3 && complexity_score < 0.7,
                large: complexity_score >= 0.7,
                estimated_effort_hours: complexity_score * 8.0, // Max 8 hours
                confidence_interval: (complexity_score * 0.8, complexity_score * 1.2),
            },
            success_probability: feasibility_score * clarity_score,
        })
    }

    /// Analyze codebase (simplified implementation)
    async fn analyze_codebase(&self, _goal: &Goal) -> Result<Option<CodebaseAnalysis>> {
        // In a real implementation, this would analyze actual codebase
        Ok(Some(CodebaseAnalysis {
            relevant_files: vec!["src/main.rs".to_string(), "src/lib.rs".to_string()],
            architectural_patterns: vec!["MVC".to_string(), "Repository".to_string()],
            technology_stack: vec!["Rust".to_string(), "Tokio".to_string()],
            complexity_metrics: ComplexityMetrics {
                cyclomatic_complexity: 5.2,
                cognitive_complexity: 8.1,
                technical_debt_ratio: 0.15,
                maintainability_index: 75.0,
            },
            test_coverage: Some(85.0),
        }))
    }

    /// Analyze patterns
    async fn analyze_patterns(&self, _goal: &Goal) -> Result<PatternAnalysis> {
        Ok(PatternAnalysis {
            design_patterns: vec!["Factory".to_string(), "Observer".to_string()],
            antipatterns: vec!["God Object".to_string()],
            best_practices: vec!["Error handling".to_string(), "Documentation".to_string()],
            improvement_opportunities: vec!["Performance optimization".to_string()],
        })
    }

    /// Assess risks
    async fn assess_risks(
        &self,
        _goal: &Goal,
        analysis: &GoalAnalysis,
    ) -> Result<Vec<RiskFinding>> {
        let mut risks = Vec::new();

        if analysis.complexity_score > 0.7 {
            risks.push(RiskFinding {
                risk_type: RiskType::Technical,
                severity: RiskSeverity::High,
                description: "High complexity goal may lead to implementation challenges"
                    .to_string(),
                mitigation: "Break down into smaller tasks".to_string(),
                probability: analysis.complexity_score,
            });
        }

        if analysis.feasibility_score < 0.5 {
            risks.push(RiskFinding {
                risk_type: RiskType::Reliability,
                severity: RiskSeverity::Medium,
                description: "Low feasibility may lead to incomplete implementation".to_string(),
                mitigation: "Conduct additional research and planning".to_string(),
                probability: 1.0 - analysis.feasibility_score,
            });
        }

        Ok(risks)
    }

    /// Generate recommendations
    async fn generate_recommendations(
        &self,
        _goal: &Goal,
        analysis: &GoalAnalysis,
    ) -> Result<Vec<String>> {
        let mut recommendations = Vec::new();

        if analysis.complexity_score > 0.5 {
            recommendations
                .push("Consider breaking down the goal into smaller, manageable tasks".to_string());
        }

        if analysis.clarity_score < 0.6 {
            recommendations.push("Define clearer success criteria".to_string());
        }

        recommendations.push("Implement comprehensive testing".to_string());
        recommendations.push("Add monitoring and observability".to_string());

        Ok(recommendations)
    }

    /// Calculate research confidence
    fn calculate_research_confidence(&self, analysis: &GoalAnalysis, risks: &[RiskFinding]) -> f32 {
        let clarity_weight = 0.4;
        let feasibility_weight = 0.4;
        let risk_weight = 0.2;

        let risk_factor = if risks.is_empty() {
            1.0
        } else {
            1.0 - (risks.iter().map(|r| r.probability).sum::<f32>() / risks.len() as f32)
        };

        (analysis.clarity_score * clarity_weight
            + analysis.feasibility_score * feasibility_weight
            + risk_factor * risk_weight)
            .min(1.0)
            .max(0.0)
    }

    /// Get cache size
    pub async fn get_cache_size(&self) -> usize {
        self.research_cache.read().await.len()
    }
}

impl PlanningCommittee {
    /// Create new planning committee
    pub async fn new(config: AiConfig) -> Result<Self> {
        let specialists = vec![
            SpecialistAgent {
                agent_type: SpecialistType::Architecture,
                expertise_areas: vec!["System design".to_string(), "Scalability".to_string()],
                conversation_context: None,
            },
            SpecialistAgent {
                agent_type: SpecialistType::Security,
                expertise_areas: vec!["Security analysis".to_string(), "Compliance".to_string()],
                conversation_context: None,
            },
            SpecialistAgent {
                agent_type: SpecialistType::Performance,
                expertise_areas: vec!["Optimization".to_string(), "Benchmarking".to_string()],
                conversation_context: None,
            },
            SpecialistAgent {
                agent_type: SpecialistType::QualityAssurance,
                expertise_areas: vec!["Testing".to_string(), "Quality metrics".to_string()],
                conversation_context: None,
            },
        ];

        Ok(Self {
            config,
            specialists,
            consensus_threshold: 0.7,
        })
    }

    /// Build consensus on execution plan
    pub async fn build_consensus(
        &self,
        plan: &ExecutionPlan,
        goal: &Goal,
    ) -> Result<PlanningConsensus> {
        info!(plan_id = %plan.plan_id, "Building planning committee consensus");

        let mut specialist_opinions = HashMap::new();

        // Get opinion from each specialist
        for specialist in &self.specialists {
            let opinion = self.get_specialist_opinion(specialist, plan, goal).await?;
            specialist_opinions.insert(specialist.agent_type.clone(), opinion);
        }

        // Calculate overall confidence
        let total_confidence: f32 = specialist_opinions.values().map(|o| o.confidence).sum();
        let overall_confidence = total_confidence / specialist_opinions.len() as f32;

        // Check if consensus reached
        let approval_count = specialist_opinions.values().filter(|o| o.approval).count();
        let consensus_reached =
            approval_count as f32 / specialist_opinions.len() as f32 >= self.consensus_threshold;

        // Collect conflicting recommendations
        let mut conflicting_recommendations = Vec::new();
        if !consensus_reached {
            for opinion in specialist_opinions.values() {
                if !opinion.approval {
                    conflicting_recommendations.extend(opinion.concerns.clone());
                }
            }
        }

        // Generate final recommendation
        let final_recommendation = if consensus_reached {
            "Plan approved by committee consensus".to_string()
        } else {
            "Plan requires modifications based on specialist concerns".to_string()
        };

        Ok(PlanningConsensus {
            consensus_id: Uuid::new_v4(),
            specialist_opinions,
            overall_confidence,
            consensus_reached,
            conflicting_recommendations,
            final_recommendation,
        })
    }

    /// Get specialist opinion on plan
    async fn get_specialist_opinion(
        &self,
        specialist: &SpecialistAgent,
        plan: &ExecutionPlan,
        _goal: &Goal,
    ) -> Result<SpecialistOpinion> {
        // Simplified specialist analysis
        let base_confidence = 0.8;
        let mut concerns = Vec::new();
        let mut suggested_modifications = Vec::new();

        match specialist.agent_type {
            SpecialistType::Architecture => {
                if plan.steps.len() > 5 {
                    concerns.push("Plan has many steps, consider consolidation".to_string());
                    suggested_modifications.push("Combine related steps".to_string());
                }
            }
            SpecialistType::Security => {
                if plan.resource_requirements.external_services.is_empty() {
                    // Good - no external dependencies
                } else {
                    concerns
                        .push("External service dependencies increase security risk".to_string());
                }
            }
            SpecialistType::Performance => {
                if plan.estimated_duration_minutes > 60 {
                    concerns.push("Long execution time may impact performance".to_string());
                    suggested_modifications
                        .push("Parallelize operations where possible".to_string());
                }
            }
            SpecialistType::QualityAssurance => {
                let has_validation = plan
                    .steps
                    .iter()
                    .any(|s| s.capability.contains("validation"));
                if !has_validation {
                    concerns.push("Plan lacks validation steps".to_string());
                    suggested_modifications.push("Add validation and testing steps".to_string());
                }
            }
        }

        let confidence = if concerns.is_empty() {
            base_confidence
        } else {
            base_confidence * 0.7
        };
        let approval = concerns.is_empty();

        Ok(SpecialistOpinion {
            specialist_type: specialist.agent_type.clone(),
            confidence,
            recommendation: if approval {
                "Approved".to_string()
            } else {
                "Requires modifications".to_string()
            },
            concerns,
            approval,
            suggested_modifications,
        })
    }
}

// Implement serialization for SpecialistType
impl Serialize for SpecialistType {
    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        match self {
            SpecialistType::Architecture => serializer.serialize_str("Architecture"),
            SpecialistType::Security => serializer.serialize_str("Security"),
            SpecialistType::Performance => serializer.serialize_str("Performance"),
            SpecialistType::QualityAssurance => serializer.serialize_str("QualityAssurance"),
        }
    }
}

impl<'de> Deserialize<'de> for SpecialistType {
    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        match s.as_str() {
            "Architecture" => Ok(SpecialistType::Architecture),
            "Security" => Ok(SpecialistType::Security),
            "Performance" => Ok(SpecialistType::Performance),
            "QualityAssurance" => Ok(SpecialistType::QualityAssurance),
            _ => Err(serde::de::Error::custom("Invalid specialist type")),
        }
    }
}

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

    fn create_test_config() -> AiConfig {
        AiConfig {
            provider: "mock".to_string(),
            model: "test".to_string(),
            max_tokens: 1000,
            temperature: 0.1,
            timeout_seconds: 30,
            retry_attempts: 1,
            rate_limit_per_minute: 10,
        }
    }

    #[tokio::test]
    async fn test_oracle_creation() {
        let config = create_test_config();
        let oracle = Oracle::new(&config).await;
        assert!(oracle.is_ok());
    }

    #[tokio::test]
    async fn test_research_assistant() {
        let config = create_test_config();
        let assistant = DeepResearchAssistant::new(config).await.unwrap();
        let goal = Goal::new("Test goal");
        let result = assistant.conduct_research(&goal).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_planning_committee() {
        let config = create_test_config();
        let committee = PlanningCommittee::new(config).await.unwrap();
        assert_eq!(committee.specialists.len(), 4);
    }

    // Specialist type serialization tests
    #[test]
    fn test_specialist_type_serialization() {
        let types = vec![
            SpecialistType::Architecture,
            SpecialistType::Security,
            SpecialistType::Performance,
            SpecialistType::QualityAssurance,
        ];

        for specialist_type in types {
            let json = serde_json::to_string(&specialist_type).unwrap();
            let parsed: SpecialistType = serde_json::from_str(&json).unwrap();
            let json2 = serde_json::to_string(&parsed).unwrap();
            assert_eq!(json, json2);
        }
    }

    #[test]
    fn test_specialist_type_invalid_deserialization() {
        let result: Result<SpecialistType, _> = serde_json::from_str("\"InvalidType\"");
        assert!(result.is_err());
    }

    // RiskType serialization tests
    #[test]
    fn test_risk_type_serialization() {
        let types = vec![
            RiskType::Security,
            RiskType::Performance,
            RiskType::Reliability,
            RiskType::Maintainability,
            RiskType::Compliance,
            RiskType::Technical,
        ];

        for risk_type in types {
            let json = serde_json::to_string(&risk_type).unwrap();
            let parsed: RiskType = serde_json::from_str(&json).unwrap();
            let json2 = serde_json::to_string(&parsed).unwrap();
            assert_eq!(json, json2);
        }
    }

    // RiskSeverity serialization tests
    #[test]
    fn test_risk_severity_serialization() {
        let severities = vec![
            RiskSeverity::Low,
            RiskSeverity::Medium,
            RiskSeverity::High,
            RiskSeverity::Critical,
        ];

        for severity in severities {
            let json = serde_json::to_string(&severity).unwrap();
            let parsed: RiskSeverity = serde_json::from_str(&json).unwrap();
            let json2 = serde_json::to_string(&parsed).unwrap();
            assert_eq!(json, json2);
        }
    }

    // ExecutionPlan serialization test
    #[test]
    fn test_execution_plan_serialization() {
        let plan = ExecutionPlan {
            plan_id: Uuid::new_v4(),
            summary: "Test plan".to_string(),
            steps: vec![],
            estimated_duration_minutes: 30,
            resource_requirements: ResourceRequirements {
                cpu_cores: 2.0,
                memory_mb: 1024,
                disk_mb: 2048,
                network_bandwidth_mbps: 10.0,
                external_services: vec!["api".to_string()],
            },
            dependencies: vec!["dep1".to_string()],
            rollback_plan: None,
        };

        let json = serde_json::to_string(&plan).unwrap();
        let parsed: ExecutionPlan = serde_json::from_str(&json).unwrap();

        assert_eq!(parsed.summary, "Test plan");
        assert_eq!(parsed.estimated_duration_minutes, 30);
    }

    // PlanStep serialization test
    #[test]
    fn test_plan_step_serialization() {
        let step = PlanStep {
            step_id: Uuid::new_v4(),
            sequence: 1,
            description: "Test step".to_string(),
            capability: "test.cap.v1".to_string(),
            parameters: HashMap::from([("key".to_string(), serde_json::json!("value"))]),
            expected_duration_minutes: 5,
            success_criteria: vec!["criterion".to_string()],
            failure_recovery: Some("retry".to_string()),
            parallel_group: Some("group1".to_string()),
        };

        let json = serde_json::to_string(&step).unwrap();
        let parsed: PlanStep = serde_json::from_str(&json).unwrap();

        assert_eq!(parsed.description, "Test step");
        assert_eq!(parsed.sequence, 1);
        assert_eq!(parsed.parallel_group, Some("group1".to_string()));
    }

    // ResourceRequirements serialization test
    #[test]
    fn test_resource_requirements_serialization() {
        let requirements = ResourceRequirements {
            cpu_cores: 4.0,
            memory_mb: 8192,
            disk_mb: 10240,
            network_bandwidth_mbps: 100.0,
            external_services: vec!["db".to_string(), "cache".to_string()],
        };

        let json = serde_json::to_string(&requirements).unwrap();
        let parsed: ResourceRequirements = serde_json::from_str(&json).unwrap();

        assert_eq!(parsed.cpu_cores, 4.0);
        assert_eq!(parsed.memory_mb, 8192);
        assert_eq!(parsed.external_services.len(), 2);
    }

    // RollbackPlan serialization test
    #[test]
    fn test_rollback_plan_serialization() {
        let plan = RollbackPlan {
            steps: vec![PlanStep {
                step_id: Uuid::new_v4(),
                sequence: 1,
                description: "Rollback step".to_string(),
                capability: "rollback.v1".to_string(),
                parameters: HashMap::new(),
                expected_duration_minutes: 2,
                success_criteria: vec!["restored".to_string()],
                failure_recovery: None,
                parallel_group: None,
            }],
            trigger_conditions: vec!["failure".to_string()],
            estimated_duration_minutes: 5,
        };

        let json = serde_json::to_string(&plan).unwrap();
        let parsed: RollbackPlan = serde_json::from_str(&json).unwrap();

        assert_eq!(parsed.steps.len(), 1);
        assert_eq!(parsed.estimated_duration_minutes, 5);
    }

    // ResearchResult serialization test
    #[test]
    fn test_research_result_serialization() {
        let result = ResearchResult {
            research_id: Uuid::new_v4(),
            goal_analysis: GoalAnalysis {
                complexity_score: 0.5,
                feasibility_score: 0.8,
                clarity_score: 0.9,
                scope_estimate: ScopeEstimate {
                    small: false,
                    medium: true,
                    large: false,
                    estimated_effort_hours: 4.0,
                    confidence_interval: (3.0, 5.0),
                },
                success_probability: 0.72,
            },
            codebase_analysis: None,
            pattern_analysis: PatternAnalysis {
                design_patterns: vec![],
                antipatterns: vec![],
                best_practices: vec![],
                improvement_opportunities: vec![],
            },
            risk_findings: vec![],
            recommendations: vec!["recommendation".to_string()],
            confidence: 0.85,
            research_duration_minutes: 5,
        };

        let json = serde_json::to_string(&result).unwrap();
        let parsed: ResearchResult = serde_json::from_str(&json).unwrap();

        assert_eq!(parsed.confidence, 0.85);
        assert_eq!(parsed.research_duration_minutes, 5);
    }

    // GoalAnalysis serialization test
    #[test]
    fn test_goal_analysis_serialization() {
        let analysis = GoalAnalysis {
            complexity_score: 0.3,
            feasibility_score: 0.9,
            clarity_score: 0.85,
            scope_estimate: ScopeEstimate {
                small: true,
                medium: false,
                large: false,
                estimated_effort_hours: 2.0,
                confidence_interval: (1.5, 2.5),
            },
            success_probability: 0.765,
        };

        let json = serde_json::to_string(&analysis).unwrap();
        let parsed: GoalAnalysis = serde_json::from_str(&json).unwrap();

        assert_eq!(parsed.complexity_score, 0.3);
        assert_eq!(parsed.scope_estimate.small, true);
    }

    // CodebaseAnalysis serialization test
    #[test]
    fn test_codebase_analysis_serialization() {
        let analysis = CodebaseAnalysis {
            relevant_files: vec!["main.rs".to_string(), "lib.rs".to_string()],
            architectural_patterns: vec!["MVC".to_string()],
            technology_stack: vec!["Rust".to_string()],
            complexity_metrics: ComplexityMetrics {
                cyclomatic_complexity: 5.0,
                cognitive_complexity: 8.0,
                technical_debt_ratio: 0.1,
                maintainability_index: 80.0,
            },
            test_coverage: Some(90.0),
        };

        let json = serde_json::to_string(&analysis).unwrap();
        let parsed: CodebaseAnalysis = serde_json::from_str(&json).unwrap();

        assert_eq!(parsed.relevant_files.len(), 2);
        assert_eq!(parsed.test_coverage, Some(90.0));
    }

    // ComplexityMetrics serialization test
    #[test]
    fn test_complexity_metrics_serialization() {
        let metrics = ComplexityMetrics {
            cyclomatic_complexity: 10.5,
            cognitive_complexity: 15.2,
            technical_debt_ratio: 0.25,
            maintainability_index: 65.0,
        };

        let json = serde_json::to_string(&metrics).unwrap();
        let parsed: ComplexityMetrics = serde_json::from_str(&json).unwrap();

        assert_eq!(parsed.cyclomatic_complexity, 10.5);
        assert_eq!(parsed.maintainability_index, 65.0);
    }

    // PatternAnalysis serialization test
    #[test]
    fn test_pattern_analysis_serialization() {
        let analysis = PatternAnalysis {
            design_patterns: vec!["Singleton".to_string(), "Factory".to_string()],
            antipatterns: vec!["God Object".to_string()],
            best_practices: vec!["Documentation".to_string()],
            improvement_opportunities: vec!["Refactoring".to_string()],
        };

        let json = serde_json::to_string(&analysis).unwrap();
        let parsed: PatternAnalysis = serde_json::from_str(&json).unwrap();

        assert_eq!(parsed.design_patterns.len(), 2);
        assert_eq!(parsed.antipatterns.len(), 1);
    }

    // RiskFinding serialization test
    #[test]
    fn test_risk_finding_serialization() {
        let finding = RiskFinding {
            risk_type: RiskType::Security,
            severity: RiskSeverity::High,
            description: "Security vulnerability".to_string(),
            mitigation: "Apply patch".to_string(),
            probability: 0.7,
        };

        let json = serde_json::to_string(&finding).unwrap();
        let parsed: RiskFinding = serde_json::from_str(&json).unwrap();

        assert_eq!(parsed.description, "Security vulnerability");
        assert_eq!(parsed.probability, 0.7);
    }

    // PlanningConsensus serialization test
    #[test]
    fn test_planning_consensus_serialization() {
        let consensus = PlanningConsensus {
            consensus_id: Uuid::new_v4(),
            specialist_opinions: HashMap::new(),
            overall_confidence: 0.8,
            consensus_reached: true,
            conflicting_recommendations: vec![],
            final_recommendation: "Approved".to_string(),
        };

        let json = serde_json::to_string(&consensus).unwrap();
        let parsed: PlanningConsensus = serde_json::from_str(&json).unwrap();

        assert!(parsed.consensus_reached);
        assert_eq!(parsed.overall_confidence, 0.8);
    }

    // SpecialistOpinion serialization test
    #[test]
    fn test_specialist_opinion_serialization() {
        let opinion = SpecialistOpinion {
            specialist_type: SpecialistType::Architecture,
            confidence: 0.85,
            recommendation: "Approved".to_string(),
            concerns: vec!["Minor concern".to_string()],
            approval: true,
            suggested_modifications: vec![],
        };

        let json = serde_json::to_string(&opinion).unwrap();
        let parsed: SpecialistOpinion = serde_json::from_str(&json).unwrap();

        assert!(parsed.approval);
        assert_eq!(parsed.concerns.len(), 1);
    }

    // RiskAssessment serialization test
    #[test]
    fn test_risk_assessment_serialization() {
        let assessment = RiskAssessment {
            overall_risk_score: 0.3,
            risk_categories: HashMap::from([
                (RiskType::Security, 0.2),
                (RiskType::Performance, 0.4),
            ]),
            mitigation_strategies: vec!["Strategy 1".to_string()],
            acceptable_risk_level: true,
        };

        let json = serde_json::to_string(&assessment).unwrap();
        let parsed: RiskAssessment = serde_json::from_str(&json).unwrap();

        assert_eq!(parsed.overall_risk_score, 0.3);
        assert!(parsed.acceptable_risk_level);
    }

    // OracleDecision serialization test
    #[test]
    fn test_oracle_decision_serialization() {
        let decision = OracleDecision {
            decision_id: Uuid::new_v4(),
            goal_id: Uuid::new_v4(),
            plan: ExecutionPlan {
                plan_id: Uuid::new_v4(),
                summary: "Test".to_string(),
                steps: vec![],
                estimated_duration_minutes: 10,
                resource_requirements: ResourceRequirements {
                    cpu_cores: 1.0,
                    memory_mb: 256,
                    disk_mb: 512,
                    network_bandwidth_mbps: 5.0,
                    external_services: vec![],
                },
                dependencies: vec![],
                rollback_plan: None,
            },
            confidence: 0.9,
            reasoning: "Test reasoning".to_string(),
            research_findings: None,
            committee_consensus: None,
            alternative_plans: vec![],
            risk_assessment: RiskAssessment {
                overall_risk_score: 0.1,
                risk_categories: HashMap::new(),
                mitigation_strategies: vec![],
                acceptable_risk_level: true,
            },
            created_at: chrono::Utc::now(),
        };

        let json = serde_json::to_string(&decision).unwrap();
        let parsed: OracleDecision = serde_json::from_str(&json).unwrap();

        assert_eq!(parsed.confidence, 0.9);
        assert_eq!(parsed.reasoning, "Test reasoning");
    }

    // OracleMetrics serialization test
    #[test]
    fn test_oracle_metrics_serialization() {
        let metrics = OracleMetrics {
            total_decisions: 100,
            high_confidence_decisions: 60,
            medium_confidence_decisions: 30,
            low_confidence_decisions: 10,
            average_confidence: 0.75,
            research_cache_size: 50,
        };

        let json = serde_json::to_string(&metrics).unwrap();
        let parsed: OracleMetrics = serde_json::from_str(&json).unwrap();

        assert_eq!(parsed.total_decisions, 100);
        assert_eq!(parsed.average_confidence, 0.75);
    }

    // ResultEvaluation serialization test
    #[test]
    fn test_result_evaluation_serialization() {
        let evaluation = ResultEvaluation {
            success: true,
            confidence: 0.95,
            summary: "Goal achieved".to_string(),
            goal_achievement_score: 0.9,
            improvement_possible: false,
            recommendations: vec!["Continue monitoring".to_string()],
        };

        let json = serde_json::to_string(&evaluation).unwrap();
        let parsed: ResultEvaluation = serde_json::from_str(&json).unwrap();

        assert!(parsed.success);
        assert_eq!(parsed.goal_achievement_score, 0.9);
    }

    // ScopeEstimate serialization test
    #[test]
    fn test_scope_estimate_serialization() {
        let estimate = ScopeEstimate {
            small: false,
            medium: true,
            large: false,
            estimated_effort_hours: 16.0,
            confidence_interval: (12.0, 20.0),
        };

        let json = serde_json::to_string(&estimate).unwrap();
        let parsed: ScopeEstimate = serde_json::from_str(&json).unwrap();

        assert!(parsed.medium);
        assert_eq!(parsed.estimated_effort_hours, 16.0);
    }

    // Clone tests
    #[test]
    fn test_specialist_type_clone() {
        let st = SpecialistType::Security;
        let cloned = st.clone();
        assert_eq!(st, cloned);
    }

    #[test]
    fn test_risk_type_clone() {
        let rt = RiskType::Compliance;
        let cloned = rt.clone();
        assert_eq!(rt, cloned);
    }

    // Oracle decision confidence calculation test
    #[tokio::test]
    async fn test_decision_confidence_calculation() {
        let config = create_test_config();
        let oracle = Oracle::new(&config).await.unwrap();

        let research = ResearchResult {
            research_id: Uuid::new_v4(),
            goal_analysis: GoalAnalysis {
                complexity_score: 0.5,
                feasibility_score: 0.8,
                clarity_score: 0.9,
                scope_estimate: ScopeEstimate {
                    small: false,
                    medium: true,
                    large: false,
                    estimated_effort_hours: 4.0,
                    confidence_interval: (3.0, 5.0),
                },
                success_probability: 0.72,
            },
            codebase_analysis: None,
            pattern_analysis: PatternAnalysis {
                design_patterns: vec![],
                antipatterns: vec![],
                best_practices: vec![],
                improvement_opportunities: vec![],
            },
            risk_findings: vec![],
            recommendations: vec![],
            confidence: 0.9,
            research_duration_minutes: 5,
        };

        let consensus = PlanningConsensus {
            consensus_id: Uuid::new_v4(),
            specialist_opinions: HashMap::new(),
            overall_confidence: 0.8,
            consensus_reached: true,
            conflicting_recommendations: vec![],
            final_recommendation: "Approved".to_string(),
        };

        let risk_assessment = RiskAssessment {
            overall_risk_score: 0.2,
            risk_categories: HashMap::new(),
            mitigation_strategies: vec![],
            acceptable_risk_level: true,
        };

        let confidence =
            oracle.calculate_decision_confidence(&research, &consensus, &risk_assessment);

        // Expected: 0.9 * 0.4 + 0.8 * 0.4 + (1 - 0.2) * 0.2 = 0.36 + 0.32 + 0.16 = 0.84
        assert!((confidence - 0.84).abs() < 0.01);
    }

    #[tokio::test]
    async fn test_evaluation_confidence_empty_results() {
        let config = create_test_config();
        let oracle = Oracle::new(&config).await.unwrap();

        let confidence = oracle.calculate_evaluation_confidence(&[]);
        assert_eq!(confidence, 0.0);
    }

    #[tokio::test]
    async fn test_get_decision_history_empty() {
        let config = create_test_config();
        let oracle = Oracle::new(&config).await.unwrap();

        let history = oracle.get_decision_history().await;
        assert!(history.is_empty());
    }

    #[tokio::test]
    async fn test_export_metrics_empty() {
        let config = create_test_config();
        let oracle = Oracle::new(&config).await.unwrap();

        let metrics = oracle.export_metrics().await;
        assert_eq!(metrics.total_decisions, 0);
        assert_eq!(metrics.average_confidence, 0.0);
    }

    #[tokio::test]
    async fn test_research_cache_size() {
        let config = create_test_config();
        let assistant = DeepResearchAssistant::new(config).await.unwrap();

        // Initially empty
        assert_eq!(assistant.get_cache_size().await, 0);

        // After research
        let goal = Goal::new("Cache test goal");
        let _ = assistant.conduct_research(&goal).await.unwrap();
        assert_eq!(assistant.get_cache_size().await, 1);
    }

    #[tokio::test]
    async fn test_calculate_research_confidence() {
        let config = create_test_config();
        let assistant = DeepResearchAssistant::new(config).await.unwrap();

        let analysis = GoalAnalysis {
            complexity_score: 0.5,
            feasibility_score: 0.8,
            clarity_score: 0.9,
            scope_estimate: ScopeEstimate {
                small: false,
                medium: true,
                large: false,
                estimated_effort_hours: 4.0,
                confidence_interval: (3.0, 5.0),
            },
            success_probability: 0.72,
        };

        // No risks
        let confidence_no_risks = assistant.calculate_research_confidence(&analysis, &[]);
        // Expected: 0.9 * 0.4 + 0.8 * 0.4 + 1.0 * 0.2 = 0.36 + 0.32 + 0.2 = 0.88
        assert!((confidence_no_risks - 0.88).abs() < 0.01);

        // With risks
        let risks = vec![RiskFinding {
            risk_type: RiskType::Technical,
            severity: RiskSeverity::Medium,
            description: "Test risk".to_string(),
            mitigation: "Mitigate".to_string(),
            probability: 0.5,
        }];

        let confidence_with_risks = assistant.calculate_research_confidence(&analysis, &risks);
        assert!(confidence_with_risks < confidence_no_risks);
    }

    // Specialist agent tests
    #[test]
    fn test_specialist_agent_creation() {
        let agent = SpecialistAgent {
            agent_type: SpecialistType::Performance,
            expertise_areas: vec!["Optimization".to_string()],
            conversation_context: Some("context".to_string()),
        };

        assert!(matches!(agent.agent_type, SpecialistType::Performance));
        assert_eq!(agent.expertise_areas.len(), 1);
        assert!(agent.conversation_context.is_some());
    }

    #[test]
    fn test_specialist_type_equality() {
        assert_eq!(SpecialistType::Architecture, SpecialistType::Architecture);
        assert_ne!(SpecialistType::Architecture, SpecialistType::Security);
    }

    #[test]
    fn test_specialist_type_hash() {
        use std::collections::HashSet;

        let mut set = HashSet::new();
        set.insert(SpecialistType::Architecture);
        set.insert(SpecialistType::Security);

        assert!(set.contains(&SpecialistType::Architecture));
        assert!(set.contains(&SpecialistType::Security));
        assert!(!set.contains(&SpecialistType::Performance));
    }
}