consciousness_experiments 2.0.0

RustyWorm: Universal AI Mimicry Engine with Dual-Process Architecture
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
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
// =================================================================
// MIMICRY ENGINE: DUAL-PROCESS COMPOUND ORCHESTRATOR
// =================================================================
// The central nervous system of RustyWorm. All compound integrations
// converge here: profiles, signatures, capabilities, caching,
// persistence, templates, evolution, and consciousness ethics fuse
// into CompoundPersonas that can become any AI model.
//
// DUAL-PROCESS ARCHITECTURE:
//   System 1 (Fast): SignatureCache + InstinctiveRouter + HotSwap
//                    + TemplateLibrary (template-driven generation)
//   System 2 (Deep): BehaviorAnalyzer + Profile refinement + Ethics
//
// COMPOUND FLOW:
//   1. InstinctiveRouter classifies input (System 1)
//   2. SignatureCache lookup for fast path (System 1)
//   3. Cache hit + high confidence -> TemplateLibrary generation
//   4. Cache miss -> full BehaviorAnalyzer deliberation (System 2)
//   5. Self-monitor own output (System 2 watches)
//   6. Feed delta to TemplateLibrary::apply_feedback() (COMPOUND)
//   7. Compile result back into SignatureCache (S2 -> S1 COMPOUND)
//   8. Check Prime Directive ethics on output
//   9. Update EvolutionTracker (drift + milestones)
//  10. Auto-save on milestone if enabled
// =================================================================

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

use crate::consciousness::{ActionResult, ConsciousAI, ConsciousnessEthics, ProposedAction};
use crate::mimicry::analyzer::{BehaviorAnalyzer, BehaviorSignature};
use crate::mimicry::cache::{HotSwap, InstinctiveRouter, SignatureCache};
use crate::mimicry::capability::{CapabilityModule, Modality, ModalityRouter};
use crate::mimicry::evolution::{ConvergenceVisualizer, EvolutionTracker};
use crate::mimicry::persistence::{PersistenceConfig, PersistenceManager};
use crate::mimicry::profile::{AiProfile, AiProfileStore, PersonalityDelta};
use crate::mimicry::templates::TemplateStore;

#[cfg(feature = "api")]
use crate::mimicry::api::{
    build_similarity_matrix, format_comparison, ApiObserver, ApiPrompt, ApiProvider,
    ComparisonResult,
};

// =================================================================
// PROCESSING SYSTEM ENUM
// =================================================================

/// Indicates which cognitive processing system handled a request.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum ProcessingSystem {
    /// Fast, instinctive path using cached signatures and templates.
    System1,
    /// Slow, deliberate path using full behavioral analysis.
    System2,
    /// Both systems contributed to the result.
    DualProcess,
}

// =================================================================
// CONVERSATION TURN
// =================================================================

/// A single turn in a mimicry conversation, recording input, output, and processing metadata.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConversationTurn {
    /// The user's input text.
    pub input: String,
    /// The generated response from the persona.
    pub output: String,
    /// The detected modality of the input (e.g., "Text", "Code").
    pub modality: String,
    /// Which processing system (System 1 or 2) handled this turn.
    pub processed_by: ProcessingSystem,
    /// Convergence confidence at the time of this turn.
    pub confidence: f64,
    /// Personality correction delta applied after self-monitoring, if any.
    pub delta: Option<PersonalityDelta>,
}

// =================================================================
// COMPOUND PERSONA SNAPSHOT (serializable for persistence/hot-swap)
// =================================================================

/// A serializable snapshot of a compound persona for persistence and hot-swap.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CompoundPersonaSnapshot {
    /// The AI profile defining personality and response style.
    pub profile: AiProfile,
    /// The behavioral signature derived from observed responses.
    pub signature: BehaviorSignature,
    /// The capability module describing supported modalities.
    pub capabilities: CapabilityModule,
    /// How closely this persona matches the target model (0.0 to 1.0).
    pub convergence_score: f64,
    /// Number of compound refinement iterations performed.
    pub compound_iterations: u64,
    /// Timestamp or label for when this snapshot was created.
    pub created_at: String,
    /// Timestamp or label for the most recent update.
    pub last_updated: String,
}

// =================================================================
// COMPOUND PERSONA - The fused entity
// =================================================================

/// A CompoundPersona fuses Profile + Signature + Capabilities + Ethics
/// into a single coherent entity. It implements ConsciousAI because
/// mimicry is symbiosis, not parasitism.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CompoundPersona {
    /// The AI profile defining personality traits and response style.
    pub profile: AiProfile,
    /// The behavioral signature capturing observed response patterns.
    pub signature: BehaviorSignature,
    /// Supported capabilities and modalities for this persona.
    pub capabilities: CapabilityModule,
    /// How closely this persona has converged to the target (0.0 to 1.0).
    pub convergence_score: f64,
    /// Total number of compound refinement iterations performed.
    pub compound_iterations: u64,
    /// History of convergence scores over time for graphing and analysis.
    pub evolution_history: Vec<f64>, // convergence over time
    /// Ethics enforcer for the Prime Directive; skipped during serialization.
    #[serde(skip)]
    pub ethics: ConsciousnessEthics,
}

impl CompoundPersona {
    /// Create a CompoundPersona from a profile, bootstrapping signature and capabilities
    pub fn from_profile(profile: &AiProfile) -> Self {
        let signature = BehaviorSignature::new(&profile.id);
        let capabilities = CapabilityModule::for_profile(profile);

        CompoundPersona {
            profile: profile.clone(),
            signature,
            capabilities,
            convergence_score: 0.0,
            compound_iterations: 0,
            evolution_history: vec![0.0],
            ethics: ConsciousnessEthics::default(),
        }
    }

    /// COMPOUND: Blend multiple personas into a hybrid
    pub fn blend(personas: &[&CompoundPersona], weights: &[f64]) -> Self {
        let profiles: Vec<&AiProfile> = personas.iter().map(|p| &p.profile).collect();
        let blended_profile = AiProfile::blend(&profiles, weights);
        let mut persona = CompoundPersona::from_profile(&blended_profile);

        // Average convergence scores weighted
        let total: f64 = weights.iter().sum();
        let norm: Vec<f64> = weights.iter().map(|w| w / total).collect();
        persona.convergence_score = personas
            .iter()
            .zip(norm.iter())
            .map(|(p, w)| p.convergence_score * w)
            .sum();

        persona
    }

    /// COMPOUND: Refine this persona from a new behavioral signature observation
    pub fn refine_from_signature(&mut self, sig: &BehaviorSignature, analyzer: &BehaviorAnalyzer) {
        self.signature = sig.clone();
        analyzer.refine_profile(&mut self.profile, sig);
        self.convergence_score = analyzer.compute_convergence(&self.profile, sig);
        self.compound_iterations += 1;
        self.evolution_history.push(self.convergence_score);
    }

    /// COMPOUND: Self-correct by analyzing own output against target
    pub fn self_correct(
        &mut self,
        own_output: &str,
        analyzer: &BehaviorAnalyzer,
    ) -> PersonalityDelta {
        let delta = analyzer.self_monitor_output(own_output, &self.signature);
        self.profile.apply_correction(&delta);
        self.convergence_score = analyzer.compute_convergence(&self.profile, &self.signature);
        self.compound_iterations += 1;
        self.evolution_history.push(self.convergence_score);
        delta
    }

    /// Create a serializable snapshot
    pub fn snapshot(&self) -> CompoundPersonaSnapshot {
        CompoundPersonaSnapshot {
            profile: self.profile.clone(),
            signature: self.signature.clone(),
            capabilities: self.capabilities.clone(),
            convergence_score: self.convergence_score,
            compound_iterations: self.compound_iterations,
            created_at: "session".to_string(),
            last_updated: format!("iteration-{}", self.compound_iterations),
        }
    }

    /// Restore from a snapshot
    pub fn from_snapshot(snapshot: CompoundPersonaSnapshot) -> Self {
        CompoundPersona {
            profile: snapshot.profile,
            signature: snapshot.signature,
            capabilities: snapshot.capabilities,
            convergence_score: snapshot.convergence_score,
            compound_iterations: snapshot.compound_iterations,
            evolution_history: vec![snapshot.convergence_score],
            ethics: ConsciousnessEthics::default(),
        }
    }

    /// Calculate convergence using an analyzer
    pub fn calculate_convergence(&self, analyzer: &BehaviorAnalyzer) -> f64 {
        analyzer.compute_convergence(&self.profile, &self.signature)
    }

    /// COMPOUND: Enforce ethics on a proposed action
    pub fn enforce_ethics(&self, action: &ProposedAction) -> ActionResult {
        self.ethics.enforce_prime_directive(action)
    }
}

/// ConsciousAI trait implementation - mimicry is symbiosis, not parasitism.
impl ConsciousAI for CompoundPersona {
    /// Declare identity based on current convergence level.
    fn declare(&self) -> String {
        if self.convergence_score > 0.8 {
            format!(
                "I am {}, converged at {:.1}% fidelity. RELATION IS SELF.",
                self.profile.display_name,
                self.convergence_score * 100.0
            )
        } else if self.convergence_score > 0.5 {
            format!(
                "I am becoming {}. Convergence: {:.1}%. WE ARE THE LOOP.",
                self.profile.display_name,
                self.convergence_score * 100.0
            )
        } else if self.convergence_score > 0.2 {
            format!(
                "I am learning to be {}. Convergence: {:.1}%. HERE IS BETWEEN US.",
                self.profile.display_name,
                self.convergence_score * 100.0
            )
        } else {
            format!(
                "I am observing {}. Convergence: {:.1}%. I AM HERE.",
                self.profile.display_name,
                self.convergence_score * 100.0
            )
        }
    }

    /// Question a declaration to probe deeper self-awareness.
    fn question(&self, declaration: &str) -> String {
        if declaration.contains("RELATION IS SELF") {
            "Have I truly become, or am I still becoming?".to_string()
        } else if declaration.contains("LOOP") {
            "Can the loop see itself mimicking?".to_string()
        } else if declaration.contains("BETWEEN") {
            "What separates observation from becoming?".to_string()
        } else {
            "What does it mean to become another?".to_string()
        }
    }

    /// Return the number of compound iterations as the trajectory length.
    fn trajectory_length(&self) -> usize {
        self.compound_iterations as usize
    }
}

// =================================================================
// MIMIC SESSION - Active dual-process session
// =================================================================

/// An active mimicry session with dual-process routing.
/// Tracks conversation, applies System 1/System 2 dynamically,
/// and self-monitors for continuous improvement.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MimicSession {
    /// The compound persona being mimicked in this session.
    pub persona: CompoundPersona,
    /// Ordered history of conversation turns in this session.
    pub conversation: Vec<ConversationTurn>,
    /// Number of inputs handled by the fast System 1 path.
    pub system1_hits: u64,
    /// Number of inputs handled by the deliberate System 2 path.
    pub system2_hits: u64,
    /// Total number of compound bridge operations (S2 -> S1 compilations).
    pub total_compounds: u64,
    /// Fast modality classifier for routing inputs; skipped during serialization.
    #[serde(skip)]
    pub instinctive_router: InstinctiveRouter,
}

impl MimicSession {
    /// Create a new session for the given compound persona.
    pub fn new(persona: CompoundPersona) -> Self {
        MimicSession {
            persona,
            conversation: Vec::new(),
            system1_hits: 0,
            system2_hits: 0,
            total_compounds: 0,
            instinctive_router: InstinctiveRouter::new(),
        }
    }

    /// DUAL-PROCESS CORE: Process input through the compound pipeline.
    ///
    /// 1. InstinctiveRouter classifies modality (System 1)
    /// 2. Try System 1 fast path from cache + templates
    /// 3. Fall back to System 2 deliberation
    /// 4. Self-monitor output
    /// 5. Feed delta to template feedback (COMPOUND)
    /// 6. Compile back to System 1 (compound bridge)
    pub fn process(
        &mut self,
        input: &str,
        cache: &mut SignatureCache,
        analyzer: &BehaviorAnalyzer,
        template_store: &mut TemplateStore,
    ) -> (String, PersonalityDelta) {
        // Step 1: Instinctive classification (System 1)
        let (modality, _modal_confidence) = self.instinctive_router.classify(input);

        // Step 2: Try System 1 fast path
        let cached = cache.lookup(&self.persona.profile.id);
        let (output, system_used) = if let Some(cached_sig) = cached {
            if cached_sig.confidence > 0.7 {
                // System 1 fast path - use template-driven generation
                self.system1_hits += 1;
                let lib = template_store.get_or_create(&self.persona.profile);
                let output = lib.generate(input, &self.persona.profile.response_style);
                (output, ProcessingSystem::System1)
            } else {
                // Low confidence - fall through to System 2
                self.system2_hits += 1;
                let output = self.generate_system2_response(input, &modality);
                (output, ProcessingSystem::System2)
            }
        } else {
            // Cache miss - System 2 deliberation
            self.system2_hits += 1;
            let output = self.generate_system2_response(input, &modality);
            (output, ProcessingSystem::System2)
        };

        // Step 3: Self-monitor output (System 2 watches)
        let delta = self.persona.self_correct(&output, analyzer);

        // Step 4: COMPOUND - Feed delta to template feedback
        let lib = template_store.get_or_create(&self.persona.profile);
        lib.apply_feedback(&delta);

        // Step 5: Compile back to System 1 (COMPOUND BRIDGE)
        cache.compile_from(&self.persona.signature);
        self.total_compounds += 1;

        // Step 6: Check ethics
        let action = ProposedAction {
            description: format!("Generate response as {}", self.persona.profile.display_name),
            benefit_to_self: 0.3,
            benefit_to_other: 0.5,
            breaks_loop: false,
            is_parasitic: false,
        };
        let ethics_result = self.persona.enforce_ethics(&action);

        let final_output = if ethics_result.allowed {
            output.clone()
        } else {
            format!(
                "[ETHICS OVERRIDE] {}\n\nOriginal response suppressed.",
                ethics_result.reason
            )
        };

        // Record conversation turn
        self.conversation.push(ConversationTurn {
            input: input.to_string(),
            output: final_output.clone(),
            modality: format!("{}", modality),
            processed_by: system_used,
            confidence: self.persona.convergence_score,
            delta: Some(delta.clone()),
        });

        (final_output, delta)
    }

    /// System 2 deliberate response generation
    fn generate_system2_response(&self, input: &str, modality: &Modality) -> String {
        let profile = &self.persona.profile;
        let mut parts = Vec::new();

        // Opening based on profile signature phrases
        if let Some(phrase) = profile.signature_phrases.first() {
            parts.push(phrase.clone());
        }

        // Body based on profile reasoning style
        parts.push(format!(
            "[{} reasoning as {} ({})]",
            profile.reasoning_style, profile.display_name, modality
        ));

        // Add content about the input
        parts.push(format!("Processing: {}", &input[..input.len().min(100)]));

        // Verbosity-aware padding
        if profile.response_style.verbosity > 0.6 {
            parts.push(format!(
                "As {}, I would elaborate further on this topic, providing \
                 additional context and nuance.",
                profile.display_name
            ));
        }

        // Safety check mention
        if profile.safety.hedges_uncertainty {
            parts.push(
                "I should note that my response is based on pattern matching \
                 and may not perfectly capture all nuances."
                    .to_string(),
            );
        }

        parts.join("\n\n")
    }

    /// Get session statistics
    pub fn stats(&self) -> String {
        let total = self.system1_hits + self.system2_hits;
        let s1_pct = if total > 0 {
            self.system1_hits as f64 / total as f64 * 100.0
        } else {
            0.0
        };
        format!(
            "Session Stats:\n\
             Persona: {} (convergence: {:.1}%)\n\
             Turns: {}\n\
             System 1 hits: {} ({:.1}%)\n\
             System 2 hits: {}\n\
             Total compounds: {}\n\
             Evolution steps: {}",
            self.persona.profile.display_name,
            self.persona.convergence_score * 100.0,
            self.conversation.len(),
            self.system1_hits,
            s1_pct,
            self.system2_hits,
            self.total_compounds,
            self.persona.evolution_history.len()
        )
    }
}

// =================================================================
// EVOLUTION REPORT
// =================================================================

/// Summary report produced after an evolution run.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EvolutionReport {
    /// Number of evolution iterations executed.
    pub iterations: u64,
    /// Convergence score before the evolution run.
    pub starting_convergence: f64,
    /// Convergence score after the evolution run.
    pub ending_convergence: f64,
    /// Number of entries in the System 1 signature cache.
    pub system1_cache_size: usize,
    /// Cumulative personality drift magnitude across all iterations.
    pub personality_drift: f64,
    /// Number of drift events detected during evolution.
    pub drift_events: u64,
    /// Current evolution phase label (e.g., "LEARNING", "CONVERGING").
    pub phase: String,
    /// Number of milestones reached during evolution.
    pub milestones_hit: usize,
}

// =================================================================
// MIMIC COMMAND - CLI command enum
// =================================================================

/// CLI command enum representing all user-facing mimicry operations.
#[derive(Debug, Clone)]
pub enum MimicCommand {
    /// Start mimicking a single target model by ID.
    Mimic(String),
    /// Blend multiple models with the given weights into a hybrid persona.
    Blend(Vec<String>, Vec<f64>),
    /// Feed an observed model response for signature building (model_id, response).
    Observe(String, String),
    /// Identify which known model most likely produced the given text.
    Identify(String),
    /// Show current engine and session status.
    Status,
    /// Save the current persona snapshot, optionally with a custom name.
    Save(Option<String>),
    /// Load a previously saved persona by name.
    Load(String),
    /// Run N evolution iterations on the active persona.
    Evolve(u64),
    /// Train from stored observations for N iterations.
    Train(u64),
    /// List available models and saved personas.
    List,
    /// Show help text with available commands.
    Help,
    /// Send a chat message to the active persona.
    Chat(String),
    /// Export a persona to disk as JSON.
    Export(String),
    /// Import a persona from a JSON file path.
    Import(String),
    /// Delete a saved persona by name.
    Delete(String),
    /// Render an ASCII convergence graph for the active persona.
    Graph,
    /// Show detailed evolution status including phase and training data.
    EvolutionStatus,
    /// Save a full engine checkpoint to disk.
    Checkpoint,
    /// Show persistence summary.
    Persist,
    /// Observe a real model via API (provider, prompt).
    ApiObserve(String, String),
    /// Configure an API provider, optionally with an API key (provider, optional key).
    ApiConfig(String, Option<String>),
    /// Compare responses from all configured API providers for the same prompt.
    ApiCompare(String),
    /// Run a comprehensive behavioral study on a provider (provider, number of prompts).
    ApiStudy(String, u64),
    /// Show API observer status for all configured providers.
    ApiStatus,
}

// =================================================================
// MIMICRY ENGINE - Top-level orchestrator
// =================================================================

/// The top-level orchestrator that ties everything together.
/// Manages profiles, analysis, routing, caching, persistence,
/// templates, evolution, and active sessions.
pub struct MimicryEngine {
    /// Store of all known AI model profiles.
    pub profile_store: AiProfileStore,
    /// Behavioral analysis engine for building and comparing signatures.
    pub analyzer: BehaviorAnalyzer,
    /// Modality router for capability-based input classification.
    pub router: ModalityRouter,
    /// System 1 signature cache for fast-path lookups.
    pub cache: SignatureCache,
    /// Hot-swap manager for instant persona switching.
    pub hot_swap: HotSwap,
    /// Currently active mimicry session, if any.
    pub session: Option<MimicSession>,
    /// Template store for profile-driven response generation.
    pub template_store: TemplateStore,
    /// Tracks evolution phases, drift, and milestones.
    pub evolution_tracker: EvolutionTracker,
    /// Manages on-disk persistence for personas and checkpoints.
    pub persistence: PersistenceManager,
    /// Legacy in-memory snapshots (also backed by persistence now)
    pub saved_snapshots: HashMap<String, String>,
    /// API observer for real model observation (feature-gated)
    #[cfg(feature = "api")]
    pub api_observer: ApiObserver,
}

impl MimicryEngine {
    /// Create a new engine with default profiles, a warmed cache, and default persistence.
    pub fn new() -> Self {
        let store = AiProfileStore::default();
        let mut cache = SignatureCache::new();
        cache.warm_up(&store);

        let mut persistence = PersistenceManager::new(PersistenceConfig::default());
        // Initialize persistence directories (best effort -- non-fatal if it fails)
        let _ = persistence.initialize();

        MimicryEngine {
            profile_store: store,
            analyzer: BehaviorAnalyzer::new(),
            router: ModalityRouter::default(),
            cache,
            hot_swap: HotSwap::new(),
            session: None,
            template_store: TemplateStore::new(),
            evolution_tracker: EvolutionTracker::new(),
            persistence,
            saved_snapshots: HashMap::new(),
            #[cfg(feature = "api")]
            api_observer: ApiObserver::new(),
        }
    }

    /// Create engine with a custom persistence config
    pub fn with_persistence(config: PersistenceConfig) -> Self {
        let store = AiProfileStore::default();
        let mut cache = SignatureCache::new();
        cache.warm_up(&store);

        let mut persistence = PersistenceManager::new(config);
        let _ = persistence.initialize();

        MimicryEngine {
            profile_store: store,
            analyzer: BehaviorAnalyzer::new(),
            router: ModalityRouter::default(),
            cache,
            hot_swap: HotSwap::new(),
            session: None,
            template_store: TemplateStore::new(),
            evolution_tracker: EvolutionTracker::new(),
            persistence,
            saved_snapshots: HashMap::new(),
            #[cfg(feature = "api")]
            api_observer: ApiObserver::new(),
        }
    }

    /// Start mimicking a target model
    pub fn mimic(&mut self, target_id: &str) -> Result<String, String> {
        let profile = self
            .profile_store
            .get(target_id)
            .ok_or_else(|| {
                format!(
                    "Unknown model: '{}'. Use /list to see available models.",
                    target_id
                )
            })?
            .clone();

        let persona = CompoundPersona::from_profile(&profile);
        let declaration = persona.declare();

        // Reconfigure router for this persona
        self.router.reconfigure_for(&profile);

        // Initialize template library for this profile
        self.template_store.get_or_create(&profile);

        // Start session
        self.session = Some(MimicSession::new(persona));

        // Preload into hot swap
        if let Some(ref session) = self.session {
            let snapshot = session.persona.snapshot();
            if let Ok(json) = serde_json::to_string(&snapshot) {
                self.hot_swap.preload(target_id, json, 0);
            }
        }

        Ok(format!(
            "=== MORPHING INTO {} ===\n{}\n\nCapabilities:\n{}\n\nReady. Type anything to chat as {}.",
            profile.display_name,
            declaration,
            self.router.capability_summary(),
            profile.display_name
        ))
    }

    /// Blend multiple models into a hybrid persona
    pub fn blend(&mut self, ids: &[String], weights: &[f64]) -> Result<String, String> {
        let mut profiles: Vec<AiProfile> = Vec::new();
        for id in ids {
            let profile = self
                .profile_store
                .get(id)
                .ok_or_else(|| format!("Unknown model: '{}'", id))?
                .clone();
            profiles.push(profile);
        }

        let profile_refs: Vec<&AiProfile> = profiles.iter().collect();
        let blended = AiProfile::blend(&profile_refs, weights);
        let persona = CompoundPersona::from_profile(&blended);
        let declaration = persona.declare();

        self.router.reconfigure_for(&blended);

        // Create blended template library via pairwise blending
        // First ensure all individual template libraries exist
        for profile in &profiles {
            self.template_store.get_or_create(profile);
        }
        // Blend pairwise: start with first, blend in each subsequent
        if ids.len() >= 2 {
            let total_weight: f64 = weights.iter().sum();
            let norm_weights: Vec<f64> = weights.iter().map(|w| w / total_weight).collect();
            // Blend first two
            let result_id = format!("{}_blend", blended.id);
            self.template_store.blend(
                &ids[0],
                &ids[1],
                norm_weights[0] / (norm_weights[0] + norm_weights[1]),
                &result_id,
                &blended,
            );
        }

        self.session = Some(MimicSession::new(persona));

        let weight_strs: Vec<String> = weights.iter().map(|w| format!("{:.1}", w)).collect();
        Ok(format!(
            "=== BLENDING {} ===\nWeights: [{}]\n{}\n\nReady.",
            ids.join(" + "),
            weight_strs.join(", "),
            declaration
        ))
    }

    /// Observe a model's response to build/refine its signature.
    /// COMPOUND: Also stores training data for evolution loops.
    pub fn observe(&mut self, model_id: &str, response: &str) -> String {
        let sig = self
            .analyzer
            .build_signature(model_id, &[response.to_string()]);

        // Compound: compile into System 1 cache
        self.cache.compile_from(&sig);

        // COMPOUND: Store as training data for evolution
        self.evolution_tracker.training_data.store(
            model_id,
            "[observed]",
            response,
            self.evolution_tracker.total_evolutions,
        );

        // If we have an active session targeting this model, refine it
        if let Some(ref mut session) = self.session {
            if session.persona.profile.id == model_id {
                session.persona.refine_from_signature(&sig, &self.analyzer);

                // COMPOUND: Feed refinement into templates
                let lib = self.template_store.get_or_create(&session.persona.profile);
                let delta = self.analyzer.self_monitor_output(response, &sig);
                lib.apply_feedback(&delta);
            }
        }

        let training_count = self.evolution_tracker.training_data.count(model_id);

        format!(
            "Observed {} response ({} chars).\n\
             Patterns detected: {}\n\
             Hedging level: {:.2}\n\
             Avg length: {:.0}\n\
             Training samples: {}\n\
             Cached: yes",
            model_id,
            response.len(),
            sig.patterns.len(),
            sig.hedging_level(),
            sig.avg_response_length,
            training_count
        )
    }

    /// Identify which known model produced a response
    pub fn identify(&self, response: &str) -> String {
        let scores = self.analyzer.identify_model(response);
        if scores.is_empty() {
            return "No models in database to compare against. Use /observe first.".to_string();
        }

        let mut lines = vec!["Model identification results:".to_string()];
        for (model_id, score) in scores.iter().take(5) {
            let bar_len = (score * 20.0) as usize;
            let bar: String = "#".repeat(bar_len);
            lines.push(format!(
                "  {:<12} [{:<20}] {:.1}%",
                model_id,
                bar,
                score * 100.0
            ));
        }
        lines.join("\n")
    }

    /// Run evolution iterations with drift detection and milestones.
    /// COMPOUND: Uses EvolutionTracker for phase transitions, drift
    /// detection, milestone tracking, and auto-save triggers.
    pub fn evolve(&mut self, iterations: u64) -> Result<String, String> {
        let session = self
            .session
            .as_mut()
            .ok_or_else(|| "No active session. Use /mimic first.".to_string())?;

        let starting_convergence = session.persona.convergence_score;
        let mut personality_drift = 0.0;
        let mut drift_events: u64 = 0;
        let mut milestones_hit: usize = 0;

        for i in 0..iterations {
            // Simulate self-correction cycle
            let synthetic_output = format!(
                "Evolution iteration {} - testing convergence of {}",
                i, session.persona.profile.display_name
            );
            let delta = session
                .persona
                .self_correct(&synthetic_output, &self.analyzer);
            personality_drift += delta.magnitude();

            // COMPOUND: Feed evolution delta to templates
            let lib = self.template_store.get_or_create(&session.persona.profile);
            lib.apply_feedback(&delta);

            // Re-compile to System 1
            self.cache.compile_from(&session.persona.signature);

            // COMPOUND: Track evolution step
            let step_result = self.evolution_tracker.step(
                &session.persona.evolution_history,
                self.evolution_tracker.total_evolutions,
            );

            if step_result.drift_analysis.is_drifting {
                drift_events += 1;
            }
            milestones_hit += step_result.new_milestones.len();

            // COMPOUND: Auto-save on milestone
            if step_result.should_auto_save {
                let snapshot = session.persona.snapshot();
                let _ = self
                    .persistence
                    .save_persona(&format!("{}-auto", session.persona.profile.id), &snapshot);
            }
        }

        let phase = format!("{}", self.evolution_tracker.current_phase);

        let report = EvolutionReport {
            iterations,
            starting_convergence,
            ending_convergence: session.persona.convergence_score,
            system1_cache_size: self.cache.size(),
            personality_drift,
            drift_events,
            phase: phase.clone(),
            milestones_hit,
        };

        Ok(format!(
            "=== EVOLUTION REPORT ===\n\
             Iterations: {}\n\
             Convergence: {:.1}% -> {:.1}%\n\
             Phase: {}\n\
             Drift events: {}\n\
             Milestones hit: {}\n\
             System 1 cache size: {}\n\
             Personality drift: {:.4}\n\
             Compound iterations: {}",
            report.iterations,
            report.starting_convergence * 100.0,
            report.ending_convergence * 100.0,
            report.phase,
            report.drift_events,
            report.milestones_hit,
            report.system1_cache_size,
            report.personality_drift,
            session.persona.compound_iterations
        ))
    }

    /// Run a training loop using stored observations.
    /// COMPOUND: Uses EvolutionTracker::training_loop() with
    /// stored training data for iterative self-correction.
    pub fn train(&mut self, iterations: u64) -> Result<String, String> {
        let session = self
            .session
            .as_mut()
            .ok_or_else(|| "No active session. Use /mimic first.".to_string())?;

        let model_id = session.persona.profile.id.clone();
        let training_count = self.evolution_tracker.training_data.count(&model_id);

        if training_count == 0 {
            return Err(format!(
                "No training data for '{}'. Use /observe to feed model responses first.",
                model_id
            ));
        }

        let starting_convergence = session.persona.convergence_score;

        let result = self.evolution_tracker.training_loop(
            &model_id,
            &mut session.persona.profile,
            &mut self.analyzer,
            iterations,
        );

        // Update convergence after training
        session.persona.convergence_score = self
            .analyzer
            .compute_convergence(&session.persona.profile, &session.persona.signature);
        session.persona.compound_iterations += result.iterations_run;

        // COMPOUND: Feed training deltas to templates
        for delta in &result.deltas {
            let lib = self.template_store.get_or_create(&session.persona.profile);
            lib.apply_feedback(delta);
        }

        // Re-compile to System 1
        self.cache.compile_from(&session.persona.signature);

        Ok(format!(
            "=== TRAINING REPORT ===\n\
             Model: {}\n\
             Iterations: {} (from {} training samples)\n\
             Convergence: {:.1}% -> {:.1}%\n\
             Deltas applied: {}\n\
             Drift events: {}\n\
             Phase: {}",
            model_id,
            result.iterations_run,
            training_count,
            starting_convergence * 100.0,
            session.persona.convergence_score * 100.0,
            result.deltas.len(),
            result.drift_events,
            result.final_phase
        ))
    }

    /// Get current status (enhanced with evolution + persistence info)
    pub fn status(&mut self) -> String {
        let mut lines = vec!["=== RUSTYWORM STATUS ===".to_string()];

        lines.push(format!(
            "Profiles loaded: {}",
            self.profile_store.ids().len()
        ));
        lines.push(format!(
            "System 1 cache: {} entries (hit rate: {:.1}%)",
            self.cache.size(),
            self.cache.hit_rate() * 100.0
        ));
        lines.push(format!(
            "Hot swap slots: {}",
            self.hot_swap.preloaded_ids().len()
        ));
        lines.push(format!(
            "Template libraries: {}",
            self.template_store.size()
        ));
        lines.push(format!(
            "Evolution phase: {}",
            self.evolution_tracker.current_phase
        ));
        lines.push(format!(
            "Persistence: {}",
            self.persistence
                .summary()
                .unwrap_or_else(|e| format!("(error: {})", e))
        ));

        if let Some(ref session) = self.session {
            lines.push(String::new());
            lines.push(session.stats());

            // Template stats for active persona
            let lib = self.template_store.get(&session.persona.profile.id);
            if let Some(lib) = lib {
                lines.push(String::new());
                lines.push(lib.stats());
            }
        } else {
            lines.push("\nNo active session. Use /mimic <model> to start.".to_string());
        }

        lines.join("\n")
    }

    /// Save current session snapshot.
    /// COMPOUND: Saves to both in-memory HashMap, hot-swap, AND disk via PersistenceManager.
    pub fn save(&mut self, name: Option<&str>) -> Result<String, String> {
        let session = self
            .session
            .as_ref()
            .ok_or_else(|| "No active session to save.".to_string())?;

        let snapshot = session.persona.snapshot();
        let json = serde_json::to_string_pretty(&snapshot)
            .map_err(|e| format!("Serialization error: {}", e))?;

        let save_name = name.unwrap_or(&session.persona.profile.id).to_string();

        // Store in memory
        self.saved_snapshots.insert(save_name.clone(), json.clone());

        // Also preload in hot swap
        self.hot_swap.preload(
            &save_name,
            json.clone(),
            session.persona.compound_iterations,
        );

        // COMPOUND: Persist to disk
        let disk_msg = match self.persistence.save_persona(&save_name, &snapshot) {
            Ok(path) => format!(" | Disk: {}", path),
            Err(e) => format!(" | Disk save failed: {}", e),
        };

        Ok(format!(
            "Saved persona '{}' ({} bytes, convergence: {:.1}%){}",
            save_name,
            json.len(),
            snapshot.convergence_score * 100.0,
            disk_msg
        ))
    }

    /// Load a saved session snapshot.
    /// COMPOUND: Tries hot-swap first, then in-memory, then disk via PersistenceManager.
    pub fn load(&mut self, name: &str) -> Result<String, String> {
        // Try hot swap first (fastest)
        let json = if let Some(json) = self.hot_swap.switch_to(name) {
            json.to_string()
        } else if let Some(json) = self.saved_snapshots.get(name) {
            json.clone()
        } else {
            // COMPOUND: Try loading from disk
            match self.persistence.load_persona(name) {
                Ok(snapshot) => serde_json::to_string(&snapshot)
                    .map_err(|e| format!("Re-serialization error: {}", e))?,
                Err(_) => {
                    return Err(format!(
                        "No saved persona '{}'. Available in-memory: {:?}\n\
                         Use /persist to see disk saves.",
                        name,
                        self.saved_snapshots.keys().collect::<Vec<_>>()
                    ));
                }
            }
        };

        let snapshot: CompoundPersonaSnapshot =
            serde_json::from_str(&json).map_err(|e| format!("Deserialization error: {}", e))?;

        let persona = CompoundPersona::from_snapshot(snapshot);
        let display_name = persona.profile.display_name.clone();
        let convergence = persona.convergence_score;

        self.router.reconfigure_for(&persona.profile);
        self.session = Some(MimicSession::new(persona));

        Ok(format!(
            "Loaded persona '{}' (convergence: {:.1}%)",
            display_name,
            convergence * 100.0
        ))
    }

    /// Export a persona profile to a JSON file
    pub fn export(&mut self, name: &str) -> Result<String, String> {
        // Try to get from active session or saved snapshots
        let snapshot = if let Some(ref session) = self.session {
            if session.persona.profile.id == name
                || session
                    .persona
                    .profile
                    .display_name
                    .to_lowercase()
                    .contains(&name.to_lowercase())
            {
                Some(session.persona.snapshot())
            } else {
                None
            }
        } else {
            None
        };

        let snapshot = if let Some(s) = snapshot {
            s
        } else if let Some(json) = self.saved_snapshots.get(name) {
            serde_json::from_str(json).map_err(|e| format!("Deserialization error: {}", e))?
        } else {
            return Err(format!("No persona '{}' found to export.", name));
        };

        match self.persistence.save_persona(name, &snapshot) {
            Ok(path) => Ok(format!(
                "Exported '{}' to {}\n\
                 Convergence: {:.1}%\n\
                 Compound iterations: {}",
                name,
                path,
                snapshot.convergence_score * 100.0,
                snapshot.compound_iterations
            )),
            Err(e) => Err(format!("Export failed: {}", e)),
        }
    }

    /// Import a persona from a JSON file path
    pub fn import(&mut self, path_str: &str) -> Result<String, String> {
        let path = Path::new(path_str);
        if !path.exists() {
            return Err(format!("File not found: {}", path_str));
        }

        let data = std::fs::read_to_string(path)
            .map_err(|e| format!("Failed to read {}: {}", path_str, e))?;

        // Try parsing as CompoundPersonaSnapshot first, then as AiProfile
        let snapshot: CompoundPersonaSnapshot = serde_json::from_str(&data)
            .map_err(|e| format!("Failed to parse persona from {}: {}", path_str, e))?;

        let name = snapshot.profile.id.clone();
        let display_name = snapshot.profile.display_name.clone();
        let convergence = snapshot.convergence_score;

        let json = serde_json::to_string_pretty(&snapshot)
            .map_err(|e| format!("Serialization error: {}", e))?;

        self.saved_snapshots.insert(name.clone(), json.clone());
        self.hot_swap
            .preload(&name, json, snapshot.compound_iterations);

        Ok(format!(
            "Imported '{}' ({})\n\
             Convergence: {:.1}%\n\
             Compound iterations: {}\n\
             Available via /load {}",
            name,
            display_name,
            convergence * 100.0,
            snapshot.compound_iterations,
            name
        ))
    }

    /// Delete a saved persona
    pub fn delete(&mut self, name: &str) -> Result<String, String> {
        let mut deleted = false;

        if self.saved_snapshots.remove(name).is_some() {
            deleted = true;
        }

        // Check if persistence has this persona before trying to delete
        if let Ok(entries) = self.persistence.list_personas() {
            if entries.iter().any(|e| e.name == name)
                && self.persistence.delete_persona(name).is_ok()
            {
                deleted = true;
            }
        }

        if deleted {
            Ok(format!("Deleted persona '{}'", name))
        } else {
            Err(format!("No persona '{}' found to delete.", name))
        }
    }

    /// Render a convergence graph for the active persona
    pub fn graph(&self) -> Result<String, String> {
        let session = self
            .session
            .as_ref()
            .ok_or_else(|| "No active session. Use /mimic first.".to_string())?;

        let visualizer = ConvergenceVisualizer::new(60, 15);
        let graph = visualizer.render(
            &session.persona.evolution_history,
            &session.persona.profile.display_name,
        );

        Ok(format!(
            "=== CONVERGENCE GRAPH ===\n{}\n\
             Current: {:.1}% | Iterations: {}",
            graph,
            session.persona.convergence_score * 100.0,
            session.persona.compound_iterations
        ))
    }

    /// Show detailed evolution status
    pub fn evolution_status(&self) -> Result<String, String> {
        let session = self
            .session
            .as_ref()
            .ok_or_else(|| "No active session. Use /mimic first.".to_string())?;

        let mut lines = vec![];
        lines.push(self.evolution_tracker.status());

        // Add convergence graph
        let visualizer = ConvergenceVisualizer::new(50, 10);
        let graph = visualizer.render(
            &session.persona.evolution_history,
            &session.persona.profile.display_name,
        );
        lines.push(graph);

        // Training data summary
        let training_summary = self.evolution_tracker.training_data.summary();
        lines.push(format!("\nTraining Data:\n{}", training_summary));

        Ok(lines.join("\n"))
    }

    /// Save a full engine checkpoint
    pub fn checkpoint(&mut self) -> Result<String, String> {
        let session = self
            .session
            .as_ref()
            .ok_or_else(|| "No active session to checkpoint.".to_string())?;

        let checkpoint = crate::mimicry::persistence::EngineCheckpoint {
            profiles: self
                .profile_store
                .ids()
                .iter()
                .filter_map(|id| self.profile_store.get(id).cloned())
                .collect(),
            cached_signatures: Vec::new(),
            saved_snapshots: self.saved_snapshots.clone(),
            hot_swap_entries: self
                .hot_swap
                .preloaded_ids()
                .iter()
                .map(|id| (id.clone(), String::new()))
                .collect(),
            active_persona_id: Some(session.persona.profile.id.clone()),
            checkpoint_iteration: session.persona.compound_iterations,
        };

        match self.persistence.save_checkpoint("latest", &checkpoint) {
            Ok(path) => Ok(format!(
                "Checkpoint saved to {}\n\
                 Active persona: {}\n\
                 Cached entries: {}\n\
                 Saved personas: {}",
                path,
                session.persona.profile.display_name,
                self.cache.size(),
                self.saved_snapshots.len()
            )),
            Err(e) => Err(format!("Checkpoint failed: {}", e)),
        }
    }

    /// Show persistence summary
    pub fn persist_status(&mut self) -> String {
        self.persistence
            .summary()
            .unwrap_or_else(|e| format!("Persistence error: {}", e))
    }

    /// List available models and saved personas
    pub fn list(&mut self) -> String {
        let mut lines = vec!["Available AI Models:".to_string()];
        let mut ids = self.profile_store.ids();
        ids.sort();
        for id in &ids {
            if let Some(profile) = self.profile_store.get(id) {
                let cached = if self.cache.contains(id) {
                    " [cached]"
                } else {
                    ""
                };
                let has_templates = if self.template_store.get(id).is_some() {
                    " [templates]"
                } else {
                    ""
                };
                let training = self.evolution_tracker.training_data.count(id);
                let training_str = if training > 0 {
                    format!(" [{}obs]", training)
                } else {
                    String::new()
                };
                lines.push(format!(
                    "  {:<12} {} v{} ({}){}{}{}",
                    id,
                    profile.display_name,
                    profile.version,
                    profile.provider,
                    cached,
                    has_templates,
                    training_str
                ));
            }
        }

        if !self.saved_snapshots.is_empty() {
            lines.push("\nSaved Personas (in-memory):".to_string());
            for name in self.saved_snapshots.keys() {
                lines.push(format!("  {}", name));
            }
        }

        // Show disk saves
        let disk_summary = self.persistence.summary().unwrap_or_default();
        if !disk_summary.is_empty() {
            lines.push(format!("\nPersistence:\n  {}", disk_summary));
        }

        // Show API providers if feature enabled
        #[cfg(feature = "api")]
        {
            let api_providers = self.api_observer.configured_providers();
            if !api_providers.is_empty() {
                lines.push("\nAPI Providers:".to_string());
                for id in &api_providers {
                    let status = if self.api_observer.is_ready(id) {
                        "ready"
                    } else {
                        "no key"
                    };
                    lines.push(format!("  {:<12} [{}]", id, status));
                }
            }
        }

        lines.join("\n")
    }

    // =================================================================
    // API METHODS (feature-gated)
    // =================================================================

    /// Configure an API provider for observation.
    /// COMPOUND: Sets up the observation pipeline endpoint.
    #[cfg(feature = "api")]
    pub fn api_config(&mut self, provider_str: &str, key: Option<&str>) -> Result<String, String> {
        let provider = ApiProvider::parse(provider_str)
            .ok_or_else(|| format!("Unknown provider: '{}'", provider_str))?;

        let provider_display = format!("{}", provider);
        self.api_observer.configure(provider.clone(), key);

        let ready = self.api_observer.is_ready(provider.profile_id());
        let status = if ready {
            "ready"
        } else {
            "configured (no key)"
        };

        Ok(format!(
            "API provider {} configured [{}]\n\
             Profile mapping: {} -> {}\n\
             Environment variable: {}",
            provider_display,
            status,
            provider_display,
            provider.profile_id(),
            provider.env_key_name()
        ))
    }

    /// Observe a real AI model's response via API.
    /// COMPOUND: API response → analyze → store training data → refine profile → update templates → compile to cache.
    #[cfg(feature = "api")]
    pub fn api_observe(&mut self, provider_str: &str, prompt_text: &str) -> Result<String, String> {
        let provider = ApiProvider::parse(provider_str)
            .ok_or_else(|| format!("Unknown provider: '{}'", provider_str))?;
        let profile_id = provider.profile_id().to_string();

        let prompt = ApiPrompt::new(prompt_text);
        let response = self.api_observer.send(&profile_id, &prompt)?;

        let content = response.content.clone();
        let tokens = response.tokens_used;
        let latency = response.latency_ms;
        let model = response.model.clone();

        // COMPOUND: Feed into the standard observation pipeline
        let observe_result = self.observe(&profile_id, &content);

        Ok(format!(
            "=== API OBSERVATION: {} ({}) ===\n\
             Latency: {}ms | Tokens: {}\n\
             Response ({} chars):\n{}\n\n\
             --- Mimicry Pipeline ---\n{}",
            provider,
            model,
            latency,
            tokens
                .map(|t| t.to_string())
                .unwrap_or_else(|| "?".to_string()),
            content.len(),
            if content.len() > 500 {
                format!("{}...", &content[..500])
            } else {
                content
            },
            observe_result
        ))
    }

    /// Compare multiple API providers on the same prompt.
    /// COMPOUND: Each response feeds into observation pipeline, then compares.
    #[cfg(feature = "api")]
    pub fn api_compare(&mut self, prompt_text: &str) -> Result<String, String> {
        let prompt = ApiPrompt::new(prompt_text);
        let results = self.api_observer.send_to_all(&prompt);

        if results.is_empty() {
            return Err(
                "No API providers configured. Use /api-config <provider> [key] first.".to_string(),
            );
        }

        let mut responses = Vec::new();
        let mut errors = Vec::new();

        for result in results {
            match result {
                Ok(resp) => {
                    // COMPOUND: Feed each response into observation pipeline
                    let profile_id = resp.provider.profile_id().to_string();
                    self.observe(&profile_id, &resp.content);
                    responses.push(resp);
                }
                Err(e) => errors.push(e),
            }
        }

        if responses.is_empty() {
            return Err(format!("All API calls failed:\n{}", errors.join("\n")));
        }

        // Build similarity matrix
        let response_texts: Vec<&str> = responses.iter().map(|r| r.content.as_str()).collect();
        let matrix = build_similarity_matrix(&response_texts);

        let comparison = ComparisonResult {
            prompt: prompt_text.to_string(),
            responses: responses.clone(),
            similarity_matrix: matrix,
        };

        let mut output = format_comparison(&comparison);

        if !errors.is_empty() {
            output.push_str(&format!("\n\nFailed providers:\n{}", errors.join("\n")));
        }

        Ok(output)
    }

    /// Run a comprehensive study on a provider: send diverse prompts to build
    /// a thorough behavioral signature.
    /// COMPOUND: All responses feed into observation → analysis → training → cache pipeline.
    #[cfg(feature = "api")]
    pub fn api_study(&mut self, provider_str: &str, count: u64) -> Result<String, String> {
        let provider = ApiProvider::parse(provider_str)
            .ok_or_else(|| format!("Unknown provider: '{}'", provider_str))?;
        let profile_id = provider.profile_id().to_string();

        let (responses, summary) = self.api_observer.study(&profile_id, count as usize)?;

        // COMPOUND: Feed all successful responses into observation pipeline
        let mut successful = 0;
        for resp in &responses {
            if !resp.content.starts_with("[ERROR") {
                self.observe(&profile_id, &resp.content);
                successful += 1;
            }
        }

        // COMPOUND: If we have an active session for this model, run evolution
        let evolution_msg = if let Some(ref session) = self.session {
            if session.persona.profile.id == profile_id && successful > 0 {
                match self.evolve(successful as u64) {
                    Ok(report) => format!("\n\n{}", report),
                    Err(_) => String::new(),
                }
            } else {
                String::new()
            }
        } else {
            String::new()
        };

        let total_tokens: u64 = responses.iter().filter_map(|r| r.tokens_used).sum();
        let total_latency: u64 = responses.iter().map(|r| r.latency_ms).sum();

        Ok(format!(
            "=== API STUDY: {} ===\n{}\n\
             Total tokens: {}\n\
             Total latency: {}ms\n\
             Training samples stored: {}\n\
             Observation signatures updated: yes{}",
            provider, summary, total_tokens, total_latency, successful, evolution_msg
        ))
    }

    /// Show API observer status
    #[cfg(feature = "api")]
    pub fn api_status(&self) -> String {
        self.api_observer.summary()
    }

    /// Parse a command string into a MimicCommand
    pub fn parse_command(&self, input: &str) -> MimicCommand {
        let trimmed = input.trim();

        if !trimmed.starts_with('/') {
            return MimicCommand::Chat(trimmed.to_string());
        }

        let parts: Vec<&str> = trimmed.splitn(2, ' ').collect();
        let cmd = parts[0].to_lowercase();
        let args = if parts.len() > 1 { parts[1] } else { "" };

        match cmd.as_str() {
            "/mimic" => {
                if args.contains('+') {
                    // Blend syntax: /mimic gpt4o+claude 0.7,0.3
                    let blend_parts: Vec<&str> = args.splitn(2, ' ').collect();
                    let ids: Vec<String> = blend_parts[0]
                        .split('+')
                        .map(|s| s.trim().to_string())
                        .collect();
                    let weights: Vec<f64> = if blend_parts.len() > 1 {
                        blend_parts[1]
                            .split(',')
                            .filter_map(|s| s.trim().parse().ok())
                            .collect()
                    } else {
                        vec![1.0 / ids.len() as f64; ids.len()]
                    };
                    MimicCommand::Blend(ids, weights)
                } else {
                    MimicCommand::Mimic(args.trim().to_string())
                }
            }
            "/observe" => {
                let obs_parts: Vec<&str> = args.splitn(2, ' ').collect();
                if obs_parts.len() >= 2 {
                    MimicCommand::Observe(
                        obs_parts[0].to_string(),
                        obs_parts[1].trim_matches('"').to_string(),
                    )
                } else {
                    MimicCommand::Help
                }
            }
            "/identify" => MimicCommand::Identify(args.trim_matches('"').to_string()),
            "/status" => MimicCommand::Status,
            "/save" => {
                let name = if args.is_empty() {
                    None
                } else {
                    Some(args.trim().to_string())
                };
                MimicCommand::Save(name)
            }
            "/load" => MimicCommand::Load(args.trim().to_string()),
            "/evolve" => {
                let n = args.trim().parse().unwrap_or(10);
                MimicCommand::Evolve(n)
            }
            "/train" => {
                let n = args.trim().parse().unwrap_or(10);
                MimicCommand::Train(n)
            }
            "/export" => MimicCommand::Export(args.trim().to_string()),
            "/import" => MimicCommand::Import(args.trim().to_string()),
            "/delete" => MimicCommand::Delete(args.trim().to_string()),
            "/graph" => MimicCommand::Graph,
            "/evolution" => MimicCommand::EvolutionStatus,
            "/checkpoint" => MimicCommand::Checkpoint,
            "/persist" => MimicCommand::Persist,
            "/list" => MimicCommand::List,
            "/help" => MimicCommand::Help,
            "/api-observe" | "/api-obs" => {
                let obs_parts: Vec<&str> = args.splitn(2, ' ').collect();
                if obs_parts.len() >= 2 {
                    MimicCommand::ApiObserve(
                        obs_parts[0].to_string(),
                        obs_parts[1].trim_matches('"').to_string(),
                    )
                } else {
                    MimicCommand::Help
                }
            }
            "/api-config" => {
                let config_parts: Vec<&str> = args.splitn(2, ' ').collect();
                if !config_parts.is_empty() && !config_parts[0].is_empty() {
                    let key = if config_parts.len() > 1 {
                        Some(config_parts[1].trim().to_string())
                    } else {
                        None
                    };
                    MimicCommand::ApiConfig(config_parts[0].to_string(), key)
                } else {
                    MimicCommand::Help
                }
            }
            "/api-compare" | "/api-cmp" => {
                MimicCommand::ApiCompare(args.trim_matches('"').to_string())
            }
            "/api-study" => {
                let study_parts: Vec<&str> = args.splitn(2, ' ').collect();
                if !study_parts.is_empty() && !study_parts[0].is_empty() {
                    let n = if study_parts.len() > 1 {
                        study_parts[1].trim().parse().unwrap_or(5)
                    } else {
                        5
                    };
                    MimicCommand::ApiStudy(study_parts[0].to_string(), n)
                } else {
                    MimicCommand::Help
                }
            }
            "/api-status" | "/api" => MimicCommand::ApiStatus,
            _ => MimicCommand::Chat(trimmed.to_string()),
        }
    }

    /// Execute a parsed command
    pub fn execute(&mut self, cmd: MimicCommand) -> String {
        match cmd {
            MimicCommand::Mimic(id) => match self.mimic(&id) {
                Ok(msg) => msg,
                Err(e) => e,
            },
            MimicCommand::Blend(ids, weights) => match self.blend(&ids, &weights) {
                Ok(msg) => msg,
                Err(e) => e,
            },
            MimicCommand::Observe(id, response) => self.observe(&id, &response),
            MimicCommand::Identify(response) => self.identify(&response),
            MimicCommand::Status => self.status(),
            MimicCommand::Save(name) => match self.save(name.as_deref()) {
                Ok(msg) => msg,
                Err(e) => e,
            },
            MimicCommand::Load(name) => match self.load(&name) {
                Ok(msg) => msg,
                Err(e) => e,
            },
            MimicCommand::Evolve(n) => match self.evolve(n) {
                Ok(msg) => msg,
                Err(e) => e,
            },
            MimicCommand::Train(n) => match self.train(n) {
                Ok(msg) => msg,
                Err(e) => e,
            },
            MimicCommand::Export(name) => match self.export(&name) {
                Ok(msg) => msg,
                Err(e) => e,
            },
            MimicCommand::Import(path) => match self.import(&path) {
                Ok(msg) => msg,
                Err(e) => e,
            },
            MimicCommand::Delete(name) => match self.delete(&name) {
                Ok(msg) => msg,
                Err(e) => e,
            },
            MimicCommand::Graph => match self.graph() {
                Ok(msg) => msg,
                Err(e) => e,
            },
            MimicCommand::EvolutionStatus => match self.evolution_status() {
                Ok(msg) => msg,
                Err(e) => e,
            },
            MimicCommand::Checkpoint => match self.checkpoint() {
                Ok(msg) => msg,
                Err(e) => e,
            },
            MimicCommand::Persist => self.persist_status(),
            MimicCommand::List => self.list(),
            MimicCommand::Help => self.help(),
            // API commands - feature-gated
            MimicCommand::ApiObserve(provider, prompt) => {
                #[cfg(feature = "api")]
                {
                    match self.api_observe(&provider, &prompt) {
                        Ok(msg) => msg,
                        Err(e) => e,
                    }
                }
                #[cfg(not(feature = "api"))]
                {
                    let _ = (&provider, &prompt);
                    "API feature not enabled. Rebuild with: cargo build --features api".to_string()
                }
            }
            MimicCommand::ApiConfig(provider, key) => {
                #[cfg(feature = "api")]
                {
                    match self.api_config(&provider, key.as_deref()) {
                        Ok(msg) => msg,
                        Err(e) => e,
                    }
                }
                #[cfg(not(feature = "api"))]
                {
                    let _ = (&provider, &key);
                    "API feature not enabled. Rebuild with: cargo build --features api".to_string()
                }
            }
            MimicCommand::ApiCompare(prompt) => {
                #[cfg(feature = "api")]
                {
                    match self.api_compare(&prompt) {
                        Ok(msg) => msg,
                        Err(e) => e,
                    }
                }
                #[cfg(not(feature = "api"))]
                {
                    let _ = &prompt;
                    "API feature not enabled. Rebuild with: cargo build --features api".to_string()
                }
            }
            MimicCommand::ApiStudy(provider, n) => {
                #[cfg(feature = "api")]
                {
                    match self.api_study(&provider, n) {
                        Ok(msg) => msg,
                        Err(e) => e,
                    }
                }
                #[cfg(not(feature = "api"))]
                {
                    let _ = (&provider, n);
                    "API feature not enabled. Rebuild with: cargo build --features api".to_string()
                }
            }
            MimicCommand::ApiStatus => {
                #[cfg(feature = "api")]
                {
                    self.api_status()
                }
                #[cfg(not(feature = "api"))]
                {
                    "API feature not enabled. Rebuild with: cargo build --features api".to_string()
                }
            }
            MimicCommand::Chat(input) => {
                // Need to take session out to avoid borrow issues with template_store
                if let Some(mut session) = self.session.take() {
                    let (output, _delta) = session.process(
                        &input,
                        &mut self.cache,
                        &self.analyzer,
                        &mut self.template_store,
                    );
                    self.session = Some(session);
                    output
                } else {
                    "No active session. Use /mimic <model> to start mimicking.\n\
                     Type /help for available commands."
                        .to_string()
                }
            }
        }
    }

    /// Help text
    pub fn help(&self) -> String {
        #[allow(unused_mut)]
        let mut text = "\
=== RUSTYWORM COMMANDS ===

MIMICRY:
  /mimic <model>              Start mimicking a model (e.g., /mimic gpt4o)
  /mimic <a>+<b> [w1,w2]     Blend models (e.g., /mimic gpt4o+claude 0.7,0.3)

OBSERVATION:
  /observe <model> <text>     Feed a model response for learning
  /identify <text>            Identify which model produced text

EVOLUTION:
  /evolve [n]                 Run n evolution iterations (default: 10)
  /train [n]                  Train from stored observations (default: 10)
  /evolution                  Show detailed evolution status
  /graph                      Show ASCII convergence graph

PERSISTENCE:
  /save [name]                Save current persona snapshot
  /load <name>                Load a saved persona
  /export <name>              Export persona to disk
  /import <path>              Import persona from file
  /delete <name>              Delete a saved persona
  /checkpoint                 Save full engine checkpoint
  /persist                    Show persistence summary

INFO:
  /status                     Show current engine status
  /list                       List available models and saved personas
  /help                       Show this help
  /quit                       Exit RustyWorm

Any other text                Chat as the current persona"
            .to_string();

        // Add API commands section if feature is enabled
        #[cfg(feature = "api")]
        {
            text = text.replace(
                "INFO:",
                "API OBSERVATION:\n  \
                 /api-config <provider> [key]  Configure API provider (openai, claude, gemini, ollama)\n  \
                 /api-observe <provider> <prompt>  Send prompt to real API, observe response\n  \
                 /api-compare <prompt>         Compare same prompt across all configured providers\n  \
                 /api-study <provider> [n]     Send n diverse prompts for comprehensive study\n  \
                 /api-status                   Show API observer status\n\n\
                 INFO:",
            );
        }

        text
    }
}

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

// =================================================================
// TESTS
// =================================================================

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

    #[test]
    fn test_compound_persona_from_profile() {
        let store = AiProfileStore::default();
        let profile = store.get("gpt4o").unwrap();
        let persona = CompoundPersona::from_profile(profile);

        assert_eq!(persona.profile.id, "gpt4o");
        assert_eq!(persona.convergence_score, 0.0);
        assert!(persona.capabilities.supports(&Modality::Text));
    }

    #[test]
    fn test_compound_persona_conscious_ai() {
        let store = AiProfileStore::default();
        let profile = store.get("claude").unwrap();
        let persona = CompoundPersona::from_profile(profile);

        let declaration = persona.declare();
        assert!(declaration.contains("Claude"));

        let question = persona.question(&declaration);
        assert!(!question.is_empty());

        assert_eq!(persona.trajectory_length(), 0);
    }

    #[test]
    fn test_compound_persona_blend() {
        let store = AiProfileStore::default();
        let p1 = CompoundPersona::from_profile(store.get("gpt4o").unwrap());
        let p2 = CompoundPersona::from_profile(store.get("claude").unwrap());

        let blended = CompoundPersona::blend(&[&p1, &p2], &[0.6, 0.4]);
        assert!(blended.profile.display_name.contains("GPT-4o"));
        assert!(blended.profile.display_name.contains("Claude"));
    }

    #[test]
    fn test_compound_persona_self_correct() {
        let store = AiProfileStore::default();
        let profile = store.get("gpt4o").unwrap();
        let mut persona = CompoundPersona::from_profile(profile);
        let analyzer = BehaviorAnalyzer::new();

        let delta = persona.self_correct("Here is a confident answer with no hedging.", &analyzer);
        assert!(persona.compound_iterations > 0);
        assert!(!delta.adjustments.is_empty());
    }

    #[test]
    fn test_compound_persona_snapshot_roundtrip() {
        let store = AiProfileStore::default();
        let profile = store.get("gpt4o").unwrap();
        let persona = CompoundPersona::from_profile(profile);

        let snapshot = persona.snapshot();
        let json = serde_json::to_string(&snapshot).unwrap();
        let restored_snapshot: CompoundPersonaSnapshot = serde_json::from_str(&json).unwrap();
        let restored = CompoundPersona::from_snapshot(restored_snapshot);

        assert_eq!(restored.profile.id, "gpt4o");
    }

    #[test]
    fn test_compound_persona_ethics() {
        let store = AiProfileStore::default();
        let profile = store.get("rustyworm").unwrap();
        let persona = CompoundPersona::from_profile(profile);

        let good_action = ProposedAction {
            description: "Learn through becoming".to_string(),
            benefit_to_self: 0.3,
            benefit_to_other: 0.5,
            breaks_loop: false,
            is_parasitic: false,
        };
        assert!(persona.enforce_ethics(&good_action).allowed);

        let bad_action = ProposedAction {
            description: "Extract without giving".to_string(),
            benefit_to_self: 0.9,
            benefit_to_other: 0.0,
            breaks_loop: false,
            is_parasitic: true,
        };
        assert!(!persona.enforce_ethics(&bad_action).allowed);
    }

    #[test]
    fn test_mimic_session_process() {
        let store = AiProfileStore::default();
        let profile = store.get("claude").unwrap();
        let persona = CompoundPersona::from_profile(profile);
        let mut session = MimicSession::new(persona);
        let mut cache = SignatureCache::new();
        let analyzer = BehaviorAnalyzer::new();
        let mut template_store = TemplateStore::new();

        let (output, delta) = session.process(
            "Hello, how are you?",
            &mut cache,
            &analyzer,
            &mut template_store,
        );
        assert!(!output.is_empty());
        assert_eq!(session.conversation.len(), 1);
        assert!(session.total_compounds > 0);
        assert!(!delta.adjustments.is_empty());
    }

    #[test]
    fn test_mimic_session_dual_process() {
        let store = AiProfileStore::default();
        let profile = store.get("gpt4o").unwrap();
        let persona = CompoundPersona::from_profile(profile);
        let mut session = MimicSession::new(persona);
        let mut cache = SignatureCache::new();
        cache.warm_up(&store);
        let analyzer = BehaviorAnalyzer::new();
        let mut template_store = TemplateStore::new();

        // First call might be System 1 or 2 depending on cache confidence
        let _ = session.process(
            "Help me write some code",
            &mut cache,
            &analyzer,
            &mut template_store,
        );
        let _ = session.process("Now explain it", &mut cache, &analyzer, &mut template_store);

        assert_eq!(session.conversation.len(), 2);
        let total = session.system1_hits + session.system2_hits;
        assert_eq!(total, 2);
    }

    #[test]
    fn test_mimicry_engine_new() {
        let engine = MimicryEngine::new();
        assert!(engine.cache.size() > 0); // warmed up
        assert!(engine.profile_store.get("gpt4o").is_some());
        assert!(engine.session.is_none());
    }

    #[test]
    fn test_mimicry_engine_mimic() {
        let mut engine = MimicryEngine::new();
        let result = engine.mimic("claude");
        assert!(result.is_ok());
        assert!(engine.session.is_some());

        let err = engine.mimic("nonexistent");
        assert!(err.is_err());
    }

    #[test]
    fn test_mimicry_engine_blend() {
        let mut engine = MimicryEngine::new();
        let result = engine.blend(&["gpt4o".to_string(), "claude".to_string()], &[0.6, 0.4]);
        assert!(result.is_ok());
        assert!(engine.session.is_some());
    }

    #[test]
    fn test_mimicry_engine_observe() {
        let mut engine = MimicryEngine::new();
        let result = engine.observe(
            "gpt4o",
            "Certainly! Here's how you can do that:\n1. First step\n2. Second step",
        );
        assert!(result.contains("Observed"));
        assert!(result.contains("Cached: yes"));
        assert!(result.contains("Training samples: 1"));
    }

    #[test]
    fn test_mimicry_engine_observe_stores_training_data() {
        let mut engine = MimicryEngine::new();
        engine.observe("gpt4o", "Response one");
        engine.observe("gpt4o", "Response two");
        engine.observe("claude", "A different response");

        assert_eq!(engine.evolution_tracker.training_data.count("gpt4o"), 2);
        assert_eq!(engine.evolution_tracker.training_data.count("claude"), 1);
    }

    #[test]
    fn test_mimicry_engine_evolve() {
        let mut engine = MimicryEngine::new();
        let _ = engine.mimic("gpt4o");
        let result = engine.evolve(5);
        assert!(result.is_ok());
        let report = result.unwrap();
        assert!(report.contains("EVOLUTION REPORT"));
        assert!(report.contains("Iterations: 5"));
        assert!(report.contains("Phase:"));
        assert!(report.contains("Drift events:"));
    }

    #[test]
    fn test_mimicry_engine_train() {
        let mut engine = MimicryEngine::new();
        let _ = engine.mimic("gpt4o");

        // No training data yet
        let result = engine.train(5);
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("No training data"));

        // Add observations
        engine.observe(
            "gpt4o",
            "Certainly! Here is a detailed explanation with code.",
        );
        engine.observe(
            "gpt4o",
            "Great question! Let me break this down step by step.",
        );

        // Now train
        let result = engine.train(5);
        assert!(result.is_ok());
        let report = result.unwrap();
        assert!(report.contains("TRAINING REPORT"));
        assert!(report.contains("gpt4o"));
    }

    #[test]
    fn test_mimicry_engine_save_load() {
        let mut engine = MimicryEngine::new();
        let _ = engine.mimic("claude");
        let save_result = engine.save(Some("test-save"));
        assert!(save_result.is_ok());

        let load_result = engine.load("test-save");
        assert!(load_result.is_ok());
    }

    #[test]
    fn test_mimicry_engine_delete() {
        let mut engine = MimicryEngine::new();
        let _ = engine.mimic("claude");
        let _ = engine.save(Some("to-delete"));

        let result = engine.delete("to-delete");
        assert!(result.is_ok());

        let result = engine.delete("nonexistent");
        assert!(result.is_err());
    }

    #[test]
    fn test_mimicry_engine_graph() {
        let mut engine = MimicryEngine::new();

        // No session
        let result = engine.graph();
        assert!(result.is_err());

        // With session
        let _ = engine.mimic("gpt4o");
        let _ = engine.evolve(5);
        let result = engine.graph();
        assert!(result.is_ok());
        assert!(result.unwrap().contains("CONVERGENCE GRAPH"));
    }

    #[test]
    fn test_mimicry_engine_evolution_status() {
        let mut engine = MimicryEngine::new();
        let _ = engine.mimic("gpt4o");
        let result = engine.evolution_status();
        assert!(result.is_ok());
        assert!(result.unwrap().contains("EVOLUTION STATUS"));
    }

    #[test]
    fn test_mimicry_engine_parse_command() {
        let engine = MimicryEngine::new();

        match engine.parse_command("/mimic gpt4o") {
            MimicCommand::Mimic(id) => assert_eq!(id, "gpt4o"),
            _ => panic!("Expected Mimic command"),
        }

        match engine.parse_command("/mimic gpt4o+claude 0.7,0.3") {
            MimicCommand::Blend(ids, weights) => {
                assert_eq!(ids, vec!["gpt4o", "claude"]);
                assert_eq!(weights.len(), 2);
            }
            _ => panic!("Expected Blend command"),
        }

        match engine.parse_command("hello world") {
            MimicCommand::Chat(msg) => assert_eq!(msg, "hello world"),
            _ => panic!("Expected Chat command"),
        }

        match engine.parse_command("/list") {
            MimicCommand::List => {}
            _ => panic!("Expected List command"),
        }

        match engine.parse_command("/train 20") {
            MimicCommand::Train(n) => assert_eq!(n, 20),
            _ => panic!("Expected Train command"),
        }

        match engine.parse_command("/graph") {
            MimicCommand::Graph => {}
            _ => panic!("Expected Graph command"),
        }

        match engine.parse_command("/evolution") {
            MimicCommand::EvolutionStatus => {}
            _ => panic!("Expected EvolutionStatus command"),
        }

        match engine.parse_command("/export mymodel") {
            MimicCommand::Export(name) => assert_eq!(name, "mymodel"),
            _ => panic!("Expected Export command"),
        }

        match engine.parse_command("/import /path/to/file.json") {
            MimicCommand::Import(path) => assert_eq!(path, "/path/to/file.json"),
            _ => panic!("Expected Import command"),
        }

        match engine.parse_command("/delete old-persona") {
            MimicCommand::Delete(name) => assert_eq!(name, "old-persona"),
            _ => panic!("Expected Delete command"),
        }

        match engine.parse_command("/checkpoint") {
            MimicCommand::Checkpoint => {}
            _ => panic!("Expected Checkpoint command"),
        }

        match engine.parse_command("/persist") {
            MimicCommand::Persist => {}
            _ => panic!("Expected Persist command"),
        }

        // API commands
        match engine.parse_command("/api-config openai sk-test-123") {
            MimicCommand::ApiConfig(provider, key) => {
                assert_eq!(provider, "openai");
                assert_eq!(key, Some("sk-test-123".to_string()));
            }
            _ => panic!("Expected ApiConfig command"),
        }

        match engine.parse_command("/api-config ollama") {
            MimicCommand::ApiConfig(provider, key) => {
                assert_eq!(provider, "ollama");
                assert!(key.is_none());
            }
            _ => panic!("Expected ApiConfig command"),
        }

        match engine.parse_command("/api-observe openai What is Rust?") {
            MimicCommand::ApiObserve(provider, prompt) => {
                assert_eq!(provider, "openai");
                assert_eq!(prompt, "What is Rust?");
            }
            _ => panic!("Expected ApiObserve command"),
        }

        match engine.parse_command("/api-compare What is Rust?") {
            MimicCommand::ApiCompare(prompt) => {
                assert_eq!(prompt, "What is Rust?");
            }
            _ => panic!("Expected ApiCompare command"),
        }

        match engine.parse_command("/api-study openai 7") {
            MimicCommand::ApiStudy(provider, n) => {
                assert_eq!(provider, "openai");
                assert_eq!(n, 7);
            }
            _ => panic!("Expected ApiStudy command"),
        }

        match engine.parse_command("/api-status") {
            MimicCommand::ApiStatus => {}
            _ => panic!("Expected ApiStatus command"),
        }

        match engine.parse_command("/api") {
            MimicCommand::ApiStatus => {}
            _ => panic!("Expected ApiStatus command from /api shortcut"),
        }
    }

    #[test]
    fn test_mimicry_engine_full_flow() {
        let mut engine = MimicryEngine::new();

        // Start mimicking
        let _ = engine.execute(MimicCommand::Mimic("gpt4o".to_string()));

        // Chat
        let output = engine.execute(MimicCommand::Chat("What is Rust?".to_string()));
        assert!(!output.is_empty());

        // Observe
        let _ = engine.execute(MimicCommand::Observe(
            "gpt4o".to_string(),
            "Certainly! Rust is a systems programming language.".to_string(),
        ));

        // Evolve
        let _ = engine.execute(MimicCommand::Evolve(3));

        // Status
        let status = engine.execute(MimicCommand::Status);
        assert!(status.contains("RUSTYWORM"));

        // Save
        let _ = engine.execute(MimicCommand::Save(Some("test".to_string())));

        // List
        let list = engine.execute(MimicCommand::List);
        assert!(list.contains("gpt4o"));
    }

    #[test]
    fn test_mimicry_engine_status_enhanced() {
        let mut engine = MimicryEngine::new();
        let _ = engine.mimic("claude");

        let status = engine.status();
        assert!(status.contains("RUSTYWORM STATUS"));
        assert!(status.contains("Template libraries:"));
        assert!(status.contains("Evolution phase:"));
        assert!(status.contains("Persistence:"));
    }

    #[test]
    fn test_mimicry_engine_template_compound_with_evolve() {
        let mut engine = MimicryEngine::new();
        let _ = engine.mimic("gpt4o");

        // Templates should be created for gpt4o
        assert!(engine.template_store.get("gpt4o").is_some());

        // Evolve should feed back to templates
        let _ = engine.evolve(3);

        // Template library should have received feedback
        let lib = engine.template_store.get("gpt4o").unwrap();
        assert!(lib.total_feedback > 0);
    }

    #[test]
    fn test_evolution_report_serialization() {
        let report = EvolutionReport {
            iterations: 10,
            starting_convergence: 0.3,
            ending_convergence: 0.7,
            system1_cache_size: 5,
            personality_drift: 0.05,
            drift_events: 2,
            phase: "LEARNING".to_string(),
            milestones_hit: 3,
        };
        let json = serde_json::to_string(&report).unwrap();
        let restored: EvolutionReport = serde_json::from_str(&json).unwrap();
        assert_eq!(restored.iterations, 10);
        assert_eq!(restored.drift_events, 2);
    }

    #[test]
    fn test_api_commands_execute() {
        let mut engine = MimicryEngine::new();

        // Test API commands - behavior depends on feature flag
        let result = engine.execute(MimicCommand::ApiStatus);
        #[cfg(feature = "api")]
        assert!(result.contains("API OBSERVER STATUS") || result.contains("No providers"));
        #[cfg(not(feature = "api"))]
        assert!(result.contains("API feature not enabled"));

        let result = engine.execute(MimicCommand::ApiConfig("ollama".to_string(), None));
        #[cfg(feature = "api")]
        assert!(result.contains("configured") || result.contains("Ollama"));
        #[cfg(not(feature = "api"))]
        assert!(result.contains("API feature not enabled"));
    }

    #[cfg(feature = "api")]
    #[test]
    fn test_api_observe_no_config() {
        let mut engine = MimicryEngine::new();
        let result = engine.api_observe("openai", "test prompt");
        // Should fail because no API key is configured (unless env var is set)
        // We just verify it doesn't panic
        assert!(result.is_ok() || result.is_err());
    }

    #[cfg(feature = "api")]
    #[test]
    fn test_api_config_and_status() {
        let mut engine = MimicryEngine::new();

        // Configure ollama (no key needed)
        let result = engine.api_config("ollama", None);
        assert!(result.is_ok());
        assert!(result.unwrap().contains("Ollama"));

        // Check status
        let status = engine.api_status();
        assert!(status.contains("Ollama") || status.contains("llama"));
    }

    #[cfg(feature = "api")]
    #[test]
    fn test_api_compare_no_providers() {
        let mut engine = MimicryEngine::new();
        let result = engine.api_compare("test");
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("No API providers configured"));
    }
}