deciduous 0.14.0

Decision graph tooling for AI-assisted development. Track every goal, decision, and outcome. Survive context loss. Query your reasoning.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
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
//! SQLite database with Diesel ORM
//!
//! Stores decision graphs and command logs for AI-assisted development.
//! Uses embedded migrations for schema management.

use crate::schema::*;
use diesel::prelude::*;
use diesel::r2d2::{ConnectionManager, Pool, PooledConnection};
use diesel::sqlite::SqliteConnection;
use serde_json::json;
use std::path::Path;
#[cfg(feature = "ts-rs")]
use ts_rs::TS;
use uuid::Uuid;

/// Build metadata JSON from optional fields (confidence, commit, prompt, files, branch)
pub fn build_metadata_json(
    confidence: Option<u8>,
    commit: Option<&str>,
    prompt: Option<&str>,
    files: Option<&str>,
    branch: Option<&str>,
) -> Option<String> {
    // Only create JSON if at least one field is present
    if confidence.is_none()
        && commit.is_none()
        && prompt.is_none()
        && files.is_none()
        && branch.is_none()
    {
        return None;
    }

    let mut obj = serde_json::Map::new();

    if let Some(c) = confidence {
        obj.insert("confidence".to_string(), json!(c.min(100)));
    }
    if let Some(h) = commit {
        obj.insert("commit".to_string(), json!(h));
    }
    if let Some(p) = prompt {
        obj.insert("prompt".to_string(), json!(p));
    }
    if let Some(f) = files {
        // Split comma-separated files into array
        let file_list: Vec<&str> = f.split(',').map(|s| s.trim()).collect();
        obj.insert("files".to_string(), json!(file_list));
    }
    if let Some(b) = branch {
        obj.insert("branch".to_string(), json!(b));
    }

    Some(serde_json::Value::Object(obj).to_string())
}

/// Get current git branch name
pub fn get_current_git_branch() -> Option<String> {
    std::process::Command::new("git")
        .args(["rev-parse", "--abbrev-ref", "HEAD"])
        .output()
        .ok()
        .and_then(|output| {
            if output.status.success() {
                String::from_utf8(output.stdout)
                    .ok()
                    .map(|s| s.trim().to_string())
                    .filter(|s| !s.is_empty() && s != "HEAD")
            } else {
                None
            }
        })
}

/// Get the current HEAD commit hash (short form, 7 chars)
pub fn get_current_git_commit() -> Option<String> {
    std::process::Command::new("git")
        .args(["rev-parse", "--short", "HEAD"])
        .output()
        .ok()
        .and_then(|output| {
            if output.status.success() {
                String::from_utf8(output.stdout)
                    .ok()
                    .map(|s| s.trim().to_string())
                    .filter(|s| !s.is_empty())
            } else {
                None
            }
        })
}

/// Walk up directory tree to find .deciduous folder (like git finds .git)
/// Can be overridden with DECIDUOUS_DB_PATH env var
fn get_db_path() -> std::path::PathBuf {
    // Check env var first - always takes priority
    if let Ok(path) = std::env::var("DECIDUOUS_DB_PATH") {
        return std::path::PathBuf::from(path);
    }

    // Walk up directory tree to find .deciduous folder
    if let Ok(current_dir) = std::env::current_dir() {
        let mut dir = current_dir.as_path();
        loop {
            let deciduous_dir = dir.join(".deciduous");
            if deciduous_dir.exists() && deciduous_dir.is_dir() {
                return deciduous_dir.join("deciduous.db");
            }
            // Move to parent directory
            match dir.parent() {
                Some(parent) => dir = parent,
                None => break, // Reached filesystem root
            }
        }
    }

    // No .deciduous found - default to current directory
    // (deciduous init will create it here)
    std::path::PathBuf::from(".deciduous/deciduous.db")
}

/// Current schema version for deciduous
pub const CURRENT_SCHEMA: DecisionSchema = DecisionSchema {
    major: 1,
    minor: 1,
    patch: 0,
    name: "decision-graph",
    features: &[
        "decision_nodes",
        "decision_edges",
        "decision_context",
        "decision_sessions",
        "command_log",
        "node_documents",
        "themes",
        "node_themes",
    ],
};

/// Describes the version and capabilities of the schema
#[derive(Debug, Clone)]
pub struct DecisionSchema {
    pub major: u32,
    pub minor: u32,
    pub patch: u32,
    pub name: &'static str,
    pub features: &'static [&'static str],
}

impl DecisionSchema {
    pub fn version_string(&self) -> String {
        format!("{}.{}.{}", self.major, self.minor, self.patch)
    }

    pub fn is_compatible_with(&self, other: &DecisionSchema) -> bool {
        self.major == other.major
    }

    pub fn is_newer_than(&self, other: &DecisionSchema) -> bool {
        (self.major, self.minor, self.patch) > (other.major, other.minor, other.patch)
    }

    pub fn has_feature(&self, feature: &str) -> bool {
        self.features.contains(&feature)
    }
}

impl std::fmt::Display for DecisionSchema {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "v{} ({})", self.version_string(), self.name)
    }
}

// ============================================================================
// Diesel Models
// ============================================================================

/// Insertable schema version
#[derive(Insertable)]
#[diesel(table_name = schema_versions)]
pub struct NewSchemaVersion<'a> {
    pub version: &'a str,
    pub name: &'a str,
    pub features: &'a str,
    pub introduced_at: &'a str,
}

/// Queryable schema version
#[derive(Queryable, Selectable, Debug, Clone, serde::Serialize)]
#[diesel(table_name = schema_versions)]
pub struct StoredSchema {
    pub id: i32,
    pub version: String,
    pub name: String,
    pub features: String,
    pub introduced_at: String,
}

// ============================================================================
// Decision Graph Models
// ============================================================================

/// Insertable decision node
#[derive(Insertable)]
#[diesel(table_name = decision_nodes)]
pub struct NewDecisionNode<'a> {
    pub change_id: &'a str,
    pub node_type: &'a str,
    pub title: &'a str,
    pub description: Option<&'a str>,
    pub status: &'a str,
    pub created_at: &'a str,
    pub updated_at: &'a str,
    pub metadata_json: Option<&'a str>,
}

/// Queryable decision node
#[derive(Queryable, Selectable, Debug, Clone, serde::Serialize)]
#[cfg_attr(feature = "ts-rs", derive(TS))]
#[cfg_attr(feature = "ts-rs", ts(export))]
#[diesel(table_name = decision_nodes)]
pub struct DecisionNode {
    pub id: i32,
    pub change_id: String,
    pub node_type: String,
    pub title: String,
    pub description: Option<String>,
    pub status: String,
    pub created_at: String,
    pub updated_at: String,
    pub metadata_json: Option<String>,
}

/// Summary of what was deleted by delete_node
#[derive(Debug)]
pub struct DeleteSummary {
    pub node_title: String,
    pub edges_deleted: usize,
}

/// Insertable decision edge
#[derive(Insertable)]
#[diesel(table_name = decision_edges)]
pub struct NewDecisionEdge<'a> {
    pub from_node_id: i32,
    pub to_node_id: i32,
    pub from_change_id: Option<&'a str>,
    pub to_change_id: Option<&'a str>,
    pub edge_type: &'a str,
    pub weight: Option<f64>,
    pub rationale: Option<&'a str>,
    pub created_at: &'a str,
}

/// Queryable decision edge
#[derive(Queryable, Selectable, Debug, Clone, serde::Serialize)]
#[cfg_attr(feature = "ts-rs", derive(TS))]
#[cfg_attr(feature = "ts-rs", ts(export))]
#[diesel(table_name = decision_edges)]
pub struct DecisionEdge {
    pub id: i32,
    pub from_node_id: i32,
    pub to_node_id: i32,
    pub from_change_id: Option<String>,
    pub to_change_id: Option<String>,
    pub edge_type: String,
    pub weight: Option<f64>,
    pub rationale: Option<String>,
    pub created_at: String,
}

/// Insertable decision context
#[derive(Insertable)]
#[diesel(table_name = decision_context)]
pub struct NewDecisionContext<'a> {
    pub node_id: i32,
    pub context_type: &'a str,
    pub content_json: &'a str,
    pub captured_at: &'a str,
}

/// Queryable decision context
#[derive(Queryable, Selectable, Debug, Clone, serde::Serialize)]
#[cfg_attr(feature = "ts-rs", derive(TS))]
#[cfg_attr(feature = "ts-rs", ts(export))]
#[diesel(table_name = decision_context)]
pub struct DecisionContext {
    pub id: i32,
    pub node_id: i32,
    pub context_type: String,
    pub content_json: String,
    pub captured_at: String,
}

/// Insertable session
#[derive(Insertable)]
#[diesel(table_name = decision_sessions)]
pub struct NewDecisionSession<'a> {
    pub name: Option<&'a str>,
    pub started_at: &'a str,
    pub ended_at: Option<&'a str>,
    pub root_node_id: Option<i32>,
    pub summary: Option<&'a str>,
}

/// Queryable session
#[derive(Queryable, Selectable, Debug, Clone, serde::Serialize)]
#[cfg_attr(feature = "ts-rs", derive(TS))]
#[cfg_attr(feature = "ts-rs", ts(export))]
#[diesel(table_name = decision_sessions)]
pub struct DecisionSession {
    pub id: i32,
    pub name: Option<String>,
    pub started_at: String,
    pub ended_at: Option<String>,
    pub root_node_id: Option<i32>,
    pub summary: Option<String>,
}

// ============================================================================
// Command Log Models
// ============================================================================

/// Insertable command log entry
#[derive(Insertable)]
#[diesel(table_name = command_log)]
pub struct NewCommandLog<'a> {
    pub command: &'a str,
    pub description: Option<&'a str>,
    pub working_dir: Option<&'a str>,
    pub exit_code: Option<i32>,
    pub stdout: Option<&'a str>,
    pub stderr: Option<&'a str>,
    pub started_at: &'a str,
    pub completed_at: Option<&'a str>,
    pub duration_ms: Option<i32>,
    pub decision_node_id: Option<i32>,
}

/// Queryable command log entry
#[derive(Queryable, Selectable, Debug, Clone, serde::Serialize)]
#[cfg_attr(feature = "ts-rs", derive(TS))]
#[cfg_attr(feature = "ts-rs", ts(export))]
#[diesel(table_name = command_log)]
pub struct CommandLog {
    pub id: i32,
    pub command: String,
    pub description: Option<String>,
    pub working_dir: Option<String>,
    pub exit_code: Option<i32>,
    pub stdout: Option<String>,
    pub stderr: Option<String>,
    pub started_at: String,
    pub completed_at: Option<String>,
    pub duration_ms: Option<i32>,
    pub decision_node_id: Option<i32>,
}

// ============================================================================
// Roadmap Board Models
// ============================================================================

/// Checkbox state enum for type safety
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "ts-rs", derive(TS))]
#[cfg_attr(feature = "ts-rs", ts(export))]
pub enum CheckboxState {
    /// Section header or item without checkbox
    None,
    /// Unchecked checkbox: - [ ]
    Unchecked,
    /// Checked checkbox: - [x]
    Checked,
}

impl CheckboxState {
    /// Convert to database string representation
    pub fn as_str(&self) -> &'static str {
        match self {
            CheckboxState::None => "none",
            CheckboxState::Unchecked => "unchecked",
            CheckboxState::Checked => "checked",
        }
    }

    /// Parse from database string representation
    pub fn parse(s: &str) -> Self {
        match s.to_lowercase().as_str() {
            "checked" => CheckboxState::Checked,
            "unchecked" => CheckboxState::Unchecked,
            _ => CheckboxState::None,
        }
    }

    /// Convert from boolean (for checkbox items)
    pub fn from_bool(checked: bool) -> Self {
        if checked {
            CheckboxState::Checked
        } else {
            CheckboxState::Unchecked
        }
    }

    /// Check if this represents a checked state
    pub fn is_checked(&self) -> bool {
        matches!(self, CheckboxState::Checked)
    }
}

impl std::fmt::Display for CheckboxState {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

/// Insertable roadmap item
#[derive(Insertable)]
#[diesel(table_name = roadmap_items)]
pub struct NewRoadmapItem<'a> {
    pub change_id: &'a str,
    pub title: &'a str,
    pub description: Option<&'a str>,
    pub section: Option<&'a str>,
    pub parent_id: Option<i32>,
    pub checkbox_state: &'a str,
    pub github_issue_number: Option<i32>,
    pub github_issue_state: Option<&'a str>,
    pub outcome_node_id: Option<i32>,
    pub outcome_change_id: Option<&'a str>,
    pub markdown_line_start: Option<i32>,
    pub markdown_line_end: Option<i32>,
    pub content_hash: Option<&'a str>,
    pub created_at: &'a str,
    pub updated_at: &'a str,
    pub last_synced_at: Option<&'a str>,
}

/// Queryable roadmap item
#[derive(Queryable, Selectable, Debug, Clone, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "ts-rs", derive(TS))]
#[cfg_attr(feature = "ts-rs", ts(export))]
#[diesel(table_name = roadmap_items)]
pub struct RoadmapItem {
    pub id: i32,
    pub change_id: String,
    pub title: String,
    pub description: Option<String>,
    pub section: Option<String>,
    pub parent_id: Option<i32>,
    pub checkbox_state: String,
    pub github_issue_number: Option<i32>,
    pub github_issue_state: Option<String>,
    pub outcome_node_id: Option<i32>,
    pub outcome_change_id: Option<String>,
    pub markdown_line_start: Option<i32>,
    pub markdown_line_end: Option<i32>,
    pub content_hash: Option<String>,
    pub created_at: String,
    pub updated_at: String,
    pub last_synced_at: Option<String>,
}

impl RoadmapItem {
    /// Get the checkbox state as a typed enum
    pub fn checkbox(&self) -> CheckboxState {
        CheckboxState::parse(&self.checkbox_state)
    }

    /// Check if this item is completed (checkbox checked)
    pub fn is_checked(&self) -> bool {
        self.checkbox().is_checked()
    }
}

/// Insertable roadmap sync state
#[derive(Insertable)]
#[diesel(table_name = roadmap_sync_state)]
pub struct NewRoadmapSyncState<'a> {
    pub roadmap_path: &'a str,
    pub roadmap_content_hash: Option<&'a str>,
    pub github_repo: Option<&'a str>,
    pub last_github_sync: Option<&'a str>,
    pub last_markdown_parse: Option<&'a str>,
    pub conflict_count: i32,
}

/// Queryable roadmap sync state
#[derive(Queryable, Selectable, Debug, Clone, serde::Serialize)]
#[cfg_attr(feature = "ts-rs", derive(TS))]
#[cfg_attr(feature = "ts-rs", ts(export))]
#[diesel(table_name = roadmap_sync_state)]
pub struct RoadmapSyncState {
    pub id: i32,
    pub roadmap_path: String,
    pub roadmap_content_hash: Option<String>,
    pub github_repo: Option<String>,
    pub last_github_sync: Option<String>,
    pub last_markdown_parse: Option<String>,
    pub conflict_count: i32,
}

/// Insertable roadmap conflict
#[derive(Insertable)]
#[diesel(table_name = roadmap_conflicts)]
pub struct NewRoadmapConflict<'a> {
    pub item_change_id: &'a str,
    pub conflict_type: &'a str,
    pub local_value: Option<&'a str>,
    pub remote_value: Option<&'a str>,
    pub resolution: Option<&'a str>,
    pub detected_at: &'a str,
    pub resolved_at: Option<&'a str>,
}

/// Queryable roadmap conflict
#[derive(Queryable, Selectable, Debug, Clone, serde::Serialize)]
#[cfg_attr(feature = "ts-rs", derive(TS))]
#[cfg_attr(feature = "ts-rs", ts(export))]
#[diesel(table_name = roadmap_conflicts)]
pub struct RoadmapConflict {
    pub id: i32,
    pub item_change_id: String,
    pub conflict_type: String,
    pub local_value: Option<String>,
    pub remote_value: Option<String>,
    pub resolution: Option<String>,
    pub detected_at: String,
    pub resolved_at: Option<String>,
}

// ============================================================================
// GitHub Issue Cache
// ============================================================================

/// Insertable GitHub issue cache entry
#[derive(Insertable, Debug)]
#[diesel(table_name = github_issue_cache)]
pub struct NewGitHubIssueCache<'a> {
    pub issue_number: i32,
    pub repo: &'a str,
    pub title: &'a str,
    pub body: Option<&'a str>,
    pub state: &'a str,
    pub html_url: &'a str,
    pub created_at: &'a str,
    pub updated_at: &'a str,
    pub cached_at: &'a str,
}

/// Queryable GitHub issue cache entry
#[derive(Queryable, Selectable, Debug, Clone, serde::Serialize)]
#[cfg_attr(feature = "ts-rs", derive(TS))]
#[cfg_attr(feature = "ts-rs", ts(export))]
#[diesel(table_name = github_issue_cache)]
pub struct GitHubIssueCache {
    pub id: i32,
    pub issue_number: i32,
    pub repo: String,
    pub title: String,
    pub body: Option<String>,
    pub state: String,
    pub html_url: String,
    pub created_at: String,
    pub updated_at: String,
    pub cached_at: String,
}

// ============================================================================
// Helper structs for raw SQL queries
// ============================================================================

/// Helper for PRAGMA table_info queries
#[derive(QueryableByName, Debug)]
struct PragmaTableInfo {
    #[diesel(sql_type = diesel::sql_types::Integer)]
    #[allow(dead_code)]
    cid: i32,
    #[diesel(sql_type = diesel::sql_types::Text)]
    name: String,
    #[diesel(sql_type = diesel::sql_types::Text)]
    #[allow(dead_code)]
    r#type: String,
    #[diesel(sql_type = diesel::sql_types::Integer)]
    #[allow(dead_code)]
    notnull: i32,
    #[diesel(sql_type = diesel::sql_types::Nullable<diesel::sql_types::Text>)]
    #[allow(dead_code)]
    dflt_value: Option<String>,
    #[diesel(sql_type = diesel::sql_types::Integer)]
    #[allow(dead_code)]
    pk: i32,
}

/// Helper for node ID queries
#[derive(QueryableByName, Debug)]
struct NodeIdOnly {
    #[diesel(sql_type = diesel::sql_types::Integer)]
    id: i32,
}

/// Helper for sqlite_master table queries
#[derive(QueryableByName, Debug)]
#[allow(dead_code)]
struct TableInfo {
    #[diesel(sql_type = diesel::sql_types::Text)]
    name: String,
}

/// Helper for FTS5 search results
#[derive(QueryableByName, Debug)]
struct FtsSearchRow {
    #[diesel(sql_type = diesel::sql_types::Integer)]
    id: i32,
    #[diesel(sql_type = diesel::sql_types::Text)]
    user_prompt: String,
    #[diesel(sql_type = diesel::sql_types::Text)]
    total_prompt: String,
    #[diesel(sql_type = diesel::sql_types::Text)]
    response: String,
    #[diesel(sql_type = diesel::sql_types::Nullable<diesel::sql_types::Text>)]
    context_json: Option<String>,
    #[diesel(sql_type = diesel::sql_types::Text)]
    inserted_at: String,
    #[diesel(sql_type = diesel::sql_types::Nullable<diesel::sql_types::Text>)]
    deleted_at: Option<String>,
    #[diesel(sql_type = diesel::sql_types::Double)]
    rank: f64,
    #[diesel(sql_type = diesel::sql_types::Text)]
    snippet_prompt: String,
    #[diesel(sql_type = diesel::sql_types::Text)]
    snippet_response: String,
}

// ============================================================================
// Database Connection
// ============================================================================

type DbPool = Pool<ConnectionManager<SqliteConnection>>;
type DbConn = PooledConnection<ConnectionManager<SqliteConnection>>;

/// Database connection wrapper with connection pool
pub struct Database {
    pool: DbPool,
}

/// Error type for database operations
#[derive(Debug)]
pub enum DbError {
    Connection(String),
    Query(diesel::result::Error),
    Pool(diesel::r2d2::Error),
    Validation(String),
}

impl std::fmt::Display for DbError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            DbError::Connection(msg) => write!(f, "Connection error: {}", msg),
            DbError::Query(e) => write!(f, "Query error: {}", e),
            DbError::Pool(e) => write!(f, "Pool error: {}", e),
            DbError::Validation(msg) => write!(f, "{}", msg),
        }
    }
}

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

impl From<diesel::result::Error> for DbError {
    fn from(e: diesel::result::Error) -> Self {
        DbError::Query(e)
    }
}

impl From<diesel::r2d2::Error> for DbError {
    fn from(e: diesel::r2d2::Error) -> Self {
        DbError::Pool(e)
    }
}

pub type Result<T> = std::result::Result<T, DbError>;

impl Database {
    /// Get the database path that will be used
    pub fn db_path() -> std::path::PathBuf {
        get_db_path()
    }

    /// Create a new database at a custom path
    pub fn new(path: &str) -> Result<Self> {
        Self::open_at(path)
    }

    /// Open database at default path (respects DECIDUOUS_DB_PATH env var)
    pub fn open() -> Result<Self> {
        let path = get_db_path();
        // Create parent directory if it doesn't exist
        if let Some(parent) = path.parent() {
            if !parent.exists() {
                std::fs::create_dir_all(parent).ok();
            }
        }
        Self::open_at(&path)
    }

    /// Open database at specified path
    pub fn open_at<P: AsRef<Path>>(path: P) -> Result<Self> {
        let path_str = path.as_ref().to_string_lossy().to_string();
        let manager = ConnectionManager::<SqliteConnection>::new(&path_str);
        let pool = Pool::builder()
            .max_size(5)
            .build(manager)
            .map_err(|e| DbError::Connection(e.to_string()))?;

        let db = Self { pool };
        // Auto-migrate FIRST - add change_id columns to existing databases before init_schema creates new tables
        let _ = db.migrate_add_change_ids_raw();
        db.init_schema()?;
        Ok(db)
    }

    /// Raw SQL migration that runs before Diesel ORM is used
    fn migrate_add_change_ids_raw(&self) -> Result<bool> {
        let mut conn = self.get_conn()?;

        // Check if decision_nodes table exists
        let tables: Vec<TableInfo> = diesel::sql_query(
            "SELECT name FROM sqlite_master WHERE type='table' AND name='decision_nodes'",
        )
        .load::<TableInfo>(&mut conn)
        .unwrap_or_default();

        if tables.is_empty() {
            return Ok(false); // Table doesn't exist yet, init_schema will create it
        }

        // Check if change_id column exists in decision_nodes
        let columns: Vec<PragmaTableInfo> = diesel::sql_query("PRAGMA table_info(decision_nodes)")
            .load(&mut conn)
            .unwrap_or_default();

        let has_change_id = columns.iter().any(|c| c.name == "change_id");

        if !has_change_id {
            // Add change_id column to decision_nodes
            diesel::sql_query("ALTER TABLE decision_nodes ADD COLUMN change_id TEXT")
                .execute(&mut conn)?;
        }

        // Always backfill any NULL change_ids (handles both new columns and stragglers)
        let nodes: Vec<NodeIdOnly> =
            diesel::sql_query("SELECT id FROM decision_nodes WHERE change_id IS NULL")
                .load(&mut conn)
                .unwrap_or_default();

        if nodes.is_empty() && has_change_id {
            return Ok(false); // Already fully migrated
        }

        for node in nodes {
            let change_id = Uuid::new_v4().to_string();
            diesel::sql_query(format!(
                "UPDATE decision_nodes SET change_id = '{}' WHERE id = {}",
                change_id, node.id
            ))
            .execute(&mut conn)?;
        }

        // Check if edge columns need migration
        let edge_columns: Vec<PragmaTableInfo> =
            diesel::sql_query("PRAGMA table_info(decision_edges)")
                .load(&mut conn)
                .unwrap_or_default();

        let has_from_change_id = edge_columns.iter().any(|c| c.name == "from_change_id");

        if !has_from_change_id {
            diesel::sql_query("ALTER TABLE decision_edges ADD COLUMN from_change_id TEXT")
                .execute(&mut conn)?;
            diesel::sql_query("ALTER TABLE decision_edges ADD COLUMN to_change_id TEXT")
                .execute(&mut conn)?;

            // Backfill edge change_ids
            diesel::sql_query(
                "UPDATE decision_edges SET
                    from_change_id = (SELECT change_id FROM decision_nodes WHERE id = decision_edges.from_node_id),
                    to_change_id = (SELECT change_id FROM decision_nodes WHERE id = decision_edges.to_node_id)"
            )
            .execute(&mut conn)?;
        }

        Ok(true) // Migration performed
    }

    fn get_conn(&self) -> Result<DbConn> {
        self.pool
            .get()
            .map_err(|e| DbError::Connection(e.to_string()))
    }

    fn init_schema(&self) -> Result<()> {
        let mut conn = self.get_conn()?;

        // Run raw SQL to create tables if they don't exist
        diesel::sql_query(
            r#"
            CREATE TABLE IF NOT EXISTS schema_versions (
                id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
                version TEXT NOT NULL UNIQUE,
                name TEXT NOT NULL,
                features TEXT NOT NULL,
                introduced_at TEXT NOT NULL
            )
        "#,
        )
        .execute(&mut conn)?;

        diesel::sql_query(
            r#"
            CREATE TABLE IF NOT EXISTS decision_nodes (
                id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
                change_id TEXT NOT NULL UNIQUE,
                node_type TEXT NOT NULL,
                title TEXT NOT NULL,
                description TEXT,
                status TEXT NOT NULL DEFAULT 'pending',
                created_at TEXT NOT NULL,
                updated_at TEXT NOT NULL,
                metadata_json TEXT
            )
        "#,
        )
        .execute(&mut conn)?;

        diesel::sql_query(
            r#"
            CREATE TABLE IF NOT EXISTS decision_edges (
                id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
                from_node_id INTEGER NOT NULL,
                to_node_id INTEGER NOT NULL,
                from_change_id TEXT,
                to_change_id TEXT,
                edge_type TEXT NOT NULL,
                weight REAL DEFAULT 1.0,
                rationale TEXT,
                created_at TEXT NOT NULL,
                FOREIGN KEY (from_node_id) REFERENCES decision_nodes(id),
                FOREIGN KEY (to_node_id) REFERENCES decision_nodes(id),
                UNIQUE(from_node_id, to_node_id, edge_type)
            )
        "#,
        )
        .execute(&mut conn)?;

        diesel::sql_query(
            r#"
            CREATE TABLE IF NOT EXISTS decision_context (
                id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
                node_id INTEGER NOT NULL,
                context_type TEXT NOT NULL,
                content_json TEXT NOT NULL,
                captured_at TEXT NOT NULL,
                FOREIGN KEY (node_id) REFERENCES decision_nodes(id)
            )
        "#,
        )
        .execute(&mut conn)?;

        diesel::sql_query(
            r#"
            CREATE TABLE IF NOT EXISTS decision_sessions (
                id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
                name TEXT,
                started_at TEXT NOT NULL,
                ended_at TEXT,
                root_node_id INTEGER,
                summary TEXT,
                FOREIGN KEY (root_node_id) REFERENCES decision_nodes(id)
            )
        "#,
        )
        .execute(&mut conn)?;

        diesel::sql_query(
            r#"
            CREATE TABLE IF NOT EXISTS session_nodes (
                session_id INTEGER NOT NULL,
                node_id INTEGER NOT NULL,
                added_at TEXT NOT NULL,
                PRIMARY KEY (session_id, node_id),
                FOREIGN KEY (session_id) REFERENCES decision_sessions(id),
                FOREIGN KEY (node_id) REFERENCES decision_nodes(id)
            )
        "#,
        )
        .execute(&mut conn)?;

        diesel::sql_query(
            r#"
            CREATE TABLE IF NOT EXISTS command_log (
                id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
                command TEXT NOT NULL,
                description TEXT,
                working_dir TEXT,
                exit_code INTEGER,
                stdout TEXT,
                stderr TEXT,
                started_at TEXT NOT NULL,
                completed_at TEXT,
                duration_ms INTEGER,
                decision_node_id INTEGER,
                FOREIGN KEY (decision_node_id) REFERENCES decision_nodes(id)
            )
        "#,
        )
        .execute(&mut conn)?;

        // Roadmap Board Tables
        diesel::sql_query(
            r#"
            CREATE TABLE IF NOT EXISTS roadmap_items (
                id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
                change_id TEXT NOT NULL UNIQUE,
                title TEXT NOT NULL,
                description TEXT,
                section TEXT,
                parent_id INTEGER,
                checkbox_state TEXT NOT NULL DEFAULT 'none',
                github_issue_number INTEGER,
                github_issue_state TEXT,
                outcome_node_id INTEGER,
                outcome_change_id TEXT,
                markdown_line_start INTEGER,
                markdown_line_end INTEGER,
                content_hash TEXT,
                created_at TEXT NOT NULL,
                updated_at TEXT NOT NULL,
                last_synced_at TEXT,
                FOREIGN KEY (parent_id) REFERENCES roadmap_items(id),
                FOREIGN KEY (outcome_node_id) REFERENCES decision_nodes(id)
            )
        "#,
        )
        .execute(&mut conn)?;

        diesel::sql_query(
            r#"
            CREATE TABLE IF NOT EXISTS roadmap_sync_state (
                id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
                roadmap_path TEXT NOT NULL,
                roadmap_content_hash TEXT,
                github_repo TEXT,
                last_github_sync TEXT,
                last_markdown_parse TEXT,
                conflict_count INTEGER NOT NULL DEFAULT 0
            )
        "#,
        )
        .execute(&mut conn)?;

        diesel::sql_query(
            r#"
            CREATE TABLE IF NOT EXISTS roadmap_conflicts (
                id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
                item_change_id TEXT NOT NULL,
                conflict_type TEXT NOT NULL,
                local_value TEXT,
                remote_value TEXT,
                resolution TEXT,
                detected_at TEXT NOT NULL,
                resolved_at TEXT,
                FOREIGN KEY (item_change_id) REFERENCES roadmap_items(change_id)
            )
        "#,
        )
        .execute(&mut conn)?;

        // GitHub issue cache for Web display
        diesel::sql_query(
            r#"
            CREATE TABLE IF NOT EXISTS github_issue_cache (
                id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
                issue_number INTEGER NOT NULL,
                repo TEXT NOT NULL,
                title TEXT NOT NULL,
                body TEXT,
                state TEXT NOT NULL,
                html_url TEXT NOT NULL,
                created_at TEXT NOT NULL,
                updated_at TEXT NOT NULL,
                cached_at TEXT NOT NULL,
                UNIQUE(repo, issue_number)
            )
        "#,
        )
        .execute(&mut conn)?;

        // Q&A interactions for chat history
        diesel::sql_query(
            r#"
            CREATE TABLE IF NOT EXISTS qa_interactions (
                id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
                user_prompt TEXT NOT NULL,
                total_prompt TEXT NOT NULL,
                response TEXT NOT NULL,
                context_json TEXT,
                inserted_at TEXT NOT NULL,
                deleted_at TEXT
            )
        "#,
        )
        .execute(&mut conn)?;

        // FTS5 virtual table for full-text search on Q&A interactions
        diesel::sql_query(
            r#"
            CREATE VIRTUAL TABLE IF NOT EXISTS qa_interactions_fts USING fts5(
                user_prompt,
                response,
                content='qa_interactions',
                content_rowid='id'
            )
        "#,
        )
        .execute(&mut conn)?;

        // Triggers to keep FTS index in sync
        diesel::sql_query(
            r#"
            CREATE TRIGGER IF NOT EXISTS qa_interactions_ai AFTER INSERT ON qa_interactions BEGIN
                INSERT INTO qa_interactions_fts(rowid, user_prompt, response)
                VALUES (new.id, new.user_prompt, new.response);
            END
        "#,
        )
        .execute(&mut conn)?;

        diesel::sql_query(
            r#"
            CREATE TRIGGER IF NOT EXISTS qa_interactions_ad AFTER DELETE ON qa_interactions BEGIN
                INSERT INTO qa_interactions_fts(qa_interactions_fts, rowid, user_prompt, response)
                VALUES ('delete', old.id, old.user_prompt, old.response);
            END
        "#,
        )
        .execute(&mut conn)?;

        diesel::sql_query(
            r#"
            CREATE TRIGGER IF NOT EXISTS qa_interactions_au AFTER UPDATE ON qa_interactions BEGIN
                INSERT INTO qa_interactions_fts(qa_interactions_fts, rowid, user_prompt, response)
                VALUES ('delete', old.id, old.user_prompt, old.response);
                INSERT INTO qa_interactions_fts(rowid, user_prompt, response)
                VALUES (new.id, new.user_prompt, new.response);
            END
        "#,
        )
        .execute(&mut conn)?;

        // Create indexes
        diesel::sql_query("CREATE INDEX IF NOT EXISTS idx_nodes_type ON decision_nodes(node_type)")
            .execute(&mut conn)?;
        diesel::sql_query("CREATE INDEX IF NOT EXISTS idx_nodes_status ON decision_nodes(status)")
            .execute(&mut conn)?;
        diesel::sql_query(
            "CREATE INDEX IF NOT EXISTS idx_nodes_change_id ON decision_nodes(change_id)",
        )
        .execute(&mut conn)?;
        diesel::sql_query(
            "CREATE INDEX IF NOT EXISTS idx_edges_from ON decision_edges(from_node_id)",
        )
        .execute(&mut conn)?;
        diesel::sql_query("CREATE INDEX IF NOT EXISTS idx_edges_to ON decision_edges(to_node_id)")
            .execute(&mut conn)?;
        diesel::sql_query(
            "CREATE INDEX IF NOT EXISTS idx_edges_from_change ON decision_edges(from_change_id)",
        )
        .execute(&mut conn)?;
        diesel::sql_query(
            "CREATE INDEX IF NOT EXISTS idx_edges_to_change ON decision_edges(to_change_id)",
        )
        .execute(&mut conn)?;
        diesel::sql_query(
            "CREATE INDEX IF NOT EXISTS idx_command_started_at ON command_log(started_at)",
        )
        .execute(&mut conn)?;

        // Roadmap indexes
        diesel::sql_query(
            "CREATE INDEX IF NOT EXISTS idx_roadmap_items_change_id ON roadmap_items(change_id)",
        )
        .execute(&mut conn)?;
        diesel::sql_query(
            "CREATE INDEX IF NOT EXISTS idx_roadmap_items_section ON roadmap_items(section)",
        )
        .execute(&mut conn)?;
        diesel::sql_query("CREATE INDEX IF NOT EXISTS idx_roadmap_items_github_issue ON roadmap_items(github_issue_number)").execute(&mut conn)?;
        diesel::sql_query("CREATE INDEX IF NOT EXISTS idx_roadmap_items_outcome ON roadmap_items(outcome_change_id)").execute(&mut conn)?;
        diesel::sql_query("CREATE INDEX IF NOT EXISTS idx_roadmap_conflicts_item ON roadmap_conflicts(item_change_id)").execute(&mut conn)?;
        diesel::sql_query("CREATE INDEX IF NOT EXISTS idx_github_issue_cache_repo ON github_issue_cache(repo, issue_number)").execute(&mut conn)?;

        // Q&A indexes
        diesel::sql_query("CREATE INDEX IF NOT EXISTS idx_qa_interactions_inserted_at ON qa_interactions(inserted_at)").execute(&mut conn)?;

        // Node Documents table
        diesel::sql_query(
            r#"
            CREATE TABLE IF NOT EXISTS node_documents (
                id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
                change_id TEXT NOT NULL UNIQUE,
                node_id INTEGER NOT NULL,
                node_change_id TEXT NOT NULL,
                content_hash TEXT NOT NULL,
                original_filename TEXT NOT NULL,
                storage_filename TEXT NOT NULL,
                mime_type TEXT NOT NULL,
                file_size INTEGER NOT NULL,
                description TEXT,
                description_source TEXT NOT NULL DEFAULT 'none',
                attached_at TEXT NOT NULL,
                attached_by TEXT,
                detached_at TEXT,
                FOREIGN KEY (node_id) REFERENCES decision_nodes(id)
            )
        "#,
        )
        .execute(&mut conn)?;

        // Document indexes
        diesel::sql_query("CREATE INDEX IF NOT EXISTS idx_docs_node_id ON node_documents(node_id)")
            .execute(&mut conn)?;
        diesel::sql_query(
            "CREATE INDEX IF NOT EXISTS idx_docs_content_hash ON node_documents(content_hash)",
        )
        .execute(&mut conn)?;
        diesel::sql_query(
            "CREATE INDEX IF NOT EXISTS idx_docs_change_id ON node_documents(change_id)",
        )
        .execute(&mut conn)?;

        // Themes table
        diesel::sql_query(
            r#"
            CREATE TABLE IF NOT EXISTS themes (
                id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
                change_id TEXT NOT NULL UNIQUE,
                name TEXT NOT NULL UNIQUE,
                color TEXT NOT NULL DEFAULT '#6b7280',
                description TEXT,
                created_at TEXT NOT NULL,
                updated_at TEXT NOT NULL
            )
        "#,
        )
        .execute(&mut conn)?;

        // Node-Themes junction table
        diesel::sql_query(
            r#"
            CREATE TABLE IF NOT EXISTS node_themes (
                node_id INTEGER NOT NULL,
                theme_id INTEGER NOT NULL,
                source TEXT NOT NULL DEFAULT 'manual',
                created_at TEXT NOT NULL,
                PRIMARY KEY (node_id, theme_id),
                FOREIGN KEY (node_id) REFERENCES decision_nodes(id) ON DELETE CASCADE,
                FOREIGN KEY (theme_id) REFERENCES themes(id) ON DELETE CASCADE
            )
        "#,
        )
        .execute(&mut conn)?;

        // Theme indexes
        diesel::sql_query("CREATE INDEX IF NOT EXISTS idx_themes_name ON themes(name)")
            .execute(&mut conn)?;
        diesel::sql_query("CREATE INDEX IF NOT EXISTS idx_themes_change_id ON themes(change_id)")
            .execute(&mut conn)?;
        diesel::sql_query(
            "CREATE INDEX IF NOT EXISTS idx_node_themes_node ON node_themes(node_id)",
        )
        .execute(&mut conn)?;
        diesel::sql_query(
            "CREATE INDEX IF NOT EXISTS idx_node_themes_theme ON node_themes(theme_id)",
        )
        .execute(&mut conn)?;

        // Register current schema
        self.register_schema(&CURRENT_SCHEMA)?;
        Ok(())
    }

    fn register_schema(&self, schema: &DecisionSchema) -> Result<()> {
        let mut conn = self.get_conn()?;
        let now = chrono::Local::now().to_rfc3339();
        let features_json = serde_json::to_string(&schema.features).unwrap_or_default();

        let new_schema = NewSchemaVersion {
            version: &schema.version_string(),
            name: schema.name,
            features: &features_json,
            introduced_at: &now,
        };

        diesel::insert_or_ignore_into(schema_versions::table)
            .values(&new_schema)
            .execute(&mut conn)?;

        Ok(())
    }

    /// Migrate existing database to add change_id columns if missing
    pub fn migrate_add_change_ids(&self) -> Result<bool> {
        let mut conn = self.get_conn()?;

        // Check if change_id column exists in decision_nodes
        let columns: Vec<(String,)> = diesel::sql_query("PRAGMA table_info(decision_nodes)")
            .load::<PragmaTableInfo>(&mut conn)
            .map(|rows| rows.into_iter().map(|r| (r.name,)).collect())
            .unwrap_or_default();

        let has_change_id = columns.iter().any(|(name,)| name == "change_id");

        if has_change_id {
            return Ok(false); // Already migrated
        }

        // Add change_id column to decision_nodes
        diesel::sql_query("ALTER TABLE decision_nodes ADD COLUMN change_id TEXT")
            .execute(&mut conn)?;

        // Backfill change_id with UUIDs for existing nodes
        let nodes: Vec<(i32,)> =
            diesel::sql_query("SELECT id FROM decision_nodes WHERE change_id IS NULL")
                .load::<NodeIdOnly>(&mut conn)
                .map(|rows| rows.into_iter().map(|r| (r.id,)).collect())
                .unwrap_or_default();

        for (node_id,) in nodes {
            let change_id = Uuid::new_v4().to_string();
            diesel::sql_query(format!(
                "UPDATE decision_nodes SET change_id = '{}' WHERE id = {}",
                change_id, node_id
            ))
            .execute(&mut conn)?;
        }

        // Create unique index on change_id
        diesel::sql_query("CREATE UNIQUE INDEX IF NOT EXISTS idx_nodes_change_id_unique ON decision_nodes(change_id)")
            .execute(&mut conn)?;

        // Add from_change_id and to_change_id columns to decision_edges
        let edge_columns: Vec<(String,)> = diesel::sql_query("PRAGMA table_info(decision_edges)")
            .load::<PragmaTableInfo>(&mut conn)
            .map(|rows| rows.into_iter().map(|r| (r.name,)).collect())
            .unwrap_or_default();

        let has_from_change_id = edge_columns.iter().any(|(name,)| name == "from_change_id");

        if !has_from_change_id {
            diesel::sql_query("ALTER TABLE decision_edges ADD COLUMN from_change_id TEXT")
                .execute(&mut conn)?;
            diesel::sql_query("ALTER TABLE decision_edges ADD COLUMN to_change_id TEXT")
                .execute(&mut conn)?;

            // Backfill edge change_ids from node change_ids
            diesel::sql_query(
                "UPDATE decision_edges SET
                    from_change_id = (SELECT change_id FROM decision_nodes WHERE id = decision_edges.from_node_id),
                    to_change_id = (SELECT change_id FROM decision_nodes WHERE id = decision_edges.to_node_id)"
            )
            .execute(&mut conn)?;

            // Create indexes
            diesel::sql_query("CREATE INDEX IF NOT EXISTS idx_edges_from_change ON decision_edges(from_change_id)")
                .execute(&mut conn)?;
            diesel::sql_query(
                "CREATE INDEX IF NOT EXISTS idx_edges_to_change ON decision_edges(to_change_id)",
            )
            .execute(&mut conn)?;
        }

        Ok(true) // Migration performed
    }

    // ========================================================================
    // Decision Graph Operations
    // ========================================================================

    /// Create a new decision node
    pub fn create_node(
        &self,
        node_type: &str,
        title: &str,
        description: Option<&str>,
        confidence: Option<u8>,
        commit: Option<&str>,
    ) -> Result<i32> {
        self.create_node_full(
            node_type,
            title,
            description,
            confidence,
            commit,
            None,
            None,
            None,
            None,
        )
    }

    /// Create a decision node with full metadata (including prompt and files)
    pub fn create_node_full(
        &self,
        node_type: &str,
        title: &str,
        description: Option<&str>,
        confidence: Option<u8>,
        commit: Option<&str>,
        prompt: Option<&str>,
        files: Option<&str>,
        branch: Option<&str>,
        created_at: Option<&str>,
    ) -> Result<i32> {
        let mut conn = self.get_conn()?;
        let now = created_at
            .map(|s| s.to_string())
            .unwrap_or_else(|| chrono::Local::now().to_rfc3339());
        let change_id = Uuid::new_v4().to_string();

        // Build metadata JSON with all optional fields
        let metadata = build_metadata_json(confidence, commit, prompt, files, branch);

        let new_node = NewDecisionNode {
            change_id: &change_id,
            node_type,
            title,
            description,
            status: "pending",
            created_at: &now,
            updated_at: &now,
            metadata_json: metadata.as_deref(),
        };

        diesel::insert_into(decision_nodes::table)
            .values(&new_node)
            .execute(&mut conn)?;

        let id: i32 = diesel::select(diesel::dsl::sql::<diesel::sql_types::Integer>(
            "last_insert_rowid()",
        ))
        .first(&mut conn)?;

        Ok(id)
    }

    /// Add a node (alias for create_node for doc examples)
    pub fn add_node(
        &self,
        node_type: &str,
        title: &str,
        description: Option<&str>,
        confidence: Option<u8>,
        commit: Option<&str>,
    ) -> Result<i32> {
        self.create_node(node_type, title, description, confidence, commit)
    }

    /// Create a node with a specific change_id (for patch application)
    pub fn create_node_with_change_id(
        &self,
        change_id: &str,
        node_type: &str,
        title: &str,
        description: Option<&str>,
        confidence: Option<u8>,
        commit: Option<&str>,
        prompt: Option<&str>,
        files: Option<&str>,
        branch: Option<&str>,
    ) -> Result<i32> {
        let mut conn = self.get_conn()?;
        let now = chrono::Local::now().to_rfc3339();

        // Build metadata JSON with all optional fields
        let metadata = build_metadata_json(confidence, commit, prompt, files, branch);

        let new_node = NewDecisionNode {
            change_id,
            node_type,
            title,
            description,
            status: "pending",
            created_at: &now,
            updated_at: &now,
            metadata_json: metadata.as_deref(),
        };

        diesel::insert_into(decision_nodes::table)
            .values(&new_node)
            .execute(&mut conn)?;

        let id: i32 = diesel::select(diesel::dsl::sql::<diesel::sql_types::Integer>(
            "last_insert_rowid()",
        ))
        .first(&mut conn)?;

        Ok(id)
    }

    /// Create an edge between nodes
    pub fn create_edge(
        &self,
        from_id: i32,
        to_id: i32,
        edge_type: &str,
        rationale: Option<&str>,
    ) -> Result<i32> {
        let mut conn = self.get_conn()?;

        // Validate both nodes exist and get their change_ids
        let from_node = decision_nodes::table
            .filter(decision_nodes::id.eq(from_id))
            .first::<DecisionNode>(&mut conn)
            .ok();
        let to_node = decision_nodes::table
            .filter(decision_nodes::id.eq(to_id))
            .first::<DecisionNode>(&mut conn)
            .ok();

        let from_change_id = from_node.as_ref().map(|n| n.change_id.clone());
        let to_change_id = to_node.as_ref().map(|n| n.change_id.clone());

        if from_node.is_none() && to_node.is_none() {
            return Err(DbError::Validation(format!(
                "Both nodes {} and {} do not exist. Run 'deciduous nodes' to see existing nodes.",
                from_id, to_id
            )));
        } else if from_node.is_none() {
            return Err(DbError::Validation(format!(
                "Source node {} does not exist. Run 'deciduous nodes' to see existing nodes.",
                from_id
            )));
        } else if to_node.is_none() {
            return Err(DbError::Validation(format!(
                "Target node {} does not exist. Run 'deciduous nodes' to see existing nodes.",
                to_id
            )));
        }

        let now = chrono::Local::now().to_rfc3339();

        let new_edge = NewDecisionEdge {
            from_node_id: from_id,
            to_node_id: to_id,
            from_change_id: from_change_id.as_deref(),
            to_change_id: to_change_id.as_deref(),
            edge_type,
            weight: Some(1.0),
            rationale,
            created_at: &now,
        };

        diesel::insert_into(decision_edges::table)
            .values(&new_edge)
            .execute(&mut conn)?;

        let id: i32 = diesel::select(diesel::dsl::sql::<diesel::sql_types::Integer>(
            "last_insert_rowid()",
        ))
        .first(&mut conn)?;

        Ok(id)
    }

    /// Add an edge (alias for create_edge for doc examples)
    pub fn add_edge(
        &self,
        from_id: i32,
        to_id: i32,
        edge_type: &str,
        rationale: Option<&str>,
    ) -> Result<i32> {
        self.create_edge(from_id, to_id, edge_type, rationale)
    }

    /// Delete an edge between two nodes
    pub fn delete_edge(&self, from_id: i32, to_id: i32) -> Result<()> {
        let mut conn = self.get_conn()?;

        // Check if the edge exists
        let edge_exists = decision_edges::table
            .filter(decision_edges::from_node_id.eq(from_id))
            .filter(decision_edges::to_node_id.eq(to_id))
            .first::<DecisionEdge>(&mut conn)
            .optional()?;

        if edge_exists.is_none() {
            // Get outgoing edges from source node to provide helpful error
            let outgoing: Vec<DecisionEdge> = decision_edges::table
                .filter(decision_edges::from_node_id.eq(from_id))
                .load(&mut conn)?;

            if outgoing.is_empty() {
                return Err(DbError::Validation(format!(
                    "No edge from node {} to node {}. Node {} has no outgoing edges.",
                    from_id, to_id, from_id
                )));
            } else {
                let targets: Vec<String> =
                    outgoing.iter().map(|e| e.to_node_id.to_string()).collect();
                return Err(DbError::Validation(format!(
                    "No edge from node {} to node {}. Node {} has edges to: {}",
                    from_id,
                    to_id,
                    from_id,
                    targets.join(", ")
                )));
            }
        }

        diesel::delete(
            decision_edges::table
                .filter(decision_edges::from_node_id.eq(from_id))
                .filter(decision_edges::to_node_id.eq(to_id)),
        )
        .execute(&mut conn)?;

        Ok(())
    }

    /// Delete a node and all its connected edges
    pub fn delete_node(&self, node_id: i32, dry_run: bool) -> Result<DeleteSummary> {
        let mut conn = self.get_conn()?;

        // Check if node exists
        let node = decision_nodes::table
            .filter(decision_nodes::id.eq(node_id))
            .first::<DecisionNode>(&mut conn)
            .optional()?;

        let node = match node {
            Some(n) => n,
            None => {
                return Err(DbError::Validation(format!(
                    "Node {} does not exist. Run 'deciduous nodes' to see existing nodes.",
                    node_id
                )));
            }
        };

        // Count edges that will be deleted
        let edges_count: i64 = decision_edges::table
            .filter(
                decision_edges::from_node_id
                    .eq(node_id)
                    .or(decision_edges::to_node_id.eq(node_id)),
            )
            .count()
            .get_result(&mut conn)?;

        let summary = DeleteSummary {
            node_title: node.title.clone(),
            edges_deleted: edges_count as usize,
        };

        if dry_run {
            return Ok(summary);
        }

        // Delete in order to respect foreign key constraints:

        // 1. Delete edges connected to this node
        diesel::delete(
            decision_edges::table.filter(
                decision_edges::from_node_id
                    .eq(node_id)
                    .or(decision_edges::to_node_id.eq(node_id)),
            ),
        )
        .execute(&mut conn)?;

        // 2. Delete context entries for this node
        diesel::delete(decision_context::table.filter(decision_context::node_id.eq(node_id)))
            .execute(&mut conn)?;

        // 3. Delete session_nodes entries for this node
        diesel::delete(session_nodes::table.filter(session_nodes::node_id.eq(node_id)))
            .execute(&mut conn)?;

        // 4. Set nullable foreign keys to NULL
        diesel::update(
            decision_sessions::table.filter(decision_sessions::root_node_id.eq(node_id)),
        )
        .set(decision_sessions::root_node_id.eq::<Option<i32>>(None))
        .execute(&mut conn)?;

        diesel::update(command_log::table.filter(command_log::decision_node_id.eq(node_id)))
            .set(command_log::decision_node_id.eq::<Option<i32>>(None))
            .execute(&mut conn)?;

        diesel::update(roadmap_items::table.filter(roadmap_items::outcome_node_id.eq(node_id)))
            .set(roadmap_items::outcome_node_id.eq::<Option<i32>>(None))
            .execute(&mut conn)?;

        // 5. Finally delete the node itself
        diesel::delete(decision_nodes::table.filter(decision_nodes::id.eq(node_id)))
            .execute(&mut conn)?;

        Ok(summary)
    }

    /// Update node status
    pub fn update_node_status(&self, node_id: i32, status: &str) -> Result<()> {
        let mut conn = self.get_conn()?;
        let now = chrono::Local::now().to_rfc3339();

        diesel::update(decision_nodes::table.filter(decision_nodes::id.eq(node_id)))
            .set((
                decision_nodes::status.eq(status),
                decision_nodes::updated_at.eq(&now),
            ))
            .execute(&mut conn)?;

        Ok(())
    }

    /// Update a node's commit hash in metadata_json
    pub fn update_node_commit(&self, node_id: i32, commit_hash: &str) -> Result<()> {
        let mut conn = self.get_conn()?;
        let now = chrono::Local::now().to_rfc3339();

        // Get current metadata
        let current_meta: Option<String> = decision_nodes::table
            .filter(decision_nodes::id.eq(node_id))
            .select(decision_nodes::metadata_json)
            .first(&mut conn)?;

        // Parse existing metadata or create new
        let mut meta: serde_json::Value = current_meta
            .as_ref()
            .and_then(|m| serde_json::from_str(m).ok())
            .unwrap_or_else(|| serde_json::json!({}));

        // Add/update commit field
        if let Some(obj) = meta.as_object_mut() {
            obj.insert("commit".to_string(), serde_json::json!(commit_hash));
        }

        let new_meta = serde_json::to_string(&meta)
            .map_err(|e| DbError::Validation(format!("JSON serialization error: {}", e)))?;

        diesel::update(decision_nodes::table.filter(decision_nodes::id.eq(node_id)))
            .set((
                decision_nodes::metadata_json.eq(Some(new_meta)),
                decision_nodes::updated_at.eq(&now),
            ))
            .execute(&mut conn)?;

        Ok(())
    }

    /// Update a node's prompt in metadata_json
    pub fn update_node_prompt(&self, node_id: i32, prompt: &str) -> Result<()> {
        let mut conn = self.get_conn()?;
        let now = chrono::Local::now().to_rfc3339();

        // Get current metadata
        let current_meta: Option<String> = decision_nodes::table
            .filter(decision_nodes::id.eq(node_id))
            .select(decision_nodes::metadata_json)
            .first(&mut conn)?;

        // Parse existing metadata or create new
        let mut meta: serde_json::Value = current_meta
            .as_ref()
            .and_then(|m| serde_json::from_str(m).ok())
            .unwrap_or_else(|| serde_json::json!({}));

        // Add/update prompt field
        if let Some(obj) = meta.as_object_mut() {
            obj.insert("prompt".to_string(), serde_json::json!(prompt));
        }

        let new_meta = serde_json::to_string(&meta)
            .map_err(|e| DbError::Validation(format!("JSON serialization error: {}", e)))?;

        diesel::update(decision_nodes::table.filter(decision_nodes::id.eq(node_id)))
            .set((
                decision_nodes::metadata_json.eq(Some(new_meta)),
                decision_nodes::updated_at.eq(&now),
            ))
            .execute(&mut conn)?;

        Ok(())
    }

    /// Get all nodes
    pub fn get_all_nodes(&self) -> Result<Vec<DecisionNode>> {
        let mut conn = self.get_conn()?;
        let nodes = decision_nodes::table
            .order(decision_nodes::created_at.asc())
            .load::<DecisionNode>(&mut conn)?;
        Ok(nodes)
    }

    /// Get all edges
    pub fn get_all_edges(&self) -> Result<Vec<DecisionEdge>> {
        let mut conn = self.get_conn()?;
        let edges = decision_edges::table
            .order(decision_edges::created_at.asc())
            .load::<DecisionEdge>(&mut conn)?;
        Ok(edges)
    }

    /// Get a single node by ID
    pub fn get_node(&self, node_id: i32) -> Result<Option<DecisionNode>> {
        let mut conn = self.get_conn()?;
        let node = decision_nodes::table
            .filter(decision_nodes::id.eq(node_id))
            .first::<DecisionNode>(&mut conn)
            .optional()?;
        Ok(node)
    }

    /// Get children of a node (outgoing edges)
    pub fn get_node_children(&self, node_id: i32) -> Result<Vec<DecisionNode>> {
        let mut conn = self.get_conn()?;

        let child_ids: Vec<i32> = decision_edges::table
            .filter(decision_edges::from_node_id.eq(node_id))
            .select(decision_edges::to_node_id)
            .load(&mut conn)?;

        let children = decision_nodes::table
            .filter(decision_nodes::id.eq_any(child_ids))
            .load::<DecisionNode>(&mut conn)?;

        Ok(children)
    }

    /// Get parents of a node (incoming edges)
    pub fn get_node_parents(&self, node_id: i32) -> Result<Vec<DecisionNode>> {
        let mut conn = self.get_conn()?;

        let parent_ids: Vec<i32> = decision_edges::table
            .filter(decision_edges::to_node_id.eq(node_id))
            .select(decision_edges::from_node_id)
            .load(&mut conn)?;

        let parents = decision_nodes::table
            .filter(decision_nodes::id.eq_any(parent_ids))
            .load::<DecisionNode>(&mut conn)?;

        Ok(parents)
    }

    /// Get full graph as JSON-serializable structure
    pub fn get_graph(&self) -> Result<DecisionGraph> {
        let nodes = self.get_all_nodes()?;
        let edges = self.get_all_edges()?;
        let themes = self.get_all_themes().unwrap_or_default();
        let node_themes = self.get_all_node_themes().unwrap_or_default();
        let documents = self.get_node_documents(None, false).unwrap_or_default();
        Ok(DecisionGraph {
            nodes,
            edges,
            config: None,
            themes,
            node_themes,
            documents,
        })
    }

    /// Get full graph with config included (for export)
    pub fn get_graph_with_config(
        &self,
        config: Option<crate::config::Config>,
    ) -> Result<DecisionGraph> {
        let nodes = self.get_all_nodes()?;
        let edges = self.get_all_edges()?;
        let themes = self.get_all_themes().unwrap_or_default();
        let node_themes = self.get_all_node_themes().unwrap_or_default();
        let documents = self.get_node_documents(None, false).unwrap_or_default();
        Ok(DecisionGraph {
            nodes,
            edges,
            config,
            themes,
            node_themes,
            documents,
        })
    }

    // ========================================================================
    // Command Log Operations
    // ========================================================================

    /// Log a command execution
    pub fn log_command(
        &self,
        command: &str,
        description: Option<&str>,
        working_dir: Option<&str>,
    ) -> Result<i32> {
        let mut conn = self.get_conn()?;
        let now = chrono::Local::now().to_rfc3339();

        let new_log = NewCommandLog {
            command,
            description,
            working_dir,
            exit_code: None,
            stdout: None,
            stderr: None,
            started_at: &now,
            completed_at: None,
            duration_ms: None,
            decision_node_id: None,
        };

        diesel::insert_into(command_log::table)
            .values(&new_log)
            .execute(&mut conn)?;

        let id: i32 = diesel::select(diesel::dsl::sql::<diesel::sql_types::Integer>(
            "last_insert_rowid()",
        ))
        .first(&mut conn)?;

        Ok(id)
    }

    /// Complete a command log entry
    pub fn complete_command(
        &self,
        log_id: i32,
        exit_code: i32,
        stdout: Option<&str>,
        stderr: Option<&str>,
        duration_ms: i32,
    ) -> Result<()> {
        let mut conn = self.get_conn()?;
        let now = chrono::Local::now().to_rfc3339();

        diesel::update(command_log::table.filter(command_log::id.eq(log_id)))
            .set((
                command_log::exit_code.eq(Some(exit_code)),
                command_log::stdout.eq(stdout),
                command_log::stderr.eq(stderr),
                command_log::completed_at.eq(Some(&now)),
                command_log::duration_ms.eq(Some(duration_ms)),
            ))
            .execute(&mut conn)?;

        Ok(())
    }

    /// Get recent commands
    pub fn get_recent_commands(&self, limit: i64) -> Result<Vec<CommandLog>> {
        let mut conn = self.get_conn()?;
        let commands = command_log::table
            .order(command_log::started_at.desc())
            .limit(limit)
            .load::<CommandLog>(&mut conn)?;
        Ok(commands)
    }

    // ========================================================================
    // Roadmap Board Operations
    // ========================================================================

    /// Create a new roadmap item
    pub fn create_roadmap_item(
        &self,
        title: &str,
        description: Option<&str>,
        section: Option<&str>,
        parent_id: Option<i32>,
        checkbox_state: &str,
    ) -> Result<i32> {
        let mut conn = self.get_conn()?;
        let now = chrono::Local::now().to_rfc3339();
        let change_id = Uuid::new_v4().to_string();

        let new_item = NewRoadmapItem {
            change_id: &change_id,
            title,
            description,
            section,
            parent_id,
            checkbox_state,
            github_issue_number: None,
            github_issue_state: None,
            outcome_node_id: None,
            outcome_change_id: None,
            markdown_line_start: None,
            markdown_line_end: None,
            content_hash: None,
            created_at: &now,
            updated_at: &now,
            last_synced_at: None,
        };

        diesel::insert_into(roadmap_items::table)
            .values(&new_item)
            .execute(&mut conn)?;

        let id: i32 = diesel::select(diesel::dsl::sql::<diesel::sql_types::Integer>(
            "last_insert_rowid()",
        ))
        .first(&mut conn)?;

        Ok(id)
    }

    /// Create a roadmap item with full metadata (for sync operations)
    pub fn create_roadmap_item_full(
        &self,
        change_id: &str,
        title: &str,
        description: Option<&str>,
        section: Option<&str>,
        parent_id: Option<i32>,
        checkbox_state: &str,
        github_issue_number: Option<i32>,
        github_issue_state: Option<&str>,
        outcome_node_id: Option<i32>,
        outcome_change_id: Option<&str>,
        markdown_line_start: Option<i32>,
        markdown_line_end: Option<i32>,
        content_hash: Option<&str>,
    ) -> Result<i32> {
        let mut conn = self.get_conn()?;
        let now = chrono::Local::now().to_rfc3339();

        let new_item = NewRoadmapItem {
            change_id,
            title,
            description,
            section,
            parent_id,
            checkbox_state,
            github_issue_number,
            github_issue_state,
            outcome_node_id,
            outcome_change_id,
            markdown_line_start,
            markdown_line_end,
            content_hash,
            created_at: &now,
            updated_at: &now,
            last_synced_at: None,
        };

        diesel::insert_into(roadmap_items::table)
            .values(&new_item)
            .execute(&mut conn)?;

        let id: i32 = diesel::select(diesel::dsl::sql::<diesel::sql_types::Integer>(
            "last_insert_rowid()",
        ))
        .first(&mut conn)?;

        Ok(id)
    }

    /// Get all roadmap items
    pub fn get_all_roadmap_items(&self) -> Result<Vec<RoadmapItem>> {
        let mut conn = self.get_conn()?;
        let items = roadmap_items::table
            .order(roadmap_items::created_at.asc())
            .load::<RoadmapItem>(&mut conn)?;
        Ok(items)
    }

    /// Clear all roadmap items (for refresh)
    pub fn clear_roadmap_items(&self) -> Result<usize> {
        let mut conn = self.get_conn()?;
        let deleted = diesel::delete(roadmap_items::table).execute(&mut conn)?;
        Ok(deleted)
    }

    /// Get roadmap items by section
    pub fn get_roadmap_items_by_section(&self, section: &str) -> Result<Vec<RoadmapItem>> {
        let mut conn = self.get_conn()?;
        let items = roadmap_items::table
            .filter(roadmap_items::section.eq(section))
            .order(roadmap_items::created_at.asc())
            .load::<RoadmapItem>(&mut conn)?;
        Ok(items)
    }

    /// Get a roadmap item by change_id
    pub fn get_roadmap_item_by_change_id(&self, change_id: &str) -> Result<Option<RoadmapItem>> {
        let mut conn = self.get_conn()?;
        let item = roadmap_items::table
            .filter(roadmap_items::change_id.eq(change_id))
            .first::<RoadmapItem>(&mut conn)
            .optional()?;
        Ok(item)
    }

    /// Update a roadmap item's GitHub issue info
    pub fn update_roadmap_item_github(
        &self,
        item_id: i32,
        issue_number: Option<i32>,
        issue_state: Option<&str>,
    ) -> Result<()> {
        let mut conn = self.get_conn()?;
        let now = chrono::Local::now().to_rfc3339();

        diesel::update(roadmap_items::table.filter(roadmap_items::id.eq(item_id)))
            .set((
                roadmap_items::github_issue_number.eq(issue_number),
                roadmap_items::github_issue_state.eq(issue_state),
                roadmap_items::updated_at.eq(&now),
            ))
            .execute(&mut conn)?;

        Ok(())
    }

    /// Update a roadmap item's GitHub issue info by finding it by title (first match)
    pub fn update_roadmap_item_github_by_title(
        &self,
        title: &str,
        issue_number: i32,
        issue_state: &str,
    ) -> Result<()> {
        let mut conn = self.get_conn()?;
        let now = chrono::Local::now().to_rfc3339();

        let affected = diesel::update(roadmap_items::table.filter(roadmap_items::title.eq(title)))
            .set((
                roadmap_items::github_issue_number.eq(Some(issue_number)),
                roadmap_items::github_issue_state.eq(Some(issue_state)),
                roadmap_items::updated_at.eq(&now),
            ))
            .execute(&mut conn)?;

        if affected == 0 {
            return Err(DbError::Validation(format!(
                "No roadmap item found with title: {}",
                title
            )));
        }

        Ok(())
    }

    /// Update a roadmap item's GitHub issue info by change_id (unique key)
    pub fn update_roadmap_item_github_by_change_id(
        &self,
        change_id: &str,
        issue_number: i32,
        issue_state: &str,
    ) -> Result<()> {
        let mut conn = self.get_conn()?;
        let now = chrono::Local::now().to_rfc3339();

        let affected =
            diesel::update(roadmap_items::table.filter(roadmap_items::change_id.eq(change_id)))
                .set((
                    roadmap_items::github_issue_number.eq(Some(issue_number)),
                    roadmap_items::github_issue_state.eq(Some(issue_state)),
                    roadmap_items::updated_at.eq(&now),
                ))
                .execute(&mut conn)?;

        if affected == 0 {
            return Err(DbError::Validation(format!(
                "No roadmap item found with change_id: {}",
                change_id
            )));
        }

        Ok(())
    }

    /// Link a roadmap item to a decision graph outcome node
    pub fn link_roadmap_to_outcome(
        &self,
        item_id: i32,
        outcome_node_id: i32,
        outcome_change_id: &str,
    ) -> Result<()> {
        let mut conn = self.get_conn()?;
        let now = chrono::Local::now().to_rfc3339();

        diesel::update(roadmap_items::table.filter(roadmap_items::id.eq(item_id)))
            .set((
                roadmap_items::outcome_node_id.eq(Some(outcome_node_id)),
                roadmap_items::outcome_change_id.eq(Some(outcome_change_id)),
                roadmap_items::updated_at.eq(&now),
            ))
            .execute(&mut conn)?;

        Ok(())
    }

    /// Unlink a roadmap item from its outcome node
    pub fn unlink_roadmap_from_outcome(&self, item_id: i32) -> Result<()> {
        let mut conn = self.get_conn()?;
        let now = chrono::Local::now().to_rfc3339();

        diesel::update(roadmap_items::table.filter(roadmap_items::id.eq(item_id)))
            .set((
                roadmap_items::outcome_node_id.eq(None::<i32>),
                roadmap_items::outcome_change_id.eq(None::<String>),
                roadmap_items::updated_at.eq(&now),
            ))
            .execute(&mut conn)?;

        Ok(())
    }

    /// Update a roadmap item's checkbox state
    pub fn update_roadmap_item_checkbox(&self, item_id: i32, checkbox_state: &str) -> Result<()> {
        let mut conn = self.get_conn()?;
        let now = chrono::Local::now().to_rfc3339();

        diesel::update(roadmap_items::table.filter(roadmap_items::id.eq(item_id)))
            .set((
                roadmap_items::checkbox_state.eq(checkbox_state),
                roadmap_items::updated_at.eq(&now),
            ))
            .execute(&mut conn)?;

        Ok(())
    }

    /// Update last synced timestamp for a roadmap item
    pub fn update_roadmap_item_synced(&self, item_id: i32) -> Result<()> {
        let mut conn = self.get_conn()?;
        let now = chrono::Local::now().to_rfc3339();

        diesel::update(roadmap_items::table.filter(roadmap_items::id.eq(item_id)))
            .set((
                roadmap_items::last_synced_at.eq(Some(&now)),
                roadmap_items::updated_at.eq(&now),
            ))
            .execute(&mut conn)?;

        Ok(())
    }

    /// Get roadmap sync state (returns None if not initialized)
    pub fn get_roadmap_sync_state(&self, roadmap_path: &str) -> Result<Option<RoadmapSyncState>> {
        let mut conn = self.get_conn()?;
        let state = roadmap_sync_state::table
            .filter(roadmap_sync_state::roadmap_path.eq(roadmap_path))
            .first::<RoadmapSyncState>(&mut conn)
            .optional()?;
        Ok(state)
    }

    /// Get or create roadmap sync state
    pub fn get_or_create_sync_state(&self, roadmap_path: &str) -> Result<RoadmapSyncState> {
        let mut conn = self.get_conn()?;

        // Try to find existing state
        let existing = roadmap_sync_state::table
            .filter(roadmap_sync_state::roadmap_path.eq(roadmap_path))
            .first::<RoadmapSyncState>(&mut conn)
            .optional()?;

        if let Some(state) = existing {
            return Ok(state);
        }

        // Create new state
        let new_state = NewRoadmapSyncState {
            roadmap_path,
            roadmap_content_hash: None,
            github_repo: None,
            last_github_sync: None,
            last_markdown_parse: None,
            conflict_count: 0,
        };

        diesel::insert_into(roadmap_sync_state::table)
            .values(&new_state)
            .execute(&mut conn)?;

        roadmap_sync_state::table
            .filter(roadmap_sync_state::roadmap_path.eq(roadmap_path))
            .first::<RoadmapSyncState>(&mut conn)
            .map_err(|e| e.into())
    }

    /// Update sync state after a sync operation
    pub fn update_sync_state(
        &self,
        state_id: i32,
        content_hash: Option<&str>,
        github_repo: Option<&str>,
        github_synced: bool,
        markdown_parsed: bool,
        conflict_count: i32,
    ) -> Result<()> {
        let mut conn = self.get_conn()?;
        let now = chrono::Local::now().to_rfc3339();

        let last_github = if github_synced {
            Some(now.clone())
        } else {
            None
        };
        let last_parse = if markdown_parsed { Some(now) } else { None };

        diesel::update(roadmap_sync_state::table.filter(roadmap_sync_state::id.eq(state_id)))
            .set((
                roadmap_sync_state::roadmap_content_hash.eq(content_hash),
                roadmap_sync_state::github_repo.eq(github_repo),
                roadmap_sync_state::last_github_sync.eq(last_github),
                roadmap_sync_state::last_markdown_parse.eq(last_parse),
                roadmap_sync_state::conflict_count.eq(conflict_count),
            ))
            .execute(&mut conn)?;

        Ok(())
    }

    /// Create a conflict record
    pub fn create_roadmap_conflict(
        &self,
        item_change_id: &str,
        conflict_type: &str,
        local_value: Option<&str>,
        remote_value: Option<&str>,
    ) -> Result<i32> {
        let mut conn = self.get_conn()?;
        let now = chrono::Local::now().to_rfc3339();

        let new_conflict = NewRoadmapConflict {
            item_change_id,
            conflict_type,
            local_value,
            remote_value,
            resolution: None,
            detected_at: &now,
            resolved_at: None,
        };

        diesel::insert_into(roadmap_conflicts::table)
            .values(&new_conflict)
            .execute(&mut conn)?;

        let id: i32 = diesel::select(diesel::dsl::sql::<diesel::sql_types::Integer>(
            "last_insert_rowid()",
        ))
        .first(&mut conn)?;

        Ok(id)
    }

    /// Get all unresolved conflicts
    pub fn get_unresolved_conflicts(&self) -> Result<Vec<RoadmapConflict>> {
        let mut conn = self.get_conn()?;
        let conflicts = roadmap_conflicts::table
            .filter(roadmap_conflicts::resolution.is_null())
            .order(roadmap_conflicts::detected_at.desc())
            .load::<RoadmapConflict>(&mut conn)?;
        Ok(conflicts)
    }

    /// Resolve a conflict
    pub fn resolve_roadmap_conflict(&self, conflict_id: i32, resolution: &str) -> Result<()> {
        let mut conn = self.get_conn()?;
        let now = chrono::Local::now().to_rfc3339();

        diesel::update(roadmap_conflicts::table.filter(roadmap_conflicts::id.eq(conflict_id)))
            .set((
                roadmap_conflicts::resolution.eq(Some(resolution)),
                roadmap_conflicts::resolved_at.eq(Some(&now)),
            ))
            .execute(&mut conn)?;

        Ok(())
    }

    /// Delete a roadmap item by ID
    pub fn delete_roadmap_item(&self, item_id: i32) -> Result<()> {
        let mut conn = self.get_conn()?;
        diesel::delete(roadmap_items::table.filter(roadmap_items::id.eq(item_id)))
            .execute(&mut conn)?;
        Ok(())
    }

    /// Check if a roadmap item is complete (has outcome AND issue closed)
    pub fn check_roadmap_item_completion(&self, item_id: i32) -> Result<(bool, bool, bool)> {
        let mut conn = self.get_conn()?;

        let item = roadmap_items::table
            .filter(roadmap_items::id.eq(item_id))
            .first::<RoadmapItem>(&mut conn)?;

        let has_outcome = item.outcome_change_id.is_some();
        let issue_closed = item.github_issue_state.as_deref() == Some("closed");
        let is_complete = has_outcome && issue_closed;

        Ok((is_complete, has_outcome, issue_closed))
    }

    // ========================================================================
    // GitHub Issue Cache Methods
    // ========================================================================

    /// Cache a GitHub issue for local display in web viewer
    pub fn cache_github_issue(
        &self,
        issue_number: i32,
        repo: &str,
        title: &str,
        body: Option<&str>,
        state: &str,
        html_url: &str,
        created_at: &str,
        updated_at: &str,
    ) -> Result<()> {
        let mut conn = self.get_conn()?;
        let now = chrono::Local::now().to_rfc3339();

        // Upsert: delete existing then insert
        diesel::delete(
            github_issue_cache::table
                .filter(github_issue_cache::repo.eq(repo))
                .filter(github_issue_cache::issue_number.eq(issue_number)),
        )
        .execute(&mut conn)?;

        let new_cache = NewGitHubIssueCache {
            issue_number,
            repo,
            title,
            body,
            state,
            html_url,
            created_at,
            updated_at,
            cached_at: &now,
        };

        diesel::insert_into(github_issue_cache::table)
            .values(&new_cache)
            .execute(&mut conn)?;

        Ok(())
    }

    /// Get a cached GitHub issue by repo and number
    pub fn get_cached_issue(
        &self,
        repo: &str,
        issue_number: i32,
    ) -> Result<Option<GitHubIssueCache>> {
        let mut conn = self.get_conn()?;

        let result = github_issue_cache::table
            .filter(github_issue_cache::repo.eq(repo))
            .filter(github_issue_cache::issue_number.eq(issue_number))
            .first::<GitHubIssueCache>(&mut conn)
            .optional()?;

        Ok(result)
    }

    /// Get all cached issues for a repo
    pub fn get_cached_issues_for_repo(&self, repo: &str) -> Result<Vec<GitHubIssueCache>> {
        let mut conn = self.get_conn()?;

        let issues = github_issue_cache::table
            .filter(github_issue_cache::repo.eq(repo))
            .order(github_issue_cache::issue_number.desc())
            .load::<GitHubIssueCache>(&mut conn)?;

        Ok(issues)
    }

    /// Get all cached issues
    pub fn get_all_cached_issues(&self) -> Result<Vec<GitHubIssueCache>> {
        let mut conn = self.get_conn()?;

        let issues = github_issue_cache::table
            .order(github_issue_cache::cached_at.desc())
            .load::<GitHubIssueCache>(&mut conn)?;

        Ok(issues)
    }

    /// Clear cached issues older than a specified duration
    pub fn clear_stale_cache(&self, max_age_hours: i64) -> Result<usize> {
        let mut conn = self.get_conn()?;
        let cutoff = chrono::Local::now() - chrono::Duration::hours(max_age_hours);
        let cutoff_str = cutoff.to_rfc3339();

        let deleted = diesel::delete(
            github_issue_cache::table.filter(github_issue_cache::cached_at.lt(&cutoff_str)),
        )
        .execute(&mut conn)?;

        Ok(deleted)
    }

    // ========================================================================
    // Document Attachment Operations
    // ========================================================================

    /// Attach a document to a node
    pub fn attach_document(
        &self,
        node_id: i32,
        content_hash: &str,
        original_filename: &str,
        storage_filename: &str,
        mime_type: &str,
        file_size: i32,
        description: Option<&str>,
        description_source: &str,
        attached_by: Option<&str>,
    ) -> Result<i32> {
        // Validate node exists and get its change_id
        let node = self
            .get_node(node_id)?
            .ok_or_else(|| DbError::Validation(format!("Node {} not found", node_id)))?;

        let mut conn = self.get_conn()?;
        let now = chrono::Local::now().to_rfc3339();
        let change_id = Uuid::new_v4().to_string();

        let new_doc = NewNodeDocument {
            change_id: &change_id,
            node_id,
            node_change_id: &node.change_id,
            content_hash,
            original_filename,
            storage_filename,
            mime_type,
            file_size,
            description,
            description_source,
            attached_at: &now,
            attached_by,
            detached_at: None,
        };

        diesel::insert_into(node_documents::table)
            .values(&new_doc)
            .execute(&mut conn)?;

        let id: i32 = diesel::select(diesel::dsl::sql::<diesel::sql_types::Integer>(
            "last_insert_rowid()",
        ))
        .first(&mut conn)?;

        Ok(id)
    }

    /// List documents, optionally filtered by node_id
    pub fn get_node_documents(
        &self,
        node_id: Option<i32>,
        include_detached: bool,
    ) -> Result<Vec<NodeDocument>> {
        let mut conn = self.get_conn()?;

        let mut query = node_documents::table.into_boxed();

        if let Some(nid) = node_id {
            query = query.filter(node_documents::node_id.eq(nid));
        }

        if !include_detached {
            query = query.filter(node_documents::detached_at.is_null());
        }

        let results = query
            .order(node_documents::attached_at.desc())
            .load::<NodeDocument>(&mut conn)?;
        Ok(results)
    }

    /// Get a specific document by ID
    pub fn get_document(&self, doc_id: i32) -> Result<Option<NodeDocument>> {
        let mut conn = self.get_conn()?;
        let result = node_documents::table
            .filter(node_documents::id.eq(doc_id))
            .first::<NodeDocument>(&mut conn)
            .optional()?;
        Ok(result)
    }

    /// Update document description
    pub fn update_document_description(
        &self,
        doc_id: i32,
        description: &str,
        source: &str,
    ) -> Result<()> {
        let mut conn = self.get_conn()?;
        diesel::update(node_documents::table.filter(node_documents::id.eq(doc_id)))
            .set((
                node_documents::description.eq(description),
                node_documents::description_source.eq(source),
            ))
            .execute(&mut conn)?;
        Ok(())
    }

    /// Soft-delete (detach) a document
    pub fn detach_document(&self, doc_id: i32) -> Result<()> {
        let mut conn = self.get_conn()?;
        let now = chrono::Local::now().to_rfc3339();
        diesel::update(node_documents::table.filter(node_documents::id.eq(doc_id)))
            .set(node_documents::detached_at.eq(&now))
            .execute(&mut conn)?;
        Ok(())
    }

    /// Get all active content hashes (for garbage collection)
    pub fn get_active_content_hashes(&self) -> Result<Vec<String>> {
        let mut conn = self.get_conn()?;
        let results = node_documents::table
            .filter(node_documents::detached_at.is_null())
            .select(node_documents::content_hash)
            .distinct()
            .load::<String>(&mut conn)?;
        Ok(results)
    }

    // ========================================================================
    // Theme Operations
    // ========================================================================

    /// Create a new theme
    pub fn create_theme(&self, name: &str, color: &str, description: Option<&str>) -> Result<i32> {
        let mut conn = self.get_conn()?;
        let now = chrono::Local::now().to_rfc3339();
        let change_id = Uuid::new_v4().to_string();
        let normalized_name = name.to_lowercase().replace(' ', "-");

        let new_theme = NewTheme {
            change_id: &change_id,
            name: &normalized_name,
            color,
            description,
            created_at: &now,
            updated_at: &now,
        };

        diesel::insert_into(themes::table)
            .values(&new_theme)
            .execute(&mut conn)?;

        let id: i32 = diesel::select(diesel::dsl::sql::<diesel::sql_types::Integer>(
            "last_insert_rowid()",
        ))
        .first(&mut conn)?;

        Ok(id)
    }

    /// Get a theme by name
    pub fn get_theme_by_name(&self, name: &str) -> Result<Option<Theme>> {
        let mut conn = self.get_conn()?;
        let normalized = name.to_lowercase().replace(' ', "-");

        let result = themes::table
            .filter(themes::name.eq(&normalized))
            .first::<Theme>(&mut conn)
            .optional()?;

        Ok(result)
    }

    /// Get all themes
    pub fn get_all_themes(&self) -> Result<Vec<Theme>> {
        let mut conn = self.get_conn()?;
        let results = themes::table
            .order(themes::name.asc())
            .load::<Theme>(&mut conn)?;
        Ok(results)
    }

    /// Delete a theme by name (also removes all node_themes associations)
    pub fn delete_theme(&self, name: &str) -> Result<bool> {
        let mut conn = self.get_conn()?;
        let normalized = name.to_lowercase().replace(' ', "-");

        let theme = themes::table
            .filter(themes::name.eq(&normalized))
            .first::<Theme>(&mut conn)
            .optional()?;

        if let Some(theme) = theme {
            // Delete junction entries first
            diesel::delete(node_themes::table.filter(node_themes::theme_id.eq(theme.id)))
                .execute(&mut conn)?;
            // Delete theme
            diesel::delete(themes::table.filter(themes::id.eq(theme.id))).execute(&mut conn)?;
            Ok(true)
        } else {
            Ok(false)
        }
    }

    /// Tag a node with a theme
    pub fn tag_node(&self, node_id: i32, theme_name: &str, source: &str) -> Result<()> {
        let theme = self.get_theme_by_name(theme_name)?.ok_or_else(|| {
            DbError::Validation(format!(
                "Theme '{}' not found. Create it with: deciduous themes create {}",
                theme_name, theme_name
            ))
        })?;

        // Validate node exists
        let _ = self
            .get_node(node_id)?
            .ok_or_else(|| DbError::Validation(format!("Node {} not found", node_id)))?;

        let mut conn = self.get_conn()?;
        let now = chrono::Local::now().to_rfc3339();

        let new_nt = NewNodeTheme {
            node_id,
            theme_id: theme.id,
            source: source.to_string(),
            created_at: now,
        };

        diesel::insert_or_ignore_into(node_themes::table)
            .values(&new_nt)
            .execute(&mut conn)?;

        Ok(())
    }

    /// Remove a theme from a node
    pub fn untag_node(&self, node_id: i32, theme_name: &str) -> Result<bool> {
        let theme = self.get_theme_by_name(theme_name)?;

        if let Some(theme) = theme {
            let mut conn = self.get_conn()?;
            let deleted = diesel::delete(
                node_themes::table
                    .filter(node_themes::node_id.eq(node_id))
                    .filter(node_themes::theme_id.eq(theme.id)),
            )
            .execute(&mut conn)?;
            Ok(deleted > 0)
        } else {
            Ok(false)
        }
    }

    /// Confirm a suggested tag (change source from "suggested" to "manual")
    pub fn confirm_tag(&self, node_id: i32, theme_name: &str) -> Result<bool> {
        let theme = self.get_theme_by_name(theme_name)?;

        if let Some(theme) = theme {
            let mut conn = self.get_conn()?;
            let updated = diesel::update(
                node_themes::table
                    .filter(node_themes::node_id.eq(node_id))
                    .filter(node_themes::theme_id.eq(theme.id)),
            )
            .set(node_themes::source.eq("manual"))
            .execute(&mut conn)?;
            Ok(updated > 0)
        } else {
            Ok(false)
        }
    }

    /// Get themes for a specific node
    pub fn get_node_themes(&self, node_id: i32) -> Result<Vec<Theme>> {
        let mut conn = self.get_conn()?;

        let theme_ids: Vec<i32> = node_themes::table
            .filter(node_themes::node_id.eq(node_id))
            .select(node_themes::theme_id)
            .load(&mut conn)?;

        let results = themes::table
            .filter(themes::id.eq_any(theme_ids))
            .order(themes::name.asc())
            .load::<Theme>(&mut conn)?;

        Ok(results)
    }

    /// Get nodes that have a specific theme
    pub fn get_nodes_by_theme(&self, theme_name: &str) -> Result<Vec<DecisionNode>> {
        let theme = self.get_theme_by_name(theme_name)?;

        if let Some(theme) = theme {
            let mut conn = self.get_conn()?;

            let node_ids: Vec<i32> = node_themes::table
                .filter(node_themes::theme_id.eq(theme.id))
                .select(node_themes::node_id)
                .load(&mut conn)?;

            let results = decision_nodes::table
                .filter(decision_nodes::id.eq_any(node_ids))
                .load::<DecisionNode>(&mut conn)?;

            Ok(results)
        } else {
            Ok(Vec::new())
        }
    }

    /// Get all node-theme associations (for export)
    pub fn get_all_node_themes(&self) -> Result<Vec<NodeTheme>> {
        let mut conn = self.get_conn()?;
        let results = node_themes::table.load::<NodeTheme>(&mut conn)?;
        Ok(results)
    }

    // ========================================================================
    // Q&A Interactions
    // ========================================================================

    /// Save a Q&A interaction (user question and Claude response)
    pub fn save_qa_interaction(
        &self,
        user_prompt: &str,
        total_prompt: &str,
        response: &str,
        context_json: Option<&str>,
    ) -> Result<i32> {
        let mut conn = self.get_conn()?;
        let now = chrono::Local::now().to_rfc3339();

        let new_interaction = NewQaInteraction {
            user_prompt,
            total_prompt,
            response,
            context_json,
            inserted_at: &now,
            deleted_at: None,
        };

        diesel::insert_into(qa_interactions::table)
            .values(&new_interaction)
            .execute(&mut conn)?;

        let id: i32 = diesel::select(diesel::dsl::sql::<diesel::sql_types::Integer>(
            "last_insert_rowid()",
        ))
        .first(&mut conn)?;

        Ok(id)
    }

    /// Get all Q&A interactions (excluding soft-deleted)
    pub fn get_qa_interactions(&self) -> Result<Vec<QaInteraction>> {
        let mut conn = self.get_conn()?;

        let interactions = qa_interactions::table
            .filter(qa_interactions::deleted_at.is_null())
            .order(qa_interactions::inserted_at.desc())
            .load::<QaInteraction>(&mut conn)?;

        Ok(interactions)
    }

    /// Soft delete a Q&A interaction
    pub fn soft_delete_qa_interaction(&self, id: i32) -> Result<()> {
        let mut conn = self.get_conn()?;
        let now = chrono::Local::now().to_rfc3339();

        diesel::update(qa_interactions::table.filter(qa_interactions::id.eq(id)))
            .set(qa_interactions::deleted_at.eq(Some(&now)))
            .execute(&mut conn)?;

        Ok(())
    }

    /// Search Q&A interactions using FTS5 full-text search
    /// Returns results ranked by relevance (BM25 algorithm)
    pub fn search_qa_interactions(&self, query: &str, limit: i32) -> Result<Vec<QaSearchResult>> {
        let mut conn = self.get_conn()?;

        // Escape single quotes in query for SQL safety
        let safe_query = query.replace('\'', "''");

        // FTS5 query with BM25 ranking and highlighted snippets
        // bm25() returns negative scores (closer to 0 = more relevant)
        // highlight() wraps matches in <mark> tags
        let sql = format!(
            r#"
            SELECT
                qa.id,
                qa.user_prompt,
                qa.total_prompt,
                qa.response,
                qa.context_json,
                qa.inserted_at,
                qa.deleted_at,
                bm25(qa_interactions_fts) as rank,
                highlight(qa_interactions_fts, 0, '<mark>', '</mark>') as snippet_prompt,
                highlight(qa_interactions_fts, 1, '<mark>', '</mark>') as snippet_response
            FROM qa_interactions_fts
            JOIN qa_interactions qa ON qa.id = qa_interactions_fts.rowid
            WHERE qa_interactions_fts MATCH '{}'
            AND qa.deleted_at IS NULL
            ORDER BY rank
            LIMIT {}
            "#,
            safe_query, limit
        );

        let rows: Vec<FtsSearchRow> = diesel::sql_query(sql).load(&mut conn).unwrap_or_default();

        Ok(rows
            .into_iter()
            .map(|row| QaSearchResult {
                interaction: QaInteraction {
                    id: row.id,
                    user_prompt: row.user_prompt,
                    total_prompt: row.total_prompt,
                    response: row.response,
                    context_json: row.context_json,
                    inserted_at: row.inserted_at,
                    deleted_at: row.deleted_at,
                },
                rank: row.rank,
                snippet_prompt: row.snippet_prompt,
                snippet_response: row.snippet_response,
            })
            .collect())
    }

    /// Get a single Q&A interaction by ID
    pub fn get_qa_interaction(&self, id: i32) -> Result<Option<QaInteraction>> {
        let mut conn = self.get_conn()?;

        let result = qa_interactions::table
            .filter(qa_interactions::id.eq(id))
            .filter(qa_interactions::deleted_at.is_null())
            .first::<QaInteraction>(&mut conn)
            .optional()?;

        Ok(result)
    }

    /// Get paginated Q&A interactions (for browsing without search)
    pub fn get_qa_interactions_paginated(
        &self,
        offset: i64,
        limit: i64,
    ) -> Result<Vec<QaInteraction>> {
        let mut conn = self.get_conn()?;

        let interactions = qa_interactions::table
            .filter(qa_interactions::deleted_at.is_null())
            .order(qa_interactions::inserted_at.desc())
            .offset(offset)
            .limit(limit)
            .load::<QaInteraction>(&mut conn)?;

        Ok(interactions)
    }

    /// Get total count of Q&A interactions (for pagination UI)
    pub fn count_qa_interactions(&self) -> Result<i64> {
        let mut conn = self.get_conn()?;

        let count: i64 = qa_interactions::table
            .filter(qa_interactions::deleted_at.is_null())
            .count()
            .get_result(&mut conn)?;

        Ok(count)
    }
}

// ============================================================================
// Q&A Interactions Models
// ============================================================================

/// Insertable Q&A interaction
#[derive(Insertable)]
#[diesel(table_name = qa_interactions)]
pub struct NewQaInteraction<'a> {
    pub user_prompt: &'a str,
    pub total_prompt: &'a str,
    pub response: &'a str,
    pub context_json: Option<&'a str>,
    pub inserted_at: &'a str,
    pub deleted_at: Option<&'a str>,
}

/// Queryable Q&A interaction
#[derive(Queryable, Selectable, Debug, Clone, serde::Serialize)]
#[cfg_attr(feature = "ts-rs", derive(TS))]
#[cfg_attr(feature = "ts-rs", ts(export))]
#[diesel(table_name = qa_interactions)]
pub struct QaInteraction {
    pub id: i32,
    pub user_prompt: String,
    pub total_prompt: String,
    pub response: String,
    pub context_json: Option<String>,
    pub inserted_at: String,
    pub deleted_at: Option<String>,
}

/// Q&A search result with FTS5 ranking and highlighted snippets
#[derive(Debug, Clone, serde::Serialize)]
#[cfg_attr(feature = "ts-rs", derive(TS))]
#[cfg_attr(feature = "ts-rs", ts(export))]
pub struct QaSearchResult {
    pub interaction: QaInteraction,
    pub rank: f64,
    pub snippet_prompt: String,
    pub snippet_response: String,
}

// ============================================================================
// Node Document Models
// ============================================================================

/// Insertable node document attachment
#[derive(Insertable)]
#[diesel(table_name = node_documents)]
pub struct NewNodeDocument<'a> {
    pub change_id: &'a str,
    pub node_id: i32,
    pub node_change_id: &'a str,
    pub content_hash: &'a str,
    pub original_filename: &'a str,
    pub storage_filename: &'a str,
    pub mime_type: &'a str,
    pub file_size: i32,
    pub description: Option<&'a str>,
    pub description_source: &'a str,
    pub attached_at: &'a str,
    pub attached_by: Option<&'a str>,
    pub detached_at: Option<&'a str>,
}

/// Queryable node document attachment
#[derive(Queryable, Selectable, Debug, Clone, serde::Serialize)]
#[cfg_attr(feature = "ts-rs", derive(TS))]
#[cfg_attr(feature = "ts-rs", ts(export))]
#[diesel(table_name = node_documents)]
pub struct NodeDocument {
    pub id: i32,
    pub change_id: String,
    pub node_id: i32,
    pub node_change_id: String,
    pub content_hash: String,
    pub original_filename: String,
    pub storage_filename: String,
    pub mime_type: String,
    pub file_size: i32,
    pub description: Option<String>,
    pub description_source: String,
    pub attached_at: String,
    pub attached_by: Option<String>,
    pub detached_at: Option<String>,
}

// ============================================================================
// Theme Models
// ============================================================================

/// Insertable theme
#[derive(Insertable)]
#[diesel(table_name = themes)]
pub struct NewTheme<'a> {
    pub change_id: &'a str,
    pub name: &'a str,
    pub color: &'a str,
    pub description: Option<&'a str>,
    pub created_at: &'a str,
    pub updated_at: &'a str,
}

/// Queryable theme
#[derive(Queryable, Selectable, Debug, Clone, serde::Serialize)]
#[cfg_attr(feature = "ts-rs", derive(TS))]
#[cfg_attr(feature = "ts-rs", ts(export))]
#[diesel(table_name = themes)]
pub struct Theme {
    pub id: i32,
    pub change_id: String,
    pub name: String,
    pub color: String,
    pub description: Option<String>,
    pub created_at: String,
    pub updated_at: String,
}

/// Insertable node-theme association
#[derive(Insertable)]
#[diesel(table_name = node_themes)]
pub struct NewNodeTheme {
    pub node_id: i32,
    pub theme_id: i32,
    pub source: String,
    pub created_at: String,
}

/// Queryable node-theme association
#[derive(Queryable, Selectable, Debug, Clone, serde::Serialize)]
#[cfg_attr(feature = "ts-rs", derive(TS))]
#[cfg_attr(feature = "ts-rs", ts(export))]
#[diesel(table_name = node_themes)]
pub struct NodeTheme {
    pub node_id: i32,
    pub theme_id: i32,
    pub source: String,
    pub created_at: String,
}

// ============================================================================
// Additional Types
// ============================================================================

/// Summary statistics from the database (kept for compatibility)
#[derive(Debug, Clone, serde::Serialize)]
pub struct DbSummary {
    pub total_nodes: i32,
    pub total_edges: i32,
}

/// Alias for backwards compatibility
pub type DbRecord = DecisionNode;

/// Full decision graph for serialization
#[derive(Debug, Clone, serde::Serialize)]
pub struct DecisionGraph {
    pub nodes: Vec<DecisionNode>,
    pub edges: Vec<DecisionEdge>,
    /// Optional config from .deciduous/config.toml (for external repo links, etc.)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub config: Option<crate::config::Config>,
    /// Theme definitions
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub themes: Vec<Theme>,
    /// Node-theme associations
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub node_themes: Vec<NodeTheme>,
    /// Document attachments
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub documents: Vec<NodeDocument>,
}

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

    // === build_metadata_json Tests ===

    #[test]
    fn test_build_metadata_empty() {
        let result = build_metadata_json(None, None, None, None, None);
        assert!(result.is_none());
    }

    #[test]
    fn test_build_metadata_confidence_only() {
        let result = build_metadata_json(Some(85), None, None, None, None);
        assert!(result.is_some());
        let json: serde_json::Value = serde_json::from_str(&result.unwrap()).unwrap();
        assert_eq!(json.get("confidence").unwrap(), 85);
    }

    #[test]
    fn test_build_metadata_confidence_clamped() {
        let result = build_metadata_json(Some(150), None, None, None, None);
        let json: serde_json::Value = serde_json::from_str(&result.unwrap()).unwrap();
        // Should be clamped to 100
        assert_eq!(json.get("confidence").unwrap(), 100);
    }

    #[test]
    fn test_build_metadata_commit() {
        let result = build_metadata_json(None, Some("abc123"), None, None, None);
        let json: serde_json::Value = serde_json::from_str(&result.unwrap()).unwrap();
        assert_eq!(json.get("commit").unwrap(), "abc123");
    }

    #[test]
    fn test_build_metadata_prompt() {
        let result = build_metadata_json(None, None, Some("User asked: do X"), None, None);
        let json: serde_json::Value = serde_json::from_str(&result.unwrap()).unwrap();
        assert_eq!(json.get("prompt").unwrap(), "User asked: do X");
    }

    #[test]
    fn test_build_metadata_files() {
        let result = build_metadata_json(None, None, None, Some("a.rs, b.rs, c.rs"), None);
        let json: serde_json::Value = serde_json::from_str(&result.unwrap()).unwrap();
        let files = json.get("files").unwrap().as_array().unwrap();
        assert_eq!(files.len(), 3);
        assert_eq!(files[0], "a.rs");
        assert_eq!(files[1], "b.rs");
        assert_eq!(files[2], "c.rs");
    }

    #[test]
    fn test_build_metadata_branch() {
        let result = build_metadata_json(None, None, None, None, Some("feature-x"));
        let json: serde_json::Value = serde_json::from_str(&result.unwrap()).unwrap();
        assert_eq!(json.get("branch").unwrap(), "feature-x");
    }

    #[test]
    fn test_build_metadata_all_fields() {
        let result = build_metadata_json(
            Some(90),
            Some("def456"),
            Some("User prompt"),
            Some("x.rs"),
            Some("main"),
        );
        let json: serde_json::Value = serde_json::from_str(&result.unwrap()).unwrap();

        assert_eq!(json.get("confidence").unwrap(), 90);
        assert_eq!(json.get("commit").unwrap(), "def456");
        assert_eq!(json.get("prompt").unwrap(), "User prompt");
        assert_eq!(json.get("branch").unwrap(), "main");
        assert!(json.get("files").unwrap().as_array().is_some());
    }

    // === DecisionSchema Tests ===

    #[test]
    fn test_schema_version_string() {
        let schema = DecisionSchema {
            major: 1,
            minor: 2,
            patch: 3,
            name: "test",
            features: &[],
        };
        assert_eq!(schema.version_string(), "1.2.3");
    }

    #[test]
    fn test_schema_compatibility_same_major() {
        let schema1 = DecisionSchema {
            major: 1,
            minor: 0,
            patch: 0,
            name: "test",
            features: &[],
        };
        let schema2 = DecisionSchema {
            major: 1,
            minor: 5,
            patch: 3,
            name: "test",
            features: &[],
        };
        assert!(schema1.is_compatible_with(&schema2));
    }

    #[test]
    fn test_schema_incompatibility_different_major() {
        let schema1 = DecisionSchema {
            major: 1,
            minor: 0,
            patch: 0,
            name: "test",
            features: &[],
        };
        let schema2 = DecisionSchema {
            major: 2,
            minor: 0,
            patch: 0,
            name: "test",
            features: &[],
        };
        assert!(!schema1.is_compatible_with(&schema2));
    }

    #[test]
    fn test_schema_is_newer_than() {
        let old = DecisionSchema {
            major: 1,
            minor: 0,
            patch: 0,
            name: "test",
            features: &[],
        };
        let new = DecisionSchema {
            major: 1,
            minor: 1,
            patch: 0,
            name: "test",
            features: &[],
        };
        assert!(new.is_newer_than(&old));
        assert!(!old.is_newer_than(&new));
        assert!(!old.is_newer_than(&old));
    }

    // === Current Schema Tests ===

    #[test]
    fn test_current_schema() {
        assert_eq!(CURRENT_SCHEMA.major, 1);
        assert_eq!(CURRENT_SCHEMA.name, "decision-graph");
        assert!(CURRENT_SCHEMA.features.contains(&"decision_nodes"));
        assert!(CURRENT_SCHEMA.features.contains(&"decision_edges"));
    }

    // === update_node_commit Tests ===

    #[test]
    fn test_update_node_commit_new_metadata() {
        let dir = tempfile::tempdir().unwrap();
        let db_path = dir.path().join("test.db");
        let db = Database::new(db_path.to_str().unwrap()).unwrap();

        // Create a node without metadata
        let node_id = db
            .create_node("action", "Test action", None, None, None)
            .unwrap();

        // Update with commit
        db.update_node_commit(node_id, "abc123def456").unwrap();

        // Verify
        let nodes = db.get_all_nodes().unwrap();
        let node = nodes.iter().find(|n| n.id == node_id).unwrap();
        let meta: serde_json::Value =
            serde_json::from_str(node.metadata_json.as_ref().unwrap()).unwrap();
        assert_eq!(meta.get("commit").unwrap(), "abc123def456");
    }

    #[test]
    fn test_update_node_commit_preserves_existing_metadata() {
        let dir = tempfile::tempdir().unwrap();
        let db_path = dir.path().join("test.db");
        let db = Database::new(db_path.to_str().unwrap()).unwrap();

        // Create a node with existing metadata (confidence and branch)
        let node_id = db
            .create_node_full(
                "action",
                "Test action",
                None,
                Some(85),
                None,
                None,
                None,
                Some("feature-x"),
                None,
            )
            .unwrap();

        // Update with commit
        db.update_node_commit(node_id, "def789").unwrap();

        // Verify commit was added and other fields preserved
        let nodes = db.get_all_nodes().unwrap();
        let node = nodes.iter().find(|n| n.id == node_id).unwrap();
        let meta: serde_json::Value =
            serde_json::from_str(node.metadata_json.as_ref().unwrap()).unwrap();

        assert_eq!(meta.get("commit").unwrap(), "def789");
        assert_eq!(meta.get("confidence").unwrap(), 85);
        assert_eq!(meta.get("branch").unwrap(), "feature-x");
    }

    #[test]
    fn test_update_node_commit_overwrites_existing_commit() {
        let dir = tempfile::tempdir().unwrap();
        let db_path = dir.path().join("test.db");
        let db = Database::new(db_path.to_str().unwrap()).unwrap();

        // Create a node with an existing commit
        let node_id = db
            .create_node_full(
                "outcome",
                "Test outcome",
                None,
                None,
                Some("old_commit_hash"),
                None,
                None,
                None,
                None,
            )
            .unwrap();

        // Update with new commit
        db.update_node_commit(node_id, "new_commit_hash").unwrap();

        // Verify commit was overwritten
        let nodes = db.get_all_nodes().unwrap();
        let node = nodes.iter().find(|n| n.id == node_id).unwrap();
        let meta: serde_json::Value =
            serde_json::from_str(node.metadata_json.as_ref().unwrap()).unwrap();

        assert_eq!(meta.get("commit").unwrap(), "new_commit_hash");
    }

    // === Theme Tests ===

    #[test]
    fn test_create_and_get_theme() {
        let dir = tempfile::tempdir().unwrap();
        let db = Database::new(dir.path().join("test.db").to_str().unwrap()).unwrap();

        let id = db
            .create_theme("security", "#ef4444", Some("Security concerns"))
            .unwrap();
        assert!(id > 0);

        let theme = db.get_theme_by_name("security").unwrap().unwrap();
        assert_eq!(theme.name, "security");
        assert_eq!(theme.color, "#ef4444");
        assert_eq!(theme.description.as_deref(), Some("Security concerns"));
    }

    #[test]
    fn test_theme_name_normalization() {
        let dir = tempfile::tempdir().unwrap();
        let db = Database::new(dir.path().join("test.db").to_str().unwrap()).unwrap();

        db.create_theme("Technical Debt", "#666", None).unwrap();
        let theme = db.get_theme_by_name("technical-debt").unwrap();
        assert!(theme.is_some());
        assert_eq!(theme.unwrap().name, "technical-debt");
    }

    #[test]
    fn test_list_themes() {
        let dir = tempfile::tempdir().unwrap();
        let db = Database::new(dir.path().join("test.db").to_str().unwrap()).unwrap();

        db.create_theme("alpha", "#111", None).unwrap();
        db.create_theme("beta", "#222", None).unwrap();
        db.create_theme("gamma", "#333", None).unwrap();

        let themes = db.get_all_themes().unwrap();
        assert_eq!(themes.len(), 3);
        // Should be sorted by name
        assert_eq!(themes[0].name, "alpha");
        assert_eq!(themes[1].name, "beta");
        assert_eq!(themes[2].name, "gamma");
    }

    #[test]
    fn test_delete_theme() {
        let dir = tempfile::tempdir().unwrap();
        let db = Database::new(dir.path().join("test.db").to_str().unwrap()).unwrap();

        db.create_theme("temp", "#000", None).unwrap();
        assert!(db.delete_theme("temp").unwrap());
        assert!(db.get_theme_by_name("temp").unwrap().is_none());
        // Deleting non-existent returns false
        assert!(!db.delete_theme("temp").unwrap());
    }

    #[test]
    fn test_tag_and_untag_node() {
        let dir = tempfile::tempdir().unwrap();
        let db = Database::new(dir.path().join("test.db").to_str().unwrap()).unwrap();

        let node_id = db
            .create_node("goal", "Improve perf", None, None, None)
            .unwrap();
        db.create_theme("performance", "#10b981", None).unwrap();

        db.tag_node(node_id, "performance", "manual").unwrap();

        let themes = db.get_node_themes(node_id).unwrap();
        assert_eq!(themes.len(), 1);
        assert_eq!(themes[0].name, "performance");

        let nodes = db.get_nodes_by_theme("performance").unwrap();
        assert_eq!(nodes.len(), 1);
        assert_eq!(nodes[0].id, node_id);

        assert!(db.untag_node(node_id, "performance").unwrap());
        let themes = db.get_node_themes(node_id).unwrap();
        assert!(themes.is_empty());
    }

    #[test]
    fn test_delete_theme_cascades_to_tags() {
        let dir = tempfile::tempdir().unwrap();
        let db = Database::new(dir.path().join("test.db").to_str().unwrap()).unwrap();

        let node_id = db.create_node("goal", "Test", None, None, None).unwrap();
        db.create_theme("temp", "#000", None).unwrap();
        db.tag_node(node_id, "temp", "manual").unwrap();

        db.delete_theme("temp").unwrap();
        let themes = db.get_node_themes(node_id).unwrap();
        assert!(themes.is_empty());
    }

    #[test]
    fn test_confirm_tag() {
        let dir = tempfile::tempdir().unwrap();
        let db = Database::new(dir.path().join("test.db").to_str().unwrap()).unwrap();

        let node_id = db.create_node("goal", "Test", None, None, None).unwrap();
        db.create_theme("ux", "#3b82f6", None).unwrap();
        db.tag_node(node_id, "ux", "suggested").unwrap();

        // Check source is "suggested"
        let all_nt = db.get_all_node_themes().unwrap();
        assert_eq!(all_nt[0].source, "suggested");

        // Confirm it
        assert!(db.confirm_tag(node_id, "ux").unwrap());

        let all_nt = db.get_all_node_themes().unwrap();
        assert_eq!(all_nt[0].source, "manual");
    }

    #[test]
    fn test_theme_in_graph_export() {
        let dir = tempfile::tempdir().unwrap();
        let db = Database::new(dir.path().join("test.db").to_str().unwrap()).unwrap();

        let node_id = db.create_node("goal", "Test", None, None, None).unwrap();
        db.create_theme("ux", "#3b82f6", None).unwrap();
        db.tag_node(node_id, "ux", "manual").unwrap();

        let graph = db.get_graph().unwrap();
        assert_eq!(graph.themes.len(), 1);
        assert_eq!(graph.node_themes.len(), 1);

        // Verify serialization includes themes
        let json = serde_json::to_string(&graph).unwrap();
        assert!(json.contains("\"themes\""));
        assert!(json.contains("\"ux\""));
    }

    // === Document Tests ===

    #[test]
    fn test_attach_and_list_documents() {
        let dir = tempfile::tempdir().unwrap();
        let db = Database::new(dir.path().join("test.db").to_str().unwrap()).unwrap();

        let node_id = db
            .create_node("goal", "Test goal", None, None, None)
            .unwrap();

        let doc_id = db
            .attach_document(
                node_id,
                "abc123hash",
                "report.pdf",
                "report.pdf.abc12345",
                "application/pdf",
                1024,
                Some("A test report"),
                "manual",
                None,
            )
            .unwrap();
        assert!(doc_id > 0);

        let docs = db.get_node_documents(Some(node_id), false).unwrap();
        assert_eq!(docs.len(), 1);
        assert_eq!(docs[0].original_filename, "report.pdf");
        assert_eq!(docs[0].description.as_deref(), Some("A test report"));
    }

    #[test]
    fn test_detach_document() {
        let dir = tempfile::tempdir().unwrap();
        let db = Database::new(dir.path().join("test.db").to_str().unwrap()).unwrap();

        let node_id = db.create_node("goal", "Test", None, None, None).unwrap();
        let doc_id = db
            .attach_document(
                node_id,
                "hash1",
                "file.txt",
                "file.txt.hash1234",
                "text/plain",
                100,
                None,
                "none",
                None,
            )
            .unwrap();

        // Detach
        db.detach_document(doc_id).unwrap();

        // Should not appear in default list
        let docs = db.get_node_documents(Some(node_id), false).unwrap();
        assert!(docs.is_empty());

        // Should appear with include_detached
        let docs = db.get_node_documents(Some(node_id), true).unwrap();
        assert_eq!(docs.len(), 1);
        assert!(docs[0].detached_at.is_some());
    }

    #[test]
    fn test_update_document_description() {
        let dir = tempfile::tempdir().unwrap();
        let db = Database::new(dir.path().join("test.db").to_str().unwrap()).unwrap();

        let node_id = db.create_node("goal", "Test", None, None, None).unwrap();
        let doc_id = db
            .attach_document(
                node_id,
                "hash1",
                "file.txt",
                "file.txt.hash1234",
                "text/plain",
                100,
                None,
                "none",
                None,
            )
            .unwrap();

        db.update_document_description(doc_id, "Updated desc", "manual")
            .unwrap();

        let doc = db.get_document(doc_id).unwrap().unwrap();
        assert_eq!(doc.description.as_deref(), Some("Updated desc"));
        assert_eq!(doc.description_source, "manual");
    }

    #[test]
    fn test_documents_in_graph_export() {
        let dir = tempfile::tempdir().unwrap();
        let db = Database::new(dir.path().join("test.db").to_str().unwrap()).unwrap();

        let node_id = db.create_node("goal", "Test", None, None, None).unwrap();
        db.attach_document(
            node_id,
            "hash1",
            "file.txt",
            "file.txt.hash1234",
            "text/plain",
            100,
            Some("A file"),
            "manual",
            None,
        )
        .unwrap();

        let graph = db.get_graph().unwrap();
        assert_eq!(graph.documents.len(), 1);

        let json = serde_json::to_string(&graph).unwrap();
        assert!(json.contains("\"documents\""));
        assert!(json.contains("file.txt"));
    }
}