yantrikdb 0.16.0

Cognitive memory engine for persistent AI systems
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
//! Autonomous Skill Acquisition — learns reusable multi-step capabilities
//! from observed user action patterns.
//!
//! # Architecture
//!
//! ```text
//! Observer events ──► Sequence mining ──► SkillCandidate (confidence 0.3)
//!                          │                     │
//!                          │            Trigger context inference
//!                          │                     │
//!                          ▼                     ▼
//!                   Repeated use         LearnedSkill (confidence ↑)
//!                          │                     │
//!                          ▼                     ▼
//!                   Reliable (0.7)        SkillTemplate (reusable)
//!//!//!                   ActionSchema node persisted in graph
//! ```
//!
//! # Skill Lifecycle
//!
//! 1. **Discovery**: Detect repeated action sequences from observer events
//! 2. **Candidacy**: Form SkillCandidate with inferred trigger context
//! 3. **Validation**: Track success/failure when skill is offered and executed
//! 4. **Promotion**: Reliable skills become ActionSchema nodes in the graph
//! 5. **Deprecation**: Skills unused for extended periods are marked stale
//!
//! # Privacy
//! - Skills reference action_kind strings and app_ids — never raw user content
//! - Query hashes used for need-based skills (BLAKE3, irreversible)
//! - All data local, never transmitted

use std::collections::HashMap;

use serde::{Deserialize, Serialize};

use super::observer::{EventBuffer, EventKind, SystemEvent, SystemEventData};

// ══════════════════════════════════════════════════════════════════════════════
// § 1  Skill Types
// ══════════════════════════════════════════════════════════════════════════════

/// Unique identifier for a learned skill.
pub type SkillId = u64;

/// How the skill was discovered.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum SkillOrigin {
    /// Mined from repeated app transition sequences.
    AppSequence,
    /// Mined from repeated tool call chains.
    ToolChain,
    /// Mined from repeated suggestion-accept patterns.
    SuggestionPattern,
    /// Mined from notification → action response patterns.
    NotificationResponse,
    /// Manually taught by the user.
    UserTaught,
}

impl SkillOrigin {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::AppSequence => "app_sequence",
            Self::ToolChain => "tool_chain",
            Self::SuggestionPattern => "suggestion_pattern",
            Self::NotificationResponse => "notification_response",
            Self::UserTaught => "user_taught",
        }
    }
}

/// Lifecycle stage of a learned skill.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum SkillStage {
    /// Just discovered from pattern mining (confidence 0.2–0.5).
    Candidate,
    /// Validated through repeated observation (confidence 0.5–0.7).
    Validated,
    /// Reliable enough to proactively offer (confidence 0.7–0.9).
    Reliable,
    /// Promoted to an ActionSchema in the cognitive graph (confidence 0.9+).
    Promoted,
    /// Not observed recently, may be outdated.
    Stale,
    /// Explicitly deprecated (user rejected or low success rate).
    Deprecated,
}

impl SkillStage {
    pub fn from_confidence(confidence: f64, last_used_age_secs: f64, deprecated: bool) -> Self {
        if deprecated {
            return Self::Deprecated;
        }
        // Stale after 30 days of non-use
        if last_used_age_secs > 30.0 * 86400.0 && confidence < 0.9 {
            return Self::Stale;
        }
        match confidence {
            c if c >= 0.9 => Self::Promoted,
            c if c >= 0.7 => Self::Reliable,
            c if c >= 0.5 => Self::Validated,
            _ => Self::Candidate,
        }
    }
}

// ══════════════════════════════════════════════════════════════════════════════
// § 2  Skill Steps and Triggers
// ══════════════════════════════════════════════════════════════════════════════

/// A single step within a learned multi-step skill.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SkillStep {
    /// Zero-based position in the sequence.
    pub ordinal: u16,
    /// The action kind string (matches observer event action_kind).
    pub action_kind: String,
    /// Optional app_id if this step involves an app transition.
    pub app_id: Option<u16>,
    /// Optional tool name if this step is a tool call.
    pub tool_name: Option<String>,
    /// Expected duration of this step in milliseconds (learned from observations).
    pub expected_duration_ms: u64,
    /// Whether this step is optional (can be skipped without breaking the skill).
    pub optional: bool,
}

/// Context conditions under which a skill should be triggered.
///
/// All fields are optional — the more that match, the stronger the trigger signal.
/// A trigger with no fields set matches any context (universal skill).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SkillTrigger {
    /// Time-of-day bins when this skill is typically used (0-23 hours).
    /// Empty = any time.
    pub time_bins: Vec<u8>,
    /// App that was open when the skill was typically initiated.
    pub initiating_app_id: Option<u16>,
    /// App transition that precedes this skill (from → to).
    pub preceding_transition: Option<(u16, u16)>,
    /// Day-of-week preference (0=Mon, 6=Sun). Empty = any day.
    pub day_of_week: Vec<u8>,
    /// Minimum session duration (seconds) before this skill is relevant.
    pub min_session_duration_secs: Option<f64>,
    /// Whether the user was idle before skill initiation.
    pub preceded_by_idle: Option<bool>,
}

impl SkillTrigger {
    pub fn new() -> Self {
        Self {
            time_bins: Vec::new(),
            initiating_app_id: None,
            preceding_transition: None,
            day_of_week: Vec::new(),
            min_session_duration_secs: None,
            preceded_by_idle: None,
        }
    }

    /// How many trigger conditions are specified (non-empty).
    pub fn specificity(&self) -> u8 {
        let mut s = 0u8;
        if !self.time_bins.is_empty() {
            s += 1;
        }
        if self.initiating_app_id.is_some() {
            s += 1;
        }
        if self.preceding_transition.is_some() {
            s += 1;
        }
        if !self.day_of_week.is_empty() {
            s += 1;
        }
        if self.min_session_duration_secs.is_some() {
            s += 1;
        }
        if self.preceded_by_idle.is_some() {
            s += 1;
        }
        s
    }

    /// Score how well the current context matches this trigger [0.0, 1.0].
    ///
    /// Returns None if no conditions are specified (universal match → 1.0).
    pub fn match_score(
        &self,
        hour: u8,
        day: u8,
        current_app: Option<u16>,
        recent_transition: Option<(u16, u16)>,
        session_duration_secs: f64,
        was_idle: bool,
    ) -> f64 {
        let spec = self.specificity();
        if spec == 0 {
            return 1.0;
        }

        let mut matches = 0u8;
        let mut total = 0u8;

        if !self.time_bins.is_empty() {
            total += 1;
            if self.time_bins.contains(&hour) {
                matches += 1;
            }
        }

        if let Some(app) = self.initiating_app_id {
            total += 1;
            if current_app == Some(app) {
                matches += 1;
            }
        }

        if let Some(expected) = self.preceding_transition {
            total += 1;
            if recent_transition == Some(expected) {
                matches += 1;
            }
        }

        if !self.day_of_week.is_empty() {
            total += 1;
            if self.day_of_week.contains(&day) {
                matches += 1;
            }
        }

        if let Some(min_dur) = self.min_session_duration_secs {
            total += 1;
            if session_duration_secs >= min_dur {
                matches += 1;
            }
        }

        if let Some(expect_idle) = self.preceded_by_idle {
            total += 1;
            if was_idle == expect_idle {
                matches += 1;
            }
        }

        if total == 0 {
            1.0
        } else {
            matches as f64 / total as f64
        }
    }
}

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

// ══════════════════════════════════════════════════════════════════════════════
// § 3  Learned Skill
// ══════════════════════════════════════════════════════════════════════════════

/// A learned multi-step skill with trigger context and reliability tracking.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LearnedSkill {
    /// Unique identifier (derived from dedup_key hash).
    pub id: SkillId,
    /// Human-readable description of what this skill does.
    pub description: String,
    /// How this skill was discovered.
    pub origin: SkillOrigin,
    /// Current lifecycle stage.
    pub stage: SkillStage,
    /// Deduplication key (e.g., "app_seq:14→20→15").
    pub dedup_key: String,
    /// The ordered sequence of steps.
    pub steps: Vec<SkillStep>,
    /// When this skill should be triggered.
    pub trigger: SkillTrigger,
    /// Current confidence [0.0, 1.0].
    pub confidence: f64,
    /// Number of times this exact sequence was observed.
    pub observation_count: u32,
    /// Number of times the skill was offered to the user.
    pub offer_count: u32,
    /// Number of times the user accepted the offered skill.
    pub acceptance_count: u32,
    /// Number of times the skill executed successfully.
    pub success_count: u32,
    /// Number of times the skill execution failed.
    pub failure_count: u32,
    /// When this skill was first discovered (Unix seconds).
    pub discovered_at: f64,
    /// When this skill was last observed or used (Unix seconds).
    pub last_seen_at: f64,
    /// Whether explicitly deprecated by user or system.
    pub deprecated: bool,
    /// Optional NodeId of the promoted ActionSchema (set after promotion).
    pub promoted_schema_id: Option<u32>,
}

impl LearnedSkill {
    /// Create a new skill candidate from a discovered pattern.
    pub fn new(
        description: String,
        origin: SkillOrigin,
        dedup_key: String,
        steps: Vec<SkillStep>,
        trigger: SkillTrigger,
        observation_count: u32,
        now: f64,
    ) -> Self {
        let id = hash_dedup_key(&dedup_key);
        Self {
            id,
            description,
            origin,
            stage: SkillStage::Candidate,
            dedup_key,
            steps,
            trigger,
            confidence: 0.3,
            observation_count,
            offer_count: 0,
            acceptance_count: 0,
            success_count: 0,
            failure_count: 0,
            discovered_at: now,
            last_seen_at: now,
            deprecated: false,
            promoted_schema_id: None,
        }
    }

    /// Record another observation of this action sequence.
    pub fn observe(&mut self, now: f64) {
        self.observation_count += 1;
        self.last_seen_at = now;
        // Confidence grows with repeated observation (diminishing returns).
        let learning_rate = 0.05;
        self.confidence += (1.0 - self.confidence) * learning_rate;
        self.update_stage(now);
    }

    /// Record that the skill was offered to the user.
    pub fn record_offer(&mut self) {
        self.offer_count += 1;
    }

    /// Record that the user accepted the offered skill.
    pub fn record_acceptance(&mut self, now: f64) {
        self.acceptance_count += 1;
        self.last_seen_at = now;
        let learning_rate = 0.10;
        self.confidence += (1.0 - self.confidence) * learning_rate;
        self.update_stage(now);
    }

    /// Record a successful skill execution.
    pub fn record_success(&mut self, now: f64) {
        self.success_count += 1;
        self.last_seen_at = now;
        let learning_rate = 0.08;
        self.confidence += (1.0 - self.confidence) * learning_rate;
        self.update_stage(now);
    }

    /// Record a failed skill execution.
    pub fn record_failure(&mut self, now: f64) {
        self.failure_count += 1;
        self.last_seen_at = now;
        let decay_rate = 0.15;
        self.confidence -= self.confidence * decay_rate;
        self.update_stage(now);
    }

    /// Record that the user rejected the offered skill.
    pub fn record_rejection(&mut self, now: f64) {
        self.last_seen_at = now;
        let decay_rate = 0.12;
        self.confidence -= self.confidence * decay_rate;
        self.update_stage(now);
    }

    /// Explicitly deprecate this skill.
    pub fn deprecate(&mut self) {
        self.deprecated = true;
        self.stage = SkillStage::Deprecated;
    }

    /// Success rate [0.0, 1.0] (NaN-safe).
    pub fn success_rate(&self) -> f64 {
        let total = self.success_count + self.failure_count;
        if total == 0 {
            0.5 // Neutral prior
        } else {
            self.success_count as f64 / total as f64
        }
    }

    /// Acceptance rate [0.0, 1.0] (NaN-safe).
    pub fn acceptance_rate(&self) -> f64 {
        if self.offer_count == 0 {
            0.5 // Neutral prior
        } else {
            self.acceptance_count as f64 / self.offer_count as f64
        }
    }

    /// Whether this skill is ready to be proactively offered.
    pub fn is_offerable(&self) -> bool {
        matches!(self.stage, SkillStage::Reliable | SkillStage::Promoted)
            && !self.deprecated
            && self.confidence >= 0.7
    }

    /// Whether this skill is eligible for promotion to an ActionSchema,
    /// judged against `config` — the promotion_* knobs. The bare
    /// [`Self::is_promotable`] previously hardcoded 0.9/10/0.75, mirroring
    /// (and ignoring) the config defaults: sweeping the knobs measured
    /// nothing (2026-08-15 knob audit).
    pub fn is_promotable_with(&self, config: &SkillConfig) -> bool {
        self.confidence >= config.promotion_confidence
            && self.observation_count >= config.promotion_min_observations
            && self.success_rate() >= config.promotion_min_success_rate
            && self.promoted_schema_id.is_none()
            && !self.deprecated
    }

    /// Promotion eligibility at the DEFAULT thresholds. Callers holding a
    /// loaded [`SkillConfig`] should use [`Self::is_promotable_with`] so the
    /// env-tuned knobs actually govern.
    pub fn is_promotable(&self) -> bool {
        self.is_promotable_with(&SkillConfig::default())
    }

    /// Number of steps in this skill.
    pub fn step_count(&self) -> usize {
        self.steps.len()
    }

    fn update_stage(&mut self, now: f64) {
        let age = now - self.last_seen_at;
        self.stage = SkillStage::from_confidence(self.confidence, age, self.deprecated);
    }
}

/// FNV-1a hash of the dedup key → SkillId.
fn hash_dedup_key(key: &str) -> SkillId {
    let mut hash: u64 = 0xcbf29ce484222325;
    for byte in key.as_bytes() {
        hash ^= *byte as u64;
        hash = hash.wrapping_mul(0x100000001b3);
    }
    hash
}

// ══════════════════════════════════════════════════════════════════════════════
// § 4  Skill Registry
// ══════════════════════════════════════════════════════════════════════════════

/// Configuration for the skill acquisition engine.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SkillConfig {
    /// Minimum times a sequence must be observed to become a candidate.
    pub min_observations: u32,
    /// Maximum number of learned skills to retain.
    pub max_skills: usize,
    /// Maximum steps in a single skill (prevents overly long chains).
    pub max_steps_per_skill: usize,
    /// Minimum confidence to offer a skill proactively.
    pub min_offer_confidence: f64,
    /// Minimum confidence and observations for ActionSchema promotion.
    pub promotion_confidence: f64,
    /// Minimum observations for promotion.
    pub promotion_min_observations: u32,
    /// Minimum success rate for promotion.
    pub promotion_min_success_rate: f64,
    /// Age in seconds after which an unused candidate is pruned.
    pub candidate_ttl_secs: f64,
    /// Age in seconds after which an unused validated skill becomes stale.
    pub stale_threshold_secs: f64,
    /// Maximum gap between events to consider them part of the same sequence (ms).
    pub max_sequence_gap_ms: u64,
    /// Whether to auto-deprecate skills with very low acceptance rates.
    pub auto_deprecate: bool,
    /// Acceptance rate below which auto-deprecation triggers.
    pub auto_deprecate_threshold: f64,
    /// Minimum offers before auto-deprecation can trigger.
    pub auto_deprecate_min_offers: u32,
}

impl Default for SkillConfig {
    fn default() -> Self {
        Self {
            min_observations: 3,
            max_skills: 200,
            max_steps_per_skill: 8,
            min_offer_confidence: 0.7,
            promotion_confidence: 0.9,
            promotion_min_observations: 10,
            promotion_min_success_rate: 0.75,
            candidate_ttl_secs: 14.0 * 86400.0,   // 14 days
            stale_threshold_secs: 30.0 * 86400.0, // 30 days
            max_sequence_gap_ms: 30_000,          // 30 seconds
            auto_deprecate: true,
            auto_deprecate_threshold: 0.15,
            auto_deprecate_min_offers: 5,
        }
    }
}

/// The skill registry — stores all learned skills.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SkillRegistry {
    /// All learned skills, keyed by dedup_key.
    pub skills: HashMap<String, LearnedSkill>,
    /// Total skills ever discovered.
    pub total_discovered: u64,
    /// Total skills promoted to ActionSchema.
    pub total_promoted: u64,
    /// Total skills deprecated.
    pub total_deprecated: u64,
    /// Last time skill discovery was run (Unix seconds).
    pub last_discovery_at: f64,
}

impl SkillRegistry {
    pub fn new() -> Self {
        Self {
            skills: HashMap::new(),
            total_discovered: 0,
            total_promoted: 0,
            total_deprecated: 0,
            last_discovery_at: 0.0,
        }
    }

    /// Get a skill by dedup_key.
    pub fn find(&self, dedup_key: &str) -> Option<&LearnedSkill> {
        self.skills.get(dedup_key)
    }

    /// Get a mutable skill by dedup_key.
    pub fn find_mut(&mut self, dedup_key: &str) -> Option<&mut LearnedSkill> {
        self.skills.get_mut(dedup_key)
    }

    /// Get a skill by SkillId.
    pub fn find_by_id(&self, id: SkillId) -> Option<&LearnedSkill> {
        self.skills.values().find(|s| s.id == id)
    }

    /// Number of active (non-deprecated) skills.
    pub fn active_count(&self) -> usize {
        self.skills.values().filter(|s| !s.deprecated).count()
    }

    /// Skills that can currently be offered.
    pub fn offerable(&self) -> Vec<&LearnedSkill> {
        self.skills.values().filter(|s| s.is_offerable()).collect()
    }

    /// Skills eligible for promotion at the default thresholds; prefer
    /// [`Self::promotable_with`] with a loaded config.
    pub fn promotable(&self) -> Vec<&LearnedSkill> {
        self.skills.values().filter(|s| s.is_promotable()).collect()
    }

    /// Skills eligible for promotion under `config`'s promotion_* knobs.
    pub fn promotable_with(&self, config: &SkillConfig) -> Vec<&LearnedSkill> {
        self.skills
            .values()
            .filter(|s| s.is_promotable_with(config))
            .collect()
    }

    /// Skills by origin.
    pub fn by_origin(&self, origin: SkillOrigin) -> Vec<&LearnedSkill> {
        self.skills
            .values()
            .filter(|s| s.origin == origin && !s.deprecated)
            .collect()
    }

    /// Skills by stage.
    pub fn by_stage(&self, stage: SkillStage) -> Vec<&LearnedSkill> {
        self.skills
            .values()
            .filter(|s| std::mem::discriminant(&s.stage) == std::mem::discriminant(&stage))
            .collect()
    }

    /// Total skill count.
    pub fn len(&self) -> usize {
        self.skills.len()
    }

    pub fn is_empty(&self) -> bool {
        self.skills.is_empty()
    }
}

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

// ══════════════════════════════════════════════════════════════════════════════
// § 5  Skill Discovery — Sequence Mining
// ══════════════════════════════════════════════════════════════════════════════

/// Result of a skill discovery run.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DiscoveryResult {
    /// Newly discovered skill candidates.
    pub new_skills: Vec<String>,
    /// Existing skills that were re-observed (dedup_keys).
    pub reinforced: Vec<String>,
    /// Skills auto-deprecated this run.
    pub auto_deprecated: Vec<String>,
    /// Skills pruned (expired candidates).
    pub pruned: Vec<String>,
    /// Total skills in registry after this run.
    pub total_skills: usize,
}

/// Run the skill discovery pipeline.
///
/// Analyzes recent events in the buffer, mines repeated sequences,
/// updates or creates skill candidates, handles lifecycle transitions.
pub fn discover_skills(
    buffer: &EventBuffer,
    registry: &mut SkillRegistry,
    config: &SkillConfig,
    now: f64,
) -> DiscoveryResult {
    let mut result = DiscoveryResult {
        new_skills: Vec::new(),
        reinforced: Vec::new(),
        auto_deprecated: Vec::new(),
        pruned: Vec::new(),
        total_skills: 0,
    };

    // Phase 1: Mine app transition sequences
    discover_app_sequence_skills(buffer, registry, config, now, &mut result);

    // Phase 2: Mine tool call chains
    discover_tool_chain_skills(buffer, registry, config, now, &mut result);

    // Phase 3: Mine suggestion acceptance patterns
    discover_suggestion_pattern_skills(buffer, registry, config, now, &mut result);

    // Phase 4: Mine notification response patterns
    discover_notification_response_skills(buffer, registry, config, now, &mut result);

    // Phase 5: Auto-deprecate low-performing skills
    if config.auto_deprecate {
        auto_deprecate_skills(registry, config, &mut result);
    }

    // Phase 6: Prune expired candidates
    prune_expired_candidates(registry, config, now, &mut result);

    // Phase 7: Enforce max skills limit
    enforce_max_skills(registry, config);

    registry.last_discovery_at = now;
    result.total_skills = registry.len();
    result
}

// ══════════════════════════════════════════════════════════════════════════════
// § 6  Sequence Mining Algorithms
// ══════════════════════════════════════════════════════════════════════════════

/// Mine app transition sequences (A→B→C patterns).
///
/// Scans the event buffer for AppOpened/AppSequence events and finds
/// repeated multi-step sequences within the configured gap threshold.
fn discover_app_sequence_skills(
    buffer: &EventBuffer,
    registry: &mut SkillRegistry,
    config: &SkillConfig,
    now: f64,
    result: &mut DiscoveryResult,
) {
    // Extract app transition chains from recent events
    let chains = extract_app_chains(
        buffer,
        config.max_sequence_gap_ms,
        config.max_steps_per_skill,
    );

    // Count occurrences of each chain
    let mut chain_counts: HashMap<Vec<u16>, u32> = HashMap::new();
    let mut chain_times: HashMap<Vec<u16>, Vec<f64>> = HashMap::new();
    for (chain, timestamp) in &chains {
        if chain.len() >= 2 {
            *chain_counts.entry(chain.clone()).or_insert(0) += 1;
            chain_times
                .entry(chain.clone())
                .or_default()
                .push(*timestamp);
        }
    }

    // Create or reinforce skills for frequent chains
    for (chain, count) in &chain_counts {
        if *count < config.min_observations {
            continue;
        }

        let dedup_key = format!(
            "app_seq:{}",
            chain
                .iter()
                .map(|id| id.to_string())
                .collect::<Vec<_>>()
                .join("")
        );

        if let Some(skill) = registry.find_mut(&dedup_key) {
            skill.observe(now);
            result.reinforced.push(dedup_key);
        } else {
            // Build steps
            let steps: Vec<SkillStep> = chain
                .iter()
                .enumerate()
                .map(|(i, &app_id)| {
                    SkillStep {
                        ordinal: i as u16,
                        action_kind: "app_open".to_string(),
                        app_id: Some(app_id),
                        tool_name: None,
                        expected_duration_ms: 0, // Unknown from app opens alone
                        optional: false,
                    }
                })
                .collect();

            // Infer trigger context from observation timestamps
            let trigger = infer_trigger_from_timestamps(
                chain_times.get(chain).unwrap_or(&Vec::new()),
                Some(chain[0]),
            );

            let description = format!(
                "App workflow: {}",
                chain
                    .iter()
                    .map(|id| format!("app#{}", id))
                    .collect::<Vec<_>>()
                    .join("")
            );

            let skill = LearnedSkill::new(
                description,
                SkillOrigin::AppSequence,
                dedup_key.clone(),
                steps,
                trigger,
                *count,
                now,
            );

            registry.skills.insert(dedup_key.clone(), skill);
            registry.total_discovered += 1;
            result.new_skills.push(dedup_key);
        }
    }
}

/// Mine tool call chain patterns (tool_A → tool_B → tool_C).
fn discover_tool_chain_skills(
    buffer: &EventBuffer,
    registry: &mut SkillRegistry,
    config: &SkillConfig,
    now: f64,
    result: &mut DiscoveryResult,
) {
    let chains = extract_tool_chains(
        buffer,
        config.max_sequence_gap_ms,
        config.max_steps_per_skill,
    );

    let mut chain_counts: HashMap<Vec<String>, u32> = HashMap::new();
    let mut chain_times: HashMap<Vec<String>, Vec<f64>> = HashMap::new();
    for (chain, timestamp) in &chains {
        if chain.len() >= 2 {
            *chain_counts.entry(chain.clone()).or_insert(0) += 1;
            chain_times
                .entry(chain.clone())
                .or_default()
                .push(*timestamp);
        }
    }

    for (chain, count) in &chain_counts {
        if *count < config.min_observations {
            continue;
        }

        let dedup_key = format!("tool_chain:{}", chain.join(""));

        if let Some(skill) = registry.find_mut(&dedup_key) {
            skill.observe(now);
            result.reinforced.push(dedup_key);
        } else {
            let steps: Vec<SkillStep> = chain
                .iter()
                .enumerate()
                .map(|(i, tool)| SkillStep {
                    ordinal: i as u16,
                    action_kind: "tool_call".to_string(),
                    app_id: None,
                    tool_name: Some(tool.clone()),
                    expected_duration_ms: 0,
                    optional: false,
                })
                .collect();

            let trigger =
                infer_trigger_from_timestamps(chain_times.get(chain).unwrap_or(&Vec::new()), None);

            let description = format!("Tool chain: {}", chain.join(""));

            let skill = LearnedSkill::new(
                description,
                SkillOrigin::ToolChain,
                dedup_key.clone(),
                steps,
                trigger,
                *count,
                now,
            );

            registry.skills.insert(dedup_key.clone(), skill);
            registry.total_discovered += 1;
            result.new_skills.push(dedup_key);
        }
    }
}

/// Mine suggestion acceptance patterns.
///
/// Detects when the same action_kind is consistently accepted,
/// suggesting the system can proactively take that action.
fn discover_suggestion_pattern_skills(
    buffer: &EventBuffer,
    registry: &mut SkillRegistry,
    config: &SkillConfig,
    now: f64,
    result: &mut DiscoveryResult,
) {
    // Count accepts and rejects per action_kind
    let mut accept_counts: HashMap<String, u32> = HashMap::new();
    let mut reject_counts: HashMap<String, u32> = HashMap::new();
    let mut accept_times: HashMap<String, Vec<f64>> = HashMap::new();

    for event in buffer.recent(buffer.len()) {
        match &event.data {
            SystemEventData::SuggestionAccepted { action_kind, .. } => {
                *accept_counts.entry(action_kind.clone()).or_insert(0) += 1;
                accept_times
                    .entry(action_kind.clone())
                    .or_default()
                    .push(event.timestamp);
            }
            SystemEventData::SuggestionRejected { action_kind, .. } => {
                *reject_counts.entry(action_kind.clone()).or_insert(0) += 1;
            }
            _ => {}
        }
    }

    for (action_kind, accepts) in &accept_counts {
        let rejects = reject_counts.get(action_kind).copied().unwrap_or(0);
        let total = accepts + rejects;
        if total < config.min_observations {
            continue;
        }

        let acceptance_rate = *accepts as f64 / total as f64;
        // Only create skill for highly accepted suggestion types
        if acceptance_rate < 0.75 {
            continue;
        }

        let dedup_key = format!("suggestion_pattern:{}", action_kind);

        if let Some(skill) = registry.find_mut(&dedup_key) {
            skill.observe(now);
            result.reinforced.push(dedup_key);
        } else {
            let steps = vec![SkillStep {
                ordinal: 0,
                action_kind: action_kind.clone(),
                app_id: None,
                tool_name: None,
                expected_duration_ms: 0,
                optional: false,
            }];

            let trigger = infer_trigger_from_timestamps(
                accept_times.get(action_kind).unwrap_or(&Vec::new()),
                None,
            );

            let description = format!(
                "Auto-action: {} ({}% acceptance rate)",
                action_kind,
                (acceptance_rate * 100.0) as u32,
            );

            let mut skill = LearnedSkill::new(
                description,
                SkillOrigin::SuggestionPattern,
                dedup_key.clone(),
                steps,
                trigger,
                *accepts,
                now,
            );
            // Start with higher confidence since we have accept/reject data
            skill.confidence = 0.3 + acceptance_rate * 0.3;

            registry.skills.insert(dedup_key.clone(), skill);
            registry.total_discovered += 1;
            result.new_skills.push(dedup_key);
        }
    }
}

/// Mine notification → action response patterns.
///
/// Detects when a specific notification type consistently triggers
/// the same user action, suggesting the system can automate the response.
fn discover_notification_response_skills(
    buffer: &EventBuffer,
    registry: &mut SkillRegistry,
    config: &SkillConfig,
    now: f64,
    result: &mut DiscoveryResult,
) {
    // Build notification_type → action_taken frequency map
    let mut response_counts: HashMap<(String, String), u32> = HashMap::new();
    let mut response_times: HashMap<(String, String), Vec<f64>> = HashMap::new();

    for event in buffer.recent(buffer.len()) {
        if let SystemEventData::NotificationActedOn {
            notif_type,
            action_taken,
        } = &event.data
        {
            let key = (notif_type.clone(), action_taken.clone());
            *response_counts.entry(key.clone()).or_insert(0) += 1;
            response_times.entry(key).or_default().push(event.timestamp);
        }
    }

    for ((notif_type, action_taken), count) in &response_counts {
        if *count < config.min_observations {
            continue;
        }

        let dedup_key = format!("notif_response:{}{}", notif_type, action_taken);

        if let Some(skill) = registry.find_mut(&dedup_key) {
            skill.observe(now);
            result.reinforced.push(dedup_key);
        } else {
            let steps = vec![
                SkillStep {
                    ordinal: 0,
                    action_kind: format!("receive_{}", notif_type),
                    app_id: None,
                    tool_name: None,
                    expected_duration_ms: 0,
                    optional: false,
                },
                SkillStep {
                    ordinal: 1,
                    action_kind: action_taken.clone(),
                    app_id: None,
                    tool_name: None,
                    expected_duration_ms: 0,
                    optional: false,
                },
            ];

            let key = (notif_type.clone(), action_taken.clone());
            let trigger = infer_trigger_from_timestamps(
                response_times.get(&key).unwrap_or(&Vec::new()),
                None,
            );

            let description = format!(
                "Auto-respond: {} notification → {}",
                notif_type, action_taken
            );

            let skill = LearnedSkill::new(
                description,
                SkillOrigin::NotificationResponse,
                dedup_key.clone(),
                steps,
                trigger,
                *count,
                now,
            );

            registry.skills.insert(dedup_key.clone(), skill);
            registry.total_discovered += 1;
            result.new_skills.push(dedup_key);
        }
    }
}

// ══════════════════════════════════════════════════════════════════════════════
// § 7  Event Chain Extraction
// ══════════════════════════════════════════════════════════════════════════════

/// Extract app transition chains from the event buffer.
///
/// Returns (chain_of_app_ids, first_timestamp_of_chain).
fn extract_app_chains(
    buffer: &EventBuffer,
    max_gap_ms: u64,
    max_steps: usize,
) -> Vec<(Vec<u16>, f64)> {
    let mut events = buffer.recent(buffer.len());
    events.reverse(); // recent() returns newest-first; we need chronological order
    let mut chains: Vec<(Vec<u16>, f64)> = Vec::new();
    let mut current_chain: Vec<u16> = Vec::new();
    let mut chain_start: f64 = 0.0;
    let mut last_ts: f64 = 0.0;

    for event in events {
        match &event.data {
            SystemEventData::AppOpened { app_id } => {
                let gap_ms = ((event.timestamp - last_ts) * 1000.0) as u64;
                if !current_chain.is_empty()
                    && (gap_ms > max_gap_ms || current_chain.len() >= max_steps)
                {
                    // End current chain, start new one
                    if current_chain.len() >= 2 {
                        chains.push((current_chain.clone(), chain_start));
                    }
                    current_chain.clear();
                }
                if current_chain.is_empty() {
                    chain_start = event.timestamp;
                }
                // Avoid consecutive duplicates
                if current_chain.last() != Some(app_id) {
                    current_chain.push(*app_id);
                }
                last_ts = event.timestamp;
            }
            SystemEventData::AppSequence {
                from_app, to_app, ..
            } => {
                // Use actual timestamp gap between events to detect chain boundaries
                let inter_event_gap_ms = if last_ts > 0.0 {
                    ((event.timestamp - last_ts) * 1000.0) as u64
                } else {
                    0
                };
                if !current_chain.is_empty()
                    && (inter_event_gap_ms > max_gap_ms || current_chain.len() >= max_steps)
                {
                    if current_chain.len() >= 2 {
                        chains.push((current_chain.clone(), chain_start));
                    }
                    current_chain.clear();
                }
                if current_chain.is_empty() {
                    chain_start = event.timestamp;
                    current_chain.push(*from_app);
                }
                if current_chain.last() != Some(to_app) {
                    current_chain.push(*to_app);
                }
                if current_chain.len() >= max_steps {
                    chains.push((current_chain.clone(), chain_start));
                    current_chain.clear();
                }
                last_ts = event.timestamp;
            }
            _ => {}
        }
    }

    // Don't forget the trailing chain
    if current_chain.len() >= 2 {
        chains.push((current_chain, chain_start));
    }

    chains
}

/// Extract tool call chains from the event buffer.
///
/// Returns (chain_of_tool_names, first_timestamp_of_chain).
fn extract_tool_chains(
    buffer: &EventBuffer,
    max_gap_ms: u64,
    max_steps: usize,
) -> Vec<(Vec<String>, f64)> {
    let mut events = buffer.recent(buffer.len());
    events.reverse(); // recent() returns newest-first; we need chronological order
    let mut chains: Vec<(Vec<String>, f64)> = Vec::new();
    let mut current_chain: Vec<String> = Vec::new();
    let mut chain_start: f64 = 0.0;
    let mut last_ts: f64 = 0.0;

    for event in events {
        if let SystemEventData::ToolCallCompleted {
            tool_name, success, ..
        } = &event.data
        {
            let gap_ms = ((event.timestamp - last_ts) * 1000.0) as u64;
            if !current_chain.is_empty()
                && (gap_ms > max_gap_ms || current_chain.len() >= max_steps)
            {
                if current_chain.len() >= 2 {
                    chains.push((current_chain.clone(), chain_start));
                }
                current_chain.clear();
            }
            if current_chain.is_empty() {
                chain_start = event.timestamp;
            }
            // Only include successful tool calls in chains
            if *success {
                current_chain.push(tool_name.clone());
            } else {
                // Failed tool call breaks the chain
                if current_chain.len() >= 2 {
                    chains.push((current_chain.clone(), chain_start));
                }
                current_chain.clear();
            }
            last_ts = event.timestamp;
        }
    }

    if current_chain.len() >= 2 {
        chains.push((current_chain, chain_start));
    }

    chains
}

// ══════════════════════════════════════════════════════════════════════════════
// § 8  Trigger Inference
// ══════════════════════════════════════════════════════════════════════════════

/// Infer trigger context from observation timestamps and optional initiating app.
///
/// Uses statistical analysis of when the pattern was observed to determine
/// time-of-day and day-of-week preferences.
fn infer_trigger_from_timestamps(timestamps: &[f64], initiating_app: Option<u16>) -> SkillTrigger {
    let mut trigger = SkillTrigger::new();
    trigger.initiating_app_id = initiating_app;

    if timestamps.is_empty() {
        return trigger;
    }

    // Extract hours and days from timestamps
    let mut hour_counts = [0u32; 24];
    let mut day_counts = [0u32; 7];

    for &ts in timestamps {
        let secs = ts as u64;
        let hour = ((secs % 86400) / 3600) as u8;
        let day = ((secs / 86400 + 3) % 7) as u8; // Unix epoch was Thursday
        hour_counts[hour as usize] += 1;
        day_counts[day as usize] += 1;
    }

    // Find peak hours (within 2 standard deviations of max)
    let total_obs = timestamps.len() as f64;
    let uniform_rate = total_obs / 24.0;

    for (hour, &count) in hour_counts.iter().enumerate() {
        // Hour is a peak if it has significantly more observations than uniform
        if count as f64 > uniform_rate * 2.0 && count >= 2 {
            trigger.time_bins.push(hour as u8);
        }
    }

    // Find preferred days (significantly above uniform rate)
    let day_uniform = total_obs / 7.0;
    for (day, &count) in day_counts.iter().enumerate() {
        if count as f64 > day_uniform * 1.5 && count >= 2 {
            trigger.day_of_week.push(day as u8);
        }
    }

    trigger
}

// ══════════════════════════════════════════════════════════════════════════════
// § 9  Lifecycle Management
// ══════════════════════════════════════════════════════════════════════════════

/// Auto-deprecate skills with persistently low acceptance rates.
fn auto_deprecate_skills(
    registry: &mut SkillRegistry,
    config: &SkillConfig,
    result: &mut DiscoveryResult,
) {
    let keys: Vec<String> = registry
        .skills
        .iter()
        .filter(|(_, s)| {
            !s.deprecated
                && s.offer_count >= config.auto_deprecate_min_offers
                && s.acceptance_rate() < config.auto_deprecate_threshold
        })
        .map(|(k, _)| k.clone())
        .collect();

    for key in keys {
        if let Some(skill) = registry.skills.get_mut(&key) {
            skill.deprecate();
            registry.total_deprecated += 1;
            result.auto_deprecated.push(key);
        }
    }
}

/// Prune expired candidate skills that never gained enough confidence.
fn prune_expired_candidates(
    registry: &mut SkillRegistry,
    config: &SkillConfig,
    now: f64,
    result: &mut DiscoveryResult,
) {
    let expired: Vec<String> = registry
        .skills
        .iter()
        .filter(|(_, s)| {
            matches!(s.stage, SkillStage::Candidate)
                && (now - s.last_seen_at) > config.candidate_ttl_secs
        })
        .map(|(k, _)| k.clone())
        .collect();

    for key in expired {
        registry.skills.remove(&key);
        result.pruned.push(key);
    }
}

/// Enforce maximum skill count by removing lowest-confidence deprecated/stale skills.
fn enforce_max_skills(registry: &mut SkillRegistry, config: &SkillConfig) {
    if registry.skills.len() <= config.max_skills {
        return;
    }

    // Collect skills sorted by priority (deprecated < stale < candidate < validated)
    let mut ranked: Vec<(String, f64, u8)> = registry
        .skills
        .iter()
        .map(|(k, s)| {
            let priority = match s.stage {
                SkillStage::Deprecated => 0,
                SkillStage::Stale => 1,
                SkillStage::Candidate => 2,
                SkillStage::Validated => 3,
                SkillStage::Reliable => 4,
                SkillStage::Promoted => 5,
            };
            (k.clone(), s.confidence, priority)
        })
        .collect();

    // Sort by priority ascending, then confidence ascending (remove lowest first)
    ranked.sort_by(|a, b| a.2.cmp(&b.2).then(a.1.total_cmp(&b.1)));

    let to_remove = registry.skills.len() - config.max_skills;
    for (key, _, _) in ranked.into_iter().take(to_remove) {
        registry.skills.remove(&key);
    }
}

// ══════════════════════════════════════════════════════════════════════════════
// § 10  Skill Matching — Find Relevant Skills for Current Context
// ══════════════════════════════════════════════════════════════════════════════

/// A scored skill match for the current context.
#[derive(Debug, Clone)]
pub struct SkillMatch {
    /// The matched skill's dedup key.
    pub dedup_key: String,
    /// The matched skill's ID.
    pub skill_id: SkillId,
    /// How well the current context matches the trigger [0.0, 1.0].
    pub trigger_score: f64,
    /// The skill's confidence.
    pub confidence: f64,
    /// Combined relevance score = trigger_score * confidence.
    pub relevance: f64,
    /// Human-readable description.
    pub description: String,
    /// Number of steps.
    pub step_count: usize,
}

/// Find skills relevant to the current context, ranked by relevance.
///
/// Returns up to `max_results` matches above `min_trigger_score`.
pub fn find_matching_skills(
    registry: &SkillRegistry,
    hour: u8,
    day: u8,
    current_app: Option<u16>,
    recent_transition: Option<(u16, u16)>,
    session_duration_secs: f64,
    was_idle: bool,
    min_trigger_score: f64,
    max_results: usize,
) -> Vec<SkillMatch> {
    let mut matches: Vec<SkillMatch> = registry
        .skills
        .iter()
        .filter(|(_, s)| s.is_offerable())
        .filter_map(|(key, skill)| {
            let trigger_score = skill.trigger.match_score(
                hour,
                day,
                current_app,
                recent_transition,
                session_duration_secs,
                was_idle,
            );
            if trigger_score < min_trigger_score {
                return None;
            }
            let relevance = trigger_score * skill.confidence;
            Some(SkillMatch {
                dedup_key: key.clone(),
                skill_id: skill.id,
                trigger_score,
                confidence: skill.confidence,
                relevance,
                description: skill.description.clone(),
                step_count: skill.step_count(),
            })
        })
        .collect();

    // Sort by relevance descending
    matches.sort_by(|a, b| b.relevance.total_cmp(&a.relevance));
    matches.truncate(max_results);
    matches
}

/// Summary statistics for the skill registry.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SkillSummary {
    pub total: usize,
    pub active: usize,
    pub candidates: usize,
    pub validated: usize,
    pub reliable: usize,
    pub promoted: usize,
    pub stale: usize,
    pub deprecated: usize,
    pub total_discovered: u64,
    pub total_promoted: u64,
    pub total_deprecated: u64,
    pub by_origin: HashMap<String, usize>,
}

/// Generate a summary of the skill registry.
pub fn summarize_skills(registry: &SkillRegistry) -> SkillSummary {
    let mut by_origin: HashMap<String, usize> = HashMap::new();
    let mut candidates = 0usize;
    let mut validated = 0usize;
    let mut reliable = 0usize;
    let mut promoted = 0usize;
    let mut stale = 0usize;
    let mut deprecated = 0usize;

    for skill in registry.skills.values() {
        *by_origin
            .entry(skill.origin.as_str().to_string())
            .or_insert(0) += 1;
        match skill.stage {
            SkillStage::Candidate => candidates += 1,
            SkillStage::Validated => validated += 1,
            SkillStage::Reliable => reliable += 1,
            SkillStage::Promoted => promoted += 1,
            SkillStage::Stale => stale += 1,
            SkillStage::Deprecated => deprecated += 1,
        }
    }

    SkillSummary {
        total: registry.len(),
        active: registry.active_count(),
        candidates,
        validated,
        reliable,
        promoted,
        stale,
        deprecated,
        total_discovered: registry.total_discovered,
        total_promoted: registry.total_promoted,
        total_deprecated: registry.total_deprecated,
        by_origin,
    }
}

// ══════════════════════════════════════════════════════════════════════════════
// § 11  Tests
// ══════════════════════════════════════════════════════════════════════════════

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

    fn ts(offset: f64) -> f64 {
        86400.0 * 100.0 + offset
    }

    fn make_buffer(events: Vec<SystemEvent>) -> EventBuffer {
        let mut buffer = EventBuffer::new(10_000);
        for event in events {
            buffer.push(event);
        }
        buffer
    }

    fn app_open(time: f64, app_id: u16) -> SystemEvent {
        SystemEvent::new(time, SystemEventData::AppOpened { app_id })
    }

    fn app_seq(time: f64, from: u16, to: u16, gap: u64) -> SystemEvent {
        SystemEvent::new(
            time,
            SystemEventData::AppSequence {
                from_app: from,
                to_app: to,
                gap_ms: gap,
            },
        )
    }

    fn tool_call(time: f64, name: &str, success: bool) -> SystemEvent {
        SystemEvent::new(
            time,
            SystemEventData::ToolCallCompleted {
                tool_name: name.to_string(),
                success,
                duration_ms: 100,
            },
        )
    }

    fn suggestion_accept(time: f64, kind: &str) -> SystemEvent {
        SystemEvent::new(
            time,
            SystemEventData::SuggestionAccepted {
                suggestion_id: 1,
                action_kind: kind.to_string(),
                latency_ms: 200,
            },
        )
    }

    fn suggestion_reject(time: f64, kind: &str) -> SystemEvent {
        SystemEvent::new(
            time,
            SystemEventData::SuggestionRejected {
                suggestion_id: 2,
                action_kind: kind.to_string(),
            },
        )
    }

    fn notif_acted(time: f64, notif_type: &str, action: &str) -> SystemEvent {
        SystemEvent::new(
            time,
            SystemEventData::NotificationActedOn {
                notif_type: notif_type.to_string(),
                action_taken: action.to_string(),
            },
        )
    }

    // ── § 1: Basic skill creation ──

    #[test]
    fn test_skill_creation() {
        let skill = LearnedSkill::new(
            "Test skill".to_string(),
            SkillOrigin::AppSequence,
            "test:key".to_string(),
            vec![SkillStep {
                ordinal: 0,
                action_kind: "app_open".to_string(),
                app_id: Some(14),
                tool_name: None,
                expected_duration_ms: 0,
                optional: false,
            }],
            SkillTrigger::new(),
            3,
            ts(0.0),
        );

        assert_eq!(skill.stage, SkillStage::Candidate);
        assert!((skill.confidence - 0.3).abs() < 0.01);
        assert_eq!(skill.observation_count, 3);
        assert!(!skill.is_offerable());
    }

    #[test]
    fn test_skill_confidence_lifecycle() {
        let mut skill = LearnedSkill::new(
            "Test".to_string(),
            SkillOrigin::ToolChain,
            "test:lifecycle".to_string(),
            vec![],
            SkillTrigger::new(),
            1,
            ts(0.0),
        );

        // Repeated observations increase confidence
        for i in 1..30 {
            skill.observe(ts(i as f64));
        }
        assert!(
            skill.confidence > 0.5,
            "Should gain confidence: {}",
            skill.confidence
        );

        // Acceptances boost faster
        for i in 30..40 {
            skill.record_acceptance(ts(i as f64));
        }
        assert!(
            skill.confidence > 0.7,
            "Should be reliable: {}",
            skill.confidence
        );

        // Failures reduce confidence
        for i in 40..50 {
            skill.record_failure(ts(i as f64));
        }
        assert!(
            skill.confidence < 0.7,
            "Failures should reduce confidence: {}",
            skill.confidence
        );
    }

    #[test]
    fn test_skill_success_rate() {
        let mut skill = LearnedSkill::new(
            "Test".to_string(),
            SkillOrigin::AppSequence,
            "test:rate".to_string(),
            vec![],
            SkillTrigger::new(),
            1,
            ts(0.0),
        );

        // Neutral prior when no data
        assert!((skill.success_rate() - 0.5).abs() < 0.01);

        skill.success_count = 7;
        skill.failure_count = 3;
        assert!((skill.success_rate() - 0.7).abs() < 0.01);
    }

    #[test]
    fn test_skill_deprecation() {
        let mut skill = LearnedSkill::new(
            "Test".to_string(),
            SkillOrigin::AppSequence,
            "test:deprecate".to_string(),
            vec![],
            SkillTrigger::new(),
            1,
            ts(0.0),
        );

        skill.confidence = 0.8;
        skill.stage = SkillStage::Reliable;
        assert!(skill.is_offerable());

        skill.deprecate();
        assert_eq!(skill.stage, SkillStage::Deprecated);
        assert!(!skill.is_offerable());
    }

    #[test]
    fn test_skill_promotability() {
        let mut skill = LearnedSkill::new(
            "Test".to_string(),
            SkillOrigin::AppSequence,
            "test:promote".to_string(),
            vec![],
            SkillTrigger::new(),
            12,
            ts(0.0),
        );

        skill.confidence = 0.95;
        skill.success_count = 10;
        skill.failure_count = 1;
        assert!(skill.is_promotable());

        // Already promoted → not promotable
        skill.promoted_schema_id = Some(42);
        assert!(!skill.is_promotable());
    }

    // ── § 2: Trigger matching ──

    #[test]
    fn test_trigger_universal() {
        let trigger = SkillTrigger::new();
        let score = trigger.match_score(12, 3, None, None, 0.0, false);
        assert!(
            (score - 1.0).abs() < 0.01,
            "Universal trigger should always match"
        );
    }

    #[test]
    fn test_trigger_specificity() {
        let mut trigger = SkillTrigger::new();
        assert_eq!(trigger.specificity(), 0);

        trigger.time_bins = vec![9, 10, 11];
        assert_eq!(trigger.specificity(), 1);

        trigger.initiating_app_id = Some(14);
        assert_eq!(trigger.specificity(), 2);
    }

    #[test]
    fn test_trigger_matching() {
        let trigger = SkillTrigger {
            time_bins: vec![9, 10, 11],
            initiating_app_id: Some(14),
            preceding_transition: None,
            day_of_week: vec![0, 1, 2, 3, 4], // Weekdays
            min_session_duration_secs: None,
            preceded_by_idle: None,
        };

        // Perfect match
        let score = trigger.match_score(10, 2, Some(14), None, 0.0, false);
        assert!((score - 1.0).abs() < 0.01, "All conditions met: {}", score);

        // Partial match (wrong hour)
        let score = trigger.match_score(22, 2, Some(14), None, 0.0, false);
        assert!((score - 2.0 / 3.0).abs() < 0.01, "2/3 match: {}", score);

        // No match
        let score = trigger.match_score(22, 5, Some(99), None, 0.0, false);
        assert!((score).abs() < 0.01, "0/3 match: {}", score);
    }

    // ── § 3: App sequence discovery ──

    #[test]
    fn test_discover_app_sequences() {
        let mut events = Vec::new();

        // Repeat the sequence 14→20→15 three times
        for round in 0..3 {
            let base = round as f64 * 100.0;
            events.push(app_seq(ts(base + 1.0), 14, 20, 2000));
            events.push(app_seq(ts(base + 3.0), 20, 15, 3000));
        }

        let buffer = make_buffer(events);
        let mut registry = SkillRegistry::new();
        let config = SkillConfig::default();

        let result = discover_skills(&buffer, &mut registry, &config, ts(500.0));

        assert!(
            !result.new_skills.is_empty(),
            "Should discover app sequence skills"
        );

        // Verify the skill was created
        let key = result.new_skills.iter().find(|k| k.starts_with("app_seq:"));
        assert!(key.is_some(), "Should have app_seq skill");

        let skill = registry.find(key.unwrap()).unwrap();
        assert_eq!(skill.origin, SkillOrigin::AppSequence);
        assert!(skill.steps.len() >= 2);
    }

    #[test]
    fn test_discover_reinforces_existing() {
        let mut events = Vec::new();
        for round in 0..5 {
            let base = round as f64 * 100.0;
            events.push(app_seq(ts(base + 1.0), 1, 2, 1000));
            events.push(app_seq(ts(base + 2.0), 2, 3, 1000));
        }

        let buffer = make_buffer(events);
        let mut registry = SkillRegistry::new();
        let config = SkillConfig::default();

        // First run: discover
        let result1 = discover_skills(&buffer, &mut registry, &config, ts(600.0));
        assert!(!result1.new_skills.is_empty());
        let initial_confidence = registry.skills.values().next().unwrap().confidence;

        // Second run: reinforce
        let result2 = discover_skills(&buffer, &mut registry, &config, ts(700.0));
        assert!(!result2.reinforced.is_empty());
        let reinforced_confidence = registry.skills.values().next().unwrap().confidence;

        assert!(
            reinforced_confidence > initial_confidence,
            "Reinforcement should increase confidence"
        );
    }

    // ── § 4: Tool chain discovery ──

    #[test]
    fn test_discover_tool_chains() {
        let mut events = Vec::new();

        // Repeat tool chain: fetch_data → transform → store, 3 times
        for round in 0..3 {
            let base = round as f64 * 100.0;
            events.push(tool_call(ts(base + 1.0), "fetch_data", true));
            events.push(tool_call(ts(base + 2.0), "transform", true));
            events.push(tool_call(ts(base + 3.0), "store", true));
        }

        let buffer = make_buffer(events);
        let mut registry = SkillRegistry::new();
        let config = SkillConfig::default();

        let result = discover_skills(&buffer, &mut registry, &config, ts(500.0));

        let tool_skills: Vec<_> = result
            .new_skills
            .iter()
            .filter(|k| k.starts_with("tool_chain:"))
            .collect();
        assert!(!tool_skills.is_empty(), "Should discover tool chain skills");
    }

    #[test]
    fn test_tool_chain_broken_by_failure() {
        let mut events = Vec::new();

        // Chain with failure in middle (should break into separate chains)
        for round in 0..3 {
            let base = round as f64 * 100.0;
            events.push(tool_call(ts(base + 1.0), "fetch", true));
            events.push(tool_call(ts(base + 2.0), "broken", false)); // breaks chain
            events.push(tool_call(ts(base + 3.0), "store", true));
        }

        let buffer = make_buffer(events);
        let mut registry = SkillRegistry::new();
        let config = SkillConfig::default();

        let result = discover_skills(&buffer, &mut registry, &config, ts(500.0));

        // Should NOT find any 3-step chain because failure breaks it
        for key in &result.new_skills {
            if key.starts_with("tool_chain:") {
                let skill = registry.find(key).unwrap();
                assert!(skill.steps.len() <= 2, "Failure should break chain");
            }
        }
    }

    // ── § 5: Suggestion pattern discovery ──

    #[test]
    fn test_discover_suggestion_patterns() {
        let mut events = Vec::new();

        // 8 accepts, 2 rejects for "remind" → 80% acceptance
        for i in 0..8 {
            events.push(suggestion_accept(ts(i as f64), "remind"));
        }
        for i in 0..2 {
            events.push(suggestion_reject(ts(10.0 + i as f64), "remind"));
        }

        let buffer = make_buffer(events);
        let mut registry = SkillRegistry::new();
        let config = SkillConfig::default();

        let result = discover_skills(&buffer, &mut registry, &config, ts(500.0));

        let pattern_skills: Vec<_> = result
            .new_skills
            .iter()
            .filter(|k| k.starts_with("suggestion_pattern:"))
            .collect();
        assert!(
            !pattern_skills.is_empty(),
            "Should discover suggestion pattern"
        );

        let skill = registry.find("suggestion_pattern:remind").unwrap();
        assert!(
            skill.confidence > 0.3,
            "High acceptance should boost initial confidence"
        );
    }

    #[test]
    fn test_suggestion_pattern_low_acceptance_ignored() {
        let mut events = Vec::new();

        // 2 accepts, 8 rejects for "nag" → 20% acceptance
        for i in 0..2 {
            events.push(suggestion_accept(ts(i as f64), "nag"));
        }
        for i in 0..8 {
            events.push(suggestion_reject(ts(10.0 + i as f64), "nag"));
        }

        let buffer = make_buffer(events);
        let mut registry = SkillRegistry::new();
        let config = SkillConfig::default();

        let result = discover_skills(&buffer, &mut registry, &config, ts(500.0));

        assert!(
            !result
                .new_skills
                .contains(&"suggestion_pattern:nag".to_string()),
            "Low acceptance should not create skill"
        );
    }

    // ── § 6: Notification response discovery ──

    #[test]
    fn test_discover_notification_responses() {
        let mut events = Vec::new();

        // User consistently marks email notifications as "archive"
        for i in 0..5 {
            events.push(notif_acted(ts(i as f64), "email", "archive"));
        }

        let buffer = make_buffer(events);
        let mut registry = SkillRegistry::new();
        let config = SkillConfig::default();

        let result = discover_skills(&buffer, &mut registry, &config, ts(500.0));

        let notif_skills: Vec<_> = result
            .new_skills
            .iter()
            .filter(|k| k.starts_with("notif_response:"))
            .collect();
        assert!(
            !notif_skills.is_empty(),
            "Should discover notification response skill"
        );

        let skill = registry.find("notif_response:email→archive").unwrap();
        assert_eq!(skill.origin, SkillOrigin::NotificationResponse);
        assert_eq!(skill.steps.len(), 2);
    }

    // ── § 7: Auto-deprecation ──

    #[test]
    fn test_auto_deprecation() {
        let mut registry = SkillRegistry::new();
        let config = SkillConfig::default();

        let mut skill = LearnedSkill::new(
            "Bad skill".to_string(),
            SkillOrigin::AppSequence,
            "test:bad".to_string(),
            vec![],
            SkillTrigger::new(),
            10,
            ts(0.0),
        );
        skill.confidence = 0.8;
        skill.stage = SkillStage::Reliable;
        skill.offer_count = 10;
        skill.acceptance_count = 1; // 10% acceptance → below threshold
        registry.skills.insert("test:bad".to_string(), skill);

        let buffer = make_buffer(vec![]);
        let result = discover_skills(&buffer, &mut registry, &config, ts(500.0));

        assert!(
            result.auto_deprecated.contains(&"test:bad".to_string()),
            "Low acceptance should trigger auto-deprecation"
        );
        assert!(registry.find("test:bad").unwrap().deprecated);
    }

    // ── § 8: Candidate pruning ──

    #[test]
    fn test_candidate_pruning() {
        let mut registry = SkillRegistry::new();
        let config = SkillConfig::default();

        let skill = LearnedSkill::new(
            "Old candidate".to_string(),
            SkillOrigin::AppSequence,
            "test:old".to_string(),
            vec![],
            SkillTrigger::new(),
            1,
            ts(0.0),
        );
        registry.skills.insert("test:old".to_string(), skill);

        // Run discovery far in the future
        let buffer = make_buffer(vec![]);
        let future = ts(0.0) + config.candidate_ttl_secs + 1000.0;
        let result = discover_skills(&buffer, &mut registry, &config, future);

        assert!(
            result.pruned.contains(&"test:old".to_string()),
            "Expired candidates should be pruned"
        );
        assert!(registry.find("test:old").is_none());
    }

    // ── § 9: Max skills enforcement ──

    #[test]
    fn test_enforce_max_skills() {
        let mut registry = SkillRegistry::new();
        let mut config = SkillConfig::default();
        config.max_skills = 3;

        // Add 5 skills with varying confidence
        for i in 0..5 {
            let mut skill = LearnedSkill::new(
                format!("Skill {}", i),
                SkillOrigin::AppSequence,
                format!("test:max_{}", i),
                vec![],
                SkillTrigger::new(),
                1,
                ts(0.0),
            );
            skill.confidence = 0.3 + i as f64 * 0.1;
            registry.skills.insert(format!("test:max_{}", i), skill);
        }

        enforce_max_skills(&mut registry, &config);

        assert_eq!(registry.len(), 3, "Should enforce max_skills limit");

        // Highest confidence skills should survive
        assert!(registry.find("test:max_4").is_some());
        assert!(registry.find("test:max_3").is_some());
        assert!(registry.find("test:max_2").is_some());
    }

    // ── § 10: Skill matching ──

    #[test]
    fn test_find_matching_skills() {
        let mut registry = SkillRegistry::new();

        // Reliable skill that matches morning hours
        let mut skill1 = LearnedSkill::new(
            "Morning workflow".to_string(),
            SkillOrigin::AppSequence,
            "test:morning".to_string(),
            vec![SkillStep {
                ordinal: 0,
                action_kind: "app_open".to_string(),
                app_id: Some(14),
                tool_name: None,
                expected_duration_ms: 0,
                optional: false,
            }],
            SkillTrigger {
                time_bins: vec![8, 9, 10],
                initiating_app_id: Some(14),
                preceding_transition: None,
                day_of_week: vec![],
                min_session_duration_secs: None,
                preceded_by_idle: None,
            },
            10,
            ts(0.0),
        );
        skill1.confidence = 0.85;
        skill1.stage = SkillStage::Reliable;

        // Reliable skill for evening
        let mut skill2 = LearnedSkill::new(
            "Evening routine".to_string(),
            SkillOrigin::AppSequence,
            "test:evening".to_string(),
            vec![],
            SkillTrigger {
                time_bins: vec![20, 21, 22],
                initiating_app_id: None,
                preceding_transition: None,
                day_of_week: vec![],
                min_session_duration_secs: None,
                preceded_by_idle: None,
            },
            10,
            ts(0.0),
        );
        skill2.confidence = 0.75;
        skill2.stage = SkillStage::Reliable;

        registry.skills.insert("test:morning".to_string(), skill1);
        registry.skills.insert("test:evening".to_string(), skill2);

        // Query in the morning with app 14 open
        let matches = find_matching_skills(&registry, 9, 2, Some(14), None, 3600.0, false, 0.3, 10);

        assert!(!matches.is_empty());
        assert_eq!(
            matches[0].dedup_key, "test:morning",
            "Morning skill should rank highest"
        );
        assert!(matches[0].relevance > 0.5);
    }

    #[test]
    fn test_find_matching_excludes_non_offerable() {
        let mut registry = SkillRegistry::new();

        // Candidate skill (not offerable)
        let skill = LearnedSkill::new(
            "Candidate".to_string(),
            SkillOrigin::AppSequence,
            "test:candidate".to_string(),
            vec![],
            SkillTrigger::new(),
            1,
            ts(0.0),
        );
        registry.skills.insert("test:candidate".to_string(), skill);

        let matches = find_matching_skills(&registry, 12, 3, None, None, 0.0, false, 0.0, 10);

        assert!(matches.is_empty(), "Candidates should not be matched");
    }

    // ── § 11: Summary ──

    #[test]
    fn test_skill_summary() {
        let mut registry = SkillRegistry::new();
        registry.total_discovered = 5;
        registry.total_promoted = 1;
        registry.total_deprecated = 1;

        let mut s1 = LearnedSkill::new(
            "A".to_string(),
            SkillOrigin::AppSequence,
            "a".to_string(),
            vec![],
            SkillTrigger::new(),
            1,
            ts(0.0),
        );
        s1.stage = SkillStage::Reliable;
        registry.skills.insert("a".to_string(), s1);

        let mut s2 = LearnedSkill::new(
            "B".to_string(),
            SkillOrigin::ToolChain,
            "b".to_string(),
            vec![],
            SkillTrigger::new(),
            1,
            ts(0.0),
        );
        s2.stage = SkillStage::Candidate;
        registry.skills.insert("b".to_string(), s2);

        let mut s3 = LearnedSkill::new(
            "C".to_string(),
            SkillOrigin::AppSequence,
            "c".to_string(),
            vec![],
            SkillTrigger::new(),
            1,
            ts(0.0),
        );
        s3.deprecated = true;
        s3.stage = SkillStage::Deprecated;
        registry.skills.insert("c".to_string(), s3);

        let summary = summarize_skills(&registry);
        assert_eq!(summary.total, 3);
        assert_eq!(summary.active, 2);
        assert_eq!(summary.reliable, 1);
        assert_eq!(summary.candidates, 1);
        assert_eq!(summary.deprecated, 1);
        assert_eq!(summary.by_origin.get("app_sequence"), Some(&2));
        assert_eq!(summary.by_origin.get("tool_chain"), Some(&1));
    }

    // ── § 12: Registry operations ──

    #[test]
    fn test_registry_queries() {
        let mut registry = SkillRegistry::new();

        let mut s1 = LearnedSkill::new(
            "A".to_string(),
            SkillOrigin::AppSequence,
            "a".to_string(),
            vec![],
            SkillTrigger::new(),
            5,
            ts(0.0),
        );
        s1.confidence = 0.8;
        s1.stage = SkillStage::Reliable;
        registry.skills.insert("a".to_string(), s1);

        let s2 = LearnedSkill::new(
            "B".to_string(),
            SkillOrigin::ToolChain,
            "b".to_string(),
            vec![],
            SkillTrigger::new(),
            1,
            ts(0.0),
        );
        registry.skills.insert("b".to_string(), s2);

        assert_eq!(registry.active_count(), 2);
        assert_eq!(registry.offerable().len(), 1);
        assert_eq!(registry.by_origin(SkillOrigin::AppSequence).len(), 1);
        assert_eq!(registry.by_origin(SkillOrigin::ToolChain).len(), 1);
        assert!(registry.find("a").is_some());
        assert!(registry.find("nonexistent").is_none());
    }

    // ── § 13: Hash stability ──

    #[test]
    fn test_dedup_key_hash_stable() {
        let h1 = hash_dedup_key("app_seq:14→20→15");
        let h2 = hash_dedup_key("app_seq:14→20→15");
        let h3 = hash_dedup_key("app_seq:14→20→16");

        assert_eq!(h1, h2, "Same key should produce same hash");
        assert_ne!(h1, h3, "Different keys should produce different hashes");
    }

    // ── § 14: Trigger inference ──

    #[test]
    fn test_trigger_inference() {
        // Events clustered around 9am (hour 9 = second 32400)
        let timestamps: Vec<f64> = (0..10)
            .map(|i| {
                86400.0 * (100 + i) as f64 + 32400.0 // 9:00 each day
            })
            .collect();

        let trigger = infer_trigger_from_timestamps(&timestamps, Some(14));

        assert!(
            trigger.time_bins.contains(&9),
            "Should detect 9am peak: {:?}",
            trigger.time_bins
        );
        assert_eq!(trigger.initiating_app_id, Some(14));
    }

    #[test]
    fn test_trigger_empty_timestamps() {
        let trigger = infer_trigger_from_timestamps(&[], None);
        assert_eq!(trigger.specificity(), 0);
    }

    // ── § 15: Edge cases ──

    #[test]
    fn test_empty_buffer_discovery() {
        let buffer = make_buffer(vec![]);
        let mut registry = SkillRegistry::new();
        let config = SkillConfig::default();

        let result = discover_skills(&buffer, &mut registry, &config, ts(0.0));

        assert!(result.new_skills.is_empty());
        assert!(result.reinforced.is_empty());
        assert_eq!(result.total_skills, 0);
    }

    #[test]
    fn test_below_minimum_observations() {
        let mut events = Vec::new();
        // Only 2 occurrences (below default min of 3)
        for round in 0..2 {
            let base = round as f64 * 100.0;
            events.push(app_seq(ts(base + 1.0), 14, 20, 2000));
        }

        let buffer = make_buffer(events);
        let mut registry = SkillRegistry::new();
        let config = SkillConfig::default();

        let result = discover_skills(&buffer, &mut registry, &config, ts(500.0));
        assert!(
            result.new_skills.is_empty(),
            "Below min_observations should not create skill"
        );
    }

    #[test]
    fn test_skill_stage_from_confidence() {
        assert_eq!(
            SkillStage::from_confidence(0.3, 0.0, false),
            SkillStage::Candidate
        );
        assert_eq!(
            SkillStage::from_confidence(0.6, 0.0, false),
            SkillStage::Validated
        );
        assert_eq!(
            SkillStage::from_confidence(0.8, 0.0, false),
            SkillStage::Reliable
        );
        assert_eq!(
            SkillStage::from_confidence(0.95, 0.0, false),
            SkillStage::Promoted
        );
        assert_eq!(
            SkillStage::from_confidence(0.8, 31.0 * 86400.0, false),
            SkillStage::Stale
        );
        assert_eq!(
            SkillStage::from_confidence(0.8, 0.0, true),
            SkillStage::Deprecated
        );
    }
}