paladin-ai 0.4.3

Enterprise AI orchestration framework with multi-agent coordination patterns
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
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
//! PaladinBuilder - Fluent builder for creating Paladin instances with validation
//!
//! This module provides a builder pattern implementation for constructing Paladin entities
//! with compile-time safety and runtime validation of configuration parameters.
//!
//! # Examples
//!
//! ```rust,no_run
//! use paladin::application::services::paladin::paladin_builder::PaladinBuilder;
//! use paladin_ports::output::llm_port::LlmPort;
//! use paladin::core::platform::container::paladin_config::OutputFormat;
//! use std::sync::Arc;
//!
//! # async fn example(llm_port: Arc<dyn LlmPort>) -> Result<(), Box<dyn std::error::Error>> {
//! let paladin = PaladinBuilder::new(llm_port)
//!     .system_prompt("You are a helpful coding assistant")
//!     .name("CodePaladin")
//!     .user_name("Developer")
//!     .model("gpt-4")
//!     .temperature(0.7)
//!     .max_loops(5)
//!     .add_stop_word("STOP")
//!     .retry_attempts(3)
//!     .timeout_seconds(300)
//!     .enable_planning(true)
//!     .output_format(OutputFormat::Json)
//!     .build().await?;
//! # Ok(())
//! # }
//! ```

use crate::application::services::paladin::error::PaladinError;
use crate::application::services::sanctum::memory_extraction_service::MemoryExtractionStrategy;
use crate::config::arsenal::MCPServerConfig;
use crate::core::base::entity::node::Node;
use crate::core::platform::container::arsenal::Armament;
use crate::core::platform::container::herald::Herald;
use crate::core::platform::container::paladin::MaxLoops;
use crate::core::platform::container::paladin::{Paladin, PaladinData};
use crate::core::platform::container::paladin_config::{OutputFormat, PaladinConfig};
use crate::infrastructure::adapters::citadel::file_citadel::FileCitadel;
use paladin_ports::output::arsenal_port::ArsenalRegistry;
use paladin_ports::output::citadel_port::CitadelPort;
use paladin_ports::output::embedding_port::EmbeddingPort;
use paladin_ports::output::garrison_port::GarrisonPort;
use paladin_ports::output::llm_port::LlmPort;
use paladin_ports::output::sanctum_port::SanctumPort;
use std::path::PathBuf;
use std::sync::Arc;
use uuid::Uuid;

/// Builder for creating Paladin instances with validation
///
/// The builder provides a fluent interface for constructing Paladins with comprehensive
/// validation of all configuration parameters. It enforces constraints like:
/// - Non-empty system prompts
/// - Temperature in range [0.0, 1.0]
/// - Max loops in range [1, 100]
///
/// # Example
///
/// ```rust,no_run
/// # use paladin::application::services::paladin::paladin_builder::PaladinBuilder;
/// # use paladin_ports::output::llm_port::LlmPort;
/// # use std::sync::Arc;
/// # async fn example(llm_port: Arc<dyn LlmPort>) -> Result<(), Box<dyn std::error::Error>> {
/// let paladin = PaladinBuilder::new(llm_port)
///     .system_prompt("You are an AI assistant")
///     .name("Assistant")
///     .model("gpt-4")
///     .temperature(0.8)
///     .build().await?;
/// # Ok(())
/// # }
/// ```
pub struct PaladinBuilder {
    llm_port: Arc<dyn LlmPort>,
    data: PaladinData,
    config: PaladinConfig,
    garrison: Option<Arc<dyn GarrisonPort>>,
    arsenal_registry: Option<Arc<dyn ArsenalRegistry>>,
    mcp_servers: Vec<MCPServerConfig>,
    citadel_port: Option<Arc<dyn CitadelPort>>,
    autosave_enabled: bool,
    state_dir: Option<String>,
    herald: Option<Arc<dyn Herald>>,
    // Sanctum RAG integration fields
    sanctum_port: Option<Arc<dyn SanctumPort>>,
    embedding_port: Option<Arc<dyn EmbeddingPort>>,
    memory_extraction_strategy: MemoryExtractionStrategy,
    // Auto-prompt generation fields
    auto_generate_prompt_enabled: bool,
    agent_description: Option<String>,
    manual_prompt_override: bool,
    // Auto-temperature selection fields
    auto_temperature_enabled: bool,
    manual_temperature_override: bool,
    // Handoff/delegation fields
    specialist_agents: Vec<Arc<Paladin>>,
    handoff_config: Option<Arc<crate::core::platform::container::autonomous_config::HandoffConfig>>,
    handoffs_configured: bool,
}

impl PaladinBuilder {
    /// Creates a new PaladinBuilder with default values
    ///
    /// # Arguments
    ///
    /// * `llm_port` - The LLM port implementation to use for this Paladin
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use paladin::application::services::paladin::paladin_builder::PaladinBuilder;
    /// # use paladin_ports::output::llm_port::LlmPort;
    /// # use std::sync::Arc;
    /// # fn example(llm_port: Arc<dyn LlmPort>) {
    /// let builder = PaladinBuilder::new(llm_port);
    /// # }
    /// ```
    pub fn new(llm_port: Arc<dyn LlmPort>) -> Self {
        Self {
            llm_port,
            data: PaladinData::default(),
            config: PaladinConfig::default(),
            garrison: None,
            arsenal_registry: None,
            mcp_servers: Vec::new(),
            citadel_port: None,
            autosave_enabled: false,
            state_dir: None,
            herald: None,
            sanctum_port: None,
            embedding_port: None,
            memory_extraction_strategy: MemoryExtractionStrategy::default(),
            auto_generate_prompt_enabled: false,
            agent_description: None,
            manual_prompt_override: false,
            auto_temperature_enabled: false,
            manual_temperature_override: false,
            specialist_agents: Vec::new(),
            handoffs_configured: false,
            handoff_config: None,
        }
    }

    /// Sets the system prompt that defines the Paladin's behavior and personality
    ///
    /// # Arguments
    ///
    /// * `prompt` - The system prompt (must be non-empty)
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use paladin::application::services::paladin::paladin_builder::PaladinBuilder;
    /// # use paladin_ports::output::llm_port::LlmPort;
    /// # use std::sync::Arc;
    /// # fn example(llm_port: Arc<dyn LlmPort>) {
    /// let builder = PaladinBuilder::new(llm_port)
    ///     .system_prompt("You are a helpful coding assistant");
    /// # }
    /// ```
    pub fn system_prompt(mut self, prompt: impl Into<String>) -> Self {
        self.data.system_prompt = prompt.into();
        self.manual_prompt_override = true; // Manual prompt takes precedence
        self
    }

    /// Sets the name of the Paladin
    ///
    /// # Arguments
    ///
    /// * `name` - The Paladin's name
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use paladin::application::services::paladin::paladin_builder::PaladinBuilder;
    /// # use paladin_ports::output::llm_port::LlmPort;
    /// # use std::sync::Arc;
    /// # fn example(llm_port: Arc<dyn LlmPort>) {
    /// let builder = PaladinBuilder::new(llm_port)
    ///     .name("CodeAssistant");
    /// # }
    /// ```
    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.data.name = name.into();
        self
    }

    /// Sets the user name that the Paladin will interact with
    ///
    /// # Arguments
    ///
    /// * `user_name` - The user's name
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use paladin::application::services::paladin::paladin_builder::PaladinBuilder;
    /// # use paladin_ports::output::llm_port::LlmPort;
    /// # use std::sync::Arc;
    /// # fn example(llm_port: Arc<dyn LlmPort>) {
    /// let builder = PaladinBuilder::new(llm_port)
    ///     .user_name("Developer");
    /// # }
    /// ```
    pub fn user_name(mut self, user_name: impl Into<String>) -> Self {
        self.data.user_name = user_name.into();
        self
    }

    /// Sets the LLM model to use
    ///
    /// # Arguments
    ///
    /// * `model` - The model identifier (e.g., "gpt-4", "gpt-3.5-turbo")
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use paladin::application::services::paladin::paladin_builder::PaladinBuilder;
    /// # use paladin_ports::output::llm_port::LlmPort;
    /// # use std::sync::Arc;
    /// # fn example(llm_port: Arc<dyn LlmPort>) {
    /// let builder = PaladinBuilder::new(llm_port)
    ///     .model("gpt-4");
    /// # }
    /// ```
    pub fn model(mut self, model: impl Into<String>) -> Self {
        self.data.model = model.into();
        self
    }

    /// Sets the temperature for LLM generation (controls randomness)
    ///
    /// # Arguments
    ///
    /// * `temperature` - Value between 0.0 (deterministic) and 1.0 (random)
    ///
    /// # Validation
    ///
    /// Temperature must be in range [0.0, 1.0] or validation will fail during build()
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use paladin::application::services::paladin::paladin_builder::PaladinBuilder;
    /// # use paladin_ports::output::llm_port::LlmPort;
    /// # use std::sync::Arc;
    /// # fn example(llm_port: Arc<dyn LlmPort>) {
    /// let builder = PaladinBuilder::new(llm_port)
    ///     .temperature(0.7);
    /// # }
    /// ```
    pub fn temperature(mut self, temperature: f32) -> Self {
        self.data.temperature = temperature;
        self.manual_temperature_override = true;
        self
    }

    /// Sets the maximum number of reasoning loops
    ///
    /// # Arguments
    ///
    /// * `max_loops` - Maximum iterations (must be between 1 and 100)
    ///
    /// # Validation
    ///
    /// max_loops must be in range [1, 100] or validation will fail during build()
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use paladin::application::services::paladin::paladin_builder::PaladinBuilder;
    /// # use paladin_ports::output::llm_port::LlmPort;
    /// # use std::sync::Arc;
    /// # fn example(llm_port: Arc<dyn LlmPort>) {
    /// let builder = PaladinBuilder::new(llm_port)
    ///     .max_loops(5);
    /// # }
    /// ```
    pub fn max_loops(mut self, max_loops: u32) -> Self {
        self.data.max_loops = MaxLoops::Fixed(max_loops);
        self
    }

    /// Enables or disables automatic system prompt generation
    ///
    /// When enabled, the Paladin will use LLM to automatically generate
    /// an optimized system prompt based on the agent description.
    ///
    /// # Arguments
    ///
    /// * `enabled` - Whether to enable auto-prompt generation
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use paladin::application::services::paladin::paladin_builder::PaladinBuilder;
    /// # use paladin_ports::output::llm_port::LlmPort;
    /// # use std::sync::Arc;
    /// # fn example(llm_port: Arc<dyn LlmPort>) {
    /// let builder = PaladinBuilder::new(llm_port)
    ///     .auto_generate_prompt(true)
    ///     .agent_description("A code review assistant specialized in Rust");
    /// # }
    /// ```
    pub fn auto_generate_prompt(mut self, enabled: bool) -> Self {
        self.auto_generate_prompt_enabled = enabled;
        self
    }

    /// Sets the agent description for auto-prompt generation
    ///
    /// This description is used by the prompt generation service to create
    /// a contextual system prompt optimized for the agent's role.
    ///
    /// # Arguments
    ///
    /// * `description` - Description of the agent's role and capabilities
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use paladin::application::services::paladin::paladin_builder::PaladinBuilder;
    /// # use paladin_ports::output::llm_port::LlmPort;
    /// # use std::sync::Arc;
    /// # fn example(llm_port: Arc<dyn LlmPort>) {
    /// let builder = PaladinBuilder::new(llm_port)
    ///     .auto_generate_prompt(true)
    ///     .agent_description("Analyzes security vulnerabilities in code");
    /// # }
    /// ```
    pub fn agent_description(mut self, description: impl Into<String>) -> Self {
        let desc = description.into();
        self.agent_description = Some(desc.clone());
        self.data.agent_description = desc; // Also set in PaladinData for autonomous features
        self
    }

    /// Forces regeneration of auto-generated prompt by clearing cache
    ///
    /// Call this method to invalidate cached prompts and force the service
    /// to generate a fresh prompt on the next build.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use paladin::application::services::paladin::paladin_builder::PaladinBuilder;
    /// # use paladin_ports::output::llm_port::LlmPort;
    /// # use std::sync::Arc;
    /// # fn example(llm_port: Arc<dyn LlmPort>) {
    /// let builder = PaladinBuilder::new(llm_port)
    ///     .auto_generate_prompt(true)
    ///     .agent_description("Data analyst")
    ///     .regenerate_prompt(); // Clear cache
    /// # }
    /// ```
    pub fn regenerate_prompt(self) -> Self {
        // Note: Cache invalidation will happen in build() method
        // when we have access to the PromptGenerationService
        self
    }

    /// Enables or disables automatic temperature selection based on task type
    ///
    /// When enabled, the Paladin will use LLM to analyze the agent description
    /// and task context to automatically select an optimal temperature value:
    /// - Creative tasks (writing, brainstorming): ~0.85
    /// - Analytical tasks (math, code, logic): ~0.2
    /// - Standard tasks (Q&A, conversation): ~0.6
    ///
    /// # Arguments
    ///
    /// * `enabled` - Whether to enable automatic temperature selection
    ///
    /// # Note
    ///
    /// If you call `temperature()` explicitly, it will override the automatic
    /// temperature selection, just like manual system prompts override auto-generated ones.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use paladin::application::services::paladin::paladin_builder::PaladinBuilder;
    /// # use paladin_ports::output::llm_port::LlmPort;
    /// # use std::sync::Arc;
    /// # fn example(llm_port: Arc<dyn LlmPort>) {
    /// let builder = PaladinBuilder::new(llm_port)
    ///     .agent_description("A creative writing assistant")
    ///     .auto_temperature(true); // Will use ~0.85 for creative tasks
    /// # }
    /// ```
    pub fn auto_temperature(mut self, enabled: bool) -> Self {
        self.auto_temperature_enabled = enabled;
        self
    }

    /// Adds a stop word that will halt execution when detected in LLM output
    ///
    /// # Arguments
    ///
    /// * `word` - The stop word to add
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use paladin::application::services::paladin::paladin_builder::PaladinBuilder;
    /// # use paladin_ports::output::llm_port::LlmPort;
    /// # use std::sync::Arc;
    /// # fn example(llm_port: Arc<dyn LlmPort>) {
    /// let builder = PaladinBuilder::new(llm_port)
    ///     .add_stop_word("STOP")
    ///     .add_stop_word("END");
    /// # }
    /// ```
    pub fn add_stop_word(mut self, word: impl Into<String>) -> Self {
        self.data.stop_words.push(word.into());
        self
    }

    /// Sets the number of retry attempts for failed LLM calls
    ///
    /// # Arguments
    ///
    /// * `attempts` - Number of retries (default: 3)
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use paladin::application::services::paladin::paladin_builder::PaladinBuilder;
    /// # use paladin_ports::output::llm_port::LlmPort;
    /// # use std::sync::Arc;
    /// # fn example(llm_port: Arc<dyn LlmPort>) {
    /// let builder = PaladinBuilder::new(llm_port)
    ///     .retry_attempts(5);
    /// # }
    /// ```
    pub fn retry_attempts(mut self, attempts: u32) -> Self {
        self.config.retry_attempts = attempts;
        self
    }

    /// Sets the execution timeout in seconds
    ///
    /// # Arguments
    ///
    /// * `seconds` - Timeout duration (default: 300)
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use paladin::application::services::paladin::paladin_builder::PaladinBuilder;
    /// # use paladin_ports::output::llm_port::LlmPort;
    /// # use std::sync::Arc;
    /// # fn example(llm_port: Arc<dyn LlmPort>) {
    /// let builder = PaladinBuilder::new(llm_port)
    ///     .timeout_seconds(600);
    /// # }
    /// ```
    pub fn timeout_seconds(mut self, seconds: u64) -> Self {
        self.config.timeout_seconds = seconds;
        self
    }

    /// Enables or disables planning mode
    ///
    /// # Arguments
    ///
    /// * `enabled` - Whether to enable planning (default: false)
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use paladin::application::services::paladin::paladin_builder::PaladinBuilder;
    /// # use paladin_ports::output::llm_port::LlmPort;
    /// # use std::sync::Arc;
    /// # fn example(llm_port: Arc<dyn LlmPort>) {
    /// let builder = PaladinBuilder::new(llm_port)
    ///     .enable_planning(true);
    /// # }
    /// ```
    pub fn enable_planning(mut self, enabled: bool) -> Self {
        self.config.enable_planning = enabled;
        self
    }

    /// Enables or disables vision capabilities for multimodal input
    ///
    /// When enabled, the Paladin can process both text and images in requests.
    /// The underlying LLM must support vision (checked during validation).
    ///
    /// # Arguments
    ///
    /// * `enabled` - Whether to enable vision (default: false)
    ///
    /// # Validation
    ///
    /// If vision is enabled, the LLM port must implement VisionCapableLlm trait,
    /// or validation will fail during build().
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use paladin::application::services::paladin::paladin_builder::PaladinBuilder;
    /// # use paladin_ports::output::llm_port::LlmPort;
    /// # use std::sync::Arc;
    /// # fn example(llm_port: Arc<dyn LlmPort>) {
    /// let builder = PaladinBuilder::new(llm_port)
    ///     .system_prompt("You are an AI that can analyze images")
    ///     .enable_vision(true);
    /// # }
    /// ```
    pub fn enable_vision(mut self, enabled: bool) -> Self {
        self.data.vision_enabled = enabled;
        self
    }

    /// Enables autonomous planning mode (Layer 1)
    ///
    /// When enabled, the Paladin will use PlanningService to decompose complex
    /// tasks into subtasks before execution. Requires planning service to be
    /// configured via `with_planning_service` in the execution service.
    ///
    /// # Arguments
    ///
    /// * `enabled` - Whether to enable autonomous planning
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use paladin::application::services::paladin::paladin_builder::PaladinBuilder;
    /// # use paladin_ports::output::llm_port::LlmPort;
    /// # use std::sync::Arc;
    /// # async fn example(llm_port: Arc<dyn LlmPort>) -> Result<(), Box<dyn std::error::Error>> {
    /// let paladin = PaladinBuilder::new(llm_port)
    ///     .system_prompt("You are an AI assistant")
    ///     .enable_autonomous_planning(true)
    ///     .build().await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn enable_autonomous_planning(mut self, enabled: bool) -> Self {
        self.data.autonomous_planning = enabled;
        self
    }

    /// Enables autonomous prompt generation (Layer 1)
    ///
    /// When enabled, the Paladin will use PromptGenerationService to generate
    /// a contextual system prompt based on agent_description. Requires prompt
    /// generation service to be configured via `with_prompt_generation_service`
    /// in the execution service.
    ///
    /// # Arguments
    ///
    /// * `enabled` - Whether to enable autonomous prompt generation
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use paladin::application::services::paladin::paladin_builder::PaladinBuilder;
    /// # use paladin_ports::output::llm_port::LlmPort;
    /// # use std::sync::Arc;
    /// # async fn example(llm_port: Arc<dyn LlmPort>) -> Result<(), Box<dyn std::error::Error>> {
    /// let paladin = PaladinBuilder::new(llm_port)
    ///     .agent_description("An AI specialized in code review")
    ///     .enable_autonomous_prompts(true)
    ///     .build().await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn enable_autonomous_prompts(mut self, enabled: bool) -> Self {
        self.data.autonomous_prompts = enabled;
        self
    }

    /// Enables dynamic temperature adjustment (Layer 2)
    ///
    /// When enabled, temperature increases linearly from the configured base
    /// value to 1.0 over the course of max_loops iterations. This encourages
    /// exploration in later loops when the agent might be stuck.
    ///
    /// # Arguments
    ///
    /// * `enabled` - Whether to enable dynamic temperature
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use paladin::application::services::paladin::paladin_builder::PaladinBuilder;
    /// # use paladin_ports::output::llm_port::LlmPort;
    /// # use std::sync::Arc;
    /// # async fn example(llm_port: Arc<dyn LlmPort>) -> Result<(), Box<dyn std::error::Error>> {
    /// let paladin = PaladinBuilder::new(llm_port)
    ///     .system_prompt("You are an AI assistant")
    ///     .temperature(0.5)  // Starting temperature
    ///     .max_loops(5)
    ///     .enable_dynamic_temperature(true)  // Will increase to 1.0 by loop 5
    ///     .build().await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn enable_dynamic_temperature(mut self, enabled: bool) -> Self {
        self.data.dynamic_temperature = enabled;
        self
    }

    /// Sets the output format for responses
    ///
    /// # Arguments
    ///
    /// * `format` - The desired output format
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use paladin::application::services::paladin::paladin_builder::PaladinBuilder;
    /// # use paladin_ports::output::llm_port::LlmPort;
    /// # use paladin::core::platform::container::paladin_config::OutputFormat;
    /// # use std::sync::Arc;
    /// # fn example(llm_port: Arc<dyn LlmPort>) {
    /// let builder = PaladinBuilder::new(llm_port)
    ///     .output_format(OutputFormat::Json);
    /// # }
    /// ```
    pub fn output_format(mut self, format: OutputFormat) -> Self {
        self.config.output_format = format;
        self
    }

    /// Attaches a Garrison memory system to the Paladin
    ///
    /// The Garrison enables the Paladin to maintain conversation context across
    /// multiple turns. It is optional for single-turn operations but required
    /// for multi-turn conversations.
    ///
    /// # Arguments
    ///
    /// * `garrison` - The Garrison port implementation to use for memory
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use paladin::application::services::paladin::paladin_builder::PaladinBuilder;
    /// # use paladin_ports::output::llm_port::LlmPort;
    /// # use paladin_ports::output::garrison_port::GarrisonPort;
    /// # use std::sync::Arc;
    /// # fn example(llm_port: Arc<dyn LlmPort>, garrison: Arc<dyn GarrisonPort>) {
    /// let builder = PaladinBuilder::new(llm_port)
    ///     .system_prompt("You are a conversational assistant")
    ///     .with_garrison(garrison);
    /// # }
    /// ```
    pub fn with_garrison(mut self, garrison: Arc<dyn GarrisonPort>) -> Self {
        self.garrison = Some(garrison);
        self
    }

    /// Attaches an Arsenal registry to the Paladin for tool execution
    ///
    /// The Arsenal enables the Paladin to discover and invoke external tools
    /// through the Model Context Protocol (MCP). Tools can be STDIO-based
    /// (command-line) or SSE-based (HTTP).
    ///
    /// # Arguments
    ///
    /// * `registry` - The Arsenal registry implementation containing registered tools
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use paladin::application::services::paladin::paladin_builder::PaladinBuilder;
    /// # use paladin_ports::output::llm_port::LlmPort;
    /// # use paladin_ports::output::arsenal_port::ArsenalRegistry;
    /// # use std::sync::Arc;
    /// # fn example(llm_port: Arc<dyn LlmPort>, registry: Arc<dyn ArsenalRegistry>) {
    /// let builder = PaladinBuilder::new(llm_port)
    ///     .system_prompt("You are a tool-using assistant")
    ///     .with_arsenal_registry(registry);
    /// # }
    /// ```
    pub fn with_arsenal_registry(mut self, registry: Arc<dyn ArsenalRegistry>) -> Self {
        self.arsenal_registry = Some(registry);
        self
    }

    /// Sets a Herald formatter for output formatting
    ///
    /// Herald formatters control how Paladin execution results are formatted for display.
    /// Built-in formatters include JSON, Markdown, and Table.
    ///
    /// # Arguments
    ///
    /// * `herald` - The Herald implementation to use for formatting
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use paladin::application::services::paladin::paladin_builder::PaladinBuilder;
    /// # use paladin::infrastructure::adapters::herald::JsonHerald;
    /// # use paladin_ports::output::llm_port::LlmPort;
    /// # use std::sync::Arc;
    /// # fn example(llm_port: Arc<dyn LlmPort>) {
    /// let herald = Arc::new(JsonHerald::default());
    /// let builder = PaladinBuilder::new(llm_port)
    ///     .system_prompt("You are a helpful assistant")
    ///     .with_herald(herald);
    /// # }
    /// ```
    pub fn with_herald(mut self, herald: Arc<dyn Herald>) -> Self {
        self.herald = Some(herald);
        self
    }

    /// Attaches a Sanctum vector store for RAG capabilities
    ///
    /// Sanctum enables Retrieval-Augmented Generation by storing and retrieving
    /// relevant context from past conversations and knowledge. When combined with
    /// an embedding port, the Paladin can automatically:
    /// - Retrieve relevant memories before generating responses
    /// - Extract and store important information after conversations
    /// - Perform semantic search over past interactions
    ///
    /// **Note**: Requires an `EmbeddingPort` to be set via `with_embedding_port()`
    ///
    /// # Arguments
    ///
    /// * `sanctum` - The Sanctum port implementation (e.g., Qdrant adapter)
    ///
    /// # Example
    ///
    /// ```ignore
    /// # use paladin::application::services::paladin::paladin_builder::PaladinBuilder;
    /// # use paladin_ports::output::llm_port::LlmPort;
    /// # use paladin_ports::output::sanctum_port::SanctumPort;
    /// # use paladin_ports::output::embedding_port::EmbeddingPort;
    /// # use std::sync::Arc;
    /// # fn example(llm_port: Arc<dyn LlmPort>, sanctum: Arc<dyn SanctumPort>, embedding: Arc<dyn EmbeddingPort>) -> Result<(), Box<dyn std::error::Error>> {
    /// let paladin = PaladinBuilder::new(llm_port)
    ///     .system_prompt("You are an assistant with RAG")
    ///     .with_sanctum(sanctum)
    ///     .with_embedding_port(embedding)
    ///     .build()?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn with_sanctum(mut self, sanctum: Arc<dyn SanctumPort>) -> Self {
        self.sanctum_port = Some(sanctum);
        self
    }

    /// Attaches an embedding port for generating vector embeddings
    ///
    /// The embedding port converts text into vector representations that can be
    /// stored in Sanctum and used for semantic search. This is required when
    /// using Sanctum for RAG capabilities.
    ///
    /// Supported embedding providers include:
    /// - OpenAI (`text-embedding-ada-002`, `text-embedding-3-small`, `text-embedding-3-large`)
    /// - Local models via transformers
    ///
    /// # Arguments
    ///
    /// * `embedding_port` - The embedding port implementation
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use paladin::application::services::paladin::paladin_builder::PaladinBuilder;
    /// # use paladin_ports::output::llm_port::LlmPort;
    /// # use paladin_ports::output::embedding_port::EmbeddingPort;
    /// # use std::sync::Arc;
    /// # fn example(llm_port: Arc<dyn LlmPort>, embedding: Arc<dyn EmbeddingPort>) {
    /// let builder = PaladinBuilder::new(llm_port)
    ///     .system_prompt("You are a RAG-enabled assistant")
    ///     .with_embedding_port(embedding);
    /// # }
    /// ```
    pub fn with_embedding_port(mut self, embedding_port: Arc<dyn EmbeddingPort>) -> Self {
        self.embedding_port = Some(embedding_port);
        self
    }

    /// Sets the strategy for extracting memories from conversations
    ///
    /// Controls when the Paladin should analyze conversation history and extract
    /// important information to store in Sanctum.
    ///
    /// # Strategies
    ///
    /// - `EveryTurn`: Extract memories after each conversation turn (most thorough but expensive)
    /// - `OnCompletion`: Extract memories only when the conversation completes (default, balanced)
    /// - `Manual`: Only extract memories when explicitly triggered
    /// - `Threshold { importance }`: Extract memories when importance threshold is exceeded
    ///
    /// # Arguments
    ///
    /// * `strategy` - The memory extraction strategy to use
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use paladin::application::services::paladin::paladin_builder::PaladinBuilder;
    /// # use paladin::application::services::sanctum::memory_extraction_service::MemoryExtractionStrategy;
    /// # use paladin_ports::output::llm_port::LlmPort;
    /// # use std::sync::Arc;
    /// # fn example(llm_port: Arc<dyn LlmPort>) {
    /// let builder = PaladinBuilder::new(llm_port)
    ///     .system_prompt("You are an assistant")
    ///     .memory_extraction_strategy(MemoryExtractionStrategy::Threshold { importance: 5 });
    /// # }
    /// ```
    pub fn memory_extraction_strategy(mut self, strategy: MemoryExtractionStrategy) -> Self {
        self.memory_extraction_strategy = strategy;
        self
    }

    /// Registers specialist agents for task delegation via handoffs
    ///
    /// Allows this Paladin to delegate tasks to specialist agents when confidence
    /// is low or tasks require specific expertise. The handoff strategy determines
    /// when delegation occurs.
    ///
    /// # Arguments
    ///
    /// * `specialists` - Vector of specialist Paladin agents available for delegation
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use paladin::application::services::paladin::paladin_builder::PaladinBuilder;
    /// # use paladin_ports::output::llm_port::LlmPort;
    /// # use std::sync::Arc;
    /// # async fn example(llm_port: Arc<dyn LlmPort>) -> Result<(), Box<dyn std::error::Error>> {
    /// // Create specialist agents
    /// let rust_expert = PaladinBuilder::new(llm_port.clone())
    ///     .system_prompt("You are a Rust programming expert")
    ///     .name("RustExpert")
    ///     .build().await?;
    ///
    /// let python_expert = PaladinBuilder::new(llm_port.clone())
    ///     .system_prompt("You are a Python programming expert")
    ///     .name("PythonExpert")
    ///     .build().await?;
    ///
    /// // Coordinator can delegate to specialists
    /// let coordinator = PaladinBuilder::new(llm_port)
    ///     .system_prompt("You are a code coordinator")
    ///     .name("Coordinator")
    ///     .with_handoffs(vec![Arc::new(rust_expert), Arc::new(python_expert)])
    ///     .build().await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn with_handoffs(mut self, specialists: Vec<Arc<Paladin>>) -> Self {
        self.specialist_agents = specialists;
        self.handoffs_configured = !self.specialist_agents.is_empty();
        self
    }

    /// Sets the handoff configuration for agent delegation
    ///
    /// Configures when and how this Paladin should delegate tasks to specialists.
    ///
    /// # Arguments
    ///
    /// * `config` - Handoff configuration including strategy and limits
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use paladin::application::services::paladin::paladin_builder::PaladinBuilder;
    /// # use paladin_ports::output::llm_port::LlmPort;
    /// # use paladin::core::platform::container::autonomous_config::{HandoffConfig, HandoffRetryConfig};
    /// # use paladin::core::platform::container::handoff::HandoffStrategy;
    /// # use std::sync::Arc;
    /// # fn example(llm_port: Arc<dyn LlmPort>) {
    /// let config = Arc::new(HandoffConfig {
    ///     enabled: true,
    ///     strategy: HandoffStrategy::threshold(0.7),
    ///     max_depth: 3,
    ///     retry: HandoffRetryConfig::default(),
    /// });
    ///
    /// let builder = PaladinBuilder::new(llm_port)
    ///     .system_prompt("You are a coordinator")
    ///     .handoff_config(config);
    /// # }
    /// ```
    pub fn handoff_config(
        mut self,
        config: Arc<crate::core::platform::container::autonomous_config::HandoffConfig>,
    ) -> Self {
        self.handoff_config = Some(config);
        self
    }

    /// Adds an STDIO-based MCP server configuration
    ///
    /// STDIO servers are command-line tools that communicate via stdin/stdout
    /// using the Model Context Protocol.
    ///
    /// # Arguments
    ///
    /// * `name` - Identifier for the server
    /// * `command` - Command to execute
    /// * `args` - Command-line arguments
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use paladin::application::services::paladin::paladin_builder::PaladinBuilder;
    /// # use paladin_ports::output::llm_port::LlmPort;
    /// # use std::sync::Arc;
    /// # fn example(llm_port: Arc<dyn LlmPort>) {
    /// let builder = PaladinBuilder::new(llm_port)
    ///     .system_prompt("You are an assistant with web search")
    ///     .add_mcp_stdio("web_search", "uvx", &["mcp-web-search"]);
    /// # }
    /// ```
    pub fn add_mcp_stdio(
        mut self,
        name: impl Into<String>,
        command: impl Into<String>,
        args: &[&str],
    ) -> Self {
        self.mcp_servers.push(MCPServerConfig {
            name: name.into(),
            server_type: "stdio".to_string(),
            command: Some(command.into()),
            args: Some(args.iter().map(|s| s.to_string()).collect()),
            endpoint: None,
        });
        self
    }

    /// Adds an SSE-based MCP server configuration
    ///
    /// SSE servers are HTTP-based tools that communicate using Server-Sent Events
    /// and the Model Context Protocol.
    ///
    /// # Arguments
    ///
    /// * `name` - Identifier for the server
    /// * `endpoint` - HTTP endpoint URL
    ///
    /// # Example
    /// ```rust,no_run
    /// # use paladin::application::services::paladin::paladin_builder::PaladinBuilder;
    /// # use paladin_ports::output::llm_port::LlmPort;
    /// # use std::sync::Arc;
    /// # fn example(llm_port: Arc<dyn LlmPort>) {
    /// let builder = PaladinBuilder::new(llm_port)
    ///     .system_prompt("You are an assistant with code analysis")
    ///     .add_mcp_sse("code_analyzer", "http://localhost:8080/mcp");
    /// # }
    /// ```
    pub fn add_mcp_sse(mut self, name: impl Into<String>, endpoint: impl Into<String>) -> Self {
        self.mcp_servers.push(MCPServerConfig {
            name: name.into(),
            server_type: "sse".to_string(),
            command: None,
            args: None,
            endpoint: Some(endpoint.into()),
        });
        self
    }

    /// Attaches a Citadel state persistence system to the Paladin
    ///
    /// The Citadel enables automatic saving and restoration of Paladin state,
    /// including configuration, execution history, and Garrison context.
    ///
    /// # Arguments
    ///
    /// * `citadel` - The Citadel port implementation to use for state persistence
    ///
    /// Enables state persistence by attaching a Citadel adapter.
    ///
    /// The Citadel system provides automatic state saving and restoration for
    /// Paladin agents. This enables fault tolerance, debugging, and long-running
    /// workflows that can survive system restarts.
    ///
    /// # Arguments
    ///
    /// * `citadel` - A Citadel adapter implementing the CitadelPort trait
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use paladin::application::services::paladin::paladin_builder::PaladinBuilder;
    /// # use paladin_ports::output::llm_port::LlmPort;
    /// # use paladin::infrastructure::adapters::citadel::file_citadel::FileCitadel;
    /// # use std::sync::Arc;
    /// # fn example(llm_port: Arc<dyn LlmPort>) -> Result<(), Box<dyn std::error::Error>> {
    /// // Create a file-based Citadel adapter
    /// let citadel = Arc::new(FileCitadel::new("./paladin-states")?);
    ///
    /// let builder = PaladinBuilder::new(llm_port)
    ///     .system_prompt("You are a stateful assistant")
    ///     .with_citadel(citadel);
    /// # Ok(())
    /// # }
    /// ```
    pub fn with_citadel(mut self, citadel: Arc<dyn CitadelPort>) -> Self {
        self.citadel_port = Some(citadel);
        self
    }

    /// Enables automatic state saving after Paladin execution
    ///
    /// When enabled, the Paladin's state will be automatically saved to the
    /// Citadel after each execution completes successfully. This enables
    /// resumption of work and audit trails.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use paladin::application::services::paladin::paladin_builder::PaladinBuilder;
    /// # use paladin_ports::output::llm_port::LlmPort;
    /// # use std::sync::Arc;
    /// # fn example(llm_port: Arc<dyn LlmPort>) {
    /// let builder = PaladinBuilder::new(llm_port)
    ///     .system_prompt("You are a persistent assistant")
    ///     .enable_autosave();
    /// # }
    /// ```
    pub fn enable_autosave(mut self) -> Self {
        self.autosave_enabled = true;
        self
    }

    /// Sets the directory path for state persistence
    ///
    /// If not set, the default directory from configuration will be used.
    /// The directory will be created automatically if it doesn't exist.
    ///
    /// # Arguments
    ///
    /// * `path` - Directory path where state files will be saved
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use paladin::application::services::paladin::paladin_builder::PaladinBuilder;
    /// # use paladin_ports::output::llm_port::LlmPort;
    /// # use std::sync::Arc;
    /// # fn example(llm_port: Arc<dyn LlmPort>) {
    /// let builder = PaladinBuilder::new(llm_port)
    ///     .system_prompt("You are a persistent assistant")
    ///     .save_state_dir("./my_citadel");
    /// # }
    /// ```
    pub fn save_state_dir(mut self, path: impl Into<String>) -> Self {
        self.state_dir = Some(path.into());
        self
    }

    /// Restores a Paladin from a previously saved state
    ///
    /// Loads the Paladin configuration, execution history, and Garrison context
    /// from the Citadel, allowing resumption of previous work.
    ///
    /// # Arguments
    ///
    /// * `state_id` - UUID of the saved state to restore
    ///
    /// # Returns
    ///
    /// - `Ok(Self)` if state was successfully restored
    /// - `Err(PaladinError)` if state couldn't be loaded or Citadel is not configured
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use paladin::application::services::paladin::paladin_builder::PaladinBuilder;
    /// # use paladin_ports::output::llm_port::LlmPort;
    /// # use paladin_ports::output::citadel_port::CitadelPort;
    /// # use uuid::Uuid;
    /// # use std::sync::Arc;
    /// # async fn example(llm_port: Arc<dyn LlmPort>, citadel: Arc<dyn CitadelPort>) -> Result<(), Box<dyn std::error::Error>> {
    /// let state_id = Uuid::parse_str("550e8400-e29b-41d4-a716-446655440000")?;
    /// let builder = PaladinBuilder::new(llm_port)
    ///     .with_citadel(citadel)
    ///     .restore_from(state_id).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn restore_from(mut self, state_id: Uuid) -> Result<Self, PaladinError> {
        let citadel = self.citadel_port.as_ref().ok_or_else(|| {
            PaladinError::ConfigurationError(
                "Citadel port must be configured to restore state".to_string(),
            )
        })?;

        let state = citadel
            .load_paladin(state_id)
            .await
            .map_err(|e| PaladinError::ConfigurationError(format!("Failed to load state: {}", e)))?
            .ok_or_else(|| {
                PaladinError::ConfigurationError(format!("State not found: {}", state_id))
            })?;

        // Restore data from state
        self.data.system_prompt = state.paladin.node.system_prompt.clone();
        self.data.name = state.paladin.node.name.clone();
        self.data.user_name = state.paladin.node.user_name.clone();
        self.data.model = state.paladin.node.model.clone();
        self.data.temperature = state.paladin.node.temperature;
        self.data.max_loops = state.paladin.node.max_loops;
        self.data.stop_words = state.paladin.node.stop_words.clone();

        // Note: Config fields (retry_attempts, timeout_seconds) are not part of PaladinData
        // They would need to be stored separately if we want to restore them

        Ok(self)
    }

    /// Validates all configuration parameters
    ///
    /// # Validation Rules
    ///
    /// - `system_prompt` must be non-empty
    /// - `temperature` must be in range [0.0, 1.0]
    /// - `max_loops` must be in range [1, 100]
    /// - If `autosave_enabled` is true, `state_dir` must be set or Citadel must be configured
    /// - If `sanctum_port` is set, `embedding_port` must also be set (required for RAG)
    ///
    /// # Returns
    ///
    /// Ok(()) if all validations pass, Err(PaladinError::ConfigurationError) otherwise
    fn validate(&self) -> Result<(), PaladinError> {
        // Validate system_prompt is non-empty
        if self.data.system_prompt.trim().is_empty() {
            return Err(PaladinError::ConfigurationError(
                "system prompt cannot be empty".to_string(),
            ));
        }

        // Validate temperature is in [0.0, 1.0]
        if !(0.0..=1.0).contains(&self.data.temperature) {
            return Err(PaladinError::ConfigurationError(format!(
                "temperature must be between 0.0 and 1.0, got {}",
                self.data.temperature
            )));
        }

        // Validate max_loops is in [1, 100]
        let loops = self.data.max_loops.as_u32();
        if (1..=100).contains(&loops) {
            // Valid range
        } else {
            return Err(PaladinError::ConfigurationError(format!(
                "max_loops must be between 1 and 100, got {}",
                loops
            )));
        }

        // Validate autosave configuration
        if self.autosave_enabled && self.citadel_port.is_none() && self.state_dir.is_none() {
            return Err(PaladinError::ConfigurationError(
                "autosave_enabled requires either citadel_port or state_dir to be set".to_string(),
            ));
        }

        // Validate Sanctum RAG dependencies
        if self.sanctum_port.is_some() && self.embedding_port.is_none() {
            return Err(PaladinError::ConfigurationError(
                "embedding_port is required when sanctum_port is set (needed for RAG operations)"
                    .to_string(),
            ));
        }

        // Validate vision capability
        if self.data.vision_enabled {
            // Check if LLM port supports vision by checking if it reports vision capability
            let capabilities = self.llm_port.get_capabilities();
            if !capabilities.supports_vision {
                return Err(PaladinError::ConfigurationError(format!(
                    "vision_enabled is true but the LLM provider '{}' does not support vision. \
                         Enable vision support in the LLM adapter or set vision_enabled to false.",
                    self.llm_port.get_provider_name()
                )));
            }
        }

        Ok(())
    }

    /// Generates the handoff tool schema with specialist names
    ///
    /// Creates an Armament (tool definition) for the handoff functionality
    /// that includes all configured specialist agent names as an enum parameter.
    ///
    /// # Returns
    ///
    /// An `Armament` instance representing the handoff tool
    fn generate_handoff_tool(&self) -> Armament {
        use serde_json::json;

        // Extract specialist names from the configured specialist agents
        let specialist_names: Vec<String> = self
            .specialist_agents
            .iter()
            .map(|p| p.node.name.clone())
            .collect();

        // Create JSON schema for handoff tool with specialist names as enum
        let parameters = json!({
            "type": "object",
            "properties": {
                "specialist_name": {
                    "type": "string",
                    "description": "Name of the specialist agent to delegate the task to",
                    "enum": specialist_names
                },
                "task_description": {
                    "type": "string",
                    "description": "Clear description of the task to delegate to the specialist"
                }
            },
            "required": ["specialist_name", "task_description"]
        });

        Armament {
            name: "handoff_to_specialist".to_string(),
            description: format!(
                "Delegate a task to one of {} specialist agents: {}",
                specialist_names.len(),
                specialist_names.join(", ")
            ),
            parameters,
            required_params: vec![
                "specialist_name".to_string(),
                "task_description".to_string(),
            ],
        }
    }

    /// Builds and returns a validated Paladin instance
    ///
    /// # Returns
    ///
    /// - `Ok(Paladin)` if validation succeeds
    /// - `Err(PaladinError::ConfigurationError)` if validation fails
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use paladin::application::services::paladin::paladin_builder::PaladinBuilder;
    /// # use paladin_ports::output::llm_port::LlmPort;
    /// # use std::sync::Arc;
    /// # async fn example(llm_port: Arc<dyn LlmPort>) -> Result<(), Box<dyn std::error::Error>> {
    /// let paladin = PaladinBuilder::new(llm_port)
    ///     .system_prompt("You are an AI assistant")
    ///     .model("gpt-4")
    ///     .build().await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn build(mut self) -> Result<Paladin, PaladinError> {
        // Handle auto-prompt generation if enabled and no manual override
        if self.auto_generate_prompt_enabled && !self.manual_prompt_override {
            if let Some(description) = &self.agent_description {
                use crate::application::services::paladin::prompt_generation_service::PromptGenerationService;

                let prompt_service = PromptGenerationService::new(self.llm_port.clone());
                let agent_name = if self.data.name.is_empty() {
                    "Agent"
                } else {
                    &self.data.name
                };

                match prompt_service
                    .generate_prompt(agent_name, description, &self.data.model)
                    .await
                {
                    Ok(generated_prompt) => {
                        log::info!("Auto-generated system prompt for agent: {}", agent_name);
                        self.data.system_prompt = generated_prompt;
                    }
                    Err(e) => {
                        return Err(PaladinError::ConfigurationError(format!(
                            "Failed to auto-generate prompt: {}",
                            e
                        )));
                    }
                }
            } else {
                return Err(PaladinError::ConfigurationError(
                    "auto_generate_prompt is enabled but agent_description is not set".to_string(),
                ));
            }
        }

        // Handle auto-temperature selection if enabled and no manual override
        if self.auto_temperature_enabled && !self.manual_temperature_override {
            if let Some(description) = &self.agent_description {
                use crate::application::services::paladin::temperature_service::TemperatureService;

                let temperature_service = TemperatureService::new(self.llm_port.clone());

                match temperature_service
                    .calculate_optimal_temperature(description, None)
                    .await
                {
                    Ok(optimal_temp) => {
                        log::info!(
                            "Auto-selected temperature {} for agent based on task type",
                            optimal_temp
                        );
                        self.data.temperature = optimal_temp;
                    }
                    Err(e) => {
                        return Err(PaladinError::ConfigurationError(format!(
                            "Failed to auto-select temperature: {}",
                            e
                        )));
                    }
                }
            } else {
                return Err(PaladinError::ConfigurationError(
                    "auto_temperature is enabled but agent_description is not set".to_string(),
                ));
            }
        }

        // Auto-register handoff tool if handoffs are configured
        if self.handoffs_configured {
            if let Some(arsenal) = &self.arsenal_registry {
                let handoff_tool = self.generate_handoff_tool();
                arsenal.register(handoff_tool).await;
                log::info!(
                    "Auto-registered handoff tool with {} specialists",
                    self.specialist_agents.len()
                );
            } else {
                log::warn!(
                    "Handoffs configured but no arsenal registry provided - handoff tool not registered"
                );
            }
        }

        // Validate configuration
        self.validate()?;

        // Initialize FileCitadel if state_dir is provided but citadel_port is not
        if let Some(state_dir) = &self.state_dir
            && self.citadel_port.is_none()
        {
            let file_citadel = FileCitadel::new(PathBuf::from(state_dir)).map_err(|e| {
                PaladinError::ConfigurationError(format!("Failed to initialize FileCitadel: {}", e))
            })?;
            self.citadel_port = Some(Arc::new(file_citadel));
        }

        // Create Paladin using Node pattern with name
        let name = if self.data.name.is_empty() {
            None
        } else {
            Some(self.data.name.clone())
        };

        Ok(Node::new(self.data, name))
    }
}

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

    #[test]
    fn test_builder_validation_empty_prompt() {
        let builder = PaladinBuilder {
            llm_port: Arc::new(MockLlmPort),
            data: PaladinData {
                system_prompt: "".to_string(),
                ..Default::default()
            },
            config: PaladinConfig::default(),
            garrison: None,
            arsenal_registry: None,
            mcp_servers: Vec::new(),
            citadel_port: None,
            autosave_enabled: false,
            state_dir: None,
            herald: None,
            sanctum_port: None,
            embedding_port: None,
            memory_extraction_strategy: MemoryExtractionStrategy::default(),
            auto_generate_prompt_enabled: false,
            agent_description: None,
            manual_prompt_override: false,
            auto_temperature_enabled: false,
            manual_temperature_override: false,
            specialist_agents: Vec::new(),
            handoffs_configured: false,
            handoff_config: None,
        };

        let result = builder.validate();
        assert!(result.is_err());
        assert!(matches!(result, Err(PaladinError::ConfigurationError(_))));
    }

    #[test]
    fn test_builder_validation_invalid_temperature() {
        let builder = PaladinBuilder {
            llm_port: Arc::new(MockLlmPort),
            data: PaladinData {
                system_prompt: "Test".to_string(),
                temperature: 1.5,
                ..Default::default()
            },
            config: PaladinConfig::default(),
            garrison: None,
            arsenal_registry: None,
            mcp_servers: Vec::new(),
            citadel_port: None,
            autosave_enabled: false,
            state_dir: None,
            herald: None,
            sanctum_port: None,
            embedding_port: None,
            memory_extraction_strategy: MemoryExtractionStrategy::default(),
            auto_generate_prompt_enabled: false,
            agent_description: None,
            manual_prompt_override: false,
            auto_temperature_enabled: false,
            manual_temperature_override: false,
            specialist_agents: Vec::new(),
            handoffs_configured: false,
            handoff_config: None,
        };

        let result = builder.validate();
        assert!(result.is_err());
    }

    #[test]
    fn test_builder_validation_invalid_max_loops() {
        let builder = PaladinBuilder {
            llm_port: Arc::new(MockLlmPort),
            data: PaladinData {
                system_prompt: "Test".to_string(),
                max_loops: MaxLoops::Fixed(0),
                ..Default::default()
            },
            config: PaladinConfig::default(),
            garrison: None,
            arsenal_registry: None,
            mcp_servers: Vec::new(),
            citadel_port: None,
            autosave_enabled: false,
            state_dir: None,
            herald: None,
            sanctum_port: None,
            embedding_port: None,
            memory_extraction_strategy: MemoryExtractionStrategy::default(),
            auto_generate_prompt_enabled: false,
            agent_description: None,
            manual_prompt_override: false,
            auto_temperature_enabled: false,
            manual_temperature_override: false,
            specialist_agents: Vec::new(),
            handoffs_configured: false,
            handoff_config: None,
        };

        let result = builder.validate();
        assert!(result.is_err());
    }

    #[test]
    fn test_builder_with_citadel() {
        let citadel = Arc::new(MockCitadelPort);
        let builder = PaladinBuilder::new(Arc::new(MockLlmPort))
            .system_prompt("Test")
            .with_citadel(citadel);

        assert!(builder.citadel_port.is_some());
    }

    #[test]
    fn test_builder_enable_autosave() {
        let builder = PaladinBuilder::new(Arc::new(MockLlmPort))
            .system_prompt("Test")
            .enable_autosave();

        assert!(builder.autosave_enabled);
    }

    #[test]
    fn test_builder_save_state_dir() {
        let builder = PaladinBuilder::new(Arc::new(MockLlmPort))
            .system_prompt("Test")
            .save_state_dir("./test_citadel");

        assert_eq!(builder.state_dir, Some("./test_citadel".to_string()));
    }

    #[test]
    fn test_builder_validation_autosave_without_citadel_or_dir() {
        let builder = PaladinBuilder {
            llm_port: Arc::new(MockLlmPort),
            data: PaladinData {
                system_prompt: "Test".to_string(),
                ..Default::default()
            },
            config: PaladinConfig::default(),
            garrison: None,
            arsenal_registry: None,
            mcp_servers: Vec::new(),
            citadel_port: None,
            autosave_enabled: true,
            state_dir: None,
            herald: None,
            sanctum_port: None,
            embedding_port: None,
            memory_extraction_strategy: MemoryExtractionStrategy::default(),
            auto_generate_prompt_enabled: false,
            agent_description: None,
            manual_prompt_override: false,
            auto_temperature_enabled: false,
            manual_temperature_override: false,
            specialist_agents: Vec::new(),
            handoffs_configured: false,
            handoff_config: None,
        };

        let result = builder.validate();
        assert!(result.is_err());
        assert!(matches!(result, Err(PaladinError::ConfigurationError(_))));
    }

    #[test]
    fn test_builder_validation_autosave_with_citadel() {
        let builder = PaladinBuilder {
            llm_port: Arc::new(MockLlmPort),
            data: PaladinData {
                system_prompt: "Test".to_string(),
                ..Default::default()
            },
            config: PaladinConfig::default(),
            garrison: None,
            arsenal_registry: None,
            mcp_servers: Vec::new(),
            citadel_port: Some(Arc::new(MockCitadelPort)),
            autosave_enabled: true,
            state_dir: None,
            herald: None,
            sanctum_port: None,
            embedding_port: None,
            memory_extraction_strategy: MemoryExtractionStrategy::default(),
            auto_generate_prompt_enabled: false,
            agent_description: None,
            manual_prompt_override: false,
            auto_temperature_enabled: false,
            manual_temperature_override: false,
            specialist_agents: Vec::new(),
            handoffs_configured: false,
            handoff_config: None,
        };

        let result = builder.validate();
        assert!(result.is_ok());
    }

    #[test]
    fn test_builder_validation_autosave_with_state_dir() {
        let builder = PaladinBuilder {
            llm_port: Arc::new(MockLlmPort),
            data: PaladinData {
                system_prompt: "Test".to_string(),
                ..Default::default()
            },
            config: PaladinConfig::default(),
            garrison: None,
            arsenal_registry: None,
            mcp_servers: Vec::new(),
            citadel_port: None,
            autosave_enabled: true,
            state_dir: Some("./test".to_string()),
            herald: None,
            sanctum_port: None,
            embedding_port: None,
            memory_extraction_strategy: MemoryExtractionStrategy::default(),
            auto_generate_prompt_enabled: false,
            agent_description: None,
            manual_prompt_override: false,
            auto_temperature_enabled: false,
            manual_temperature_override: false,
            specialist_agents: Vec::new(),
            handoffs_configured: false,
            handoff_config: None,
        };

        let result = builder.validate();
        assert!(result.is_ok());
    }

    #[test]
    fn test_builder_with_sanctum() {
        let sanctum = Arc::new(MockSanctumPort);
        let builder = PaladinBuilder::new(Arc::new(MockLlmPort))
            .system_prompt("Test")
            .with_sanctum(sanctum);

        assert!(builder.sanctum_port.is_some());
    }

    #[test]
    fn test_builder_with_embedding_port() {
        let embedding = Arc::new(MockEmbeddingPort);
        let builder = PaladinBuilder::new(Arc::new(MockLlmPort))
            .system_prompt("Test")
            .with_embedding_port(embedding);

        assert!(builder.embedding_port.is_some());
    }

    #[test]
    fn test_builder_memory_extraction_strategy() {
        let builder = PaladinBuilder::new(Arc::new(MockLlmPort))
            .system_prompt("Test")
            .memory_extraction_strategy(MemoryExtractionStrategy::EveryTurn);

        assert!(matches!(
            builder.memory_extraction_strategy,
            MemoryExtractionStrategy::EveryTurn
        ));
    }

    #[test]
    fn test_builder_validation_sanctum_without_embedding() {
        let builder = PaladinBuilder {
            llm_port: Arc::new(MockLlmPort),
            data: PaladinData {
                system_prompt: "Test".to_string(),
                ..Default::default()
            },
            config: PaladinConfig::default(),
            garrison: None,
            arsenal_registry: None,
            mcp_servers: Vec::new(),
            citadel_port: None,
            autosave_enabled: false,
            state_dir: None,
            herald: None,
            sanctum_port: Some(Arc::new(MockSanctumPort)),
            embedding_port: None,
            memory_extraction_strategy: MemoryExtractionStrategy::default(),
            auto_generate_prompt_enabled: false,
            agent_description: None,
            manual_prompt_override: false,
            auto_temperature_enabled: false,
            manual_temperature_override: false,
            specialist_agents: Vec::new(),
            handoffs_configured: false,
            handoff_config: None,
        };

        let result = builder.validate();
        assert!(result.is_err());
        assert!(matches!(result, Err(PaladinError::ConfigurationError(_))));
    }

    #[test]
    fn test_builder_validation_sanctum_with_embedding() {
        let builder = PaladinBuilder {
            llm_port: Arc::new(MockLlmPort),
            data: PaladinData {
                system_prompt: "Test".to_string(),
                ..Default::default()
            },
            config: PaladinConfig::default(),
            garrison: None,
            arsenal_registry: None,
            mcp_servers: Vec::new(),
            citadel_port: None,
            autosave_enabled: false,
            state_dir: None,
            herald: None,
            sanctum_port: Some(Arc::new(MockSanctumPort)),
            embedding_port: Some(Arc::new(MockEmbeddingPort)),
            memory_extraction_strategy: MemoryExtractionStrategy::default(),
            auto_generate_prompt_enabled: false,
            agent_description: None,
            manual_prompt_override: false,
            auto_temperature_enabled: false,
            manual_temperature_override: false,
            specialist_agents: Vec::new(),
            handoffs_configured: false,
            handoff_config: None,
        };

        let result = builder.validate();
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_builder_restore_from_without_citadel() {
        let builder = PaladinBuilder::new(Arc::new(MockLlmPort));
        let state_id = Uuid::new_v4();

        let result = builder.restore_from(state_id).await;
        assert!(result.is_err());
        assert!(matches!(result, Err(PaladinError::ConfigurationError(_))));
    }

    #[tokio::test]
    async fn test_builder_restore_from_state_not_found() {
        let citadel = Arc::new(MockCitadelPort);
        let builder = PaladinBuilder::new(Arc::new(MockLlmPort)).with_citadel(citadel);
        let state_id = Uuid::new_v4();

        let result = builder.restore_from(state_id).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_builder_restore_from_success() {
        let citadel = Arc::new(MockCitadelPortWithState);
        let builder = PaladinBuilder::new(Arc::new(MockLlmPort)).with_citadel(citadel);
        let state_id = Uuid::parse_str("550e8400-e29b-41d4-a716-446655440000").unwrap();

        let result = builder.restore_from(state_id).await;
        assert!(result.is_ok());

        let restored_builder = result.unwrap();
        assert_eq!(restored_builder.data.system_prompt, "Restored prompt");
        assert_eq!(restored_builder.data.name, "RestoredPaladin");
        assert_eq!(restored_builder.data.model, "gpt-4");
    }

    // Mock for internal tests
    struct MockLlmPort;

    #[async_trait::async_trait]
    impl LlmPort for MockLlmPort {
        async fn generate(
            &self,
            _request: paladin_ports::output::llm_port::LlmRequest,
        ) -> Result<
            paladin_ports::output::llm_port::LlmResponse,
            paladin_ports::output::llm_port::LlmError,
        > {
            unimplemented!()
        }

        async fn generate_stream(
            &self,
            _request: paladin_ports::output::llm_port::LlmRequest,
        ) -> Result<
            Box<
                dyn futures::Stream<
                        Item = Result<
                            paladin_ports::output::llm_port::StreamingResponse,
                            paladin_ports::output::llm_port::LlmError,
                        >,
                    > + Send,
            >,
            paladin_ports::output::llm_port::LlmError,
        > {
            unimplemented!()
        }

        async fn validate_model(
            &self,
            _model: &str,
        ) -> Result<bool, paladin_ports::output::llm_port::LlmError> {
            Ok(true)
        }

        async fn get_available_models(
            &self,
        ) -> Result<Vec<String>, paladin_ports::output::llm_port::LlmError> {
            Ok(vec![])
        }

        fn get_provider_name(&self) -> &'static str {
            "Mock"
        }

        fn get_capabilities(&self) -> paladin_ports::output::llm_port::ProviderCapabilities {
            paladin_ports::output::llm_port::ProviderCapabilities::default()
        }
    }

    // Mock CitadelPort for testing
    struct MockCitadelPort;

    #[async_trait::async_trait]
    impl CitadelPort for MockCitadelPort {
        async fn save_paladin(
            &self,
            _state: &crate::core::platform::container::citadel::PaladinState,
        ) -> Result<(), crate::application::errors::citadel_error::CitadelError> {
            Ok(())
        }

        async fn load_paladin(
            &self,
            _state_id: Uuid,
        ) -> Result<
            Option<crate::core::platform::container::citadel::PaladinState>,
            crate::application::errors::citadel_error::CitadelError,
        > {
            Ok(None)
        }

        async fn save_battalion(
            &self,
            _state: &crate::core::platform::container::citadel::BattalionState,
        ) -> Result<(), crate::application::errors::citadel_error::CitadelError> {
            Ok(())
        }

        async fn load_battalion(
            &self,
            _state_id: Uuid,
        ) -> Result<
            Option<crate::core::platform::container::citadel::BattalionState>,
            crate::application::errors::citadel_error::CitadelError,
        > {
            Ok(None)
        }

        async fn list_saved(
            &self,
        ) -> Result<
            Vec<crate::core::platform::container::citadel::StateSummary>,
            crate::application::errors::citadel_error::CitadelError,
        > {
            Ok(vec![])
        }
    }

    // Mock CitadelPort that returns a state for testing restore
    struct MockCitadelPortWithState;

    #[async_trait::async_trait]
    impl CitadelPort for MockCitadelPortWithState {
        async fn save_paladin(
            &self,
            _state: &crate::core::platform::container::citadel::PaladinState,
        ) -> Result<(), crate::application::errors::citadel_error::CitadelError> {
            Ok(())
        }

        async fn load_paladin(
            &self,
            state_id: Uuid,
        ) -> Result<
            Option<crate::core::platform::container::citadel::PaladinState>,
            crate::application::errors::citadel_error::CitadelError,
        > {
            if state_id == Uuid::parse_str("550e8400-e29b-41d4-a716-446655440000").unwrap() {
                // Create PaladinData
                let data = crate::core::platform::container::citadel::PaladinData {
                    system_prompt: "Restored prompt".to_string(),
                    name: "RestoredPaladin".to_string(),
                    user_name: "User".to_string(),
                    model: "gpt-4".to_string(),
                    temperature: 0.8,
                    max_loops: MaxLoops::Fixed(5),
                    stop_words: vec![],
                    status: crate::core::platform::container::citadel::PaladinStatus::Idle,
                    vision_enabled: false,
                    ..Default::default()
                };

                // Create Paladin (Node<PaladinData>)
                let paladin = Node::new(data, Some("RestoredPaladin".to_string()));

                Ok(Some(
                    crate::core::platform::container::citadel::PaladinState {
                        paladin,
                        garrison: vec![],
                        execution_history: vec![],
                        created_at: chrono::Utc::now(),
                        updated_at: chrono::Utc::now(),
                        schema_version: "1.0.0".to_string(),
                    },
                ))
            } else {
                Ok(None)
            }
        }

        async fn save_battalion(
            &self,
            _state: &crate::core::platform::container::citadel::BattalionState,
        ) -> Result<(), crate::application::errors::citadel_error::CitadelError> {
            Ok(())
        }

        async fn load_battalion(
            &self,
            _state_id: Uuid,
        ) -> Result<
            Option<crate::core::platform::container::citadel::BattalionState>,
            crate::application::errors::citadel_error::CitadelError,
        > {
            Ok(None)
        }

        async fn list_saved(
            &self,
        ) -> Result<
            Vec<crate::core::platform::container::citadel::StateSummary>,
            crate::application::errors::citadel_error::CitadelError,
        > {
            Ok(vec![])
        }
    }

    // Mock SanctumPort for testing
    struct MockSanctumPort;

    #[async_trait::async_trait]
    impl paladin_ports::output::sanctum_port::SanctumPort for MockSanctumPort {
        async fn store(
            &self,
            _entry: crate::core::platform::container::sanctum::SanctumEntry,
        ) -> Result<(), paladin_ports::output::sanctum_port::SanctumError> {
            Ok(())
        }

        async fn store_batch(
            &self,
            _entries: Vec<crate::core::platform::container::sanctum::SanctumEntry>,
        ) -> Result<(), paladin_ports::output::sanctum_port::SanctumError> {
            Ok(())
        }

        async fn search(
            &self,
            _query: paladin_ports::output::sanctum_port::SanctumQuery,
        ) -> Result<
            Vec<paladin_ports::output::sanctum_port::SanctumSearchResult>,
            paladin_ports::output::sanctum_port::SanctumError,
        > {
            Ok(vec![])
        }

        async fn delete(
            &self,
            _id: &str,
        ) -> Result<bool, paladin_ports::output::sanctum_port::SanctumError> {
            Ok(false)
        }

        async fn update(
            &self,
            _entry: crate::core::platform::container::sanctum::SanctumEntry,
        ) -> Result<(), paladin_ports::output::sanctum_port::SanctumError> {
            Ok(())
        }

        async fn count(
            &self,
            _filter: Option<paladin_ports::output::sanctum_port::SanctumFilter>,
        ) -> Result<usize, paladin_ports::output::sanctum_port::SanctumError> {
            Ok(0)
        }
    }

    // Mock EmbeddingPort for testing
    struct MockEmbeddingPort;

    #[async_trait::async_trait]
    impl paladin_ports::output::embedding_port::EmbeddingPort for MockEmbeddingPort {
        async fn embed_text(
            &self,
            _text: &str,
        ) -> Result<
            paladin_ports::output::embedding_port::Embedding,
            paladin_ports::output::embedding_port::EmbeddingError,
        > {
            Ok(paladin_ports::output::embedding_port::Embedding {
                vector: vec![0.0; 1536],
                model: "mock-model".to_string(),
                dimension: 1536,
                token_count: Some(10),
            })
        }

        async fn embed_batch(
            &self,
            texts: &[&str],
        ) -> Result<
            Vec<paladin_ports::output::embedding_port::Embedding>,
            paladin_ports::output::embedding_port::EmbeddingError,
        > {
            Ok(texts
                .iter()
                .map(|_| paladin_ports::output::embedding_port::Embedding {
                    vector: vec![0.0; 1536],
                    model: "mock-model".to_string(),
                    dimension: 1536,
                    token_count: Some(10),
                })
                .collect())
        }

        fn dimension(&self) -> usize {
            1536
        }

        fn model_name(&self) -> &str {
            "mock-model"
        }
    }

    #[tokio::test]
    async fn test_auto_generate_prompt_enabled() {
        // Given: A builder with auto-prompt generation enabled
        let llm_port = Arc::new(MockLlmPort);
        let builder = PaladinBuilder::new(llm_port)
            .auto_generate_prompt(true)
            .agent_description("A code review assistant")
            .name("ReviewBot");

        // Then: The builder should have auto-generation enabled
        assert!(builder.auto_generate_prompt_enabled);
        assert_eq!(
            builder.agent_description,
            Some("A code review assistant".to_string())
        );
    }

    #[tokio::test]
    async fn test_auto_generate_prompt_builder_method() {
        // Given: A builder with auto-prompt disabled
        let llm_port = Arc::new(MockLlmPort);
        let builder = PaladinBuilder::new(llm_port).auto_generate_prompt(false);

        // Then: Auto-generation should be disabled
        assert!(!builder.auto_generate_prompt_enabled);
    }

    #[tokio::test]
    async fn test_agent_description_method() {
        // Given: A builder
        let llm_port = Arc::new(MockLlmPort);
        let builder = PaladinBuilder::new(llm_port).agent_description("Test description");

        // Then: Description should be set
        assert_eq!(
            builder.agent_description,
            Some("Test description".to_string())
        );
    }

    #[tokio::test]
    async fn test_manual_prompt_override() {
        // Given: A builder with auto-generation enabled
        let llm_port = Arc::new(MockLlmPort);
        let builder = PaladinBuilder::new(llm_port)
            .auto_generate_prompt(true)
            .agent_description("Test agent")
            .system_prompt("Manual prompt"); // Manual override

        // Then: Manual override flag should be set
        assert!(builder.manual_prompt_override);
        assert_eq!(builder.data.system_prompt, "Manual prompt");
    }

    #[tokio::test]
    async fn test_regenerate_prompt_method() {
        // Given: A builder
        let llm_port = Arc::new(MockLlmPort);
        let builder = PaladinBuilder::new(llm_port)
            .auto_generate_prompt(true)
            .agent_description("Test")
            .regenerate_prompt(); // Should not panic

        // Then: Builder should still be valid
        assert!(builder.auto_generate_prompt_enabled);
    }

    // Mock ArsenalRegistry for testing
    struct MockArsenalRegistry {
        registered_tools: Arc<tokio::sync::Mutex<Vec<Armament>>>,
    }

    impl MockArsenalRegistry {
        fn new() -> Self {
            Self {
                registered_tools: Arc::new(tokio::sync::Mutex::new(Vec::new())),
            }
        }

        async fn get_registered_tools(&self) -> Vec<Armament> {
            self.registered_tools.lock().await.clone()
        }
    }

    #[async_trait::async_trait]
    impl ArsenalRegistry for MockArsenalRegistry {
        async fn register(&self, armament: Armament) {
            self.registered_tools.lock().await.push(armament);
        }

        async fn unregister(&self, name: &str) -> Option<Armament> {
            let mut tools = self.registered_tools.lock().await;
            tools
                .iter()
                .position(|t| t.name == name)
                .map(|pos| tools.remove(pos))
        }

        async fn get(&self, name: &str) -> Option<Armament> {
            self.registered_tools
                .lock()
                .await
                .iter()
                .find(|t| t.name == name)
                .cloned()
        }
    }

    #[tokio::test]
    async fn test_builder_auto_registers_handoff_tool_when_configured() {
        // Given: A Paladin with specialist agents configured
        let llm_port: Arc<dyn LlmPort> = Arc::new(MockLlmPort);
        let arsenal = Arc::new(MockArsenalRegistry::new());

        let specialist1: Paladin = PaladinBuilder::new(Arc::clone(&llm_port))
            .system_prompt("Rust expert")
            .name("RustExpert")
            .build()
            .await
            .unwrap();

        let specialist2: Paladin = PaladinBuilder::new(Arc::clone(&llm_port))
            .system_prompt("Python expert")
            .name("PythonExpert")
            .build()
            .await
            .unwrap();

        // When: Building a coordinator with handoffs configured
        let _coordinator: Paladin = PaladinBuilder::new(Arc::clone(&llm_port))
            .system_prompt("Coordinator")
            .name("Coordinator")
            .with_arsenal_registry(Arc::clone(&arsenal) as Arc<dyn ArsenalRegistry>)
            .with_handoffs(vec![Arc::new(specialist1), Arc::new(specialist2)])
            .build()
            .await
            .unwrap();

        // Then: Handoff tool should be auto-registered
        let tools = arsenal.get_registered_tools().await;
        assert_eq!(tools.len(), 1);
        assert_eq!(tools[0].name, "handoff_to_specialist");
        assert!(tools[0].description.contains("2 specialist agents"));
    }

    #[tokio::test]
    async fn test_builder_does_not_register_handoff_tool_when_not_configured() {
        // Given: A Paladin without handoffs
        let llm_port: Arc<dyn LlmPort> = Arc::new(MockLlmPort);
        let arsenal = Arc::new(MockArsenalRegistry::new());

        // When: Building without handoffs
        let _paladin: Paladin = PaladinBuilder::new(Arc::clone(&llm_port))
            .system_prompt("Regular agent")
            .name("Agent")
            .with_arsenal_registry(Arc::clone(&arsenal) as Arc<dyn ArsenalRegistry>)
            .build()
            .await
            .unwrap();

        // Then: No tools should be registered
        let tools = arsenal.get_registered_tools().await;
        assert_eq!(tools.len(), 0);
    }

    #[tokio::test]
    async fn test_handoff_tool_schema_includes_all_specialists() {
        // Given: A builder with 3 specialists
        let llm_port: Arc<dyn LlmPort> = Arc::new(MockLlmPort);
        let arsenal = Arc::new(MockArsenalRegistry::new());

        let specialists: Vec<Arc<Paladin>> = vec!["Expert1", "Expert2", "Expert3"]
            .into_iter()
            .map(|name| {
                Arc::new(
                    PaladinBuilder::new(Arc::clone(&llm_port))
                        .system_prompt(format!("{} system prompt", name))
                        .name(name)
                        .build()
                        .now_or_never()
                        .unwrap()
                        .unwrap(),
                )
            })
            .collect();

        // When: Building coordinator
        let _coordinator: Paladin = PaladinBuilder::new(Arc::clone(&llm_port))
            .system_prompt("Coordinator")
            .name("Coordinator")
            .with_arsenal_registry(Arc::clone(&arsenal) as Arc<dyn ArsenalRegistry>)
            .with_handoffs(specialists)
            .build()
            .await
            .unwrap();

        // Then: Tool schema should include all 3 specialist names in enum
        let tools = arsenal.get_registered_tools().await;
        let handoff_tool = &tools[0];

        let specialist_param = handoff_tool.parameters["properties"]["specialist_name"].clone();
        let enum_values = specialist_param["enum"]
            .as_array()
            .unwrap()
            .iter()
            .map(|v| v.as_str().unwrap())
            .collect::<Vec<_>>();

        assert_eq!(enum_values.len(), 3);
        assert!(enum_values.contains(&"Expert1"));
        assert!(enum_values.contains(&"Expert2"));
        assert!(enum_values.contains(&"Expert3"));
    }

    #[tokio::test]
    async fn test_handoff_tool_auto_registration_is_idempotent() {
        // Given: Arsenal with handoff tool already registered
        let llm_port: Arc<dyn LlmPort> = Arc::new(MockLlmPort);
        let arsenal = Arc::new(MockArsenalRegistry::new());

        let specialist: Arc<Paladin> = Arc::new(
            PaladinBuilder::new(Arc::clone(&llm_port))
                .system_prompt("Expert")
                .name("Expert")
                .build()
                .await
                .unwrap(),
        );

        // When: Building multiple coordinators with same specialists
        for _ in 0..3 {
            let _coordinator: Paladin = PaladinBuilder::new(Arc::clone(&llm_port))
                .system_prompt("Coordinator")
                .name("Coordinator")
                .with_arsenal_registry(Arc::clone(&arsenal) as Arc<dyn ArsenalRegistry>)
                .with_handoffs(vec![Arc::clone(&specialist)])
                .build()
                .await
                .unwrap();
        }

        // Then: Only one (or multiple with same name) tool should be registered
        // Note: ArsenalRegistry's register() replaces tools with same name, so we'll have 3 identical ones
        let tools = arsenal.get_registered_tools().await;
        assert_eq!(tools.len(), 3); // Each build() registers one
        assert!(tools.iter().all(|t| t.name == "handoff_to_specialist"));
    }

    #[tokio::test]
    async fn test_handoff_tool_schema_validation() {
        // Given: A builder with specialists
        let llm_port: Arc<dyn LlmPort> = Arc::new(MockLlmPort);
        let arsenal = Arc::new(MockArsenalRegistry::new());

        let specialist: Arc<Paladin> = Arc::new(
            PaladinBuilder::new(Arc::clone(&llm_port))
                .system_prompt("Expert")
                .name("TestExpert")
                .build()
                .await
                .unwrap(),
        );

        // When: Building coordinator
        let _coordinator: Paladin = PaladinBuilder::new(Arc::clone(&llm_port))
            .system_prompt("Coordinator")
            .name("Coordinator")
            .with_arsenal_registry(Arc::clone(&arsenal) as Arc<dyn ArsenalRegistry>)
            .with_handoffs(vec![specialist])
            .build()
            .await
            .unwrap();

        // Then: Tool schema should be valid JSON Schema with correct structure
        let tools = arsenal.get_registered_tools().await;
        let handoff_tool = &tools[0];

        // Validate required fields
        assert!(
            handoff_tool
                .required_params
                .contains(&"specialist_name".to_string())
        );
        assert!(
            handoff_tool
                .required_params
                .contains(&"task_description".to_string())
        );

        // Validate schema structure
        assert_eq!(handoff_tool.parameters["type"], "object");
        assert!(handoff_tool.parameters["properties"].is_object());
        assert!(handoff_tool.parameters["properties"]["specialist_name"].is_object());
        assert!(handoff_tool.parameters["properties"]["task_description"].is_object());

        // Validate parameter types
        assert_eq!(
            handoff_tool.parameters["properties"]["specialist_name"]["type"],
            "string"
        );
        assert_eq!(
            handoff_tool.parameters["properties"]["task_description"]["type"],
            "string"
        );
    }
}