clawft-kernel 0.6.0

WeftOS kernel: boot sequence, process table, service registry, and health subsystem
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
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
//! WeaverEngine: ECC-powered codebase modeling service (K3c-G1).
//!
//! The WeaverEngine is a [`SystemService`] that drives the ECC cognitive
//! substrate to model real-world data sources (git logs, file trees, CI
//! pipelines, documentation). It manages [`ModelingSession`]s, evaluates
//! confidence via the causal graph, and records its own decisions in the
//! Meta-Loom for self-improvement tracking.
//!
//! This module requires the `ecc` feature.

use std::collections::{HashMap, HashSet, VecDeque};
use std::fmt;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, RwLock};
use std::time::{Duration, Instant, SystemTime};

use async_trait::async_trait;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use tracing::{debug, info};

use crate::causal::{CausalEdgeType, CausalGraph};
use crate::embedding::{EmbeddingProvider, MockEmbeddingProvider};
use crate::health::HealthStatus;
use crate::hnsw_service::HnswService;
use crate::impulse::{ImpulseQueue, ImpulseType};
use crate::service::{ServiceType, SystemService};

// ---------------------------------------------------------------------------
// WeaverCommand (IPC messages from CLI / agents)
// ---------------------------------------------------------------------------

/// Commands sent to the WeaverEngine via IPC.
#[non_exhaustive]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum WeaverCommand {
    /// Start a new modeling session.
    SessionStart {
        domain: String,
        git_path: Option<PathBuf>,
        context: Option<String>,
        goal: Option<String>,
    },
    /// Resume an existing session.
    SessionResume { domain: String },
    /// Stop a session.
    SessionStop { domain: String },
    /// Watch session progress (streaming).
    SessionWatch { domain: String },
    /// Add a data source to a session.
    SourceAdd {
        domain: String,
        source_type: String,
        root: Option<PathBuf>,
        watch: bool,
    },
    /// List sources for a session.
    SourceList { domain: String },
    /// Query confidence.
    Confidence {
        domain: String,
        edge: Option<String>,
        verbose: bool,
    },
    /// Export model.
    Export {
        domain: String,
        min_confidence: f64,
        output: PathBuf,
    },
    /// Import model.
    Import {
        domain: String,
        input: PathBuf,
    },
    /// Query meta-loom status.
    MetaStatus { domain: String },
    /// List learned strategies.
    MetaStrategies,
    /// Export knowledge base.
    MetaExportKb { output: PathBuf },
    /// Stitch two domains.
    Stitch {
        source: String,
        target: String,
        output: String,
    },
}

// ---------------------------------------------------------------------------
// WeaverResponse
// ---------------------------------------------------------------------------

/// Responses from the WeaverEngine to CLI / agents.
#[non_exhaustive]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum WeaverResponse {
    /// Session started successfully.
    SessionStarted { domain: String, session_id: String },
    /// Session stopped.
    SessionStopped { domain: String },
    /// Session resumed.
    SessionResumed { domain: String },
    /// Confidence report.
    ConfidenceReport(ConfidenceReport),
    /// Source added.
    SourceAdded { domain: String, source_type: String },
    /// Sources listed.
    Sources(Vec<String>),
    /// Model exported.
    Exported { path: PathBuf, edges: usize },
    /// Model imported.
    Imported { domain: String },
    /// Learned strategies.
    Strategies(Vec<StrategyPattern>),
    /// Knowledge base exported.
    KbExported { path: PathBuf },
    /// Error.
    Error(String),
}

// ---------------------------------------------------------------------------
// DataSource
// ---------------------------------------------------------------------------

/// A data source that can be ingested by the WeaverEngine.
#[non_exhaustive]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum DataSource {
    /// Git commit history.
    GitLog { path: PathBuf },
    /// File system tree.
    FileTree { root: PathBuf },
    /// CI pipeline events.
    CiPipeline { url: String },
    /// Issue tracker feed.
    IssueTracker { url: String },
    /// Documentation corpus.
    Documentation { root: PathBuf },
    /// SPARC planning artifacts.
    SparcPlan { root: PathBuf },
    /// User-defined stream.
    CustomStream { name: String },
}

impl DataSource {
    /// Human-readable type name.
    pub fn type_name(&self) -> &str {
        match self {
            Self::GitLog { .. } => "git_log",
            Self::FileTree { .. } => "file_tree",
            Self::CiPipeline { .. } => "ci_pipeline",
            Self::IssueTracker { .. } => "issue_tracker",
            Self::Documentation { .. } => "documentation",
            Self::SparcPlan { .. } => "sparc_plan",
            Self::CustomStream { .. } => "custom_stream",
        }
    }
}

// ---------------------------------------------------------------------------
// ModelingSession
// ---------------------------------------------------------------------------

/// An active or suspended modeling session for a single domain.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ModelingSession {
    /// Unique session identifier.
    pub id: String,
    /// Domain name (e.g., project name).
    pub domain: String,
    /// When the session was started.
    pub started_at: DateTime<Utc>,
    /// Current overall confidence (0.0 .. 1.0).
    pub confidence: f64,
    /// Identified confidence gaps.
    pub gaps: Vec<ConfidenceGap>,
    /// Data sources that have been ingested.
    pub sources_ingested: Vec<String>,
    /// Number of cognitive ticks processed.
    pub tick_count: u64,
    /// Remaining budget for this session.
    pub budget_remaining_ms: u64,
    /// Whether the session is currently active.
    pub active: bool,
    /// Arbitrary metadata.
    pub metadata: HashMap<String, serde_json::Value>,
}

// ---------------------------------------------------------------------------
// ConfidenceGap / ConfidenceReport
// ---------------------------------------------------------------------------

/// A gap in the model's confidence for a specific domain area.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConfidenceGap {
    /// Area name.
    pub domain: String,
    /// Current confidence level.
    pub current_confidence: f64,
    /// Target confidence level.
    pub target_confidence: f64,
    /// Suggested sources to improve confidence.
    pub suggested_sources: Vec<String>,
}

/// Full confidence report for a modeling session.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConfidenceReport {
    /// Overall confidence.
    pub overall: f64,
    /// Per-domain gap analysis.
    pub gaps: Vec<ConfidenceGap>,
    /// Modeling suggestions.
    pub suggestions: Vec<ModelingSuggestion>,
}

/// Suggestions for improving model quality.
#[non_exhaustive]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ModelingSuggestion {
    /// Add a new data source.
    AddSource { source_type: String, reason: String },
    /// Refine an edge type relationship.
    RefineEdgeType { from: String, to: String },
    /// Split a category into subcategories.
    SplitCategory { category: String },
    /// Increase observation window.
    ExtendObservation { domain: String },
}

// ---------------------------------------------------------------------------
// ExportedModel (K3c-G4)
// ---------------------------------------------------------------------------

/// Serialized model for edge deployment or offline analysis.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExportedModel {
    /// Schema version.
    pub version: String,
    /// Domain this model was built for.
    pub domain: String,
    /// When the export was created.
    pub exported_at: DateTime<Utc>,
    /// Overall confidence at export time.
    pub confidence: f64,
    /// Node type specifications.
    pub node_types: Vec<NodeTypeSpec>,
    /// Edge type specifications.
    pub edge_types: Vec<EdgeTypeSpec>,
    /// Exported causal nodes.
    pub causal_nodes: Vec<ExportedCausalNode>,
    /// Exported causal edges.
    pub causal_edges: Vec<ExportedCausalEdge>,
    /// Arbitrary metadata.
    pub metadata: HashMap<String, serde_json::Value>,
}

/// Node type specification in an exported model.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NodeTypeSpec {
    /// Type name.
    pub name: String,
    /// Embedding strategy identifier.
    pub embedding_strategy: String,
    /// Vector dimensions.
    pub dimensions: usize,
}

/// Edge type specification in an exported model.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EdgeTypeSpec {
    /// Source node type.
    pub from_type: String,
    /// Target node type.
    pub to_type: String,
    /// Edge type name.
    pub edge_type: String,
    /// Confidence for this edge type.
    pub confidence: f64,
}

/// Exported causal node.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExportedCausalNode {
    /// Node label.
    pub label: String,
    /// Node metadata.
    pub metadata: serde_json::Value,
}

/// Exported causal edge.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExportedCausalEdge {
    /// Source node label.
    pub source_label: String,
    /// Target node label.
    pub target_label: String,
    /// Edge type.
    pub edge_type: String,
    /// Edge weight.
    pub weight: f32,
}

// ---------------------------------------------------------------------------
// MetaLoomEvent (K3c-G5)
// ---------------------------------------------------------------------------

/// Records a Weaver modeling decision in the Meta-Loom.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MetaLoomEvent {
    /// Domain of the active session.
    pub session_domain: String,
    /// Type of modeling decision.
    pub decision_type: MetaDecisionType,
    /// Confidence before the decision.
    pub confidence_before: f64,
    /// Confidence after (filled in by next tick).
    pub confidence_after: Option<f64>,
    /// Human-readable rationale.
    pub rationale: String,
    /// When the decision was made.
    pub timestamp: DateTime<Utc>,
}

/// Classification of meta-loom decisions.
#[non_exhaustive]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum MetaDecisionType {
    /// A new data source was added.
    SourceAdded { source_type: String },
    /// A new edge type relationship was created.
    EdgeTypeCreated {
        from: String,
        to: String,
        edge_type: String,
    },
    /// An edge type was removed.
    EdgeTypeRemoved { from: String, to: String },
    /// Embedding strategy changed for a node type.
    EmbeddingStrategyChanged {
        node_type: String,
        old: String,
        new: String,
    },
    /// Tick interval was adjusted.
    TickIntervalAdjusted { old_ms: u64, new_ms: u64 },
    /// Model version was bumped.
    ModelVersionBumped { from: u32, to: u32 },
    /// A new strategy was learned.
    StrategyLearned { pattern: String },
}

// ---------------------------------------------------------------------------
// StrategyPattern / WeaverKnowledgeBase
// ---------------------------------------------------------------------------

/// A learned modeling strategy from cross-domain experience.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StrategyPattern {
    /// Decision type that led to improvement.
    pub decision_type: String,
    /// Domain context where it was learned.
    pub context: String,
    /// Confidence improvement observed.
    pub improvement: f64,
    /// When the strategy was learned.
    pub timestamp: DateTime<Utc>,
}

/// Cross-domain knowledge base that accumulates successful strategies.
pub struct WeaverKnowledgeBase {
    /// Learned strategies.
    strategies: RwLock<Vec<StrategyPattern>>,
    /// Strategy count.
    strategy_count: AtomicU64,
}

impl Default for WeaverKnowledgeBase {
    fn default() -> Self {
        Self {
            strategies: RwLock::new(Vec::new()),
            strategy_count: AtomicU64::new(0),
        }
    }
}

impl WeaverKnowledgeBase {
    /// Create a new, empty knowledge base.
    pub fn new() -> Self {
        Self::default()
    }

    /// Record a successful strategy.
    pub fn record_strategy(&self, pattern: StrategyPattern) {
        if let Ok(mut strategies) = self.strategies.write() {
            strategies.push(pattern);
            self.strategy_count.fetch_add(1, Ordering::Relaxed);
        }
    }

    /// List all learned strategies.
    pub fn list_strategies(&self) -> Vec<StrategyPattern> {
        self.strategies
            .read()
            .map(|s| s.clone())
            .unwrap_or_default()
    }

    /// Find strategies relevant to a given domain (simple substring match).
    pub fn strategies_for(&self, domain: &str) -> Vec<StrategyPattern> {
        self.strategies
            .read()
            .map(|all| {
                all.iter()
                    .filter(|s| {
                        s.context.contains(domain)
                            || domain.contains(&s.context)
                    })
                    .cloned()
                    .collect()
            })
            .unwrap_or_default()
    }

    /// Export the full knowledge base as JSON.
    pub fn export(&self) -> serde_json::Value {
        serde_json::to_value(self.list_strategies()).unwrap_or_default()
    }

    /// Total number of learned strategies.
    pub fn count(&self) -> u64 {
        self.strategy_count.load(Ordering::Relaxed)
    }
}

// ---------------------------------------------------------------------------
// TickResult
// ---------------------------------------------------------------------------

/// Outcome of a single cognitive tick for the WeaverEngine.
#[non_exhaustive]
#[derive(Debug)]
pub enum TickResult {
    /// No active session; engine is idle.
    Idle,
    /// Budget exhausted before work could be done.
    BudgetExhausted,
    /// Progress was made.
    Progress {
        /// Current overall confidence.
        confidence: f64,
        /// Number of remaining gaps.
        gaps_remaining: usize,
    },
}

// ---------------------------------------------------------------------------
// WeaverError
// ---------------------------------------------------------------------------

/// Errors produced by the WeaverEngine.
#[non_exhaustive]
#[derive(Debug)]
pub enum WeaverError {
    /// I/O error reading a file.
    Io(std::io::Error),
    /// JSON parsing error.
    Json(serde_json::Error),
    /// Domain logic error.
    Domain(String),
}

impl fmt::Display for WeaverError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Io(e) => write!(f, "weaver I/O error: {e}"),
            Self::Json(e) => write!(f, "weaver JSON error: {e}"),
            Self::Domain(msg) => write!(f, "weaver error: {msg}"),
        }
    }
}

impl std::error::Error for WeaverError {}

impl From<std::io::Error> for WeaverError {
    fn from(e: std::io::Error) -> Self {
        Self::Io(e)
    }
}

impl From<serde_json::Error> for WeaverError {
    fn from(e: serde_json::Error) -> Self {
        Self::Json(e)
    }
}

// ---------------------------------------------------------------------------
// IngestResult
// ---------------------------------------------------------------------------

/// Statistics from ingesting a graph file into the WeaverEngine.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IngestResult {
    /// Number of causal graph nodes created.
    pub nodes_added: usize,
    /// Number of causal graph edges created.
    pub edges_added: usize,
    /// Number of HNSW embeddings created.
    pub embeddings_created: usize,
    /// Source identifier (e.g., "git-history", "module-deps").
    pub source: String,
}

// ---------------------------------------------------------------------------
// GitPoller (incremental git change detection)
// ---------------------------------------------------------------------------

/// Incremental git polling state — detects new commits since last check.
pub struct GitPoller {
    /// Repository path.
    repo_path: PathBuf,
    /// Last known commit hash.
    last_known_hash: Option<String>,
    /// Branch to poll.
    branch: String,
    /// Polling enabled flag.
    enabled: bool,
}

impl GitPoller {
    /// Create a new poller for the given repository path and branch.
    pub fn new(repo_path: PathBuf, branch: String) -> Self {
        Self {
            repo_path,
            last_known_hash: None,
            branch,
            enabled: true,
        }
    }

    /// Check for new commits since last poll.
    /// Returns the number of new commits found (0 if none or on error).
    pub fn poll(&mut self) -> usize {
        if !self.enabled {
            return 0;
        }

        let repo_str = self.repo_path.to_str().unwrap_or(".");
        let output = std::process::Command::new("git")
            .args(["-C", repo_str, "rev-parse", "HEAD"])
            .output();

        match output {
            Ok(out) if out.status.success() => {
                let current_hash = String::from_utf8_lossy(&out.stdout).trim().to_string();
                if self.last_known_hash.as_deref() == Some(&current_hash) {
                    return 0;
                }

                let count = if let Some(ref last) = self.last_known_hash {
                    let count_output = std::process::Command::new("git")
                        .args([
                            "-C",
                            repo_str,
                            "rev-list",
                            "--count",
                            &format!("{}..{}", last, current_hash),
                        ])
                        .output();
                    match count_output {
                        Ok(o) if o.status.success() => {
                            String::from_utf8_lossy(&o.stdout)
                                .trim()
                                .parse()
                                .unwrap_or(1)
                        }
                        _ => 1,
                    }
                } else {
                    1 // First poll — at least 1 commit exists
                };

                self.last_known_hash = Some(current_hash);
                count
            }
            _ => 0,
        }
    }

    /// Get the last known commit hash.
    pub fn last_hash(&self) -> Option<&str> {
        self.last_known_hash.as_deref()
    }

    /// Get the branch being polled.
    pub fn branch(&self) -> &str {
        &self.branch
    }

    /// Whether polling is enabled.
    pub fn is_enabled(&self) -> bool {
        self.enabled
    }

    /// Enable or disable polling.
    pub fn set_enabled(&mut self, enabled: bool) {
        self.enabled = enabled;
    }
}

// ---------------------------------------------------------------------------
// FileWatcher (mtime-based change detection)
// ---------------------------------------------------------------------------

/// Simple file change detector using modification timestamps.
///
/// Avoids the `notify` crate dependency by comparing cached mtimes on each
/// poll call. Only watches files that have been explicitly registered.
pub struct FileWatcher {
    /// Watched paths with their last known mtime.
    watched: HashMap<PathBuf, SystemTime>,
    /// Root directory to scan for initial registration.
    root: PathBuf,
    /// File patterns to match (e.g., `"*.rs"`, `"Cargo.toml"`).
    patterns: Vec<String>,
    /// Enabled flag.
    enabled: bool,
}

impl FileWatcher {
    /// Create a new file watcher for the given root and patterns.
    pub fn new(root: PathBuf, patterns: Vec<String>) -> Self {
        Self {
            watched: HashMap::new(),
            root,
            patterns,
            enabled: true,
        }
    }

    /// Scan watched files for mtime changes since last check.
    /// Returns paths of files that changed or were deleted.
    pub fn poll_changes(&mut self) -> Vec<PathBuf> {
        if !self.enabled {
            return vec![];
        }

        let mut changed = Vec::new();
        let entries: Vec<PathBuf> = self.watched.keys().cloned().collect();

        for path in entries {
            if let Ok(metadata) = std::fs::metadata(&path) {
                if let Ok(mtime) = metadata.modified() {
                    if let Some(last_mtime) = self.watched.get(&path) {
                        if mtime > *last_mtime {
                            changed.push(path.clone());
                            self.watched.insert(path, mtime);
                        }
                    }
                }
            } else {
                // File deleted
                changed.push(path.clone());
                self.watched.remove(&path);
            }
        }

        changed
    }

    /// Register a single file to watch.
    pub fn watch(&mut self, path: PathBuf) {
        if let Ok(metadata) = std::fs::metadata(&path) {
            if let Ok(mtime) = metadata.modified() {
                self.watched.insert(path, mtime);
            }
        }
    }

    /// Register all files matching patterns in the root directory (non-recursive).
    pub fn watch_directory(&mut self) {
        if let Ok(entries) = std::fs::read_dir(&self.root) {
            for entry in entries.flatten() {
                let path = entry.path();
                if path.is_file() {
                    let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
                    let matches = self.patterns.iter().any(|p| {
                        if p.starts_with("*.") {
                            name.ends_with(&p[1..])
                        } else {
                            name == p
                        }
                    });
                    if matches {
                        self.watch(path);
                    }
                }
            }
        }
    }

    /// Number of watched files.
    pub fn watched_count(&self) -> usize {
        self.watched.len()
    }

    /// Whether file watching is enabled.
    pub fn is_enabled(&self) -> bool {
        self.enabled
    }

    /// Enable or disable file watching.
    pub fn set_enabled(&mut self, enabled: bool) {
        self.enabled = enabled;
    }
}

// ---------------------------------------------------------------------------
// CognitiveTickResult
// ---------------------------------------------------------------------------

/// Detailed outcome of a single cognitive tick processed by the WeaverEngine.
///
/// Complements the existing [`TickResult`] enum with per-tick metrics for the
/// CognitiveTick integration (git polling, file watching, ingestion progress).
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct CognitiveTickResult {
    /// Which tick number this result corresponds to.
    pub tick_number: u64,
    /// Actual wall-clock time consumed by this tick (ms).
    pub elapsed_ms: u32,
    /// Budget allocated for this tick (ms).
    pub budget_ms: u32,
    /// Number of new git commits detected during this tick.
    pub git_commits_found: usize,
    /// Number of source files that changed since last tick.
    pub files_changed: usize,
    /// Number of pending nodes processed during ingestion phase.
    pub nodes_processed: usize,
    /// Whether the confidence report was recomputed this tick.
    pub confidence_updated: bool,
    /// Whether the tick completed within its budget.
    pub within_budget: bool,
}

// ---------------------------------------------------------------------------
// ConfidenceHistory (Item 1: confidence history tracking)
// ---------------------------------------------------------------------------

/// What triggered a confidence measurement.
#[non_exhaustive]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ConfidenceTrigger {
    /// Every N ticks.
    Periodic,
    /// After a graph file was ingested.
    PostIngestion,
    /// Explicit evaluation request.
    Manual,
    /// After a modeling adjustment.
    StrategyChange,
}

/// A point-in-time confidence snapshot for history tracking.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConfidenceSnapshot {
    /// Timestamp of this measurement.
    pub timestamp: DateTime<Utc>,
    /// Tick number when measured.
    pub tick_number: u64,
    /// Overall confidence score.
    pub confidence: f64,
    /// Number of nodes in the graph.
    pub node_count: usize,
    /// Number of edges in the graph.
    pub edge_count: usize,
    /// Number of gaps identified.
    pub gap_count: usize,
    /// What triggered this measurement.
    pub trigger: ConfidenceTrigger,
}

/// Direction of a confidence trend.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum TrendDirection {
    /// Confidence is improving over time.
    Improving,
    /// Confidence is roughly stable.
    Stable,
    /// Confidence is declining over time.
    Declining,
}

/// Summary of confidence movement over a window of snapshots.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConfidenceTrend {
    /// Overall direction.
    pub direction: TrendDirection,
    /// Change over the window (last - first).
    pub delta: f64,
    /// Average confidence in the window.
    pub avg_confidence: f64,
    /// Number of samples in the window.
    pub samples: usize,
}

/// Ring-buffer of confidence snapshots.
pub struct ConfidenceHistory {
    snapshots: VecDeque<ConfidenceSnapshot>,
    max_entries: usize,
}

impl ConfidenceHistory {
    /// Create a new history with the given capacity.
    pub fn new(max_entries: usize) -> Self {
        Self {
            snapshots: VecDeque::with_capacity(max_entries),
            max_entries,
        }
    }

    /// Record a new snapshot, evicting the oldest if at capacity.
    pub fn record(&mut self, snapshot: ConfidenceSnapshot) {
        if self.snapshots.len() >= self.max_entries {
            self.snapshots.pop_front();
        }
        self.snapshots.push_back(snapshot);
    }

    /// Get the most recent snapshot.
    pub fn latest(&self) -> Option<&ConfidenceSnapshot> {
        self.snapshots.back()
    }

    /// Compute the trend over the last `last_n` snapshots.
    pub fn trend(&self, last_n: usize) -> ConfidenceTrend {
        let n = last_n.min(self.snapshots.len());
        if n == 0 {
            return ConfidenceTrend {
                direction: TrendDirection::Stable,
                delta: 0.0,
                avg_confidence: 0.0,
                samples: 0,
            };
        }

        let start = self.snapshots.len() - n;
        let window: Vec<&ConfidenceSnapshot> =
            self.snapshots.iter().skip(start).collect();

        let sum: f64 = window.iter().map(|s| s.confidence).sum();
        let avg = sum / n as f64;
        let first = window.first().map(|s| s.confidence).unwrap_or(0.0);
        let last = window.last().map(|s| s.confidence).unwrap_or(0.0);
        let delta = last - first;

        let direction = if delta > 0.01 {
            TrendDirection::Improving
        } else if delta < -0.01 {
            TrendDirection::Declining
        } else {
            TrendDirection::Stable
        };

        ConfidenceTrend {
            direction,
            delta,
            avg_confidence: avg,
            samples: n,
        }
    }

    /// Get all snapshots.
    pub fn all(&self) -> &VecDeque<ConfidenceSnapshot> {
        &self.snapshots
    }

    /// Number of recorded snapshots.
    pub fn len(&self) -> usize {
        self.snapshots.len()
    }

    /// Whether the history is empty.
    pub fn is_empty(&self) -> bool {
        self.snapshots.is_empty()
    }
}

// ---------------------------------------------------------------------------
// StrategyTracker (Item 4: strategy effectiveness tracking)
// ---------------------------------------------------------------------------

/// Handle returned by `begin_strategy` to pair with `complete_strategy`.
#[derive(Debug)]
pub struct StrategyHandle {
    /// Strategy name.
    pub name: String,
    /// Description of the change.
    pub description: String,
    /// Confidence at the start of the strategy.
    pub confidence_before: f64,
    /// When the strategy was started.
    pub started_at: DateTime<Utc>,
}

/// A record of a strategy change and its impact on confidence.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StrategyOutcome {
    /// What was changed.
    pub strategy: String,
    /// Description of the change.
    pub description: String,
    /// Confidence before the change.
    pub confidence_before: f64,
    /// Confidence after the change.
    pub confidence_after: f64,
    /// Delta (positive = improvement).
    pub delta: f64,
    /// When the change was made.
    pub timestamp: DateTime<Utc>,
    /// Whether this was beneficial (delta > 0.01).
    pub beneficial: bool,
}

/// Tracker that learns which strategy changes improve confidence.
pub struct StrategyTracker {
    outcomes: Vec<StrategyOutcome>,
    max_outcomes: usize,
}

impl StrategyTracker {
    /// Create a new tracker with the given capacity.
    pub fn new(max_outcomes: usize) -> Self {
        Self {
            outcomes: Vec::new(),
            max_outcomes,
        }
    }

    /// Begin tracking a strategy. Returns a handle for `complete_strategy`.
    pub fn begin_strategy(
        &self,
        name: &str,
        description: &str,
        current_confidence: f64,
    ) -> StrategyHandle {
        StrategyHandle {
            name: name.to_string(),
            description: description.to_string(),
            confidence_before: current_confidence,
            started_at: Utc::now(),
        }
    }

    /// Complete a strategy and record its outcome.
    pub fn complete_strategy(
        &mut self,
        handle: StrategyHandle,
        new_confidence: f64,
    ) {
        let delta = new_confidence - handle.confidence_before;
        let outcome = StrategyOutcome {
            strategy: handle.name,
            description: handle.description,
            confidence_before: handle.confidence_before,
            confidence_after: new_confidence,
            delta,
            timestamp: handle.started_at,
            beneficial: delta > 0.01,
        };

        if self.outcomes.len() >= self.max_outcomes {
            self.outcomes.remove(0);
        }
        self.outcomes.push(outcome);
    }

    /// Get the most effective strategies, sorted by delta descending.
    pub fn most_effective(&self, top_n: usize) -> Vec<&StrategyOutcome> {
        let mut sorted: Vec<&StrategyOutcome> = self.outcomes.iter().collect();
        sorted.sort_by(|a, b| {
            b.delta
                .partial_cmp(&a.delta)
                .unwrap_or(std::cmp::Ordering::Equal)
        });
        sorted.truncate(top_n);
        sorted
    }

    /// Get strategies that hurt confidence (negative delta).
    pub fn harmful_strategies(&self) -> Vec<&StrategyOutcome> {
        self.outcomes
            .iter()
            .filter(|o| o.delta < -0.01)
            .collect()
    }

    /// Recommend next strategy based on past effectiveness.
    ///
    /// Returns the name of the most effective beneficial strategy,
    /// or `None` if no beneficial strategies have been recorded.
    pub fn recommend(&self) -> Option<String> {
        self.outcomes
            .iter()
            .filter(|o| o.beneficial)
            .max_by(|a, b| {
                a.delta
                    .partial_cmp(&b.delta)
                    .unwrap_or(std::cmp::Ordering::Equal)
            })
            .map(|o| o.strategy.clone())
    }

    /// All recorded outcomes.
    pub fn outcomes(&self) -> &[StrategyOutcome] {
        &self.outcomes
    }

    /// Number of recorded outcomes.
    pub fn len(&self) -> usize {
        self.outcomes.len()
    }

    /// Whether the tracker is empty.
    pub fn is_empty(&self) -> bool {
        self.outcomes.is_empty()
    }
}

// ---------------------------------------------------------------------------
// TickHistory / TickRecommendation (Item 6: tick interval recommendation)
// ---------------------------------------------------------------------------

/// Tick interval recommendation based on observed change patterns.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TickRecommendation {
    /// Recommended interval in milliseconds.
    pub recommended_ms: u32,
    /// Current interval.
    pub current_ms: u32,
    /// Reason for recommendation.
    pub reason: String,
    /// Observed changes per minute.
    pub changes_per_minute: f64,
    /// Confidence in this recommendation (0.0 - 1.0).
    pub recommendation_confidence: f64,
}

/// Ring-buffer of recent tick results for analysis.
pub struct TickHistory {
    results: VecDeque<CognitiveTickResult>,
    max_entries: usize,
}

impl TickHistory {
    /// Create a new tick history with the given capacity.
    pub fn new(max_entries: usize) -> Self {
        Self {
            results: VecDeque::with_capacity(max_entries),
            max_entries,
        }
    }

    /// Record a tick result, evicting the oldest if at capacity.
    pub fn record(&mut self, result: CognitiveTickResult) {
        if self.results.len() >= self.max_entries {
            self.results.pop_front();
        }
        self.results.push_back(result);
    }

    /// Compute the average changes per minute based on recorded ticks.
    ///
    /// Uses total elapsed time and total change events to derive rate.
    pub fn changes_per_minute(&self) -> f64 {
        if self.results.len() < 2 {
            return 0.0;
        }

        let total_changes: usize = self
            .results
            .iter()
            .map(|r| r.git_commits_found + r.files_changed)
            .sum();

        let total_elapsed_ms: u64 =
            self.results.iter().map(|r| r.elapsed_ms as u64).sum();
        if total_elapsed_ms == 0 {
            return 0.0;
        }

        let minutes = total_elapsed_ms as f64 / 60_000.0;
        if minutes < 0.001 {
            return 0.0;
        }

        total_changes as f64 / minutes
    }

    /// Compute average budget usage ratio (elapsed / budget).
    pub fn avg_budget_usage(&self) -> f64 {
        if self.results.is_empty() {
            return 0.0;
        }

        let sum: f64 = self
            .results
            .iter()
            .filter(|r| r.budget_ms > 0)
            .map(|r| r.elapsed_ms as f64 / r.budget_ms as f64)
            .sum();

        let count = self
            .results
            .iter()
            .filter(|r| r.budget_ms > 0)
            .count();

        if count == 0 {
            return 0.0;
        }

        sum / count as f64
    }

    /// Count consecutive idle ticks (no changes) at the tail.
    pub fn idle_ticks(&self) -> usize {
        self.results
            .iter()
            .rev()
            .take_while(|r| {
                r.git_commits_found == 0
                    && r.files_changed == 0
                    && r.nodes_processed == 0
            })
            .count()
    }

    /// Number of recorded results.
    pub fn len(&self) -> usize {
        self.results.len()
    }

    /// Whether the history is empty.
    pub fn is_empty(&self) -> bool {
        self.results.is_empty()
    }

    /// All recorded tick results.
    pub fn all(&self) -> &VecDeque<CognitiveTickResult> {
        &self.results
    }
}

// ---------------------------------------------------------------------------
// WeaverEngine
// ---------------------------------------------------------------------------

/// ECC-powered codebase modeling service.
///
/// Manages modeling sessions, drives confidence evaluation via the
/// causal graph, and records modeling decisions in the Meta-Loom.
pub struct WeaverEngine {
    /// Active modeling sessions keyed by domain.
    sessions: RwLock<HashMap<String, ModelingSession>>,
    /// Cross-domain knowledge base.
    knowledge_base: Arc<WeaverKnowledgeBase>,
    /// Embedding provider for vectorization.
    embedding_provider: Arc<dyn EmbeddingProvider>,
    /// Causal graph reference.
    causal_graph: Arc<CausalGraph>,
    /// HNSW service reference.
    #[allow(dead_code)]
    hnsw: Arc<HnswService>,
    /// Impulse queue for emitting meta-loom signals.
    impulse_queue: Option<Arc<ImpulseQueue>>,
    /// Meta-loom event history per domain.
    meta_loom_events: RwLock<HashMap<String, Vec<MetaLoomEvent>>>,
    /// Total ticks processed across all sessions.
    tick_count: AtomicU64,
    /// Git poller for incremental commit detection.
    git_poller: Option<GitPoller>,
    /// File watcher for source file change detection.
    file_watcher: Option<FileWatcher>,
    /// Ticks since the last confidence recomputation.
    ticks_since_confidence_update: u64,
    /// Last computed confidence report (cached).
    last_confidence: Option<ConfidenceReport>,
    /// Confidence history ring buffer (Item 1).
    confidence_history: ConfidenceHistory,
    /// Strategy effectiveness tracker (Item 4).
    strategy_tracker: StrategyTracker,
    /// Tick result history for interval recommendation (Item 6).
    tick_history: TickHistory,
    /// Current tick interval in milliseconds (Item 6).
    current_tick_interval_ms: u32,
}

impl WeaverEngine {
    /// Create a new WeaverEngine with the given dependencies.
    pub fn new(
        causal_graph: Arc<CausalGraph>,
        hnsw: Arc<HnswService>,
        embedding_provider: Arc<dyn EmbeddingProvider>,
    ) -> Self {
        Self {
            sessions: RwLock::new(HashMap::new()),
            knowledge_base: Arc::new(WeaverKnowledgeBase::new()),
            embedding_provider,
            causal_graph,
            hnsw,
            impulse_queue: None,
            meta_loom_events: RwLock::new(HashMap::new()),
            tick_count: AtomicU64::new(0),
            git_poller: None,
            file_watcher: None,
            ticks_since_confidence_update: 0,
            last_confidence: None,
            confidence_history: ConfidenceHistory::new(500),
            strategy_tracker: StrategyTracker::new(200),
            tick_history: TickHistory::new(500),
            current_tick_interval_ms: 1000,
        }
    }

    /// Create a WeaverEngine with a mock embedding provider (for tests).
    pub fn new_with_mock(
        causal_graph: Arc<CausalGraph>,
        hnsw: Arc<HnswService>,
    ) -> Self {
        Self::new(
            causal_graph,
            hnsw,
            Arc::new(MockEmbeddingProvider::new(64)),
        )
    }

    /// Set the impulse queue for emitting meta-loom signals.
    pub fn set_impulse_queue(&mut self, queue: Arc<ImpulseQueue>) {
        self.impulse_queue = Some(queue);
    }

    /// Get a reference to the knowledge base.
    pub fn knowledge_base(&self) -> &Arc<WeaverKnowledgeBase> {
        &self.knowledge_base
    }

    /// Get a reference to the embedding provider.
    pub fn embedding_provider(&self) -> &Arc<dyn EmbeddingProvider> {
        &self.embedding_provider
    }

    /// Get a reference to the causal graph.
    pub fn causal_graph(&self) -> &Arc<CausalGraph> {
        &self.causal_graph
    }

    /// Get a reference to the HNSW service.
    pub fn hnsw(&self) -> &Arc<HnswService> {
        &self.hnsw
    }

    // ── Graph file ingestion ──────────────────────────────────────

    /// Ingest a graph JSON file (git-history, module-deps, or decisions).
    ///
    /// Reads a `.weftos/graph/*.json` file, creates causal graph nodes for
    /// each entry, creates edges between related nodes, and inserts
    /// embeddings into the HNSW index for each node's text representation.
    pub fn ingest_graph_file(&self, path: &Path) -> Result<IngestResult, WeaverError> {
        let data = std::fs::read_to_string(path)?;
        let graph: serde_json::Value = serde_json::from_str(&data)?;

        let source = graph["source"]
            .as_str()
            .unwrap_or("unknown")
            .to_string();

        let empty_vec = vec![];
        let nodes = graph["nodes"].as_array().unwrap_or(&empty_vec);
        let edges = graph["edges"].as_array().unwrap_or(&empty_vec);

        let mut nodes_added = 0usize;
        let mut edges_added = 0usize;
        let mut embeddings_created = 0usize;

        // Map from JSON node id (string) to causal graph NodeId.
        let mut id_map: HashMap<String, u64> = HashMap::with_capacity(nodes.len());

        // Phase 1: Create nodes.
        for node in nodes {
            let node_id_str = node["id"].as_str().unwrap_or("").to_string();
            if node_id_str.is_empty() {
                continue;
            }

            let label = if let Some(title) = node["title"].as_str() {
                format!("{source}/{node_id_str}: {title}")
            } else if let Some(subject) = node["subject"].as_str() {
                format!("{source}/{node_id_str}: {subject}")
            } else {
                format!("{source}/{node_id_str}")
            };

            let causal_id = self.causal_graph.add_node(
                label.clone(),
                node.clone(),
            );
            id_map.insert(node_id_str.clone(), causal_id);
            nodes_added += 1;

            // Create an HNSW embedding for the node's text.
            let embed_text = Self::node_to_embed_text(node, &source);
            if !embed_text.is_empty() {
                // Use synchronous hash-embed for ingestion (avoiding async).
                let embed_vec = self.sync_embed(&embed_text);
                self.hnsw.insert(
                    format!("{source}/{}", node_id_str),
                    embed_vec,
                    node.clone(),
                );
                embeddings_created += 1;
            }
        }

        // Phase 2: Create edges.
        for edge in edges {
            let from_str = edge["from"].as_str().unwrap_or("");
            let to_str = edge["to"].as_str().unwrap_or("");
            let edge_type_str = edge["type"].as_str().unwrap_or("Correlates");
            let weight = edge["weight"].as_f64().unwrap_or(1.0) as f32;

            let from_id = id_map.get(from_str).copied();
            let to_id = id_map.get(to_str).copied();

            if let (Some(src), Some(tgt)) = (from_id, to_id) {
                let edge_type = Self::parse_edge_type(edge_type_str);
                let linked = self.causal_graph.link(
                    src, tgt, edge_type, weight, 0, 0,
                );
                if linked {
                    edges_added += 1;
                }
            }
        }

        info!(
            source = %source,
            nodes_added,
            edges_added,
            embeddings_created,
            "graph file ingested"
        );

        Ok(IngestResult {
            nodes_added,
            edges_added,
            embeddings_created,
            source,
        })
    }

    /// Ingest a graph file with strategy tracking and confidence history.
    ///
    /// Wraps [`ingest_graph_file`] with before/after confidence measurement,
    /// recording the result in the [`StrategyTracker`] and
    /// [`ConfidenceHistory`].
    pub fn ingest_graph_file_tracked(
        &mut self,
        path: &Path,
    ) -> Result<IngestResult, WeaverError> {
        let confidence_before = self.compute_confidence().overall;
        let source_name = path
            .file_stem()
            .and_then(|s| s.to_str())
            .unwrap_or("unknown");
        let handle = self.strategy_tracker.begin_strategy(
            &format!("ingest:{source_name}"),
            &format!("Ingesting graph file {}", path.display()),
            confidence_before,
        );

        let result = self.ingest_graph_file(path)?;

        let report = self.compute_confidence();
        let confidence_after = report.overall;

        // Record strategy outcome (Item 4).
        self.strategy_tracker
            .complete_strategy(handle, confidence_after);

        // Record post-ingestion confidence snapshot (Item 1).
        let snapshot = ConfidenceSnapshot {
            timestamp: Utc::now(),
            tick_number: self.tick_count.load(Ordering::Relaxed),
            confidence: confidence_after,
            node_count: self.causal_graph.node_count() as usize,
            edge_count: self.causal_graph.edge_count() as usize,
            gap_count: report.gaps.len(),
            trigger: ConfidenceTrigger::PostIngestion,
        };
        self.confidence_history.record(snapshot);

        // Also record a StrategyChange snapshot if confidence changed.
        if (confidence_after - confidence_before).abs() > 0.001 {
            let change_snapshot = ConfidenceSnapshot {
                timestamp: Utc::now(),
                tick_number: self.tick_count.load(Ordering::Relaxed),
                confidence: confidence_after,
                node_count: self.causal_graph.node_count() as usize,
                edge_count: self.causal_graph.edge_count() as usize,
                gap_count: report.gaps.len(),
                trigger: ConfidenceTrigger::StrategyChange,
            };
            self.confidence_history.record(change_snapshot);
        }

        Ok(result)
    }

    /// Convert a graph node's fields into embeddable text.
    fn node_to_embed_text(node: &serde_json::Value, source: &str) -> String {
        match source {
            "git-history" => {
                let subject = node["subject"].as_str().unwrap_or("");
                let author = node["author"].as_str().unwrap_or("");
                let files = node["files"]
                    .as_array()
                    .map(|arr| {
                        arr.iter()
                            .filter_map(|v| v.as_str())
                            .collect::<Vec<_>>()
                            .join(", ")
                    })
                    .unwrap_or_default();
                format!("commit by {author}: {subject} files: {files}")
            }
            "module-dependencies" => {
                let id = node["id"].as_str().unwrap_or("");
                let deps = node["dependencies"]
                    .as_array()
                    .map(|arr| {
                        arr.iter()
                            .filter_map(|v| v.as_str())
                            .collect::<Vec<_>>()
                            .join(", ")
                    })
                    .unwrap_or_default();
                let lines = node["lines"].as_u64().unwrap_or(0);
                format!("module {id} ({lines} lines) depends on: {deps}")
            }
            "decisions-and-phases" => {
                let title = node["title"].as_str().unwrap_or("");
                let rationale = node["rationale"].as_str().unwrap_or("");
                let panel = node["panel"].as_str().unwrap_or("");
                format!("decision ({panel}): {title} — {rationale}")
            }
            _ => {
                // Fallback: serialize the whole node.
                serde_json::to_string(node).unwrap_or_default()
            }
        }
    }

    /// Parse an edge type string to a CausalEdgeType.
    fn parse_edge_type(s: &str) -> CausalEdgeType {
        match s {
            "Causes" => CausalEdgeType::Causes,
            "Inhibits" => CausalEdgeType::Inhibits,
            "Correlates" => CausalEdgeType::Correlates,
            "Enables" => CausalEdgeType::Enables,
            "Follows" => CausalEdgeType::Follows,
            "Contradicts" => CausalEdgeType::Contradicts,
            "TriggeredBy" => CausalEdgeType::TriggeredBy,
            "EvidenceFor" => CausalEdgeType::EvidenceFor,
            _ => CausalEdgeType::Correlates,
        }
    }

    /// Synchronous embedding using the mock fallback (for ingestion loops).
    ///
    /// This avoids the need for async in the ingestion path. The mock
    /// provider's `hash_embed` is deterministic and instant.
    fn sync_embed(&self, text: &str) -> Vec<f32> {
        use sha2::{Digest, Sha256};
        let dims = self.embedding_provider.dimensions();
        let mut hasher = Sha256::new();
        hasher.update(text.as_bytes());
        let hash = hasher.finalize();
        let mut vec = Vec::with_capacity(dims);
        for i in 0..dims {
            let byte = hash[i % 32];
            vec.push((byte as f32 / 128.0) - 1.0);
        }
        vec
    }

    // ── Confidence scoring from graph data ────────────────────────

    /// Compute confidence based on graph coverage.
    ///
    /// Examines the causal graph to determine what fraction of nodes have
    /// edges (both incoming and outgoing), the edge density, and identifies
    /// orphan nodes that lack causal connections.
    pub fn compute_confidence(&self) -> ConfidenceReport {
        let node_count = self.causal_graph.node_count() as usize;
        let edge_count = self.causal_graph.edge_count() as usize;

        if node_count == 0 {
            return ConfidenceReport {
                overall: 0.0,
                gaps: vec![ConfidenceGap {
                    domain: "graph".to_string(),
                    current_confidence: 0.0,
                    target_confidence: 0.8,
                    suggested_sources: vec![
                        "git_log".into(),
                        "module_deps".into(),
                        "decisions".into(),
                    ],
                }],
                suggestions: vec![ModelingSuggestion::AddSource {
                    source_type: "git_log".to_string(),
                    reason: "No graph data ingested yet".to_string(),
                }],
            };
        }

        // Edge density: ratio of actual edges to maximum possible.
        let max_edges = if node_count > 1 {
            node_count * (node_count - 1)
        } else {
            1
        };
        let edge_density = (edge_count as f64 / max_edges as f64).min(1.0);

        // Node connectivity: fraction of nodes that have at least one edge.
        // We sample by checking forward + reverse edges for each node id up to
        // the known count (sequential IDs starting from 1).
        let mut connected_nodes = 0usize;
        let mut orphan_labels: Vec<String> = Vec::new();
        let next_id = self.causal_graph.node_count() + 1;
        // Iterate over plausible node IDs. The CausalGraph allocates IDs
        // sequentially starting at 1 so scanning 1..next_id covers all.
        for nid in 1..next_id {
            if self.causal_graph.get_node(nid).is_some() {
                let fwd = self.causal_graph.get_forward_edges(nid);
                let rev = self.causal_graph.get_reverse_edges(nid);
                if !fwd.is_empty() || !rev.is_empty() {
                    connected_nodes += 1;
                } else if let Some(node) = self.causal_graph.get_node(nid) {
                    orphan_labels.push(node.label.clone());
                }
            }
        }

        let connectivity = if node_count > 0 {
            connected_nodes as f64 / node_count as f64
        } else {
            0.0
        };

        // Composite confidence: weighted average of components.
        // - Connectivity (40%): nodes with edges / total nodes
        // - Edge density (20%): capped contribution from edge density
        // - Node volume (20%): diminishing returns above 100 nodes
        // - Source diversity (20%): number of distinct source prefixes
        let volume_score = (node_count as f64 / 100.0).min(1.0);
        let density_capped = (edge_density * 50.0).min(1.0); // amplify sparse graphs

        let overall = (connectivity * 0.40
            + density_capped * 0.20
            + volume_score * 0.20
            + self.source_diversity_score() * 0.20)
            .min(1.0);

        // Build gaps.
        let mut gaps = Vec::new();
        if connectivity < 0.7 {
            gaps.push(ConfidenceGap {
                domain: "node_connectivity".to_string(),
                current_confidence: connectivity,
                target_confidence: 0.7,
                suggested_sources: vec!["module_deps".into(), "git_log".into()],
            });
        }
        if volume_score < 0.5 {
            gaps.push(ConfidenceGap {
                domain: "data_volume".to_string(),
                current_confidence: volume_score,
                target_confidence: 0.5,
                suggested_sources: vec!["git_log".into(), "file_tree".into()],
            });
        }

        // Suggestions from orphan nodes.
        let mut suggestions = Vec::new();
        if !orphan_labels.is_empty() {
            let sample: Vec<_> = orphan_labels.iter().take(5).cloned().collect();
            suggestions.push(ModelingSuggestion::AddSource {
                source_type: "causal_edges".to_string(),
                reason: format!(
                    "{} orphan nodes without edges (e.g., {})",
                    orphan_labels.len(),
                    sample.join(", ")
                ),
            });
        }

        ConfidenceReport {
            overall,
            gaps,
            suggestions,
        }
    }

    /// Count distinct source prefixes in node labels to gauge diversity.
    fn source_diversity_score(&self) -> f64 {
        let sessions = match self.sessions.read() {
            Ok(s) => s,
            Err(_) => return 0.0,
        };
        let total_sources: usize = sessions.values().map(|s| s.sources_ingested.len()).sum();
        // Diminishing returns: 3 sources = 1.0.
        (total_sources as f64 / 3.0).min(1.0)
    }

    // ── Model export to file ──────────────────────────────────────

    /// Export the current model state to a JSON file at the given path.
    ///
    /// Produces a `weave-model.json` that includes the causal graph nodes,
    /// edges, confidence report, and metadata.
    pub fn export_model_to_file(
        &self,
        domain: &str,
        min_confidence: f64,
        path: &Path,
    ) -> Result<ExportedModel, WeaverError> {
        let model = self.export_model(domain, min_confidence)
            .map_err(WeaverError::Domain)?;
        let json = serde_json::to_string_pretty(&model)?;
        std::fs::write(path, json)?;
        info!(domain, ?path, "model exported to file");
        Ok(model)
    }

    /// Import a model from a JSON file.
    pub fn import_model_from_file(
        &self,
        domain: &str,
        path: &Path,
    ) -> Result<(), WeaverError> {
        let data = std::fs::read_to_string(path)?;
        let model: ExportedModel = serde_json::from_str(&data)?;
        self.import_model(domain, model)
            .map_err(WeaverError::Domain)?;
        info!(domain, ?path, "model imported from file");
        Ok(())
    }

    // ── Session management ────────────────────────────────────────

    /// Start a new modeling session.
    pub fn start_session(
        &self,
        domain: &str,
        context: Option<&str>,
        _goal: Option<&str>,
    ) -> Result<String, String> {
        let session_id = uuid::Uuid::new_v4().to_string();
        let session = ModelingSession {
            id: session_id.clone(),
            domain: domain.to_string(),
            started_at: Utc::now(),
            confidence: 0.0,
            gaps: Vec::new(),
            sources_ingested: Vec::new(),
            tick_count: 0,
            budget_remaining_ms: 300_000, // 5 min default
            active: true,
            metadata: {
                let cap = if context.is_some() { 1 } else { 0 };
                let mut m = HashMap::with_capacity(cap);
                if let Some(ctx) = context {
                    m.insert("context".to_string(), serde_json::Value::String(ctx.to_string()));
                }
                m
            },
        };

        let mut sessions = self.sessions.write().map_err(|e| e.to_string())?;
        if sessions.contains_key(domain) {
            return Err(format!("session already exists for domain: {domain}"));
        }
        sessions.insert(domain.to_string(), session);

        // Record meta-loom event.
        self.record_meta_loom(
            domain,
            MetaDecisionType::ModelVersionBumped { from: 0, to: 1 },
            "Session initialized",
            0.0,
        );

        // Emit impulse.
        self.emit_impulse(ImpulseType::Custom(0x32));

        info!(domain, session_id = %session_id, "weaver session started");
        Ok(session_id)
    }

    /// Stop a modeling session.
    pub fn stop_session(&self, domain: &str) -> Result<(), String> {
        let mut sessions = self.sessions.write().map_err(|e| e.to_string())?;
        let session = sessions
            .get_mut(domain)
            .ok_or_else(|| format!("no session for domain: {domain}"))?;
        session.active = false;
        info!(domain, "weaver session stopped");
        Ok(())
    }

    /// Resume a stopped session.
    pub fn resume_session(&self, domain: &str) -> Result<(), String> {
        let mut sessions = self.sessions.write().map_err(|e| e.to_string())?;
        let session = sessions
            .get_mut(domain)
            .ok_or_else(|| format!("no session for domain: {domain}"))?;
        session.active = true;
        info!(domain, "weaver session resumed");
        Ok(())
    }

    /// Get a snapshot of a session.
    pub fn get_session(&self, domain: &str) -> Option<ModelingSession> {
        self.sessions
            .read()
            .ok()?
            .get(domain)
            .cloned()
    }

    /// List all session domains.
    pub fn list_sessions(&self) -> Vec<String> {
        self.sessions
            .read()
            .map(|s| s.keys().cloned().collect())
            .unwrap_or_default()
    }

    // ── Source management ─────────────────────────────────────────

    /// Add a data source to a session.
    pub fn add_source(
        &self,
        domain: &str,
        source_type: &str,
        _root: Option<&PathBuf>,
    ) -> Result<(), String> {
        let mut sessions = self.sessions.write().map_err(|e| e.to_string())?;
        let session = sessions
            .get_mut(domain)
            .ok_or_else(|| format!("no session for domain: {domain}"))?;
        session.sources_ingested.push(source_type.to_string());

        // Record meta-loom event.
        drop(sessions); // release lock before recording
        self.record_meta_loom(
            domain,
            MetaDecisionType::SourceAdded {
                source_type: source_type.to_string(),
            },
            &format!("Added source: {source_type}"),
            self.get_session(domain).map(|s| s.confidence).unwrap_or(0.0),
        );

        // Emit impulse for source request.
        self.emit_impulse(ImpulseType::Custom(0x33));

        Ok(())
    }

    // ── Confidence evaluation ─────────────────────────────────────

    /// Evaluate confidence for a session domain.
    pub fn evaluate_confidence(&self, domain: &str) -> Result<ConfidenceReport, String> {
        let sessions = self.sessions.read().map_err(|e| e.to_string())?;
        let session = sessions
            .get(domain)
            .ok_or_else(|| format!("no session for domain: {domain}"))?;

        // Simple confidence model based on source count and graph size.
        let source_count = session.sources_ingested.len() as f64;
        let node_count = self.causal_graph.node_count() as f64;

        // Confidence grows with data, capped at 1.0.
        let base_confidence = (source_count * 0.15 + node_count * 0.01).min(1.0);

        let mut gaps = Vec::new();
        if source_count < 3.0 {
            gaps.push(ConfidenceGap {
                domain: domain.to_string(),
                current_confidence: base_confidence,
                target_confidence: 0.8,
                suggested_sources: vec!["git_log".into(), "file_tree".into()],
            });
        }

        let suggestions = if source_count < 2.0 {
            vec![ModelingSuggestion::AddSource {
                source_type: "git_log".into(),
                reason: "No git history ingested yet".into(),
            }]
        } else {
            Vec::new()
        };

        Ok(ConfidenceReport {
            overall: base_confidence,
            gaps,
            suggestions,
        })
    }

    // ── Cognitive tick handler ─────────────────────────────────────

    /// Process a single cognitive tick.
    ///
    /// Called by the CognitiveTick service during each tick cycle.
    /// Budget-aware: yields if budget is exhausted.
    pub fn tick(&self, budget: Duration) -> TickResult {
        let budget_start = Instant::now();

        let mut sessions = match self.sessions.write() {
            Ok(s) => s,
            Err(_) => return TickResult::Idle,
        };

        // Find an active session.
        let active_domain = sessions
            .iter()
            .find(|(_, s)| s.active)
            .map(|(d, _)| d.clone());

        let domain = match active_domain {
            Some(d) => d,
            None => return TickResult::Idle,
        };

        let session = match sessions.get_mut(&domain) {
            Some(s) => s,
            None => return TickResult::Idle,
        };

        // Phase 1: Evaluate confidence.
        let source_count = session.sources_ingested.len() as f64;
        let node_count = self.causal_graph.node_count() as f64;
        let confidence = (source_count * 0.15 + node_count * 0.01).min(1.0);
        session.confidence = confidence;

        // Phase 2: Identify gaps.
        let mut gaps = Vec::new();
        if confidence < 0.8 {
            gaps.push(ConfidenceGap {
                domain: domain.clone(),
                current_confidence: confidence,
                target_confidence: 0.8,
                suggested_sources: vec!["git_log".into(), "file_tree".into()],
            });
        }
        session.gaps = gaps.clone();

        if budget_start.elapsed() > budget {
            return TickResult::BudgetExhausted;
        }

        // Phase 3: Create a causal node to record the tick.
        let tick_label = format!("weaver.tick.{}.{}", domain, session.tick_count);
        self.causal_graph.add_node(
            tick_label,
            serde_json::json!({
                "domain": domain,
                "confidence": confidence,
                "tick": session.tick_count,
            }),
        );

        session.tick_count += 1;
        self.tick_count.fetch_add(1, Ordering::Relaxed);

        TickResult::Progress {
            confidence,
            gaps_remaining: gaps.len(),
        }
    }

    // ── Export / Import (K3c-G4) ──────────────────────────────────

    /// Export the model for a domain.
    pub fn export_model(
        &self,
        domain: &str,
        min_confidence: f64,
    ) -> Result<ExportedModel, String> {
        let sessions = self.sessions.read().map_err(|e| e.to_string())?;
        let session = sessions
            .get(domain)
            .ok_or_else(|| format!("no session for domain: {domain}"))?;

        // Collect all edges and filter by confidence.
        let edge_types: Vec<EdgeTypeSpec> = session
            .sources_ingested
            .iter()
            .enumerate()
            .map(|(i, src)| EdgeTypeSpec {
                from_type: "source".into(),
                to_type: "domain".into(),
                edge_type: format!("ingested_{src}"),
                confidence: (i as f64 + 1.0) * 0.2,
            })
            .filter(|e| e.confidence >= min_confidence)
            .collect();

        // Collect causal nodes from the graph.
        let mut causal_nodes = Vec::new();
        let mut causal_edges_out = Vec::new();
        let next_id = self.causal_graph.node_count() + 1;
        for nid in 1..next_id {
            if let Some(node) = self.causal_graph.get_node(nid) {
                causal_nodes.push(ExportedCausalNode {
                    label: node.label.clone(),
                    metadata: node.metadata.clone(),
                });
                // Collect forward edges from this node.
                for edge in self.causal_graph.get_forward_edges(nid) {
                    if let Some(target_node) = self.causal_graph.get_node(edge.target) {
                        causal_edges_out.push(ExportedCausalEdge {
                            source_label: node.label.clone(),
                            target_label: target_node.label.clone(),
                            edge_type: format!("{}", edge.edge_type),
                            weight: edge.weight,
                        });
                    }
                }
            }
        }

        Ok(ExportedModel {
            version: "1.0".to_string(),
            domain: domain.to_string(),
            exported_at: Utc::now(),
            confidence: session.confidence,
            node_types: vec![NodeTypeSpec {
                name: "default".into(),
                embedding_strategy: self.embedding_provider.model_name().to_string(),
                dimensions: self.embedding_provider.dimensions(),
            }],
            edge_types,
            causal_nodes,
            causal_edges: causal_edges_out,
            metadata: session.metadata.clone(),
        })
    }

    /// Import a previously exported model.
    pub fn import_model(
        &self,
        domain: &str,
        model: ExportedModel,
    ) -> Result<(), String> {
        // Version check.
        if !model.version.starts_with("1.") {
            return Err(format!(
                "incompatible model version: expected 1.x, got {}",
                model.version
            ));
        }

        let session = ModelingSession {
            id: uuid::Uuid::new_v4().to_string(),
            domain: domain.to_string(),
            started_at: Utc::now(),
            confidence: model.confidence,
            gaps: Vec::new(),
            sources_ingested: model
                .edge_types
                .iter()
                .map(|e| e.edge_type.clone())
                .collect(),
            tick_count: 0,
            budget_remaining_ms: 300_000,
            active: true,
            metadata: model.metadata,
        };

        let mut sessions = self.sessions.write().map_err(|e| e.to_string())?;
        sessions.insert(domain.to_string(), session);

        // Record meta-loom.
        drop(sessions);
        self.record_meta_loom(
            domain,
            MetaDecisionType::ModelVersionBumped { from: 0, to: 1 },
            "Imported from exported model",
            model.confidence,
        );

        info!(domain, "weaver model imported");
        Ok(())
    }

    // ── Command handler (IPC) ─────────────────────────────────────

    /// Handle a WeaverCommand received via IPC.
    pub fn handle_command(&self, cmd: WeaverCommand) -> WeaverResponse {
        match cmd {
            WeaverCommand::SessionStart {
                domain,
                context,
                goal,
                ..
            } => match self.start_session(
                &domain,
                context.as_deref(),
                goal.as_deref(),
            ) {
                Ok(session_id) => WeaverResponse::SessionStarted { domain, session_id },
                Err(e) => WeaverResponse::Error(e),
            },
            WeaverCommand::SessionStop { domain } => match self.stop_session(&domain) {
                Ok(()) => WeaverResponse::SessionStopped { domain },
                Err(e) => WeaverResponse::Error(e),
            },
            WeaverCommand::SessionResume { domain } => match self.resume_session(&domain) {
                Ok(()) => WeaverResponse::SessionResumed { domain },
                Err(e) => WeaverResponse::Error(e),
            },
            WeaverCommand::SourceAdd {
                domain,
                source_type,
                root,
                ..
            } => match self.add_source(&domain, &source_type, root.as_ref()) {
                Ok(()) => WeaverResponse::SourceAdded {
                    domain,
                    source_type,
                },
                Err(e) => WeaverResponse::Error(e),
            },
            WeaverCommand::SourceList { domain } => {
                match self.get_session(&domain) {
                    Some(s) => WeaverResponse::Sources(s.sources_ingested),
                    None => WeaverResponse::Error(format!("no session for domain: {domain}")),
                }
            }
            WeaverCommand::Confidence { domain, .. } => {
                match self.evaluate_confidence(&domain) {
                    Ok(report) => WeaverResponse::ConfidenceReport(report),
                    Err(e) => WeaverResponse::Error(e),
                }
            }
            WeaverCommand::Export {
                domain,
                min_confidence,
                output,
            } => match self.export_model(&domain, min_confidence) {
                Ok(model) => {
                    let edges = model.edge_types.len();
                    // In a real implementation, this would write to disk.
                    debug!(?output, edges, "model exported");
                    WeaverResponse::Exported { path: output, edges }
                }
                Err(e) => WeaverResponse::Error(e),
            },
            WeaverCommand::Import { domain, input } => {
                // In a real implementation, this would read from disk.
                debug!(?input, "model import requested");
                WeaverResponse::Imported { domain }
            }
            WeaverCommand::MetaStrategies => {
                let strategies = self.knowledge_base.list_strategies();
                WeaverResponse::Strategies(strategies)
            }
            WeaverCommand::MetaExportKb { output } => {
                debug!(?output, "KB export requested");
                WeaverResponse::KbExported { path: output }
            }
            _ => WeaverResponse::Error("command not implemented".into()),
        }
    }

    // ── Meta-Loom (K3c-G5) ───────────────────────────────────────

    /// Record a meta-loom event.
    fn record_meta_loom(
        &self,
        domain: &str,
        decision: MetaDecisionType,
        rationale: &str,
        confidence_before: f64,
    ) {
        let event = MetaLoomEvent {
            session_domain: domain.to_string(),
            decision_type: decision,
            confidence_before,
            confidence_after: None,
            rationale: rationale.to_string(),
            timestamp: Utc::now(),
        };

        // Record in causal graph under meta-loom namespace.
        let label = format!("meta-loom/{}", domain);
        self.causal_graph.add_node(
            label,
            serde_json::to_value(&event).unwrap_or_default(),
        );

        // Store in local event history.
        if let Ok(mut events) = self.meta_loom_events.write() {
            events
                .entry(domain.to_string())
                .or_default()
                .push(event);
        }
    }

    /// Get meta-loom events for a domain.
    pub fn meta_loom_events(&self, domain: &str) -> Vec<MetaLoomEvent> {
        self.meta_loom_events
            .read()
            .ok()
            .and_then(|m| m.get(domain).cloned())
            .unwrap_or_default()
    }

    /// Emit an impulse if the queue is configured.
    fn emit_impulse(&self, impulse_type: ImpulseType) {
        if let Some(queue) = &self.impulse_queue {
            queue.emit(
                0x03, // CausalGraph
                [0u8; 32],
                0x03, // self-referential
                impulse_type,
                serde_json::Value::Null,
                0,
            );
        }
    }

    // ── CognitiveTick integration ──────────────────────────────────

    /// Handle a cognitive tick — process pending work within budget.
    ///
    /// Called by the CognitiveTick service each cycle. Performs git polling,
    /// file change detection, pending ingestion, and periodic confidence
    /// recomputation, all within the supplied time budget.
    pub fn on_tick(&mut self, budget_ms: u32) -> CognitiveTickResult {
        let start = Instant::now();
        let budget = Duration::from_millis(budget_ms as u64);
        let mut result = CognitiveTickResult {
            tick_number: self.tick_count.load(Ordering::Relaxed),
            budget_ms,
            ..Default::default()
        };

        // 1. Check for new git commits (if git polling enabled).
        if start.elapsed() < budget {
            if let Some(new_commits) = self.poll_git() {
                result.git_commits_found = new_commits;
            }
        }

        // 2. Check for file changes (if file watcher enabled).
        if start.elapsed() < budget {
            if let Some(changed_files) = self.poll_file_changes() {
                result.files_changed = changed_files;
            }
        }

        // 3. Process pending ingestion queue (delegate to existing tick()).
        if start.elapsed() < budget {
            let remaining = budget.saturating_sub(start.elapsed());
            let tick_result = self.tick(remaining);
            if let TickResult::Progress { .. } = tick_result {
                result.nodes_processed = 1;
            }
        }

        // 4. Recompute confidence every 100 ticks and record snapshot.
        if start.elapsed() < budget && self.ticks_since_confidence_update > 100 {
            let report = self.compute_confidence();
            self.last_confidence = Some(report.clone());
            self.ticks_since_confidence_update = 0;
            result.confidence_updated = true;

            // Record confidence snapshot (Item 1).
            let snapshot = ConfidenceSnapshot {
                timestamp: Utc::now(),
                tick_number: self.tick_count.load(Ordering::Relaxed),
                confidence: report.overall,
                node_count: self.causal_graph.node_count() as usize,
                edge_count: self.causal_graph.edge_count() as usize,
                gap_count: report.gaps.len(),
                trigger: ConfidenceTrigger::Periodic,
            };
            self.confidence_history.record(snapshot);
        }

        result.elapsed_ms = start.elapsed().as_millis() as u32;
        result.within_budget = start.elapsed() <= budget;
        self.tick_count.fetch_add(1, Ordering::Relaxed);
        self.ticks_since_confidence_update += 1;

        // Record tick result in history (Item 6).
        self.tick_history.record(result.clone());

        result
    }

    /// Enable git polling for a repository path and branch.
    pub fn enable_git_polling(&mut self, repo_path: PathBuf, branch: String) {
        self.git_poller = Some(GitPoller::new(repo_path, branch));
    }

    /// Enable file watching for source files under a root directory.
    pub fn enable_file_watching(&mut self, root: PathBuf, patterns: Vec<String>) {
        let mut watcher = FileWatcher::new(root, patterns);
        watcher.watch_directory();
        self.file_watcher = Some(watcher);
    }

    /// Poll git for new commits (internal helper for on_tick).
    fn poll_git(&mut self) -> Option<usize> {
        self.git_poller.as_mut().map(|p| p.poll())
    }

    /// Poll file watcher for changed files (internal helper for on_tick).
    fn poll_file_changes(&mut self) -> Option<usize> {
        self.file_watcher.as_mut().map(|w| w.poll_changes().len())
    }

    /// Get the cached confidence report from the last recomputation.
    pub fn cached_confidence(&self) -> Option<&ConfidenceReport> {
        self.last_confidence.as_ref()
    }

    /// Get a reference to the git poller, if enabled.
    pub fn git_poller(&self) -> Option<&GitPoller> {
        self.git_poller.as_ref()
    }

    /// Get a reference to the file watcher, if enabled.
    pub fn file_watcher(&self) -> Option<&FileWatcher> {
        self.file_watcher.as_ref()
    }

    /// Total ticks processed.
    pub fn total_ticks(&self) -> u64 {
        self.tick_count.load(Ordering::Relaxed)
    }

    // ── Confidence history accessors (Item 1) ────────────────────

    /// Get a reference to the confidence history.
    pub fn confidence_history(&self) -> &ConfidenceHistory {
        &self.confidence_history
    }

    /// Get a mutable reference to the confidence history.
    pub fn confidence_history_mut(&mut self) -> &mut ConfidenceHistory {
        &mut self.confidence_history
    }

    // ── Strategy tracker accessors (Item 4) ──────────────────────

    /// Get a reference to the strategy tracker.
    pub fn strategy_tracker(&self) -> &StrategyTracker {
        &self.strategy_tracker
    }

    /// Get a mutable reference to the strategy tracker.
    pub fn strategy_tracker_mut(&mut self) -> &mut StrategyTracker {
        &mut self.strategy_tracker
    }

    // ── Tick history / interval recommendation (Item 6) ──────────

    /// Get a reference to the tick history.
    pub fn tick_history(&self) -> &TickHistory {
        &self.tick_history
    }

    /// Set the current tick interval (for recommendation calculations).
    pub fn set_tick_interval_ms(&mut self, ms: u32) {
        self.current_tick_interval_ms = ms;
    }

    /// Analyze recent tick history and recommend interval adjustment.
    ///
    /// Looks at recent change frequency to determine if the tick interval
    /// should be faster, slower, or idle. Thresholds:
    /// - Frequent changes (>10/min): recommend 200ms (fast).
    /// - Moderate changes (1-10/min): recommend 1000ms (default).
    /// - Rare changes (<1/min): recommend 3000ms (slow).
    /// - No changes for 100+ ticks: recommend 5000ms (idle mode).
    pub fn recommend_tick_interval(&self) -> TickRecommendation {
        let idle = self.tick_history.idle_ticks();
        let cpm = self.tick_history.changes_per_minute();
        let sample_count = self.tick_history.len();

        // Not enough data to make a confident recommendation.
        if sample_count < 5 {
            return TickRecommendation {
                recommended_ms: self.current_tick_interval_ms,
                current_ms: self.current_tick_interval_ms,
                reason: "Insufficient data for recommendation".to_string(),
                changes_per_minute: cpm,
                recommendation_confidence: 0.1,
            };
        }

        // Idle mode: no changes for many consecutive ticks.
        if idle >= 100 {
            return TickRecommendation {
                recommended_ms: 5000,
                current_ms: self.current_tick_interval_ms,
                reason: format!(
                    "No changes for {idle} consecutive ticks; entering idle mode"
                ),
                changes_per_minute: cpm,
                recommendation_confidence: 0.9,
            };
        }

        // High frequency changes: speed up.
        if cpm > 10.0 {
            return TickRecommendation {
                recommended_ms: 200,
                current_ms: self.current_tick_interval_ms,
                reason: format!(
                    "High change rate ({cpm:.1}/min); recommending fast ticks"
                ),
                changes_per_minute: cpm,
                recommendation_confidence: 0.8,
            };
        }

        // Moderate frequency: default speed.
        if cpm >= 1.0 {
            return TickRecommendation {
                recommended_ms: 1000,
                current_ms: self.current_tick_interval_ms,
                reason: format!(
                    "Moderate change rate ({cpm:.1}/min); default interval"
                ),
                changes_per_minute: cpm,
                recommendation_confidence: 0.7,
            };
        }

        // Low frequency: slow down.
        TickRecommendation {
            recommended_ms: 3000,
            current_ms: self.current_tick_interval_ms,
            reason: format!(
                "Low change rate ({cpm:.2}/min); recommending slower ticks"
            ),
            changes_per_minute: cpm,
            recommendation_confidence: 0.6,
        }
    }
}

#[async_trait]
impl SystemService for WeaverEngine {
    fn name(&self) -> &str {
        "weaver"
    }

    fn service_type(&self) -> ServiceType {
        ServiceType::Core
    }

    async fn start(&self) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        info!("weaver engine started");
        Ok(())
    }

    async fn stop(&self) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        // Stop all active sessions.
        if let Ok(mut sessions) = self.sessions.write() {
            for (_, session) in sessions.iter_mut() {
                session.active = false;
            }
        }
        info!(
            total_ticks = self.total_ticks(),
            kb_strategies = self.knowledge_base.count(),
            "weaver engine stopped"
        );
        Ok(())
    }

    async fn health_check(&self) -> HealthStatus {
        // Always healthy: both active and idle states are normal.
        HealthStatus::Healthy
    }
}

// ---------------------------------------------------------------------------
// ModelDiff (K3c-G4b)
// ---------------------------------------------------------------------------

/// Differences between two exported models.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ModelDiff {
    /// Model A identifier (domain).
    pub model_a: String,
    /// Model B identifier (domain).
    pub model_b: String,
    /// Confidence delta (B - A).
    pub confidence_delta: f64,
    /// Node types only in A.
    pub nodes_only_a: Vec<String>,
    /// Node types only in B.
    pub nodes_only_b: Vec<String>,
    /// Node types in both.
    pub nodes_common: Vec<String>,
    /// Edge types only in A.
    pub edges_only_a: Vec<String>,
    /// Edge types only in B.
    pub edges_only_b: Vec<String>,
    /// Edge types in both.
    pub edges_common: Vec<String>,
    /// Causal nodes added in B vs A.
    pub causal_nodes_added: usize,
    /// Causal nodes removed in B vs A.
    pub causal_nodes_removed: usize,
    /// Causal edges added.
    pub causal_edges_added: usize,
    /// Causal edges removed.
    pub causal_edges_removed: usize,
    /// Summary assessment.
    pub summary: String,
}

/// Compare two exported models and produce a structured diff.
pub fn diff_models(a: &ExportedModel, b: &ExportedModel) -> ModelDiff {
    // Node types by name.
    let a_node_names: HashSet<&str> = a.node_types.iter().map(|n| n.name.as_str()).collect();
    let b_node_names: HashSet<&str> = b.node_types.iter().map(|n| n.name.as_str()).collect();

    let nodes_only_a: Vec<String> = a_node_names
        .difference(&b_node_names)
        .map(|s| s.to_string())
        .collect();
    let nodes_only_b: Vec<String> = b_node_names
        .difference(&a_node_names)
        .map(|s| s.to_string())
        .collect();
    let nodes_common: Vec<String> = a_node_names
        .intersection(&b_node_names)
        .map(|s| s.to_string())
        .collect();

    // Edge types by (from, to, type) composite key.
    let edge_key =
        |e: &EdgeTypeSpec| format!("{}->{}:{}", e.from_type, e.to_type, e.edge_type);
    let a_edge_keys: HashSet<String> = a.edge_types.iter().map(|e| edge_key(e)).collect();
    let b_edge_keys: HashSet<String> = b.edge_types.iter().map(|e| edge_key(e)).collect();

    let edges_only_a: Vec<String> = a_edge_keys.difference(&b_edge_keys).cloned().collect();
    let edges_only_b: Vec<String> = b_edge_keys.difference(&a_edge_keys).cloned().collect();
    let edges_common: Vec<String> = a_edge_keys.intersection(&b_edge_keys).cloned().collect();

    // Causal nodes by label.
    let a_causal_labels: HashSet<&str> =
        a.causal_nodes.iter().map(|n| n.label.as_str()).collect();
    let b_causal_labels: HashSet<&str> =
        b.causal_nodes.iter().map(|n| n.label.as_str()).collect();

    let causal_nodes_added = b_causal_labels.difference(&a_causal_labels).count();
    let causal_nodes_removed = a_causal_labels.difference(&b_causal_labels).count();

    // Causal edges by (from, to).
    let causal_edge_key =
        |e: &ExportedCausalEdge| format!("{}->{}", e.source_label, e.target_label);
    let a_causal_edge_keys: HashSet<String> =
        a.causal_edges.iter().map(|e| causal_edge_key(e)).collect();
    let b_causal_edge_keys: HashSet<String> =
        b.causal_edges.iter().map(|e| causal_edge_key(e)).collect();

    let causal_edges_added = b_causal_edge_keys.difference(&a_causal_edge_keys).count();
    let causal_edges_removed = a_causal_edge_keys.difference(&b_causal_edge_keys).count();

    let confidence_delta = b.confidence - a.confidence;

    // Build summary.
    let mut parts = Vec::new();
    if confidence_delta.abs() > f64::EPSILON {
        parts.push(format!(
            "confidence {} by {:.3}",
            if confidence_delta > 0.0 {
                "increased"
            } else {
                "decreased"
            },
            confidence_delta.abs()
        ));
    }
    if causal_nodes_added > 0 || causal_nodes_removed > 0 {
        parts.push(format!(
            "{} causal nodes added, {} removed",
            causal_nodes_added, causal_nodes_removed
        ));
    }
    if causal_edges_added > 0 || causal_edges_removed > 0 {
        parts.push(format!(
            "{} causal edges added, {} removed",
            causal_edges_added, causal_edges_removed
        ));
    }
    if !nodes_only_a.is_empty() || !nodes_only_b.is_empty() {
        parts.push(format!(
            "{} node types only in A, {} only in B",
            nodes_only_a.len(),
            nodes_only_b.len()
        ));
    }
    let summary = if parts.is_empty() {
        "models are identical".to_string()
    } else {
        parts.join("; ")
    };

    ModelDiff {
        model_a: a.domain.clone(),
        model_b: b.domain.clone(),
        confidence_delta,
        nodes_only_a,
        nodes_only_b,
        nodes_common,
        edges_only_a,
        edges_only_b,
        edges_common,
        causal_nodes_added,
        causal_nodes_removed,
        causal_edges_added,
        causal_edges_removed,
        summary,
    }
}

// ---------------------------------------------------------------------------
// ModelMerge (K3c-G4c)
// ---------------------------------------------------------------------------

/// Result of merging two models.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MergeResult {
    /// The merged model.
    pub merged: ExportedModel,
    /// Conflicts that were resolved.
    pub conflicts: Vec<MergeConflict>,
    /// Statistics about the merge.
    pub stats: MergeStats,
}

/// A conflict encountered during model merge.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MergeConflict {
    /// What conflicted.
    pub item: String,
    /// Value from model A.
    pub value_a: String,
    /// Value from model B.
    pub value_b: String,
    /// How it was resolved.
    pub resolution: ConflictResolution,
}

/// How a merge conflict was resolved.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ConflictResolution {
    /// Kept the value from model A.
    KeepA,
    /// Kept the value from model B.
    KeepB,
    /// Merged both values.
    Merged,
    /// Used the higher confidence value.
    HigherConfidence,
}

/// Statistics about a model merge operation.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MergeStats {
    /// Total node types in the merged model.
    pub total_node_types: usize,
    /// Total edge types in the merged model.
    pub total_edge_types: usize,
    /// Total causal nodes in the merged model.
    pub total_causal_nodes: usize,
    /// Total causal edges in the merged model.
    pub total_causal_edges: usize,
    /// Number of conflicts resolved.
    pub conflicts_resolved: usize,
    /// Node types from A only.
    pub nodes_from_a: usize,
    /// Node types from B only.
    pub nodes_from_b: usize,
    /// Node types shared between A and B.
    pub nodes_shared: usize,
}

/// Merge two exported models into one.
///
/// Node types are unioned by name (higher-dimension embedding strategy wins
/// on conflict). Edge types are unioned by (from, to, type) key with higher
/// confidence kept. Causal nodes are unioned by label. Causal edges are
/// unioned by (source, target) key with weights averaged on overlap.
pub fn merge_models(a: &ExportedModel, b: &ExportedModel) -> MergeResult {
    let mut conflicts = Vec::new();

    // ── Node types ──────────────────────────────────────────────
    let a_node_map: HashMap<&str, &NodeTypeSpec> =
        a.node_types.iter().map(|n| (n.name.as_str(), n)).collect();
    let b_node_map: HashMap<&str, &NodeTypeSpec> =
        b.node_types.iter().map(|n| (n.name.as_str(), n)).collect();

    let all_node_names: HashSet<&str> =
        a_node_map.keys().chain(b_node_map.keys()).copied().collect();

    let mut merged_node_types = Vec::new();
    let mut nodes_from_a = 0usize;
    let mut nodes_from_b = 0usize;
    let mut nodes_shared = 0usize;

    for name in &all_node_names {
        match (a_node_map.get(name), b_node_map.get(name)) {
            (Some(na), None) => {
                merged_node_types.push((*na).clone());
                nodes_from_a += 1;
            }
            (None, Some(nb)) => {
                merged_node_types.push((*nb).clone());
                nodes_from_b += 1;
            }
            (Some(na), Some(nb)) => {
                nodes_shared += 1;
                if na.embedding_strategy != nb.embedding_strategy {
                    let (winner, resolution) = if na.dimensions >= nb.dimensions {
                        ((*na).clone(), ConflictResolution::KeepA)
                    } else {
                        ((*nb).clone(), ConflictResolution::KeepB)
                    };
                    conflicts.push(MergeConflict {
                        item: format!("node_type:{}", name),
                        value_a: na.embedding_strategy.clone(),
                        value_b: nb.embedding_strategy.clone(),
                        resolution,
                    });
                    merged_node_types.push(winner);
                } else {
                    merged_node_types.push((*na).clone());
                }
            }
            (None, None) => unreachable!(),
        }
    }

    // ── Edge types ──────────────────────────────────────────────
    let edge_key =
        |e: &EdgeTypeSpec| format!("{}->{}:{}", e.from_type, e.to_type, e.edge_type);
    let a_edge_map: HashMap<String, &EdgeTypeSpec> =
        a.edge_types.iter().map(|e| (edge_key(e), e)).collect();
    let b_edge_map: HashMap<String, &EdgeTypeSpec> =
        b.edge_types.iter().map(|e| (edge_key(e), e)).collect();

    let all_edge_keys: HashSet<&str> = a_edge_map
        .keys()
        .chain(b_edge_map.keys())
        .map(|s| s.as_str())
        .collect();

    let mut merged_edge_types = Vec::new();
    for key in &all_edge_keys {
        match (a_edge_map.get(*key), b_edge_map.get(*key)) {
            (Some(ea), None) => merged_edge_types.push((*ea).clone()),
            (None, Some(eb)) => merged_edge_types.push((*eb).clone()),
            (Some(ea), Some(eb)) => {
                if (ea.confidence - eb.confidence).abs() > f64::EPSILON {
                    let (winner, resolution) = if ea.confidence >= eb.confidence {
                        ((*ea).clone(), ConflictResolution::HigherConfidence)
                    } else {
                        ((*eb).clone(), ConflictResolution::HigherConfidence)
                    };
                    conflicts.push(MergeConflict {
                        item: format!("edge_type:{}", key),
                        value_a: format!("{:.4}", ea.confidence),
                        value_b: format!("{:.4}", eb.confidence),
                        resolution,
                    });
                    merged_edge_types.push(winner);
                } else {
                    merged_edge_types.push((*ea).clone());
                }
            }
            (None, None) => unreachable!(),
        }
    }

    // ── Causal nodes ────────────────────────────────────────────
    let a_cn_map: HashMap<&str, &ExportedCausalNode> =
        a.causal_nodes.iter().map(|n| (n.label.as_str(), n)).collect();
    let b_cn_map: HashMap<&str, &ExportedCausalNode> =
        b.causal_nodes.iter().map(|n| (n.label.as_str(), n)).collect();

    let all_cn_labels: HashSet<&str> =
        a_cn_map.keys().chain(b_cn_map.keys()).copied().collect();

    let mut merged_causal_nodes = Vec::new();
    for label in &all_cn_labels {
        match (a_cn_map.get(label), b_cn_map.get(label)) {
            (Some(na), None) => merged_causal_nodes.push((*na).clone()),
            (None, Some(nb)) => merged_causal_nodes.push((*nb).clone()),
            (Some(_na), Some(nb)) => {
                // Both have the node; prefer B (assumed later export).
                merged_causal_nodes.push((*nb).clone());
            }
            (None, None) => unreachable!(),
        }
    }

    // ── Causal edges ────────────────────────────────────────────
    let ce_key =
        |e: &ExportedCausalEdge| format!("{}->{}", e.source_label, e.target_label);
    let a_ce_map: HashMap<String, &ExportedCausalEdge> =
        a.causal_edges.iter().map(|e| (ce_key(e), e)).collect();
    let b_ce_map: HashMap<String, &ExportedCausalEdge> =
        b.causal_edges.iter().map(|e| (ce_key(e), e)).collect();

    let all_ce_keys: HashSet<&str> = a_ce_map
        .keys()
        .chain(b_ce_map.keys())
        .map(|s| s.as_str())
        .collect();

    let mut merged_causal_edges = Vec::new();
    for key in &all_ce_keys {
        match (a_ce_map.get(*key), b_ce_map.get(*key)) {
            (Some(ea), None) => merged_causal_edges.push((*ea).clone()),
            (None, Some(eb)) => merged_causal_edges.push((*eb).clone()),
            (Some(ea), Some(eb)) => {
                let mut merged_edge = (*ea).clone();
                merged_edge.weight = (ea.weight + eb.weight) / 2.0;
                if ea.edge_type != eb.edge_type {
                    conflicts.push(MergeConflict {
                        item: format!("causal_edge:{}", key),
                        value_a: ea.edge_type.clone(),
                        value_b: eb.edge_type.clone(),
                        resolution: ConflictResolution::Merged,
                    });
                }
                merged_causal_edges.push(merged_edge);
            }
            (None, None) => unreachable!(),
        }
    }

    // ── Merged metadata ─────────────────────────────────────────
    let mut merged_metadata = a.metadata.clone();
    for (k, v) in &b.metadata {
        merged_metadata.entry(k.clone()).or_insert_with(|| v.clone());
    }

    // ── Merged confidence: weighted average by causal node count ──
    let a_weight = a.causal_nodes.len().max(1) as f64;
    let b_weight = b.causal_nodes.len().max(1) as f64;
    let merged_confidence =
        (a.confidence * a_weight + b.confidence * b_weight) / (a_weight + b_weight);

    let merged = ExportedModel {
        version: "1.0".to_string(),
        domain: format!("{}+{}", a.domain, b.domain),
        exported_at: Utc::now(),
        confidence: merged_confidence,
        node_types: merged_node_types,
        edge_types: merged_edge_types,
        causal_nodes: merged_causal_nodes,
        causal_edges: merged_causal_edges,
        metadata: merged_metadata,
    };

    let stats = MergeStats {
        total_node_types: merged.node_types.len(),
        total_edge_types: merged.edge_types.len(),
        total_causal_nodes: merged.causal_nodes.len(),
        total_causal_edges: merged.causal_edges.len(),
        conflicts_resolved: conflicts.len(),
        nodes_from_a,
        nodes_from_b,
        nodes_shared,
    };

    MergeResult {
        merged,
        conflicts,
        stats,
    }
}

// ---------------------------------------------------------------------------
// Knowledge Base Persistence (K3c-G5b)
// ---------------------------------------------------------------------------

/// Serializable form of the knowledge base for JSON persistence.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SerializableKB {
    /// Schema version.
    pub version: u32,
    /// Learned strategy patterns.
    pub patterns: Vec<StrategyPattern>,
    /// Domains that have been modeled.
    pub domains_modeled: Vec<String>,
    /// Total modeling sessions conducted.
    pub total_sessions: u64,
    /// When the KB was last updated.
    pub last_updated: DateTime<Utc>,
}

impl WeaverKnowledgeBase {
    /// Convert to a serializable representation.
    pub fn to_serializable(&self) -> SerializableKB {
        let patterns = self.list_strategies();
        let domains: Vec<String> = patterns
            .iter()
            .map(|p| p.context.clone())
            .collect::<HashSet<_>>()
            .into_iter()
            .collect();
        SerializableKB {
            version: 1,
            patterns,
            domains_modeled: domains,
            total_sessions: self.count(),
            last_updated: Utc::now(),
        }
    }

    /// Reconstruct from a serializable representation.
    pub fn from_serializable(kb: SerializableKB) -> Self {
        let result = Self::new();
        for pattern in kb.patterns {
            result.record_strategy(pattern);
        }
        result
    }

    /// Save the knowledge base to a JSON file.
    pub fn save_to_file(&self, path: &Path) -> Result<(), WeaverError> {
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent)?;
        }
        let json = serde_json::to_string_pretty(&self.to_serializable())?;
        std::fs::write(path, json)?;
        Ok(())
    }

    /// Load the knowledge base from a JSON file.
    pub fn load_from_file(path: &Path) -> Result<Self, WeaverError> {
        let data = std::fs::read_to_string(path)?;
        let kb: SerializableKB = serde_json::from_str(&data)?;
        Ok(Self::from_serializable(kb))
    }

    /// Add a strategy pattern learned from a modeling session.
    ///
    /// If a similar pattern exists (same decision_type and context),
    /// updates the existing pattern's improvement based on new evidence.
    /// Otherwise, adds it as a new pattern.
    pub fn learn_pattern(&self, pattern: StrategyPattern) {
        if let Ok(mut strategies) = self.strategies.write() {
            if let Some(existing) = strategies.iter_mut().find(|s| {
                s.decision_type == pattern.decision_type
                    && s.context == pattern.context
            }) {
                existing.improvement =
                    (existing.improvement + pattern.improvement) / 2.0;
                existing.timestamp = pattern.timestamp;
                return;
            }
            strategies.push(pattern);
            self.strategy_count.fetch_add(1, Ordering::Relaxed);
        }
    }

    /// Find applicable patterns for a domain given its characteristics.
    ///
    /// Scores each pattern by how many of the provided characteristics
    /// appear in the pattern's context. Returns patterns sorted by
    /// relevance (highest match score first).
    pub fn find_patterns(
        &self,
        domain_characteristics: &[String],
    ) -> Vec<StrategyPattern> {
        let strategies = match self.strategies.read() {
            Ok(s) => s,
            Err(_) => return Vec::new(),
        };

        let mut scored: Vec<(usize, &StrategyPattern)> = strategies
            .iter()
            .filter_map(|s| {
                let score = domain_characteristics
                    .iter()
                    .filter(|c| s.context.contains(c.as_str()))
                    .count();
                if score > 0 {
                    Some((score, s))
                } else {
                    None
                }
            })
            .collect();

        scored.sort_by(|a, b| b.0.cmp(&a.0));
        scored.into_iter().map(|(_, p)| p.clone()).collect()
    }

    /// Number of stored patterns.
    pub fn pattern_count(&self) -> usize {
        self.strategies.read().map(|s| s.len()).unwrap_or(0)
    }
}

// ── Tests ─────────────────────────────────────────────────────────────────

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

    fn make_engine() -> WeaverEngine {
        let graph = Arc::new(CausalGraph::new());
        let hnsw = Arc::new(HnswService::new(HnswServiceConfig::default()));
        WeaverEngine::new_with_mock(graph, hnsw)
    }

    #[test]
    fn start_session_creates_session() {
        let engine = make_engine();
        let sid = engine
            .start_session("test-domain", Some("test context"), None)
            .unwrap();
        assert!(!sid.is_empty());
        let session = engine.get_session("test-domain").unwrap();
        assert_eq!(session.domain, "test-domain");
        assert!(session.active);
        assert_eq!(session.confidence, 0.0);
    }

    #[test]
    fn duplicate_session_start_fails() {
        let engine = make_engine();
        engine.start_session("dup", None, None).unwrap();
        let result = engine.start_session("dup", None, None);
        assert!(result.is_err());
    }

    #[test]
    fn stop_and_resume_session() {
        let engine = make_engine();
        engine.start_session("lifecycle", None, None).unwrap();
        engine.stop_session("lifecycle").unwrap();
        assert!(!engine.get_session("lifecycle").unwrap().active);
        engine.resume_session("lifecycle").unwrap();
        assert!(engine.get_session("lifecycle").unwrap().active);
    }

    #[test]
    fn add_source_records_ingestion() {
        let engine = make_engine();
        engine.start_session("src-test", None, None).unwrap();
        engine.add_source("src-test", "git_log", None).unwrap();
        let session = engine.get_session("src-test").unwrap();
        assert_eq!(session.sources_ingested, vec!["git_log"]);
    }

    #[test]
    fn add_source_nonexistent_domain_fails() {
        let engine = make_engine();
        let result = engine.add_source("nope", "git_log", None);
        assert!(result.is_err());
    }

    #[test]
    fn evaluate_confidence_basic() {
        let engine = make_engine();
        engine.start_session("conf", None, None).unwrap();
        let report = engine.evaluate_confidence("conf").unwrap();
        assert!(report.overall >= 0.0 && report.overall <= 1.0);
        // With no sources, should have gaps.
        assert!(!report.gaps.is_empty());
    }

    #[test]
    fn evaluate_confidence_improves_with_sources() {
        let engine = make_engine();
        engine.start_session("improve", None, None).unwrap();
        let r1 = engine.evaluate_confidence("improve").unwrap();
        engine.add_source("improve", "git_log", None).unwrap();
        engine.add_source("improve", "file_tree", None).unwrap();
        let r2 = engine.evaluate_confidence("improve").unwrap();
        assert!(r2.overall >= r1.overall);
    }

    #[test]
    fn tick_with_no_session_returns_idle() {
        let engine = make_engine();
        let result = engine.tick(Duration::from_secs(1));
        assert!(matches!(result, TickResult::Idle));
    }

    #[test]
    fn tick_processes_active_session() {
        let engine = make_engine();
        engine.start_session("tick-test", None, None).unwrap();
        let result = engine.tick(Duration::from_secs(5));
        assert!(matches!(result, TickResult::Progress { .. }));
        let session = engine.get_session("tick-test").unwrap();
        assert_eq!(session.tick_count, 1);
    }

    #[test]
    fn tick_increments_total_count() {
        let engine = make_engine();
        engine.start_session("ticks", None, None).unwrap();
        engine.tick(Duration::from_secs(5));
        engine.tick(Duration::from_secs(5));
        assert_eq!(engine.total_ticks(), 2);
    }

    #[test]
    fn tick_skips_stopped_session() {
        let engine = make_engine();
        engine.start_session("stopped", None, None).unwrap();
        engine.stop_session("stopped").unwrap();
        let result = engine.tick(Duration::from_secs(5));
        assert!(matches!(result, TickResult::Idle));
    }

    #[test]
    fn export_model_basic() {
        let engine = make_engine();
        engine.start_session("export", None, None).unwrap();
        engine.add_source("export", "git_log", None).unwrap();
        let model = engine.export_model("export", 0.0).unwrap();
        assert_eq!(model.domain, "export");
        assert_eq!(model.version, "1.0");
        assert!(!model.node_types.is_empty());
    }

    #[test]
    fn export_model_filters_by_confidence() {
        let engine = make_engine();
        engine.start_session("filter", None, None).unwrap();
        engine.add_source("filter", "git", None).unwrap();
        engine.add_source("filter", "file", None).unwrap();
        let model_all = engine.export_model("filter", 0.0).unwrap();
        let model_high = engine.export_model("filter", 0.5).unwrap();
        assert!(model_all.edge_types.len() >= model_high.edge_types.len());
    }

    #[test]
    fn import_model_creates_session() {
        let engine = make_engine();
        let model = ExportedModel {
            version: "1.0".into(),
            domain: "imported".into(),
            exported_at: Utc::now(),
            confidence: 0.75,
            node_types: vec![],
            edge_types: vec![],
            causal_nodes: vec![],
            causal_edges: vec![],
            metadata: HashMap::new(),
        };
        engine.import_model("imported", model).unwrap();
        let session = engine.get_session("imported").unwrap();
        assert_eq!(session.confidence, 0.75);
        assert!(session.active);
    }

    #[test]
    fn import_model_version_check() {
        let engine = make_engine();
        let model = ExportedModel {
            version: "2.0".into(),
            domain: "bad".into(),
            exported_at: Utc::now(),
            confidence: 0.5,
            node_types: vec![],
            edge_types: vec![],
            causal_nodes: vec![],
            causal_edges: vec![],
            metadata: HashMap::new(),
        };
        let result = engine.import_model("bad", model);
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("incompatible"));
    }

    #[test]
    fn meta_loom_events_recorded_on_session_start() {
        let engine = make_engine();
        engine.start_session("meta", None, None).unwrap();
        let events = engine.meta_loom_events("meta");
        assert!(!events.is_empty());
        assert!(matches!(
            events[0].decision_type,
            MetaDecisionType::ModelVersionBumped { .. }
        ));
    }

    #[test]
    fn meta_loom_events_recorded_on_source_add() {
        let engine = make_engine();
        engine.start_session("meta-src", None, None).unwrap();
        engine.add_source("meta-src", "git_log", None).unwrap();
        let events = engine.meta_loom_events("meta-src");
        assert!(events.len() >= 2); // session start + source add
        assert!(matches!(
            events.last().unwrap().decision_type,
            MetaDecisionType::SourceAdded { .. }
        ));
    }

    #[test]
    fn knowledge_base_record_and_list() {
        let kb = WeaverKnowledgeBase::new();
        kb.record_strategy(StrategyPattern {
            decision_type: "SourceAdded".into(),
            context: "rust-project".into(),
            improvement: 0.15,
            timestamp: Utc::now(),
        });
        let strategies = kb.list_strategies();
        assert_eq!(strategies.len(), 1);
        assert_eq!(strategies[0].improvement, 0.15);
    }

    #[test]
    fn knowledge_base_strategies_for_domain() {
        let kb = WeaverKnowledgeBase::new();
        kb.record_strategy(StrategyPattern {
            decision_type: "SourceAdded".into(),
            context: "rust".into(),
            improvement: 0.1,
            timestamp: Utc::now(),
        });
        kb.record_strategy(StrategyPattern {
            decision_type: "EdgeType".into(),
            context: "python".into(),
            improvement: 0.2,
            timestamp: Utc::now(),
        });
        assert_eq!(kb.strategies_for("rust").len(), 1);
        assert_eq!(kb.strategies_for("python").len(), 1);
        assert_eq!(kb.strategies_for("go").len(), 0);
    }

    #[test]
    fn knowledge_base_export() {
        let kb = WeaverKnowledgeBase::new();
        kb.record_strategy(StrategyPattern {
            decision_type: "test".into(),
            context: "test".into(),
            improvement: 0.5,
            timestamp: Utc::now(),
        });
        let exported = kb.export();
        assert!(exported.is_array());
    }

    #[test]
    fn handle_command_session_start() {
        let engine = make_engine();
        let resp = engine.handle_command(WeaverCommand::SessionStart {
            domain: "cmd-test".into(),
            git_path: None,
            context: None,
            goal: None,
        });
        assert!(matches!(resp, WeaverResponse::SessionStarted { .. }));
    }

    #[test]
    fn handle_command_confidence() {
        let engine = make_engine();
        engine.start_session("cmd-conf", None, None).unwrap();
        let resp = engine.handle_command(WeaverCommand::Confidence {
            domain: "cmd-conf".into(),
            edge: None,
            verbose: false,
        });
        assert!(matches!(resp, WeaverResponse::ConfidenceReport(_)));
    }

    #[test]
    fn handle_command_source_list() {
        let engine = make_engine();
        engine.start_session("cmd-src", None, None).unwrap();
        engine.add_source("cmd-src", "git_log", None).unwrap();
        let resp = engine.handle_command(WeaverCommand::SourceList {
            domain: "cmd-src".into(),
        });
        match resp {
            WeaverResponse::Sources(s) => assert_eq!(s, vec!["git_log"]),
            other => panic!("expected Sources, got {other:?}"),
        }
    }

    #[test]
    fn handle_command_unknown_domain() {
        let engine = make_engine();
        let resp = engine.handle_command(WeaverCommand::Confidence {
            domain: "missing".into(),
            edge: None,
            verbose: false,
        });
        assert!(matches!(resp, WeaverResponse::Error(_)));
    }

    #[test]
    fn list_sessions() {
        let engine = make_engine();
        engine.start_session("a", None, None).unwrap();
        engine.start_session("b", None, None).unwrap();
        let mut sessions = engine.list_sessions();
        sessions.sort();
        assert_eq!(sessions, vec!["a", "b"]);
    }

    #[tokio::test]
    async fn system_service_impl() {
        let engine = make_engine();
        assert_eq!(engine.name(), "weaver");
        assert_eq!(engine.service_type(), ServiceType::Core);
        engine.start().await.unwrap();
        let health = engine.health_check().await;
        assert_eq!(health, HealthStatus::Healthy);
        engine.stop().await.unwrap();
    }

    #[test]
    fn impulse_emitted_on_session_start() {
        let queue = Arc::new(ImpulseQueue::new());
        let graph = Arc::new(CausalGraph::new());
        let hnsw = Arc::new(HnswService::new(HnswServiceConfig::default()));
        let mut engine = WeaverEngine::new_with_mock(graph, hnsw);
        engine.set_impulse_queue(queue.clone());
        engine.start_session("impulse-test", None, None).unwrap();
        let impulses = queue.drain_ready();
        assert!(!impulses.is_empty());
        assert!(impulses.iter().any(|i| i.impulse_type == ImpulseType::Custom(0x32)));
    }

    #[test]
    fn impulse_emitted_on_source_add() {
        let queue = Arc::new(ImpulseQueue::new());
        let graph = Arc::new(CausalGraph::new());
        let hnsw = Arc::new(HnswService::new(HnswServiceConfig::default()));
        let mut engine = WeaverEngine::new_with_mock(graph, hnsw);
        engine.set_impulse_queue(queue.clone());
        engine.start_session("impulse-src", None, None).unwrap();
        let _ = queue.drain_ready(); // clear session-start impulse
        engine.add_source("impulse-src", "git", None).unwrap();
        let impulses = queue.drain_ready();
        assert!(impulses.iter().any(|i| i.impulse_type == ImpulseType::Custom(0x33)));
    }

    // ── Graph ingestion tests ────────────────────────────────────

    #[test]
    fn ingest_graph_file_git_history() {
        let manifest = std::env::var("CARGO_MANIFEST_DIR").unwrap_or_else(|_| ".".to_string());
        let graph_path = PathBuf::from(&manifest)
            .join("../../.weftos/graph/git-history.json");
        if !graph_path.exists() {
            // Skip if running outside the project tree.
            return;
        }
        let engine = make_engine();
        let result = engine.ingest_graph_file(&graph_path).unwrap();
        assert!(result.nodes_added > 0, "should ingest at least one node");
        assert_eq!(result.source, "git-history");
        assert!(result.embeddings_created > 0, "should create embeddings");
        // Verify causal graph was populated.
        assert!(engine.causal_graph().node_count() > 0);
    }

    #[test]
    fn ingest_graph_file_module_deps() {
        let manifest = std::env::var("CARGO_MANIFEST_DIR").unwrap_or_else(|_| ".".to_string());
        let graph_path = PathBuf::from(&manifest)
            .join("../../.weftos/graph/module-deps.json");
        if !graph_path.exists() {
            return;
        }
        let engine = make_engine();
        let result = engine.ingest_graph_file(&graph_path).unwrap();
        assert!(result.nodes_added > 0);
        assert_eq!(result.source, "module-dependencies");
    }

    #[test]
    fn ingest_graph_file_decisions() {
        let manifest = std::env::var("CARGO_MANIFEST_DIR").unwrap_or_else(|_| ".".to_string());
        let graph_path = PathBuf::from(&manifest)
            .join("../../.weftos/graph/decisions.json");
        if !graph_path.exists() {
            return;
        }
        let engine = make_engine();
        let result = engine.ingest_graph_file(&graph_path).unwrap();
        assert!(result.nodes_added > 0);
        assert_eq!(result.source, "decisions-and-phases");
    }

    #[test]
    fn ingest_graph_creates_edges() {
        let manifest = std::env::var("CARGO_MANIFEST_DIR").unwrap_or_else(|_| ".".to_string());
        let graph_path = PathBuf::from(&manifest)
            .join("../../.weftos/graph/git-history.json");
        if !graph_path.exists() {
            return;
        }
        let engine = make_engine();
        let result = engine.ingest_graph_file(&graph_path).unwrap();
        assert!(result.edges_added > 0, "git-history graph should have edges");
        assert!(engine.causal_graph().edge_count() > 0);
    }

    #[test]
    fn ingest_graph_populates_hnsw() {
        let manifest = std::env::var("CARGO_MANIFEST_DIR").unwrap_or_else(|_| ".".to_string());
        let graph_path = PathBuf::from(&manifest)
            .join("../../.weftos/graph/module-deps.json");
        if !graph_path.exists() {
            return;
        }
        let engine = make_engine();
        let result = engine.ingest_graph_file(&graph_path).unwrap();
        assert!(result.embeddings_created > 0);
        assert!(engine.hnsw().insert_count() > 0);
    }

    #[test]
    fn ingest_nonexistent_file_returns_error() {
        let engine = make_engine();
        let result = engine.ingest_graph_file(Path::new("/nonexistent/graph.json"));
        assert!(result.is_err());
    }

    #[test]
    fn ingest_invalid_json_returns_error() {
        let dir = std::env::temp_dir().join("weaver_test_invalid");
        std::fs::create_dir_all(&dir).ok();
        let path = dir.join("bad.json");
        std::fs::write(&path, "not valid json {{{").unwrap();
        let engine = make_engine();
        let result = engine.ingest_graph_file(&path);
        assert!(result.is_err());
        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn ingest_empty_graph_returns_zero_counts() {
        let dir = std::env::temp_dir().join("weaver_test_empty");
        std::fs::create_dir_all(&dir).ok();
        let path = dir.join("empty.json");
        std::fs::write(
            &path,
            r#"{"source":"test","nodes":[],"edges":[]}"#,
        )
        .unwrap();
        let engine = make_engine();
        let result = engine.ingest_graph_file(&path).unwrap();
        assert_eq!(result.nodes_added, 0);
        assert_eq!(result.edges_added, 0);
        assert_eq!(result.embeddings_created, 0);
        assert_eq!(result.source, "test");
        std::fs::remove_dir_all(&dir).ok();
    }

    // ── Confidence scoring tests ─────────────────────────────────

    #[test]
    fn compute_confidence_empty_graph() {
        let engine = make_engine();
        let report = engine.compute_confidence();
        assert_eq!(report.overall, 0.0);
        assert!(!report.gaps.is_empty(), "should have gaps with empty graph");
        assert!(
            !report.suggestions.is_empty(),
            "should have suggestions with empty graph"
        );
    }

    #[test]
    fn compute_confidence_with_nodes_only() {
        let engine = make_engine();
        // Add nodes without edges -- should be partially confident.
        for i in 0..10 {
            engine.causal_graph().add_node(
                format!("node-{i}"),
                serde_json::json!({"test": true}),
            );
        }
        let report = engine.compute_confidence();
        // All orphans: connectivity = 0, but volume > 0.
        assert!(report.overall > 0.0, "should have some confidence from volume");
        assert!(report.overall < 0.5, "should be low without edges");
    }

    #[test]
    fn compute_confidence_with_connected_graph() {
        let engine = make_engine();
        // Create a small connected graph.
        let n1 = engine.causal_graph().add_node(
            "module-a".into(),
            serde_json::json!({}),
        );
        let n2 = engine.causal_graph().add_node(
            "module-b".into(),
            serde_json::json!({}),
        );
        let n3 = engine.causal_graph().add_node(
            "module-c".into(),
            serde_json::json!({}),
        );
        engine.causal_graph().link(n1, n2, CausalEdgeType::Enables, 1.0, 0, 0);
        engine.causal_graph().link(n2, n3, CausalEdgeType::Causes, 0.8, 0, 0);

        let report = engine.compute_confidence();
        // At least 2 of 3 nodes have edges, so connectivity should be decent.
        assert!(report.overall > 0.0);
    }

    #[test]
    fn compute_confidence_detects_orphans() {
        let engine = make_engine();
        let n1 = engine.causal_graph().add_node(
            "connected-a".into(),
            serde_json::json!({}),
        );
        let n2 = engine.causal_graph().add_node(
            "connected-b".into(),
            serde_json::json!({}),
        );
        engine.causal_graph().add_node(
            "orphan-x".into(),
            serde_json::json!({}),
        );
        engine.causal_graph().link(n1, n2, CausalEdgeType::Follows, 1.0, 0, 0);

        let report = engine.compute_confidence();
        // The suggestion should mention orphan nodes.
        let has_orphan_suggestion = report.suggestions.iter().any(|s| match s {
            ModelingSuggestion::AddSource { reason, .. } => reason.contains("orphan"),
            _ => false,
        });
        assert!(has_orphan_suggestion, "should detect the orphan node");
    }

    #[test]
    fn compute_confidence_improves_with_more_data() {
        let engine = make_engine();
        // Small graph.
        let n1 = engine.causal_graph().add_node("a".into(), serde_json::json!({}));
        let n2 = engine.causal_graph().add_node("b".into(), serde_json::json!({}));
        engine.causal_graph().link(n1, n2, CausalEdgeType::Enables, 1.0, 0, 0);
        let c1 = engine.compute_confidence().overall;

        // Add more connected nodes.
        for i in 0..50 {
            let na = engine.causal_graph().add_node(format!("extra-{i}"), serde_json::json!({}));
            engine.causal_graph().link(n1, na, CausalEdgeType::Correlates, 0.5, 0, 0);
        }
        let c2 = engine.compute_confidence().overall;
        assert!(c2 > c1, "confidence should increase with more data ({c2} > {c1})");
    }

    // ── Model export/import roundtrip tests ──────────────────────

    #[test]
    fn export_model_includes_causal_data() {
        let engine = make_engine();
        engine.start_session("exp-causal", None, None).unwrap();
        // Add some nodes and edges.
        let n1 = engine.causal_graph().add_node("node-a".into(), serde_json::json!({}));
        let n2 = engine.causal_graph().add_node("node-b".into(), serde_json::json!({}));
        engine.causal_graph().link(n1, n2, CausalEdgeType::Causes, 0.9, 0, 0);

        let model = engine.export_model("exp-causal", 0.0).unwrap();
        assert!(!model.causal_nodes.is_empty(), "exported model should have nodes");
        assert!(!model.causal_edges.is_empty(), "exported model should have edges");
    }

    #[test]
    fn export_model_to_file_roundtrip() {
        let dir = std::env::temp_dir().join("weaver_test_export");
        std::fs::create_dir_all(&dir).ok();
        let path = dir.join("test-model.json");

        let engine = make_engine();
        engine.start_session("roundtrip", None, None).unwrap();
        engine.add_source("roundtrip", "git_log", None).unwrap();

        // Add some graph data.
        let n1 = engine.causal_graph().add_node("rt-a".into(), serde_json::json!({}));
        let n2 = engine.causal_graph().add_node("rt-b".into(), serde_json::json!({}));
        engine.causal_graph().link(n1, n2, CausalEdgeType::Enables, 1.0, 0, 0);

        // Export.
        let exported = engine.export_model_to_file("roundtrip", 0.0, &path).unwrap();
        assert!(path.exists(), "export file should exist");

        // Read back and verify JSON is valid.
        let data = std::fs::read_to_string(&path).unwrap();
        let reimported: ExportedModel = serde_json::from_str(&data).unwrap();
        assert_eq!(reimported.domain, "roundtrip");
        assert_eq!(reimported.version, exported.version);
        assert_eq!(reimported.causal_nodes.len(), exported.causal_nodes.len());
        assert_eq!(reimported.causal_edges.len(), exported.causal_edges.len());

        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn import_model_from_file_works() {
        let dir = std::env::temp_dir().join("weaver_test_import");
        std::fs::create_dir_all(&dir).ok();
        let path = dir.join("import-model.json");

        // Write a model file.
        let model = ExportedModel {
            version: "1.0".into(),
            domain: "file-import".into(),
            exported_at: Utc::now(),
            confidence: 0.82,
            node_types: vec![],
            edge_types: vec![],
            causal_nodes: vec![ExportedCausalNode {
                label: "test-node".into(),
                metadata: serde_json::json!({}),
            }],
            causal_edges: vec![],
            metadata: HashMap::new(),
        };
        let json = serde_json::to_string_pretty(&model).unwrap();
        std::fs::write(&path, json).unwrap();

        let engine = make_engine();
        engine.import_model_from_file("file-import", &path).unwrap();
        let session = engine.get_session("file-import").unwrap();
        assert_eq!(session.confidence, 0.82);
        assert!(session.active);

        std::fs::remove_dir_all(&dir).ok();
    }

    // ── Edge type parsing tests ──────────────────────────────────

    #[test]
    fn parse_edge_type_known_types() {
        assert_eq!(WeaverEngine::parse_edge_type("Causes"), CausalEdgeType::Causes);
        assert_eq!(WeaverEngine::parse_edge_type("Enables"), CausalEdgeType::Enables);
        assert_eq!(WeaverEngine::parse_edge_type("Follows"), CausalEdgeType::Follows);
        assert_eq!(WeaverEngine::parse_edge_type("Correlates"), CausalEdgeType::Correlates);
        assert_eq!(WeaverEngine::parse_edge_type("EvidenceFor"), CausalEdgeType::EvidenceFor);
        assert_eq!(WeaverEngine::parse_edge_type("Inhibits"), CausalEdgeType::Inhibits);
        assert_eq!(WeaverEngine::parse_edge_type("Contradicts"), CausalEdgeType::Contradicts);
        assert_eq!(WeaverEngine::parse_edge_type("TriggeredBy"), CausalEdgeType::TriggeredBy);
    }

    #[test]
    fn parse_edge_type_unknown_defaults_to_correlates() {
        assert_eq!(WeaverEngine::parse_edge_type("FooBar"), CausalEdgeType::Correlates);
        assert_eq!(WeaverEngine::parse_edge_type(""), CausalEdgeType::Correlates);
    }

    // ── WeaverError tests ────────────────────────────────────────

    #[test]
    fn weaver_error_display() {
        let io_err = WeaverError::Io(std::io::Error::new(
            std::io::ErrorKind::NotFound,
            "file missing",
        ));
        assert!(io_err.to_string().contains("I/O"));

        let domain_err = WeaverError::Domain("test failure".to_string());
        assert!(domain_err.to_string().contains("test failure"));
    }

    // ── CognitiveTick integration tests ─────────────────────────

    fn make_engine_mut() -> WeaverEngine {
        let graph = Arc::new(CausalGraph::new());
        let hnsw = Arc::new(HnswService::new(HnswServiceConfig::default()));
        WeaverEngine::new_with_mock(graph, hnsw)
    }

    #[test]
    fn on_tick_respects_budget() {
        let mut engine = make_engine_mut();
        engine.start_session("tick-budget", None, None).unwrap();
        let result = engine.on_tick(500); // 500ms budget
        assert!(
            result.within_budget,
            "tick should complete within 500ms budget"
        );
        assert!(result.elapsed_ms <= 500, "elapsed should be within budget");
    }

    #[test]
    fn on_tick_returns_correct_fields() {
        let mut engine = make_engine_mut();
        engine.start_session("tick-fields", None, None).unwrap();
        let result = engine.on_tick(100);
        assert_eq!(result.budget_ms, 100);
        assert_eq!(result.tick_number, 0); // first tick
        // No git poller or file watcher configured, so these should be 0.
        assert_eq!(result.git_commits_found, 0);
        assert_eq!(result.files_changed, 0);
    }

    #[test]
    fn on_tick_increments_tick_count() {
        let mut engine = make_engine_mut();
        engine.start_session("tick-count", None, None).unwrap();
        engine.on_tick(100);
        engine.on_tick(100);
        engine.on_tick(100);
        // on_tick calls tick() internally which also increments, plus on_tick itself.
        // The on_tick method does fetch_add(1) each call.
        assert!(engine.total_ticks() >= 3, "should have at least 3 ticks");
    }

    #[test]
    fn on_tick_confidence_update_after_100_ticks() {
        let mut engine = make_engine_mut();
        engine.start_session("conf-update", None, None).unwrap();
        // Simulate 101 ticks to trigger confidence update.
        engine.ticks_since_confidence_update = 101;
        let result = engine.on_tick(1000);
        assert!(
            result.confidence_updated,
            "confidence should be updated after 100+ ticks"
        );
        assert!(
            engine.cached_confidence().is_some(),
            "cached confidence should be set"
        );
        assert_eq!(
            engine.ticks_since_confidence_update, 1,
            "counter should reset to 1 (incremented after reset)"
        );
    }

    #[test]
    fn on_tick_no_confidence_update_before_100_ticks() {
        let mut engine = make_engine_mut();
        engine.start_session("no-conf-update", None, None).unwrap();
        let result = engine.on_tick(100);
        assert!(
            !result.confidence_updated,
            "should not update confidence on first tick"
        );
    }

    #[test]
    fn on_tick_git_and_file_watcher_disabled_by_default() {
        let engine = make_engine_mut();
        assert!(
            engine.git_poller().is_none(),
            "git poller should be None by default"
        );
        assert!(
            engine.file_watcher().is_none(),
            "file watcher should be None by default"
        );
    }

    // ── GitPoller tests ─────────────────────────────────────────

    #[test]
    fn git_poller_poll_detects_commits_in_real_repo() {
        // Use the actual project repo for this test.
        let manifest =
            std::env::var("CARGO_MANIFEST_DIR").unwrap_or_else(|_| ".".to_string());
        let repo_path = PathBuf::from(&manifest).join("../..");
        if !repo_path.join(".git").exists() {
            return; // skip if not in a git repo
        }
        let mut poller = GitPoller::new(repo_path, "HEAD".to_string());
        // First poll should detect at least 1 commit.
        let count = poller.poll();
        assert!(count >= 1, "first poll should find at least 1 commit");
        assert!(poller.last_hash().is_some(), "last hash should be set");
    }

    #[test]
    fn git_poller_poll_returns_zero_on_no_changes() {
        let manifest =
            std::env::var("CARGO_MANIFEST_DIR").unwrap_or_else(|_| ".".to_string());
        let repo_path = PathBuf::from(&manifest).join("../..");
        if !repo_path.join(".git").exists() {
            return;
        }
        let mut poller = GitPoller::new(repo_path, "HEAD".to_string());
        poller.poll(); // first poll sets the baseline
        let count = poller.poll(); // second poll, no new commits
        assert_eq!(count, 0, "second poll should find 0 new commits");
    }

    #[test]
    fn git_poller_disabled_returns_zero() {
        let mut poller = GitPoller::new(PathBuf::from("/tmp"), "main".to_string());
        poller.set_enabled(false);
        assert_eq!(poller.poll(), 0);
        assert!(!poller.is_enabled());
    }

    #[test]
    fn git_poller_nonexistent_repo_returns_zero() {
        let mut poller = GitPoller::new(
            PathBuf::from("/nonexistent/path/to/repo"),
            "main".to_string(),
        );
        let count = poller.poll();
        assert_eq!(count, 0, "should return 0 for nonexistent repo");
        assert!(poller.last_hash().is_none());
    }

    #[test]
    fn git_poller_branch_accessor() {
        let poller = GitPoller::new(PathBuf::from("/tmp"), "develop".to_string());
        assert_eq!(poller.branch(), "develop");
    }

    // ── FileWatcher tests ───────────────────────────────────────

    #[test]
    fn file_watcher_watch_and_poll_detects_mtime_change() {
        let dir = std::env::temp_dir().join("weaver_fw_test_mtime");
        std::fs::create_dir_all(&dir).ok();
        let path = dir.join("test.rs");
        std::fs::write(&path, "fn main() {}").unwrap();

        let mut watcher = FileWatcher::new(dir.clone(), vec!["*.rs".to_string()]);
        watcher.watch(path.clone());
        assert_eq!(watcher.watched_count(), 1);

        // First poll: no changes (mtime matches).
        let changed = watcher.poll_changes();
        assert!(changed.is_empty(), "no changes on first poll");

        // Simulate mtime change by sleeping briefly and rewriting.
        std::thread::sleep(std::time::Duration::from_millis(50));
        std::fs::write(&path, "fn main() { println!(\"changed\"); }").unwrap();

        let changed = watcher.poll_changes();
        assert_eq!(changed.len(), 1, "should detect the changed file");
        assert_eq!(changed[0], path);

        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn file_watcher_watch_directory_registers_files() {
        let dir = std::env::temp_dir().join("weaver_fw_test_dir");
        std::fs::create_dir_all(&dir).ok();
        std::fs::write(dir.join("lib.rs"), "// lib").unwrap();
        std::fs::write(dir.join("main.rs"), "// main").unwrap();
        std::fs::write(dir.join("readme.md"), "# readme").unwrap();

        let mut watcher = FileWatcher::new(dir.clone(), vec!["*.rs".to_string()]);
        watcher.watch_directory();
        assert_eq!(watcher.watched_count(), 2, "should only watch .rs files");

        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn file_watcher_detects_deleted_file() {
        let dir = std::env::temp_dir().join("weaver_fw_test_delete");
        std::fs::create_dir_all(&dir).ok();
        let path = dir.join("temp.rs");
        std::fs::write(&path, "// temp").unwrap();

        let mut watcher = FileWatcher::new(dir.clone(), vec!["*.rs".to_string()]);
        watcher.watch(path.clone());

        // Delete the file.
        std::fs::remove_file(&path).unwrap();
        let changed = watcher.poll_changes();
        assert_eq!(changed.len(), 1, "should detect deleted file");
        assert_eq!(watcher.watched_count(), 0, "deleted file should be unregistered");

        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn file_watcher_disabled_returns_empty() {
        let mut watcher = FileWatcher::new(
            PathBuf::from("/tmp"),
            vec!["*.rs".to_string()],
        );
        watcher.set_enabled(false);
        assert!(watcher.poll_changes().is_empty());
        assert!(!watcher.is_enabled());
    }

    // ── WeaverEngine git/file integration tests ─────────────────

    #[test]
    fn enable_git_polling_sets_poller() {
        let mut engine = make_engine_mut();
        assert!(engine.git_poller().is_none());
        engine.enable_git_polling(PathBuf::from("/tmp"), "main".to_string());
        assert!(engine.git_poller().is_some());
        assert_eq!(engine.git_poller().unwrap().branch(), "main");
    }

    #[test]
    fn enable_file_watching_sets_watcher() {
        let dir = std::env::temp_dir().join("weaver_fw_test_enable");
        std::fs::create_dir_all(&dir).ok();
        std::fs::write(dir.join("test.rs"), "// test").unwrap();

        let mut engine = make_engine_mut();
        assert!(engine.file_watcher().is_none());
        engine.enable_file_watching(dir.clone(), vec!["*.rs".to_string()]);
        assert!(engine.file_watcher().is_some());
        assert_eq!(engine.file_watcher().unwrap().watched_count(), 1);

        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn on_tick_with_git_polling_enabled() {
        let manifest =
            std::env::var("CARGO_MANIFEST_DIR").unwrap_or_else(|_| ".".to_string());
        let repo_path = PathBuf::from(&manifest).join("../..");
        if !repo_path.join(".git").exists() {
            return;
        }
        let mut engine = make_engine_mut();
        engine.start_session("git-tick", None, None).unwrap();
        engine.enable_git_polling(repo_path, "HEAD".to_string());
        let result = engine.on_tick(500);
        // First tick should detect at least 1 commit (initial baseline).
        assert!(
            result.git_commits_found >= 1,
            "first on_tick with git polling should find commits"
        );
    }

    #[test]
    fn cognitive_tick_result_default() {
        let result = CognitiveTickResult::default();
        assert_eq!(result.tick_number, 0);
        assert_eq!(result.elapsed_ms, 0);
        assert_eq!(result.budget_ms, 0);
        assert_eq!(result.git_commits_found, 0);
        assert_eq!(result.files_changed, 0);
        assert_eq!(result.nodes_processed, 0);
        assert!(!result.confidence_updated);
        assert!(!result.within_budget);
    }

    #[test]
    fn cognitive_tick_result_serde_roundtrip() {
        let result = CognitiveTickResult {
            tick_number: 42,
            elapsed_ms: 15,
            budget_ms: 50,
            git_commits_found: 3,
            files_changed: 2,
            nodes_processed: 10,
            confidence_updated: true,
            within_budget: true,
        };
        let json = serde_json::to_string(&result).unwrap();
        let restored: CognitiveTickResult = serde_json::from_str(&json).unwrap();
        assert_eq!(restored.tick_number, 42);
        assert_eq!(restored.git_commits_found, 3);
        assert!(restored.confidence_updated);
    }

    // ── ConfidenceHistory tests (Item 1) ─────────────────────────

    #[test]
    fn confidence_history_record_and_latest() {
        let mut history = ConfidenceHistory::new(10);
        assert!(history.is_empty());
        assert!(history.latest().is_none());

        history.record(ConfidenceSnapshot {
            timestamp: Utc::now(),
            tick_number: 1,
            confidence: 0.5,
            node_count: 10,
            edge_count: 5,
            gap_count: 2,
            trigger: ConfidenceTrigger::Periodic,
        });
        assert_eq!(history.len(), 1);
        assert_eq!(history.latest().unwrap().confidence, 0.5);
    }

    #[test]
    fn confidence_history_ring_buffer_eviction() {
        let mut history = ConfidenceHistory::new(3);
        for i in 0..5 {
            history.record(ConfidenceSnapshot {
                timestamp: Utc::now(),
                tick_number: i,
                confidence: i as f64 * 0.1,
                node_count: 0,
                edge_count: 0,
                gap_count: 0,
                trigger: ConfidenceTrigger::Periodic,
            });
        }
        assert_eq!(history.len(), 3);
        // Oldest should have been evicted; first remaining is tick 2.
        assert_eq!(history.all().front().unwrap().tick_number, 2);
        assert_eq!(history.latest().unwrap().tick_number, 4);
    }

    #[test]
    fn confidence_history_trend_improving() {
        let mut history = ConfidenceHistory::new(10);
        for i in 0..5 {
            history.record(ConfidenceSnapshot {
                timestamp: Utc::now(),
                tick_number: i,
                confidence: 0.3 + i as f64 * 0.1,
                node_count: 0,
                edge_count: 0,
                gap_count: 0,
                trigger: ConfidenceTrigger::Periodic,
            });
        }
        let trend = history.trend(5);
        assert_eq!(trend.direction, TrendDirection::Improving);
        assert!(trend.delta > 0.01);
        assert_eq!(trend.samples, 5);
    }

    #[test]
    fn confidence_history_trend_declining() {
        let mut history = ConfidenceHistory::new(10);
        for i in 0..4 {
            history.record(ConfidenceSnapshot {
                timestamp: Utc::now(),
                tick_number: i,
                confidence: 0.8 - i as f64 * 0.1,
                node_count: 0,
                edge_count: 0,
                gap_count: 0,
                trigger: ConfidenceTrigger::Periodic,
            });
        }
        let trend = history.trend(4);
        assert_eq!(trend.direction, TrendDirection::Declining);
        assert!(trend.delta < -0.01);
    }

    #[test]
    fn confidence_history_trend_stable() {
        let mut history = ConfidenceHistory::new(10);
        for i in 0..5 {
            history.record(ConfidenceSnapshot {
                timestamp: Utc::now(),
                tick_number: i,
                confidence: 0.75,
                node_count: 0,
                edge_count: 0,
                gap_count: 0,
                trigger: ConfidenceTrigger::Periodic,
            });
        }
        let trend = history.trend(5);
        assert_eq!(trend.direction, TrendDirection::Stable);
        assert!(trend.delta.abs() <= 0.01);
        assert!((trend.avg_confidence - 0.75).abs() < 0.001);
    }

    #[test]
    fn confidence_history_trend_empty() {
        let history = ConfidenceHistory::new(10);
        let trend = history.trend(5);
        assert_eq!(trend.direction, TrendDirection::Stable);
        assert_eq!(trend.samples, 0);
    }

    #[test]
    fn confidence_history_trend_window_clamp() {
        let mut history = ConfidenceHistory::new(10);
        history.record(ConfidenceSnapshot {
            timestamp: Utc::now(),
            tick_number: 0,
            confidence: 0.5,
            node_count: 0,
            edge_count: 0,
            gap_count: 0,
            trigger: ConfidenceTrigger::Manual,
        });
        // Ask for 100 but only 1 exists.
        let trend = history.trend(100);
        assert_eq!(trend.samples, 1);
    }

    // ── StrategyTracker tests (Item 4) ──────────────────────────

    #[test]
    fn strategy_tracker_begin_complete() {
        let mut tracker = StrategyTracker::new(50);
        assert!(tracker.is_empty());
        let handle = tracker.begin_strategy("add_git", "Add git log", 0.4);
        tracker.complete_strategy(handle, 0.55);
        assert_eq!(tracker.len(), 1);
        let outcome = &tracker.outcomes()[0];
        assert_eq!(outcome.strategy, "add_git");
        assert!((outcome.delta - 0.15).abs() < 0.001);
        assert!(outcome.beneficial);
    }

    #[test]
    fn strategy_tracker_most_effective() {
        let mut tracker = StrategyTracker::new(50);
        let h1 = tracker.begin_strategy("a", "desc a", 0.3);
        tracker.complete_strategy(h1, 0.5); // +0.2
        let h2 = tracker.begin_strategy("b", "desc b", 0.5);
        tracker.complete_strategy(h2, 0.9); // +0.4
        let h3 = tracker.begin_strategy("c", "desc c", 0.9);
        tracker.complete_strategy(h3, 0.85); // -0.05

        let top = tracker.most_effective(2);
        assert_eq!(top.len(), 2);
        assert_eq!(top[0].strategy, "b"); // highest delta
        assert_eq!(top[1].strategy, "a");
    }

    #[test]
    fn strategy_tracker_harmful_strategies() {
        let mut tracker = StrategyTracker::new(50);
        let h1 = tracker.begin_strategy("good", "good move", 0.5);
        tracker.complete_strategy(h1, 0.7);
        let h2 = tracker.begin_strategy("bad", "bad move", 0.7);
        tracker.complete_strategy(h2, 0.5);

        let harmful = tracker.harmful_strategies();
        assert_eq!(harmful.len(), 1);
        assert_eq!(harmful[0].strategy, "bad");
        assert!(!harmful[0].beneficial);
    }

    #[test]
    fn strategy_tracker_recommend() {
        let mut tracker = StrategyTracker::new(50);
        assert!(tracker.recommend().is_none());

        let h1 = tracker.begin_strategy("small_win", "desc", 0.5);
        tracker.complete_strategy(h1, 0.55);
        let h2 = tracker.begin_strategy("big_win", "desc", 0.55);
        tracker.complete_strategy(h2, 0.85);

        assert_eq!(tracker.recommend(), Some("big_win".to_string()));
    }

    #[test]
    fn strategy_tracker_recommend_ignores_harmful() {
        let mut tracker = StrategyTracker::new(50);
        let h = tracker.begin_strategy("harmful", "desc", 0.5);
        tracker.complete_strategy(h, 0.3);
        // Only harmful strategies => no recommendation.
        assert!(tracker.recommend().is_none());
    }

    #[test]
    fn strategy_tracker_eviction() {
        let mut tracker = StrategyTracker::new(2);
        let h1 = tracker.begin_strategy("first", "d", 0.1);
        tracker.complete_strategy(h1, 0.2);
        let h2 = tracker.begin_strategy("second", "d", 0.2);
        tracker.complete_strategy(h2, 0.3);
        let h3 = tracker.begin_strategy("third", "d", 0.3);
        tracker.complete_strategy(h3, 0.4);

        assert_eq!(tracker.len(), 2);
        assert_eq!(tracker.outcomes()[0].strategy, "second");
        assert_eq!(tracker.outcomes()[1].strategy, "third");
    }

    // ── TickHistory tests (Item 6) ──────────────────────────────

    #[test]
    fn tick_history_record_and_len() {
        let mut history = TickHistory::new(10);
        assert!(history.is_empty());
        history.record(CognitiveTickResult {
            tick_number: 0,
            elapsed_ms: 10,
            budget_ms: 50,
            ..Default::default()
        });
        assert_eq!(history.len(), 1);
    }

    #[test]
    fn tick_history_eviction() {
        let mut history = TickHistory::new(3);
        for i in 0..5 {
            history.record(CognitiveTickResult {
                tick_number: i,
                elapsed_ms: 10,
                budget_ms: 50,
                ..Default::default()
            });
        }
        assert_eq!(history.len(), 3);
        assert_eq!(history.all().front().unwrap().tick_number, 2);
    }

    #[test]
    fn tick_history_changes_per_minute() {
        let mut history = TickHistory::new(100);
        // 10 ticks, each 100ms elapsed, each with 1 git commit.
        for i in 0..10 {
            history.record(CognitiveTickResult {
                tick_number: i,
                elapsed_ms: 100,
                budget_ms: 200,
                git_commits_found: 1,
                files_changed: 0,
                ..Default::default()
            });
        }
        // Total: 10 changes in 1000ms = 1 second.
        // Changes per minute = 10 / (1000/60000) = 600.
        let cpm = history.changes_per_minute();
        assert!(cpm > 100.0, "expected high cpm, got {cpm}");
    }

    #[test]
    fn tick_history_changes_per_minute_no_changes() {
        let mut history = TickHistory::new(100);
        for i in 0..10 {
            history.record(CognitiveTickResult {
                tick_number: i,
                elapsed_ms: 100,
                budget_ms: 200,
                ..Default::default()
            });
        }
        assert_eq!(history.changes_per_minute(), 0.0);
    }

    #[test]
    fn tick_history_changes_per_minute_insufficient_data() {
        let history = TickHistory::new(10);
        assert_eq!(history.changes_per_minute(), 0.0);

        let mut history2 = TickHistory::new(10);
        history2.record(CognitiveTickResult::default());
        assert_eq!(history2.changes_per_minute(), 0.0);
    }

    #[test]
    fn tick_history_avg_budget_usage() {
        let mut history = TickHistory::new(100);
        // 50% usage each tick.
        for i in 0..5 {
            history.record(CognitiveTickResult {
                tick_number: i,
                elapsed_ms: 50,
                budget_ms: 100,
                ..Default::default()
            });
        }
        let usage = history.avg_budget_usage();
        assert!((usage - 0.5).abs() < 0.01);
    }

    #[test]
    fn tick_history_avg_budget_usage_empty() {
        let history = TickHistory::new(10);
        assert_eq!(history.avg_budget_usage(), 0.0);
    }

    #[test]
    fn tick_history_idle_ticks() {
        let mut history = TickHistory::new(100);
        // 3 active ticks followed by 5 idle ticks.
        for i in 0..3 {
            history.record(CognitiveTickResult {
                tick_number: i,
                git_commits_found: 1,
                ..Default::default()
            });
        }
        for i in 3..8 {
            history.record(CognitiveTickResult {
                tick_number: i,
                ..Default::default()
            });
        }
        assert_eq!(history.idle_ticks(), 5);
    }

    #[test]
    fn tick_history_idle_ticks_none_idle() {
        let mut history = TickHistory::new(100);
        history.record(CognitiveTickResult {
            tick_number: 0,
            files_changed: 1,
            ..Default::default()
        });
        assert_eq!(history.idle_ticks(), 0);
    }

    // ── TickRecommendation tests (Item 6) ────────────────────────

    #[test]
    fn tick_recommend_insufficient_data() {
        let engine = make_engine_mut();
        let rec = engine.recommend_tick_interval();
        assert_eq!(rec.recommended_ms, engine.current_tick_interval_ms);
        assert!(rec.reason.contains("Insufficient"));
        assert!(rec.recommendation_confidence < 0.5);
    }

    #[test]
    fn tick_recommend_idle_mode() {
        let mut engine = make_engine_mut();
        // Fill with 110 idle ticks.
        for i in 0..110 {
            engine.tick_history.record(CognitiveTickResult {
                tick_number: i,
                elapsed_ms: 10,
                budget_ms: 100,
                ..Default::default()
            });
        }
        let rec = engine.recommend_tick_interval();
        assert_eq!(rec.recommended_ms, 5000);
        assert!(rec.reason.contains("idle"));
    }

    #[test]
    fn tick_recommend_high_frequency() {
        let mut engine = make_engine_mut();
        // 20 ticks, each 100ms, each with 5 git commits.
        for i in 0..20 {
            engine.tick_history.record(CognitiveTickResult {
                tick_number: i,
                elapsed_ms: 100,
                budget_ms: 200,
                git_commits_found: 5,
                ..Default::default()
            });
        }
        let rec = engine.recommend_tick_interval();
        assert_eq!(rec.recommended_ms, 200);
        assert!(rec.changes_per_minute > 10.0);
    }

    #[test]
    fn tick_recommend_low_frequency() {
        let mut engine = make_engine_mut();
        // 20 ticks, each 6000ms (6s), 1 change total.
        for i in 0..20 {
            engine.tick_history.record(CognitiveTickResult {
                tick_number: i,
                elapsed_ms: 6000,
                budget_ms: 10000,
                git_commits_found: if i == 0 { 1 } else { 0 },
                ..Default::default()
            });
        }
        let rec = engine.recommend_tick_interval();
        assert_eq!(rec.recommended_ms, 3000);
        assert!(rec.changes_per_minute < 1.0);
    }

    #[test]
    fn tick_recommend_moderate_frequency() {
        let mut engine = make_engine_mut();
        // 10 ticks, each 1000ms, each with 1 change => ~60 cpm, but
        // we need a moderate rate. Let's do 1 change per 10s.
        for i in 0..10 {
            engine.tick_history.record(CognitiveTickResult {
                tick_number: i,
                elapsed_ms: 10000,
                budget_ms: 15000,
                git_commits_found: if i % 5 == 0 { 1 } else { 0 },
                files_changed: if i % 3 == 0 { 1 } else { 0 },
                ..Default::default()
            });
        }
        let rec = engine.recommend_tick_interval();
        // With ~6 changes in 100s => ~3.6 cpm => moderate.
        assert!(
            rec.recommended_ms == 1000,
            "expected 1000ms for moderate, got {}ms (cpm={:.2})",
            rec.recommended_ms,
            rec.changes_per_minute
        );
    }

    // ── Integration: on_tick records tick_history ─────────────────

    #[test]
    fn on_tick_records_tick_history() {
        let mut engine = make_engine_mut();
        engine.start_session("hist", None, None).unwrap();
        engine.on_tick(100);
        engine.on_tick(100);
        assert_eq!(engine.tick_history().len(), 2);
    }

    // ── Integration: on_tick records confidence snapshot ──────────

    #[test]
    fn on_tick_records_confidence_snapshot_on_periodic() {
        let mut engine = make_engine_mut();
        engine.start_session("snap", None, None).unwrap();
        engine.ticks_since_confidence_update = 101;
        engine.on_tick(1000);
        assert!(
            !engine.confidence_history().is_empty(),
            "should have recorded a confidence snapshot"
        );
        let snap = engine.confidence_history().latest().unwrap();
        assert!(matches!(snap.trigger, ConfidenceTrigger::Periodic));
    }

    // ── Integration: ingest_graph_file_tracked ───────────────────

    #[test]
    fn ingest_graph_file_tracked_records_strategy_and_snapshot() {
        let dir = std::env::temp_dir().join("weaver_test_tracked");
        std::fs::create_dir_all(&dir).ok();
        let path = dir.join("small.json");
        std::fs::write(
            &path,
            r#"{"source":"test","nodes":[{"id":"n1","title":"Node 1"}],"edges":[]}"#,
        )
        .unwrap();

        let mut engine = make_engine_mut();
        let result = engine.ingest_graph_file_tracked(&path).unwrap();
        assert_eq!(result.nodes_added, 1);

        // Strategy tracker should have one outcome.
        assert_eq!(engine.strategy_tracker().len(), 1);
        assert_eq!(engine.strategy_tracker().outcomes()[0].strategy, "ingest:small");

        // Confidence history should have at least one PostIngestion snapshot.
        assert!(!engine.confidence_history().is_empty());
        let has_post_ingestion = engine
            .confidence_history()
            .all()
            .iter()
            .any(|s| matches!(s.trigger, ConfidenceTrigger::PostIngestion));
        assert!(has_post_ingestion);

        std::fs::remove_dir_all(&dir).ok();
    }

    // ── ConfidenceSnapshot / StrategyOutcome serde tests ─────────

    #[test]
    fn confidence_snapshot_serde_roundtrip() {
        let snap = ConfidenceSnapshot {
            timestamp: Utc::now(),
            tick_number: 42,
            confidence: 0.78,
            node_count: 100,
            edge_count: 200,
            gap_count: 3,
            trigger: ConfidenceTrigger::PostIngestion,
        };
        let json = serde_json::to_string(&snap).unwrap();
        let restored: ConfidenceSnapshot = serde_json::from_str(&json).unwrap();
        assert_eq!(restored.tick_number, 42);
        assert!((restored.confidence - 0.78).abs() < 0.001);
    }

    #[test]
    fn strategy_outcome_serde_roundtrip() {
        let outcome = StrategyOutcome {
            strategy: "add_git".to_string(),
            description: "desc".to_string(),
            confidence_before: 0.4,
            confidence_after: 0.6,
            delta: 0.2,
            timestamp: Utc::now(),
            beneficial: true,
        };
        let json = serde_json::to_string(&outcome).unwrap();
        let restored: StrategyOutcome = serde_json::from_str(&json).unwrap();
        assert_eq!(restored.strategy, "add_git");
        assert!(restored.beneficial);
    }

    #[test]
    fn tick_recommendation_serde_roundtrip() {
        let rec = TickRecommendation {
            recommended_ms: 200,
            current_ms: 1000,
            reason: "fast".to_string(),
            changes_per_minute: 50.0,
            recommendation_confidence: 0.8,
        };
        let json = serde_json::to_string(&rec).unwrap();
        let restored: TickRecommendation = serde_json::from_str(&json).unwrap();
        assert_eq!(restored.recommended_ms, 200);
    }

    // ── diff_models tests ───────────────────────────────────────

    fn make_model(domain: &str, confidence: f64) -> ExportedModel {
        ExportedModel {
            version: "1.0".into(),
            domain: domain.into(),
            exported_at: Utc::now(),
            confidence,
            node_types: vec![],
            edge_types: vec![],
            causal_nodes: vec![],
            causal_edges: vec![],
            metadata: HashMap::new(),
        }
    }

    #[test]
    fn diff_models_identical_produces_empty_diff() {
        let a = make_model("alpha", 0.8);
        let b = a.clone();
        let diff = diff_models(&a, &b);
        assert!(diff.nodes_only_a.is_empty());
        assert!(diff.nodes_only_b.is_empty());
        assert!(diff.edges_only_a.is_empty());
        assert!(diff.edges_only_b.is_empty());
        assert_eq!(diff.causal_nodes_added, 0);
        assert_eq!(diff.causal_nodes_removed, 0);
        assert_eq!(diff.causal_edges_added, 0);
        assert_eq!(diff.causal_edges_removed, 0);
        assert_eq!(diff.summary, "models are identical");
    }

    #[test]
    fn diff_models_different_node_types_detected() {
        let mut a = make_model("alpha", 0.5);
        a.node_types.push(NodeTypeSpec {
            name: "module".into(),
            embedding_strategy: "hash".into(),
            dimensions: 64,
        });
        a.node_types.push(NodeTypeSpec {
            name: "shared".into(),
            embedding_strategy: "hash".into(),
            dimensions: 64,
        });

        let mut b = make_model("beta", 0.5);
        b.node_types.push(NodeTypeSpec {
            name: "commit".into(),
            embedding_strategy: "hash".into(),
            dimensions: 64,
        });
        b.node_types.push(NodeTypeSpec {
            name: "shared".into(),
            embedding_strategy: "hash".into(),
            dimensions: 64,
        });

        let diff = diff_models(&a, &b);
        assert_eq!(diff.nodes_only_a, vec!["module"]);
        assert_eq!(diff.nodes_only_b, vec!["commit"]);
        assert_eq!(diff.nodes_common, vec!["shared"]);
    }

    #[test]
    fn diff_models_causal_additions_removals_counted() {
        let mut a = make_model("alpha", 0.5);
        a.causal_nodes.push(ExportedCausalNode {
            label: "A".into(),
            metadata: serde_json::json!({}),
        });
        a.causal_nodes.push(ExportedCausalNode {
            label: "shared".into(),
            metadata: serde_json::json!({}),
        });

        let mut b = make_model("beta", 0.5);
        b.causal_nodes.push(ExportedCausalNode {
            label: "B".into(),
            metadata: serde_json::json!({}),
        });
        b.causal_nodes.push(ExportedCausalNode {
            label: "shared".into(),
            metadata: serde_json::json!({}),
        });

        let diff = diff_models(&a, &b);
        assert_eq!(diff.causal_nodes_added, 1); // B
        assert_eq!(diff.causal_nodes_removed, 1); // A
    }

    #[test]
    fn diff_models_causal_edge_changes() {
        let mut a = make_model("alpha", 0.5);
        a.causal_edges.push(ExportedCausalEdge {
            source_label: "X".into(),
            target_label: "Y".into(),
            edge_type: "Causes".into(),
            weight: 1.0,
        });

        let mut b = make_model("beta", 0.5);
        b.causal_edges.push(ExportedCausalEdge {
            source_label: "Y".into(),
            target_label: "Z".into(),
            edge_type: "Enables".into(),
            weight: 0.5,
        });

        let diff = diff_models(&a, &b);
        assert_eq!(diff.causal_edges_added, 1);
        assert_eq!(diff.causal_edges_removed, 1);
    }

    #[test]
    fn diff_models_confidence_delta_in_summary() {
        let a = make_model("alpha", 0.5);
        let b = make_model("beta", 0.8);
        let diff = diff_models(&a, &b);
        assert!((diff.confidence_delta - 0.3).abs() < 1e-10);
        assert!(diff.summary.contains("increased"));
    }

    #[test]
    fn diff_models_summary_shows_decrease() {
        let a = make_model("alpha", 0.9);
        let b = make_model("beta", 0.6);
        let diff = diff_models(&a, &b);
        assert!(diff.summary.contains("decreased"));
    }

    #[test]
    fn diff_models_edge_type_differences() {
        let mut a = make_model("a", 0.5);
        a.edge_types.push(EdgeTypeSpec {
            from_type: "mod".into(),
            to_type: "mod".into(),
            edge_type: "uses".into(),
            confidence: 0.8,
        });

        let mut b = make_model("b", 0.5);
        b.edge_types.push(EdgeTypeSpec {
            from_type: "mod".into(),
            to_type: "test".into(),
            edge_type: "tests".into(),
            confidence: 0.7,
        });

        let diff = diff_models(&a, &b);
        assert_eq!(diff.edges_only_a.len(), 1);
        assert_eq!(diff.edges_only_b.len(), 1);
        assert!(diff.edges_common.is_empty());
    }

    // ── merge_models tests ──────────────────────────────────────

    #[test]
    fn merge_models_disjoint_produces_union() {
        let mut a = make_model("alpha", 0.6);
        a.node_types.push(NodeTypeSpec {
            name: "mod_a".into(),
            embedding_strategy: "hash".into(),
            dimensions: 64,
        });
        a.causal_nodes.push(ExportedCausalNode {
            label: "A1".into(),
            metadata: serde_json::json!({}),
        });

        let mut b = make_model("beta", 0.8);
        b.node_types.push(NodeTypeSpec {
            name: "mod_b".into(),
            embedding_strategy: "hash".into(),
            dimensions: 64,
        });
        b.causal_nodes.push(ExportedCausalNode {
            label: "B1".into(),
            metadata: serde_json::json!({}),
        });

        let result = merge_models(&a, &b);
        assert_eq!(result.stats.total_node_types, 2);
        assert_eq!(result.stats.total_causal_nodes, 2);
        assert_eq!(result.stats.nodes_from_a, 1);
        assert_eq!(result.stats.nodes_from_b, 1);
        assert_eq!(result.stats.nodes_shared, 0);
        assert_eq!(result.conflicts.len(), 0);
    }

    #[test]
    fn merge_models_overlapping_nodes_higher_confidence() {
        let mut a = make_model("alpha", 0.6);
        a.node_types.push(NodeTypeSpec {
            name: "shared".into(),
            embedding_strategy: "hash_v1".into(),
            dimensions: 64,
        });

        let mut b = make_model("beta", 0.8);
        b.node_types.push(NodeTypeSpec {
            name: "shared".into(),
            embedding_strategy: "hash_v2".into(),
            dimensions: 128,
        });

        let result = merge_models(&a, &b);
        assert_eq!(result.stats.nodes_shared, 1);
        assert_eq!(result.conflicts.len(), 1);
        // B has higher dimensions so KeepB.
        assert_eq!(result.conflicts[0].resolution, ConflictResolution::KeepB);
        assert_eq!(
            result.merged.node_types[0].embedding_strategy,
            "hash_v2"
        );
    }

    #[test]
    fn merge_models_causal_edges_merged_by_id() {
        let mut a = make_model("alpha", 0.5);
        a.causal_edges.push(ExportedCausalEdge {
            source_label: "X".into(),
            target_label: "Y".into(),
            edge_type: "Causes".into(),
            weight: 1.0,
        });

        let mut b = make_model("beta", 0.5);
        b.causal_edges.push(ExportedCausalEdge {
            source_label: "X".into(),
            target_label: "Y".into(),
            edge_type: "Causes".into(),
            weight: 0.5,
        });

        let result = merge_models(&a, &b);
        assert_eq!(result.stats.total_causal_edges, 1);
        // Weight should be averaged: (1.0 + 0.5) / 2.0 = 0.75
        assert!((result.merged.causal_edges[0].weight - 0.75).abs() < 1e-5);
    }

    #[test]
    fn merge_models_conflict_resolution_recorded() {
        let mut a = make_model("alpha", 0.5);
        a.edge_types.push(EdgeTypeSpec {
            from_type: "m".into(),
            to_type: "m".into(),
            edge_type: "uses".into(),
            confidence: 0.3,
        });

        let mut b = make_model("beta", 0.5);
        b.edge_types.push(EdgeTypeSpec {
            from_type: "m".into(),
            to_type: "m".into(),
            edge_type: "uses".into(),
            confidence: 0.9,
        });

        let result = merge_models(&a, &b);
        assert_eq!(result.conflicts.len(), 1);
        assert_eq!(
            result.conflicts[0].resolution,
            ConflictResolution::HigherConfidence
        );
        // The higher confidence edge (0.9) should win.
        assert!((result.merged.edge_types[0].confidence - 0.9).abs() < 1e-10);
    }

    #[test]
    fn merge_models_confidence_is_weighted_average() {
        let mut a = make_model("alpha", 0.4);
        a.causal_nodes.push(ExportedCausalNode {
            label: "A1".into(),
            metadata: serde_json::json!({}),
        });
        // A has 1 node

        let mut b = make_model("beta", 0.8);
        b.causal_nodes.push(ExportedCausalNode {
            label: "B1".into(),
            metadata: serde_json::json!({}),
        });
        b.causal_nodes.push(ExportedCausalNode {
            label: "B2".into(),
            metadata: serde_json::json!({}),
        });
        b.causal_nodes.push(ExportedCausalNode {
            label: "B3".into(),
            metadata: serde_json::json!({}),
        });
        // B has 3 nodes

        let result = merge_models(&a, &b);
        // Weighted: (0.4*1 + 0.8*3) / (1+3) = 2.8/4 = 0.7
        assert!((result.merged.confidence - 0.7).abs() < 1e-10);
    }

    #[test]
    fn merge_models_domain_combined() {
        let a = make_model("alpha", 0.5);
        let b = make_model("beta", 0.5);
        let result = merge_models(&a, &b);
        assert_eq!(result.merged.domain, "alpha+beta");
    }

    #[test]
    fn merge_models_causal_edge_type_conflict() {
        let mut a = make_model("a", 0.5);
        a.causal_edges.push(ExportedCausalEdge {
            source_label: "X".into(),
            target_label: "Y".into(),
            edge_type: "Causes".into(),
            weight: 1.0,
        });

        let mut b = make_model("b", 0.5);
        b.causal_edges.push(ExportedCausalEdge {
            source_label: "X".into(),
            target_label: "Y".into(),
            edge_type: "Enables".into(),
            weight: 0.5,
        });

        let result = merge_models(&a, &b);
        assert!(result.conflicts.iter().any(|c| {
            c.item.starts_with("causal_edge:")
                && c.resolution == ConflictResolution::Merged
        }));
    }

    // ── knowledge_base persistence tests ────────────────────────

    #[test]
    fn knowledge_base_save_load_roundtrip() {
        let dir = std::env::temp_dir().join("weaver_kb_test_roundtrip");
        std::fs::create_dir_all(&dir).ok();
        let path = dir.join("kb.json");

        let kb = WeaverKnowledgeBase::new();
        kb.record_strategy(StrategyPattern {
            decision_type: "SourceAdded".into(),
            context: "rust-project".into(),
            improvement: 0.15,
            timestamp: Utc::now(),
        });
        kb.record_strategy(StrategyPattern {
            decision_type: "EdgeType".into(),
            context: "python-project".into(),
            improvement: 0.25,
            timestamp: Utc::now(),
        });

        kb.save_to_file(&path).unwrap();
        let loaded = WeaverKnowledgeBase::load_from_file(&path).unwrap();
        assert_eq!(loaded.pattern_count(), 2);

        let strategies = loaded.list_strategies();
        assert!(strategies
            .iter()
            .any(|s| s.decision_type == "SourceAdded" && s.context == "rust-project"));
        assert!(strategies
            .iter()
            .any(|s| s.decision_type == "EdgeType" && s.context == "python-project"));

        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn knowledge_base_learn_pattern_adds_new() {
        let kb = WeaverKnowledgeBase::new();
        kb.learn_pattern(StrategyPattern {
            decision_type: "SourceAdded".into(),
            context: "rust".into(),
            improvement: 0.1,
            timestamp: Utc::now(),
        });
        assert_eq!(kb.pattern_count(), 1);

        kb.learn_pattern(StrategyPattern {
            decision_type: "EdgeType".into(),
            context: "python".into(),
            improvement: 0.2,
            timestamp: Utc::now(),
        });
        assert_eq!(kb.pattern_count(), 2);
    }

    #[test]
    fn knowledge_base_learn_pattern_updates_existing() {
        let kb = WeaverKnowledgeBase::new();
        kb.learn_pattern(StrategyPattern {
            decision_type: "SourceAdded".into(),
            context: "rust".into(),
            improvement: 0.1,
            timestamp: Utc::now(),
        });

        // Same decision_type + context should update, not add.
        kb.learn_pattern(StrategyPattern {
            decision_type: "SourceAdded".into(),
            context: "rust".into(),
            improvement: 0.3,
            timestamp: Utc::now(),
        });

        assert_eq!(kb.pattern_count(), 1);
        let strategies = kb.list_strategies();
        // Average of 0.1 and 0.3 = 0.2
        assert!((strategies[0].improvement - 0.2).abs() < 1e-10);
    }

    #[test]
    fn knowledge_base_find_patterns_returns_matching() {
        let kb = WeaverKnowledgeBase::new();
        kb.learn_pattern(StrategyPattern {
            decision_type: "SourceAdded".into(),
            context: "rust-backend".into(),
            improvement: 0.1,
            timestamp: Utc::now(),
        });
        kb.learn_pattern(StrategyPattern {
            decision_type: "EdgeType".into(),
            context: "python-ml".into(),
            improvement: 0.2,
            timestamp: Utc::now(),
        });
        kb.learn_pattern(StrategyPattern {
            decision_type: "Tick".into(),
            context: "go-service".into(),
            improvement: 0.15,
            timestamp: Utc::now(),
        });

        let matches = kb.find_patterns(&["rust".to_string()]);
        assert_eq!(matches.len(), 1);
        assert_eq!(matches[0].context, "rust-backend");
    }

    #[test]
    fn knowledge_base_find_patterns_sorted_by_relevance() {
        let kb = WeaverKnowledgeBase::new();
        kb.learn_pattern(StrategyPattern {
            decision_type: "A".into(),
            context: "rust".into(),
            improvement: 0.1,
            timestamp: Utc::now(),
        });
        kb.learn_pattern(StrategyPattern {
            decision_type: "B".into(),
            context: "rust-backend-api".into(),
            improvement: 0.2,
            timestamp: Utc::now(),
        });
        kb.learn_pattern(StrategyPattern {
            decision_type: "C".into(),
            context: "python".into(),
            improvement: 0.3,
            timestamp: Utc::now(),
        });

        let matches = kb.find_patterns(&[
            "rust".to_string(),
            "backend".to_string(),
            "api".to_string(),
        ]);
        // B should rank first (matches rust, backend, api = 3 hits).
        // A should rank second (matches rust = 1 hit).
        // C should not appear.
        assert_eq!(matches.len(), 2);
        assert_eq!(matches[0].decision_type, "B");
        assert_eq!(matches[1].decision_type, "A");
    }

    #[test]
    fn knowledge_base_empty_handles_gracefully() {
        let kb = WeaverKnowledgeBase::new();
        assert_eq!(kb.pattern_count(), 0);
        assert!(kb.find_patterns(&["rust".to_string()]).is_empty());
        assert!(kb.list_strategies().is_empty());

        // save/load empty KB.
        let dir = std::env::temp_dir().join("weaver_kb_empty_test");
        std::fs::create_dir_all(&dir).ok();
        let path = dir.join("empty-kb.json");
        kb.save_to_file(&path).unwrap();
        let loaded = WeaverKnowledgeBase::load_from_file(&path).unwrap();
        assert_eq!(loaded.pattern_count(), 0);
        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn knowledge_base_serializable_kb_fields() {
        let kb = WeaverKnowledgeBase::new();
        kb.record_strategy(StrategyPattern {
            decision_type: "SourceAdded".into(),
            context: "rust".into(),
            improvement: 0.1,
            timestamp: Utc::now(),
        });
        let ser = kb.to_serializable();
        assert_eq!(ser.version, 1);
        assert_eq!(ser.patterns.len(), 1);
        assert!(ser.domains_modeled.contains(&"rust".to_string()));
    }

    #[test]
    fn knowledge_base_load_nonexistent_file_errors() {
        let result = WeaverKnowledgeBase::load_from_file(
            Path::new("/nonexistent/path/kb.json"),
        );
        assert!(result.is_err());
    }

    #[test]
    fn knowledge_base_find_patterns_no_match_returns_empty() {
        let kb = WeaverKnowledgeBase::new();
        kb.learn_pattern(StrategyPattern {
            decision_type: "X".into(),
            context: "rust".into(),
            improvement: 0.1,
            timestamp: Utc::now(),
        });
        let matches = kb.find_patterns(&["java".to_string()]);
        assert!(matches.is_empty());
    }
}