zynk 1.1.0

Portable protocol and helper CLI for multi-agent collaboration.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
use crate::{CliError, CliResult};
use clap::{Args, Subcommand};
use rand::{rngs::OsRng, Rng};
use rusqlite::{
    params, Connection, OpenFlags, OptionalExtension, Transaction, TransactionBehavior,
};
use sha2::{Digest, Sha256};
use std::collections::{BTreeMap, HashMap, HashSet};
use std::fs;
use std::io::Read;
use std::path::{Path, PathBuf};
use std::time::Duration;

const CURRENT_SCHEMA_VERSION: i64 = 10;

/// SQLite GLOB matching the canonical `YYYY-MM-DDTHH:MM:SSZ` timestamp form.
/// `?` matches exactly one character, so offset forms like `+07:00` (length 25)
/// never match. See ADR 026 D1.
const CANONICAL_TS_GLOB: &str = "????-??-??T??:??:??Z";
const BUSY_TIMEOUT_MS: u64 = 5000;

#[derive(Debug, Args)]
pub struct DbArgs {
    #[arg(
        long,
        default_value = ".zynk/zynk.db",
        help = "SQLite database path for live zynk state"
    )]
    pub db: PathBuf,
    #[command(subcommand)]
    pub command: DbCommand,
}

#[derive(Debug, Subcommand)]
pub enum DbCommand {
    /// Create or migrate the live-state SQLite database.
    Init,
    /// Append audit records to the live-state SQLite database.
    Audit(Box<DbAuditCommand>),
    /// Import human-readable artifacts into the live-state SQLite database.
    Import(Box<DbImportCommand>),
    /// Export live-state SQLite data into human-readable artifacts.
    Export(Box<DbExportCommand>),
    /// Serve the DB-backed local dashboard console.
    Serve(crate::db_dashboard::DbServeArgs),
}

#[derive(Debug, Args)]
pub struct DbAuditCommand {
    #[command(subcommand)]
    pub command: DbAuditSubcommand,
}

#[derive(Debug, Subcommand)]
pub enum DbAuditSubcommand {
    /// Append one ADR 023 audit record transactionally.
    Append(DbAuditAppendArgs),
}

#[derive(Debug, Args)]
pub struct DbAuditAppendArgs {
    #[arg(long)]
    pub session_id: String,
    #[arg(long)]
    pub audit_id: Option<String>,
    #[arg(long)]
    pub timestamp: String,
    #[arg(long)]
    pub source_agent_id: Option<String>,
    #[arg(long)]
    pub target_agent_id: Option<String>,
    #[arg(long)]
    pub source_address: String,
    #[arg(long)]
    pub target_address: String,
    #[arg(long)]
    pub transport: String,
    #[arg(long)]
    pub transport_thread_id: Option<String>,
    #[arg(long)]
    pub workspace_id: String,
    #[arg(long)]
    pub mid: String,
    #[arg(long = "type")]
    pub record_type: String,
    #[arg(long)]
    pub mode: Option<String>,
    #[arg(long)]
    pub r#ref: Option<String>,
    #[arg(long)]
    pub re: Option<String>,
    #[arg(long, value_parser = ["agent", "operator", "helper-tool", "unknown"])]
    pub command_origin: String,
    #[arg(long)]
    pub payload: Option<String>,
    #[arg(long)]
    pub payload_file: Option<PathBuf>,
    #[arg(long, default_value = "hash-only")]
    pub payload_redaction_policy: String,
    #[arg(long, default_value_t = 12)]
    pub excerpt_chars: usize,
    #[arg(long)]
    pub delivery_status: String,
    #[arg(long)]
    pub observed_by: String,
    #[arg(long, value_parser = ["transport", "agent", "operator", "helper-tool"])]
    pub verified_by: String,
}

#[derive(Debug, Args)]
pub struct DbImportCommand {
    #[command(subcommand)]
    pub command: DbImportSubcommand,
}

#[derive(Debug, Subcommand)]
pub enum DbImportSubcommand {
    /// Import v0.1 outputs/sessions artifacts.
    Outputs(DbImportOutputsArgs),
}

#[derive(Debug, Args)]
pub struct DbExportCommand {
    #[command(subcommand)]
    pub command: DbExportSubcommand,
}

#[derive(Debug, Subcommand)]
pub enum DbExportSubcommand {
    /// Export one session to outputs/sessions artifacts.
    Outputs(DbExportOutputsArgs),
}

#[derive(Debug, Args)]
#[command(
    after_help = "v0.2 exports status.md and audit.md only; summary.md is not exported because the DB schema does not store summary body content."
)]
pub struct DbExportOutputsArgs {
    #[arg(
        long,
        default_value = "outputs",
        help = "runtime outputs root; writes <root>/sessions/<session-id>"
    )]
    pub root: PathBuf,
    #[arg(long)]
    pub session_id: String,
}

#[derive(Debug, Args)]
#[command(
    after_help = "Legacy DB recovery: if an upgraded database warns about non-canonical \
timestamps, rebuild it from artifacts with: rm .zynk/zynk.db && zynk db init && \
zynk db import outputs --root outputs"
)]
pub struct DbImportOutputsArgs {
    #[arg(
        long,
        default_value = "outputs",
        help = "runtime outputs root; reads <root>/sessions/*"
    )]
    pub root: PathBuf,
    #[arg(long)]
    pub session_id: Option<String>,
    #[arg(long)]
    pub timestamp: Option<String>,
}

pub fn run(args: DbArgs) -> CliResult<()> {
    match args.command {
        DbCommand::Init => {
            initialize(&args.db)?;
            println!("{}", display_path(&args.db)?.display());
            Ok(())
        }
        DbCommand::Audit(command) => run_audit_command(&args.db, *command),
        DbCommand::Import(command) => run_import_command(&args.db, *command),
        DbCommand::Export(command) => run_export_command(&args.db, *command),
        DbCommand::Serve(serve_args) => crate::db_dashboard::serve(&args.db, serve_args),
    }
}

fn run_audit_command(path: &Path, command: DbAuditCommand) -> CliResult<()> {
    match command.command {
        DbAuditSubcommand::Append(args) => {
            let audit_id = append_audit_record(path, &args)?;
            println!("{audit_id}");
            Ok(())
        }
    }
}

fn run_import_command(path: &Path, command: DbImportCommand) -> CliResult<()> {
    match command.command {
        DbImportSubcommand::Outputs(args) => {
            let summary = import_outputs(path, &args)?;
            println!(
                "sessions imported: {}; warnings: {}",
                summary.sessions_seen, summary.warning_count
            );
            Ok(())
        }
    }
}

fn run_export_command(path: &Path, command: DbExportCommand) -> CliResult<()> {
    match command.command {
        DbExportSubcommand::Outputs(args) => {
            let summary = export_outputs(path, &args)?;
            println!(
                "session exported: {}; written: {}; unchanged: {}",
                args.session_id, summary.written, summary.unchanged
            );
            Ok(())
        }
    }
}

fn display_path(path: &Path) -> CliResult<PathBuf> {
    if path.is_absolute() {
        return Ok(path.to_path_buf());
    }
    std::env::current_dir()
        .map(|cwd| cwd.join(path))
        .map_err(|error| CliError::failure(format!("failed to read current directory: {error}")))
}

fn initialize(path: &Path) -> CliResult<()> {
    // ADR 028 C1: db init at a `.zynk` default path also self-protects.
    ensure_zynk_gitignore(path)?;
    open_database(path).map(|_| ())
}

pub(crate) fn open_database(path: &Path) -> CliResult<Connection> {
    if let Some(parent) = path
        .parent()
        .filter(|parent| !parent.as_os_str().is_empty())
    {
        fs::create_dir_all(parent).map_err(|error| {
            CliError::failure(format!("failed to create {}: {error}", parent.display()))
        })?;
    }

    let mut connection = Connection::open(path).map_err(|error| {
        CliError::failure(format!("failed to open {}: {error}", path.display()))
    })?;
    configure_connection(&connection)?;
    migrate(&mut connection)?;
    Ok(connection)
}

fn configure_connection(connection: &Connection) -> CliResult<()> {
    configure_read_connection(connection)?;
    connection
        .pragma_update(None, "journal_mode", "WAL")
        .map_err(|error| CliError::failure(format!("failed to enable SQLite WAL mode: {error}")))?;
    Ok(())
}

pub(crate) fn open_read_database(path: &Path) -> CliResult<Connection> {
    let connection =
        Connection::open_with_flags(path, OpenFlags::SQLITE_OPEN_READ_ONLY).map_err(|error| {
            CliError::failure(format!("failed to open {}: {error}", path.display()))
        })?;
    configure_read_connection(&connection)?;
    Ok(connection)
}

fn configure_read_connection(connection: &Connection) -> CliResult<()> {
    connection
        .busy_timeout(Duration::from_millis(BUSY_TIMEOUT_MS))
        .map_err(|error| {
            CliError::failure(format!("failed to set SQLite busy timeout: {error}"))
        })?;
    connection
        .pragma_update(None, "foreign_keys", "ON")
        .map_err(|error| {
            CliError::failure(format!("failed to enable SQLite foreign keys: {error}"))
        })?;
    Ok(())
}

fn migrate(connection: &mut Connection) -> CliResult<()> {
    let version: i64 = connection
        .pragma_query_value(None, "user_version", |row| row.get(0))
        .map_err(|error| {
            CliError::failure(format!("failed to read SQLite schema version: {error}"))
        })?;
    if version > CURRENT_SCHEMA_VERSION {
        return Err(CliError::failure(format!(
            "database schema version {version} is newer than this zynk binary supports ({CURRENT_SCHEMA_VERSION}); upgrade zynk"
        )));
    }
    // T9: nothing to apply at the current version; avoid opening an empty
    // migration transaction on every DB open.
    if version == CURRENT_SCHEMA_VERSION {
        return Ok(());
    }
    let transaction = connection
        .transaction()
        .map_err(|error| CliError::failure(format!("failed to start SQLite migration: {error}")))?;
    create_schema_migrations(&transaction)?;
    if version < 1 {
        apply_v1(&transaction)?;
        set_user_version(&transaction, 1)?;
    }
    if version < 2 {
        apply_v2(&transaction)?;
        set_user_version(&transaction, 2)?;
    }
    if version < 3 {
        apply_v3(&transaction)?;
        set_user_version(&transaction, 3)?;
    }
    if version < 4 {
        apply_v4(&transaction)?;
        set_user_version(&transaction, 4)?;
    }
    if version < 5 {
        apply_v5(&transaction)?;
        set_user_version(&transaction, 5)?;
    }
    if version < 6 {
        apply_v6(&transaction)?;
        set_user_version(&transaction, 6)?;
    }
    if version < 7 {
        apply_v7(&transaction)?;
        set_user_version(&transaction, 7)?;
    }
    if version < 8 {
        apply_v8(&transaction)?;
        set_user_version(&transaction, 8)?;
    }
    if version < 9 {
        apply_v9(&transaction)?;
        set_user_version(&transaction, 9)?;
    }
    if version < 10 {
        apply_v10(&transaction)?;
        set_user_version(&transaction, 10)?;
    }
    transaction.commit().map_err(|error| {
        CliError::failure(format!("failed to commit SQLite migration: {error}"))
    })?;
    // ADR 026 D1/C3: after upgrading a legacy DB, the timestamp triggers only
    // constrain future writes. Pre-existing non-canonical rows remain and would
    // still sort incorrectly, so emit a visible one-time warning with the
    // recovery recipe rather than relying on --help text alone.
    if version < 4 {
        warn_if_noncanonical_timestamps(connection)?;
    }
    Ok(())
}

fn warn_if_noncanonical_timestamps(connection: &Connection) -> CliResult<()> {
    let count = noncanonical_timestamp_count(connection)?;
    if count > 0 {
        eprintln!(
            "warning: {count} pre-existing row(s) carry non-canonical timestamps and will sort \
incorrectly; this upgrade does not rewrite them. Recover with: \
rm .zynk/zynk.db && zynk db init && zynk db import outputs --root outputs"
        );
    }
    Ok(())
}

/// Count rows in sort-critical columns whose timestamp is not canonical UTC-Z.
fn noncanonical_timestamp_count(connection: &Connection) -> CliResult<i64> {
    let glob = CANONICAL_TS_GLOB;
    let sql = format!(
        "SELECT
            (SELECT COUNT(*) FROM audit_records WHERE timestamp NOT GLOB '{glob}')
          + (SELECT COUNT(*) FROM status_events WHERE timestamp NOT GLOB '{glob}')
          + (SELECT COUNT(*) FROM messages WHERE timestamp NOT GLOB '{glob}')
          + (SELECT COUNT(*) FROM sessions
                WHERE created_at NOT GLOB '{glob}'
                   OR updated_at NOT GLOB '{glob}'
                   OR (completed_at IS NOT NULL AND completed_at NOT GLOB '{glob}'))"
    );
    connection
        .query_row(&sql, [], |row| row.get(0))
        .map_err(|error| CliError::failure(format!("failed to scan timestamps: {error}")))
}

fn set_user_version(connection: &Connection, version: i64) -> CliResult<()> {
    connection
        .pragma_update(None, "user_version", version)
        .map_err(|error| {
            CliError::failure(format!("failed to set SQLite schema version: {error}"))
        })?;
    Ok(())
}

fn create_schema_migrations(connection: &Connection) -> CliResult<()> {
    connection
        .execute_batch(
            "CREATE TABLE IF NOT EXISTS schema_migrations (
                version INTEGER PRIMARY KEY,
                name TEXT NOT NULL,
                applied_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now'))
            );",
        )
        .map_err(|error| {
            CliError::failure(format!("failed to create schema_migrations: {error}"))
        })?;
    Ok(())
}

fn apply_v1(connection: &Connection) -> CliResult<()> {
    // T4: no inner idempotency guard — migrate() only calls this when
    // user_version < 1, the single source of truth for "run v1".
    connection
        .execute_batch(
            "CREATE TABLE projects (
                project_id TEXT PRIMARY KEY,
                name TEXT NOT NULL,
                root_path TEXT NOT NULL,
                created_at TEXT NOT NULL,
                updated_at TEXT NOT NULL
            );
            CREATE TABLE agents (
                agent_id TEXT PRIMARY KEY,
                display_name TEXT NOT NULL,
                agent_kind TEXT NOT NULL,
                current_transport TEXT,
                current_address TEXT,
                -- D4: nullable by design. An agent with no active session
                -- legitimately has no current status; session_agents.agent_status
                -- (below) is NOT NULL because an agent in a session always has one.
                current_agent_status TEXT CHECK (
                    current_agent_status IS NULL
                    OR current_agent_status IN ('idle', 'working', 'blocked', 'done', 'unknown')
                ),
                created_at TEXT NOT NULL,
                updated_at TEXT NOT NULL
            );
            CREATE TABLE sessions (
                session_id TEXT PRIMARY KEY,
                project_id TEXT NOT NULL REFERENCES projects(project_id),
                title TEXT NOT NULL,
                phase TEXT NOT NULL,
                mode TEXT NOT NULL,
                workflow_status TEXT NOT NULL CHECK (
                    workflow_status IN ('idle', 'working', 'blocked', 'waiting-for-operator', 'done')
                ),
                lead_agent_id TEXT REFERENCES agents(agent_id),
                artifact_ref TEXT,
                created_at TEXT NOT NULL,
                updated_at TEXT NOT NULL,
                completed_at TEXT
            );
            CREATE TABLE agent_addresses (
                agent_id TEXT NOT NULL REFERENCES agents(agent_id),
                transport TEXT NOT NULL,
                workspace_id TEXT,
                address TEXT NOT NULL,
                first_seen_at TEXT NOT NULL,
                last_seen_at TEXT NOT NULL,
                PRIMARY KEY (agent_id, transport, address, first_seen_at)
            );
            CREATE TABLE session_agents (
                session_id TEXT NOT NULL REFERENCES sessions(session_id),
                agent_id TEXT NOT NULL REFERENCES agents(agent_id),
                role TEXT NOT NULL,
                -- D4: NOT NULL — an agent within a session always has a status
                -- (the Herdr agent_status domain, distinct from sessions.workflow_status).
                agent_status TEXT NOT NULL CHECK (
                    agent_status IN ('idle', 'working', 'blocked', 'done', 'unknown')
                ),
                last_seen_at TEXT NOT NULL,
                PRIMARY KEY (session_id, agent_id)
            );
            CREATE TABLE audit_records (
                audit_id TEXT PRIMARY KEY,
                previous_audit_id TEXT REFERENCES audit_records(audit_id),
                session_id TEXT NOT NULL REFERENCES sessions(session_id),
                source_agent_id TEXT,
                target_agent_id TEXT,
                source_address TEXT NOT NULL,
                target_address TEXT NOT NULL,
                transport TEXT NOT NULL,
                workspace_id TEXT NOT NULL,
                mid TEXT NOT NULL,
                record_type TEXT NOT NULL,
                command_origin TEXT NOT NULL CHECK (
                    command_origin IN ('agent', 'operator', 'helper-tool', 'unknown')
                ),
                mode TEXT,
                ref TEXT,
                re TEXT,
                payload_hash TEXT NOT NULL,
                payload_redaction_policy TEXT NOT NULL CHECK (
                    payload_redaction_policy IN ('hash-only', 'excerpt', 'full')
                ),
                content_size INTEGER NOT NULL,
                delivery_status TEXT NOT NULL CHECK (
                    delivery_status IN ('drafted', 'sent', 'observed', 'failed', 'unknown')
                ),
                observed_by TEXT NOT NULL,
                verified_by TEXT NOT NULL CHECK (
                    verified_by IN ('transport', 'agent', 'operator', 'helper-tool')
                ),
                timestamp TEXT NOT NULL
            );
            CREATE TABLE messages (
                message_id TEXT PRIMARY KEY,
                session_id TEXT NOT NULL REFERENCES sessions(session_id),
                mid TEXT NOT NULL,
                source_agent_id TEXT REFERENCES agents(agent_id),
                target_agent_id TEXT REFERENCES agents(agent_id),
                message_type TEXT NOT NULL,
                mode TEXT,
                ref TEXT,
                transport TEXT NOT NULL,
                transport_thread_id TEXT,
                payload_redaction_policy TEXT NOT NULL CHECK (
                    payload_redaction_policy IN ('hash-only', 'excerpt', 'full')
                ),
                payload_excerpt TEXT,
                payload_hash TEXT NOT NULL,
                latest_delivery_status TEXT NOT NULL CHECK (
                    latest_delivery_status IN ('drafted', 'sent', 'observed', 'failed', 'unknown')
                ),
                latest_verified_by TEXT NOT NULL CHECK (
                    latest_verified_by IN ('transport', 'agent', 'operator', 'helper-tool')
                ),
                latest_audit_id TEXT REFERENCES audit_records(audit_id),
                timestamp TEXT NOT NULL,
                UNIQUE (session_id, mid)
            );
            CREATE TABLE status_events (
                status_event_id INTEGER PRIMARY KEY,
                session_id TEXT NOT NULL REFERENCES sessions(session_id),
                timestamp TEXT NOT NULL,
                phase TEXT NOT NULL,
                mode TEXT NOT NULL,
                workflow_status TEXT NOT NULL CHECK (
                    workflow_status IN ('idle', 'working', 'blocked', 'waiting-for-operator', 'done')
                ),
                completed_since_last_update TEXT NOT NULL,
                in_progress TEXT NOT NULL,
                next_action TEXT NOT NULL,
                blockers TEXT NOT NULL,
                asks_for_zevs TEXT NOT NULL,
                risk_or_residual_uncertainty TEXT NOT NULL,
                expected_wait TEXT NOT NULL
            );
            CREATE TABLE artifacts (
                artifact_id INTEGER PRIMARY KEY,
                session_id TEXT NOT NULL REFERENCES sessions(session_id),
                kind TEXT NOT NULL,
                path TEXT NOT NULL,
                title TEXT,
                content_hash TEXT,
                updated_at TEXT NOT NULL,
                UNIQUE (session_id, path)
            );
            CREATE TABLE imports (
                import_id INTEGER PRIMARY KEY,
                source_kind TEXT NOT NULL CHECK (source_kind IN ('outputs', 'agent-loop')),
                source_path TEXT NOT NULL,
                source_hash TEXT NOT NULL,
                imported_at TEXT NOT NULL,
                result TEXT NOT NULL,
                warning_summary TEXT NOT NULL
            );
            INSERT OR IGNORE INTO schema_migrations (version, name) VALUES (1, 'initial-live-state');",
        )
        .map_err(|error| {
            CliError::failure(format!("failed to apply SQLite migration 1: {error}"))
        })?;
    Ok(())
}

fn apply_v2(connection: &Connection) -> CliResult<()> {
    if !table_has_column(connection, "audit_records", "command_origin")? {
        connection
            .execute_batch(
                "ALTER TABLE audit_records
                    ADD COLUMN command_origin TEXT NOT NULL DEFAULT 'unknown' CHECK (
                        command_origin IN ('agent', 'operator', 'helper-tool', 'unknown')
                    );",
            )
            .map_err(|error| {
                CliError::failure(format!(
                    "failed to add audit_records.command_origin: {error}"
                ))
            })?;
    }

    connection
        .execute_batch(
            "CREATE UNIQUE INDEX IF NOT EXISTS audit_records_one_child_per_previous
                ON audit_records(session_id, previous_audit_id)
                WHERE previous_audit_id IS NOT NULL;
            CREATE TRIGGER IF NOT EXISTS audit_records_no_sent_agent_insert
                BEFORE INSERT ON audit_records
                WHEN NEW.delivery_status = 'sent' AND NEW.verified_by = 'agent'
            BEGIN
                SELECT RAISE(ABORT, 'delivery_status=sent requires transport, helper-tool, or operator verification');
            END;
            CREATE TRIGGER IF NOT EXISTS audit_records_no_update
                BEFORE UPDATE ON audit_records
            BEGIN
                SELECT RAISE(ABORT, 'audit_records are append-only');
            END;
            CREATE TRIGGER IF NOT EXISTS audit_records_no_delete
                BEFORE DELETE ON audit_records
            BEGIN
                SELECT RAISE(ABORT, 'audit_records are append-only');
            END;
            CREATE TRIGGER IF NOT EXISTS messages_no_sent_agent_insert
                BEFORE INSERT ON messages
                WHEN NEW.latest_delivery_status = 'sent' AND NEW.latest_verified_by = 'agent'
            BEGIN
                SELECT RAISE(ABORT, 'delivery_status=sent requires transport, helper-tool, or operator verification');
            END;
            CREATE TRIGGER IF NOT EXISTS messages_no_sent_agent_update
                BEFORE UPDATE ON messages
                WHEN NEW.latest_delivery_status = 'sent' AND NEW.latest_verified_by = 'agent'
            BEGIN
                SELECT RAISE(ABORT, 'delivery_status=sent requires transport, helper-tool, or operator verification');
            END;
            INSERT OR IGNORE INTO schema_migrations (version, name) VALUES (2, 'audit-chain-constraints');",
        )
        .map_err(|error| {
            CliError::failure(format!("failed to apply SQLite migration 2: {error}"))
        })?;
    Ok(())
}

fn apply_v3(connection: &Connection) -> CliResult<()> {
    if !table_has_column(connection, "status_events", "event_text")? {
        connection
            .execute_batch(
                "ALTER TABLE status_events
                    ADD COLUMN event_text TEXT NOT NULL DEFAULT '';",
            )
            .map_err(|error| {
                CliError::failure(format!("failed to add status_events.event_text: {error}"))
            })?;
    }
    connection
        .execute(
            "INSERT OR IGNORE INTO schema_migrations (version, name)
             VALUES (3, 'status-event-text')",
            [],
        )
        .map_err(|error| {
            CliError::failure(format!("failed to apply SQLite migration 3: {error}"))
        })?;
    Ok(())
}

// ADR 026 v0.2.1 hardening: status_events.content_hash (+ backfill) and
// canonical-timestamp enforcement triggers on sort-critical columns.
fn apply_v4(connection: &Connection) -> CliResult<()> {
    if !table_has_column(connection, "status_events", "content_hash")? {
        connection
            .execute_batch(
                "ALTER TABLE status_events
                    ADD COLUMN content_hash TEXT NOT NULL DEFAULT '';",
            )
            .map_err(|error| {
                CliError::failure(format!("failed to add status_events.content_hash: {error}"))
            })?;
    }
    // C5: backfill existing rows with the same helper the import path uses, so a
    // legacy row's hash equals what a re-import computes (preserves idempotency).
    backfill_status_content_hash(connection)?;

    let glob = CANONICAL_TS_GLOB;
    connection
        .execute_batch(&format!(
            "CREATE TRIGGER IF NOT EXISTS audit_records_ts_canonical_insert
                BEFORE INSERT ON audit_records
                WHEN NEW.timestamp NOT GLOB '{glob}'
             BEGIN SELECT RAISE(ABORT, 'audit_records.timestamp must be RFC3339 UTC seconds (Z)'); END;
             CREATE TRIGGER IF NOT EXISTS status_events_ts_canonical_insert
                BEFORE INSERT ON status_events
                WHEN NEW.timestamp NOT GLOB '{glob}'
             BEGIN SELECT RAISE(ABORT, 'status_events.timestamp must be RFC3339 UTC seconds (Z)'); END;
             CREATE TRIGGER IF NOT EXISTS messages_ts_canonical_insert
                BEFORE INSERT ON messages
                WHEN NEW.timestamp NOT GLOB '{glob}'
             BEGIN SELECT RAISE(ABORT, 'messages.timestamp must be RFC3339 UTC seconds (Z)'); END;
             CREATE TRIGGER IF NOT EXISTS messages_ts_canonical_update
                BEFORE UPDATE ON messages
                WHEN NEW.timestamp NOT GLOB '{glob}'
             BEGIN SELECT RAISE(ABORT, 'messages.timestamp must be RFC3339 UTC seconds (Z)'); END;
             CREATE TRIGGER IF NOT EXISTS sessions_ts_canonical_insert
                BEFORE INSERT ON sessions
                WHEN NEW.created_at NOT GLOB '{glob}'
                  OR NEW.updated_at NOT GLOB '{glob}'
                  OR (NEW.completed_at IS NOT NULL AND NEW.completed_at NOT GLOB '{glob}')
             BEGIN SELECT RAISE(ABORT, 'sessions timestamps must be RFC3339 UTC seconds (Z)'); END;
             CREATE TRIGGER IF NOT EXISTS sessions_ts_canonical_update
                BEFORE UPDATE ON sessions
                WHEN NEW.created_at NOT GLOB '{glob}'
                  OR NEW.updated_at NOT GLOB '{glob}'
                  OR (NEW.completed_at IS NOT NULL AND NEW.completed_at NOT GLOB '{glob}')
             BEGIN SELECT RAISE(ABORT, 'sessions timestamps must be RFC3339 UTC seconds (Z)'); END;"
        ))
        .map_err(|error| {
            CliError::failure(format!("failed to create v4 timestamp triggers: {error}"))
        })?;

    connection
        .execute(
            "INSERT OR IGNORE INTO schema_migrations (version, name)
             VALUES (4, 'timestamp-canonical-and-content-hash')",
            [],
        )
        .map_err(|error| {
            CliError::failure(format!("failed to apply SQLite migration 4: {error}"))
        })?;
    Ok(())
}

// ADR 027: additive nullable audit_records.due + extend the canonical-timestamp
// shape guard to cover a non-null due.
fn apply_v5(connection: &Connection) -> CliResult<()> {
    // ADD COLUMN does not rewrite rows and coexists with the append-only
    // UPDATE/DELETE triggers; existing rows read due=NULL ("no deadline").
    if !table_has_column(connection, "audit_records", "due")? {
        connection
            .execute_batch("ALTER TABLE audit_records ADD COLUMN due TEXT;")
            .map_err(|error| {
                CliError::failure(format!("failed to add audit_records.due: {error}"))
            })?;
    }
    // Extend the v4 canonical-timestamp shape guard to also reject a non-null due
    // that is not canonical UTC-Z. CREATE TRIGGER IF NOT EXISTS would not replace
    // the existing trigger, so drop then recreate. This runs inside the migration
    // transaction, so there is no window where the invariant is unenforced. The
    // GLOB is defense-in-depth only; real RFC3339 validation happens at the CLI /
    // import boundary (ADR 027 C4).
    let glob = CANONICAL_TS_GLOB;
    connection
        .execute_batch(&format!(
            "DROP TRIGGER IF EXISTS audit_records_ts_canonical_insert;
             CREATE TRIGGER audit_records_ts_canonical_insert
                BEFORE INSERT ON audit_records
                WHEN NEW.timestamp NOT GLOB '{glob}'
                  OR (NEW.due IS NOT NULL AND NEW.due NOT GLOB '{glob}')
             BEGIN SELECT RAISE(ABORT, 'audit_records.timestamp and due must be RFC3339 UTC seconds (Z)'); END;"
        ))
        .map_err(|error| {
            CliError::failure(format!("failed to update v5 due trigger: {error}"))
        })?;
    connection
        .execute(
            "INSERT OR IGNORE INTO schema_migrations (version, name)
             VALUES (5, 'audit-due-and-db-canonical-write-path')",
            [],
        )
        .map_err(|error| {
            CliError::failure(format!("failed to apply SQLite migration 5: {error}"))
        })?;
    Ok(())
}

// ADR 033 M1: additive typed work-telemetry store. One row per work event; the
// payload column holds the validated, serialized typed value (serde_norway), not
// an untyped blob. The UNIQUE(session_id, kind, content_hash) backs the
// INSERT OR IGNORE content-dedup in `project_work_event`.
fn apply_v6(connection: &Connection) -> CliResult<()> {
    connection
        .execute_batch(
            "CREATE TABLE work_events (
                work_event_id INTEGER PRIMARY KEY,
                session_id TEXT NOT NULL REFERENCES sessions(session_id),
                actor_agent_id TEXT NOT NULL,
                kind TEXT NOT NULL CHECK (kind IN
                    ('think','tool','diff','plan','artifact','usage','system','gate','conflict')),
                timestamp TEXT NOT NULL,
                payload TEXT NOT NULL,
                content_hash TEXT NOT NULL,
                created_at TEXT NOT NULL,
                UNIQUE (session_id, kind, content_hash)
            );
            CREATE INDEX work_events_session_ts ON work_events (session_id, timestamp);
            INSERT OR IGNORE INTO schema_migrations (version, name) VALUES (6, 'work-events');",
        )
        .map_err(|error| CliError::failure(format!("failed to apply schema v6: {error}")))?;
    Ok(())
}

// ADR 033 M2 (D4): typed operator-decision projection. audit_records holds the
// immutable proof; this table is the typed query/effect surface keyed by audit_id.
fn apply_v7(connection: &Connection) -> CliResult<()> {
    connection
        .execute_batch(
            "CREATE TABLE operator_decisions (
                audit_id TEXT PRIMARY KEY REFERENCES audit_records(audit_id),
                session_id TEXT NOT NULL REFERENCES sessions(session_id),
                decision_type TEXT NOT NULL CHECK (decision_type IN
                    ('gate-decision','conflict-resolve','mode-switch','interrupt','redirect')),
                target_work_event_id INTEGER REFERENCES work_events(work_event_id),
                verdict TEXT,
                resolution TEXT,
                mode_to TEXT,
                target_agent TEXT,
                reason TEXT,
                note TEXT,
                decision_status TEXT NOT NULL DEFAULT 'decided'
                    CHECK (decision_status IN ('decided')),
                notification_status TEXT NOT NULL DEFAULT 'not-requested'
                    CHECK (notification_status IN ('not-requested','sent','failed')),
                notification_audit_id TEXT REFERENCES audit_records(audit_id),
                notification_mid TEXT,
                notification_error TEXT,
                created_at TEXT NOT NULL
            );
            CREATE INDEX operator_decisions_session ON operator_decisions (session_id, created_at);
            CREATE INDEX operator_decisions_target ON operator_decisions (target_work_event_id);
            INSERT OR IGNORE INTO schema_migrations (version, name) VALUES (7, 'operator-decisions');",
        )
        .map_err(|error| CliError::failure(format!("failed to apply schema v7: {error}")))?;
    Ok(())
}

// ADR 034 M3: the local encrypted custody vault. One row per RETAINED record;
// ciphertext+nonce keyed by audit_id; the KEY lives outside the DB (the 0600 key
// file). cipher_id/key_version give crypto agility (an unsupported value fails loud
// on reveal).
fn apply_v8(connection: &Connection) -> CliResult<()> {
    connection
        .execute_batch(
            "CREATE TABLE custody_vault (
                audit_id TEXT PRIMARY KEY REFERENCES audit_records(audit_id),
                ciphertext BLOB NOT NULL,
                nonce BLOB NOT NULL,
                cipher_id TEXT NOT NULL,
                key_version INTEGER NOT NULL,
                created_at TEXT NOT NULL
            );
            INSERT OR IGNORE INTO schema_migrations (version, name) VALUES (8, 'custody-vault');",
        )
        .map_err(|error| CliError::failure(format!("failed to apply schema v8: {error}")))?;
    Ok(())
}

// ADR 024 §1a / ADR 034 D8 (v1 M3a R3 P4): the AUTHORITATIVE DB-layer guard that a
// non-transport operator proof (any decision record_type, plus `reveal`) must never
// be `delivery_status=sent` — it is an observed/operator event, not a delivered
// message. Mirrors the existing `audit_records_no_sent_agent_insert` (v2) trigger and
// the CLI pre-check in `append_audit_record`/`validate_audit_args`, but as its own v9
// migration so existing v8 DBs gain it on upgrade and covers EVERY producer that
// bypasses the CLI (`db audit append`, `db import`, any direct insert). The hardcoded
// 6-type list = `crate::decision::DECISION_RECORD_TYPES` (the 5 decision types) +
// `reveal`; it matches `is_non_transport_proof_record_type`.
fn apply_v9(connection: &Connection) -> CliResult<()> {
    connection
        .execute_batch(
            "CREATE TRIGGER IF NOT EXISTS audit_records_no_sent_nontransport_proof_insert
                BEFORE INSERT ON audit_records
                WHEN NEW.delivery_status = 'sent'
                 AND NEW.record_type IN ('gate-decision','conflict-resolve','mode-switch','interrupt','redirect','reveal')
            BEGIN
                SELECT RAISE(ABORT, 'a non-transport operator proof (decision/reveal) must not be delivery_status=sent (ADR 024 / ADR 034 D8)');
            END;
            INSERT OR IGNORE INTO schema_migrations (version, name) VALUES (9, 'reject-sent-nontransport-proof');",
        )
        .map_err(|error| CliError::failure(format!("failed to apply schema v9: {error}")))?;
    Ok(())
}

// ADR 036 Track B: the participant_overlay projection table + its integrity triggers
// (the DB layer is the choke point — every producer hits these). One audit-proof-keyed
// row per assignment; the proof IS the provenance. The machine reasons ONLY over the
// CHECK-constrained `trait_id` vocabulary, never over the free-form role. Forward-only,
// additive: existing v9 DBs gain an empty table. apply_v9 stays immutable; the v10
// sent-guard is its OWN new trigger (adds `participant-overlay` to the non-transport
// proof family — never `sent`).
fn apply_v10(connection: &Connection) -> CliResult<()> {
    let glob = CANONICAL_TS_GLOB;
    connection
        .execute_batch(&format!(
            "CREATE TABLE participant_overlay (
                audit_id TEXT PRIMARY KEY REFERENCES audit_records(audit_id),
                session_id TEXT NOT NULL REFERENCES sessions(session_id),
                subject_actor_id TEXT NOT NULL,
                overlay_kind TEXT NOT NULL CHECK (overlay_kind IN ('actor-kind','role','trait')),
                actor_kind TEXT CHECK (actor_kind IS NULL OR actor_kind IN ('human','agent','external')),
                role_id TEXT, role_label TEXT,
                trait_id TEXT CHECK (trait_id IS NULL OR trait_id IN
                    ('independent','can_edit_source','non_iterating','can_verify_gate','can_merge_approve')),
                trait_value INTEGER CHECK (trait_value IS NULL OR trait_value IN (0,1)),
                asserter_actor_id TEXT NOT NULL,
                asserter_kind TEXT NOT NULL CHECK (asserter_kind IN ('operator','profile')),
                supersedes_audit_id TEXT REFERENCES audit_records(audit_id),
                superseded_by_audit_id TEXT REFERENCES audit_records(audit_id),
                created_at TEXT NOT NULL,
                -- trackbrc1 P2: EXACT per-kind row shape — every OTHER kind's columns NULL.
                -- The pre-fix CHECK nulled only a SUBSET (e.g. it left role_label/trait_value
                -- free on an actor-kind row), letting a cross-kind smuggle insert. Each arm now
                -- pins its own non-NULL columns AND nulls all four cross-kind columns.
                CHECK (
                    (overlay_kind='actor-kind' AND actor_kind IS NOT NULL
                        AND role_id IS NULL AND role_label IS NULL AND trait_id IS NULL AND trait_value IS NULL)
                    OR (overlay_kind='role'    AND role_id IS NOT NULL AND role_label IS NOT NULL
                        AND actor_kind IS NULL AND trait_id IS NULL AND trait_value IS NULL)
                    OR (overlay_kind='trait'   AND trait_id IS NOT NULL AND trait_value IS NOT NULL
                        AND actor_kind IS NULL AND role_id IS NULL AND role_label IS NULL)
                )
            );
            CREATE UNIQUE INDEX participant_overlay_current_kindrole ON participant_overlay (session_id, subject_actor_id, overlay_kind)
                WHERE superseded_by_audit_id IS NULL AND overlay_kind IN ('actor-kind','role');
            CREATE UNIQUE INDEX participant_overlay_current_trait ON participant_overlay (session_id, subject_actor_id, trait_id)
                WHERE superseded_by_audit_id IS NULL AND overlay_kind='trait';
            CREATE INDEX participant_overlay_subject ON participant_overlay (session_id, subject_actor_id, overlay_kind);

            -- D3.1: provenance binding for ALL overlay kinds (C1) — a row cannot claim a
            -- different session/asserter/time than its proof (audit_records). NULL-safe
            -- `IS NOT`: audit_records.source_agent_id is nullable, so a `<>` against a NULL
            -- proof source would yield NULL (no abort) and let the row bypass the binding;
            -- the overlay columns are NOT NULL, so `IS NOT` ABORTs both a mismatch AND a
            -- NULL proof value.
            CREATE TRIGGER participant_overlay_provenance_binding_insert
                BEFORE INSERT ON participant_overlay
                WHEN NEW.session_id IS NOT (SELECT a.session_id FROM audit_records a WHERE a.audit_id = NEW.audit_id)
                  OR NEW.asserter_actor_id IS NOT (SELECT a.source_agent_id FROM audit_records a WHERE a.audit_id = NEW.audit_id)
                  OR NEW.created_at IS NOT (SELECT a.timestamp FROM audit_records a WHERE a.audit_id = NEW.audit_id)
            BEGIN
                SELECT RAISE(ABORT, 'participant_overlay row session_id/asserter_actor_id/created_at must match its proof (ADR 036 D3.1 provenance binding)');
            END;

            -- D3.2: no self-grant of a trait (asserter == subject). actor-kind/role are
            -- self-describing, not integrity claims — exempt.
            CREATE TRIGGER participant_overlay_no_self_grant_trait_insert
                BEFORE INSERT ON participant_overlay
                WHEN NEW.overlay_kind = 'trait' AND NEW.asserter_actor_id = NEW.subject_actor_id
            BEGIN
                SELECT RAISE(ABORT, 'an integrity trait must not be self-granted (asserter == subject) (ADR 036 D3.2)');
            END;

            -- D3.3: operator-grade proof for a trait (C3) — verified_by='operator' AND
            -- command_origin='operator' AND transport='none'. Subsumes the weaker
            -- verified_by!=agent: helper-tool/transport are not authority to grant a trait.
            CREATE TRIGGER participant_overlay_operator_grade_trait_insert
                BEFORE INSERT ON participant_overlay
                WHEN NEW.overlay_kind = 'trait'
                 AND NOT EXISTS (
                    SELECT 1 FROM audit_records a
                    WHERE a.audit_id = NEW.audit_id
                      AND a.verified_by = 'operator'
                      AND a.command_origin = 'operator'
                      AND a.transport = 'none'
                 )
            BEGIN
                SELECT RAISE(ABORT, 'an integrity trait requires an operator-grade proof (verified_by=operator, command_origin=operator, transport=none) (ADR 036 D3.3)');
            END;

            -- D3.4: canonical timestamp on created_at (the v4 GLOB pattern) — deterministic
            -- ORDER BY without trusting the producer.
            CREATE TRIGGER participant_overlay_ts_canonical_insert
                BEFORE INSERT ON participant_overlay
                WHEN NEW.created_at NOT GLOB '{glob}'
            BEGIN
                SELECT RAISE(ABORT, 'participant_overlay.created_at must be RFC3339 UTC seconds (Z) (ADR 036 D3.4)');
            END;

            -- D3.5: v10 sent-guard — a `participant-overlay` proof is non-transport operator
            -- proof and must never be delivery_status=sent (the ADR 024 family). A NEW v10
            -- trigger (apply_v9 stays immutable).
            CREATE TRIGGER audit_records_no_sent_participant_overlay_insert
                BEFORE INSERT ON audit_records
                WHEN NEW.delivery_status = 'sent' AND NEW.record_type = 'participant-overlay'
            BEGIN
                SELECT RAISE(ABORT, 'a participant-overlay proof must not be delivery_status=sent (ADR 024 family / ADR 036 D3.5)');
            END;

            INSERT OR IGNORE INTO schema_migrations (version, name) VALUES (10, 'participant-overlay');"
        ))
        .map_err(|error| CliError::failure(format!("failed to apply schema v10: {error}")))?;
    Ok(())
}

/// A retained `custody_vault` row (ADR 034 M3): the encrypted payload + its nonce and
/// the crypto identity. The key lives OUTSIDE the DB (the 0600 key file); reveal
/// (M3a T5) decrypts `ciphertext` under that key and re-verifies the plaintext hash.
/// `created_at` is read on demand from the row, not carried here.
#[derive(Debug)]
pub(crate) struct CustodyRow {
    pub ciphertext: Vec<u8>,
    pub nonce: Vec<u8>,
    pub cipher_id: String,
    pub key_version: i64,
}

/// Open the projection DB (auto-create + migrate, like `project_audit`) and insert
/// the retained ciphertext into `custody_vault`. This is the `pub(crate)` entry the
/// `--retain-custody` audited write (M3a T4) calls — it keeps `open_projection_database`
/// private while reusing the same opener every projection uses. ANY error propagates
/// so the caller can fail LOUD (ADR 034 D7: a requested retention never silently
/// degrades to no-retain). Never logs key material or plaintext.
pub(crate) fn project_custody_vault(
    db_path: &Path,
    audit_id: &str,
    ciphertext: &[u8],
    nonce: &[u8],
    cipher_id: &str,
    key_version: i64,
    created_at: &str,
) -> CliResult<()> {
    let connection = open_projection_database(db_path)?;
    insert_custody_vault(
        &connection,
        audit_id,
        ciphertext,
        nonce,
        cipher_id,
        key_version,
        created_at,
    )
}

/// Insert a retained ciphertext into `custody_vault`, keyed by `audit_id` (the PK,
/// which FKs `audit_records`). `INSERT OR IGNORE` makes it idempotent: a re-run for
/// an already-retained record is a silent no-op (never an error, never a duplicate),
/// so a retried `--retain-custody` write can't conflict. BLOBs bind as `&[u8]`.
/// Consumed by the `--retain-custody` audited write in M3a T4.
pub(crate) fn insert_custody_vault(
    conn: &Connection,
    audit_id: &str,
    ciphertext: &[u8],
    nonce: &[u8],
    cipher_id: &str,
    key_version: i64,
    created_at: &str,
) -> CliResult<()> {
    conn.execute(
        "INSERT OR IGNORE INTO custody_vault
            (audit_id, ciphertext, nonce, cipher_id, key_version, created_at)
         VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
        params![
            audit_id,
            ciphertext,
            nonce,
            cipher_id,
            key_version,
            created_at
        ],
    )
    .map_err(|error| CliError::failure(format!("failed to insert custody_vault row: {error}")))?;
    Ok(())
}

/// Read a retained `custody_vault` row by `audit_id`. `None` when the record was
/// never retained (not revealable). BLOB columns read back as `Vec<u8>`. Consumed by
/// `zynk reveal` (M3a T5) to fetch the ciphertext+nonce+crypto identity.
pub(crate) fn read_custody_vault(
    conn: &Connection,
    audit_id: &str,
) -> CliResult<Option<CustodyRow>> {
    conn.query_row(
        "SELECT ciphertext, nonce, cipher_id, key_version
         FROM custody_vault WHERE audit_id = ?1",
        params![audit_id],
        |row| {
            Ok(CustodyRow {
                ciphertext: row.get(0)?,
                nonce: row.get(1)?,
                cipher_id: row.get(2)?,
                key_version: row.get(3)?,
            })
        },
    )
    .optional()
    .map_err(|error| CliError::failure(format!("failed to read custody_vault row: {error}")))
}

/// Read BOTH the `session_id` and `payload_hash` of an audit record by `audit_id`,
/// `None` when no such record. Consumed by `zynk reveal` (M3a T5): the reveal proof
/// lands in the SAME session as the revealed record (chained/visible there), and the
/// `payload_hash` is the disclosure contract the recomputed plaintext hash is checked
/// against. One read so the two values can never diverge.
pub(crate) fn read_reveal_target(
    conn: &Connection,
    audit_id: &str,
) -> CliResult<Option<(String, String)>> {
    conn.query_row(
        "SELECT session_id, payload_hash FROM audit_records WHERE audit_id = ?1",
        params![audit_id],
        |row| Ok((row.get(0)?, row.get(1)?)),
    )
    .optional()
    .map_err(|error| CliError::failure(format!("failed to read audit record for reveal: {error}")))
}

fn backfill_status_content_hash(connection: &Connection) -> CliResult<()> {
    let mut select = connection
        .prepare(
            "SELECT status_event_id, phase, mode, workflow_status,
                    completed_since_last_update, in_progress, next_action, blockers,
                    asks_for_zevs, risk_or_residual_uncertainty, expected_wait, event_text
             FROM status_events
             WHERE content_hash = ''",
        )
        .map_err(|error| {
            CliError::failure(format!(
                "failed to read status_events for backfill: {error}"
            ))
        })?;
    let rows = select
        .query_map([], |row| {
            let id: i64 = row.get(0)?;
            let fields = (1..=11)
                .map(|i| row.get::<_, String>(i))
                .collect::<Result<Vec<_>, _>>()?;
            Ok((id, fields))
        })
        .map_err(|error| {
            CliError::failure(format!(
                "failed to read status_events for backfill: {error}"
            ))
        })?
        .collect::<Result<Vec<_>, _>>()
        .map_err(|error| {
            CliError::failure(format!(
                "failed to read status_events for backfill: {error}"
            ))
        })?;
    for (id, fields) in rows {
        let refs: Vec<&str> = fields.iter().map(String::as_str).collect();
        let hash = status_content_hash(&refs);
        connection
            .execute(
                "UPDATE status_events SET content_hash = ?1 WHERE status_event_id = ?2",
                params![hash, id],
            )
            .map_err(|error| {
                CliError::failure(format!("failed to backfill content_hash: {error}"))
            })?;
    }
    Ok(())
}

/// Canonical content hash for status-event dedup (ADR 026 D3). Order-fixed over
/// the 11 content fields (NOT session_id/timestamp). Used by both the v4
/// backfill and the import dedup so they agree.
fn status_content_hash(fields: &[&str]) -> String {
    let mut hasher = Sha256::new();
    hasher.update(fields.join("\n").as_bytes());
    format!("sha256:{:x}", hasher.finalize())
}

#[derive(Default)]
struct ImportSummary {
    sessions_seen: usize,
    warning_count: usize,
}

#[derive(Debug)]
pub(crate) struct ImportedStatus {
    pub(crate) session_id: String,
    pub(crate) last_update: String,
    pub(crate) lead_agent: String,
    pub(crate) phase: String,
    pub(crate) mode: String,
    pub(crate) artifact_ref: String,
    pub(crate) workflow_status: String,
    pub(crate) completed_since_last_update: String,
    pub(crate) in_progress: String,
    pub(crate) next_action: String,
    pub(crate) blockers: String,
    pub(crate) asks_for_zevs: String,
    pub(crate) risk_or_residual_uncertainty: String,
    pub(crate) expected_wait: String,
    pub(crate) rolling_events: Vec<String>,
}

#[derive(Debug, Clone)]
pub(crate) struct ImportedAuditRecord {
    pub(crate) audit_id: String,
    pub(crate) previous_audit_id: Option<String>,
    pub(crate) timestamp: String,
    pub(crate) source_agent_id: Option<String>,
    pub(crate) source_address: String,
    pub(crate) target_agent_id: Option<String>,
    pub(crate) target_address: String,
    pub(crate) transport: String,
    pub(crate) workspace_id: String,
    pub(crate) session_id: String,
    pub(crate) mid: String,
    pub(crate) record_type: String,
    pub(crate) command_origin: String,
    pub(crate) mode: Option<String>,
    pub(crate) r#ref: Option<String>,
    pub(crate) re: Option<String>,
    pub(crate) payload_hash: String,
    pub(crate) payload_redaction_policy: String,
    pub(crate) content_size: i64,
    pub(crate) delivery_status: String,
    pub(crate) observed_by: String,
    pub(crate) verified_by: String,
    pub(crate) due: Option<String>,
    /// ADR 029 C6: the readable corpus excerpt (None for hash-only), carried into
    /// `messages.payload_excerpt` so the file-first path populates corpus content,
    /// not just the file artifact.
    pub(crate) payload_excerpt: Option<String>,
}

/// v1 M1 R1 P2 (ADR 027 file-as-authority recovery): one parsed `work-event` block
/// from a session's `work.md`, ready to project back into `work_events` via the
/// SAME `project_work_event` the live path uses. The payload is the typed enum
/// (round-tripped through `WorkEventPayload::from_storage`), never a raw blob.
#[derive(Debug, Clone)]
pub(crate) struct ImportedWorkEvent {
    pub(crate) actor: String,
    pub(crate) timestamp: String,
    /// v1 M1 R2 P4: the file-rendered per-session ordinal (`seq=` header), part of the
    /// event identity so two same-second identical events stay distinct rows and a
    /// re-import is a stable-hash no-op.
    pub(crate) seq: usize,
    pub(crate) payload: crate::work_event::WorkEventPayload,
}

enum ImportedAuditInsert {
    Inserted,
    Existing,
    RebasedToRoot { original_error: String },
}

#[derive(Default)]
struct ExportSummary {
    written: usize,
    unchanged: usize,
}

#[derive(Debug, Clone)]
struct ExportedAuditRecord {
    audit_id: String,
    previous_audit_id: Option<String>,
    timestamp: String,
    source_agent: String,
    source_address: String,
    target_agent: String,
    target_address: String,
    transport: String,
    workspace_id: String,
    session_id: String,
    mid: String,
    record_type: String,
    command_origin: String,
    mode: Option<String>,
    r#ref: Option<String>,
    re: Option<String>,
    payload_hash: String,
    payload_redaction_policy: String,
    content_size: i64,
    delivery_status: String,
    observed_by: String,
    verified_by: String,
    due: Option<String>,
}

fn export_outputs(path: &Path, args: &DbExportOutputsArgs) -> CliResult<ExportSummary> {
    let connection = open_read_database(path)?;
    let status = load_export_status(&connection, &args.session_id)?;
    let events = load_export_status_events(&connection, &args.session_id)?;
    let audit_records = load_export_audit_records(&connection, &args.session_id)?;
    let session_dir = args.root.join("sessions").join(&args.session_id);
    let exports = [
        (
            session_dir.join("status.md"),
            render_export_status(&status, &events),
        ),
        (
            session_dir.join("audit.md"),
            render_export_audit(&args.session_id, &audit_records),
        ),
    ];
    let mut summary = ExportSummary::default();
    for (path, content) in exports {
        if write_if_changed(&path, &content)? {
            summary.written += 1;
        } else {
            summary.unchanged += 1;
        }
    }
    Ok(summary)
}

fn load_export_status(connection: &Connection, session_id: &str) -> CliResult<ImportedStatus> {
    connection
        .query_row(
            "SELECT s.session_id,
                    COALESCE(se.timestamp, s.updated_at),
                    COALESCE(s.lead_agent_id, 'unknown'),
                    COALESCE(se.phase, s.phase),
                    -- ADR 033 M2b T3 (C3=b): the EXPORT intentionally stays status-only
                    -- (NO latest-writer across operator decisions, unlike the live/snapshot
                    -- dashboard reads). `status.md` is the agent-authored status artifact;
                    -- folding a decision-derived mode in here would fake the operator's
                    -- mode-switch into the agent status timeline — the exact provenance
                    -- conflation C3=b's rationale rejected. The operator decision is
                    -- exported separately via the audit chain, so the export's mode is by
                    -- design the status-authored mode.
                    COALESCE(se.mode, s.mode),
                    COALESCE(s.artifact_ref, 'unknown'),
                    COALESCE(se.workflow_status, s.workflow_status),
                    COALESCE(se.completed_since_last_update, 'unknown'),
                    COALESCE(se.in_progress, 'unknown'),
                    COALESCE(se.next_action, 'unknown'),
                    COALESCE(se.blockers, 'unknown'),
                    COALESCE(se.asks_for_zevs, 'unknown'),
                    COALESCE(se.risk_or_residual_uncertainty, 'unknown'),
                    COALESCE(se.expected_wait, 'unknown')
             FROM sessions AS s
             LEFT JOIN status_events AS se
               ON se.status_event_id = (
                    SELECT status_event_id
                    FROM status_events
                    WHERE session_id = s.session_id
                    ORDER BY timestamp DESC, status_event_id DESC
                    LIMIT 1
               )
             WHERE s.session_id = ?1",
            [session_id],
            |row| {
                Ok(ImportedStatus {
                    session_id: row.get(0)?,
                    last_update: row.get(1)?,
                    lead_agent: row.get(2)?,
                    phase: row.get(3)?,
                    mode: row.get(4)?,
                    artifact_ref: row.get(5)?,
                    workflow_status: row.get(6)?,
                    completed_since_last_update: row.get(7)?,
                    in_progress: row.get(8)?,
                    next_action: row.get(9)?,
                    blockers: row.get(10)?,
                    asks_for_zevs: row.get(11)?,
                    risk_or_residual_uncertainty: row.get(12)?,
                    expected_wait: row.get(13)?,
                    rolling_events: Vec::new(),
                })
            },
        )
        .optional()
        .map_err(|error| CliError::failure(format!("failed to load session for export: {error}")))?
        .ok_or_else(|| CliError::failure(format!("session not found: {session_id}")))
}

fn load_export_status_events(connection: &Connection, session_id: &str) -> CliResult<Vec<String>> {
    let mut statement = connection
        .prepare(
            "SELECT timestamp, workflow_status, next_action, event_text
             FROM status_events
             WHERE session_id = ?1
             ORDER BY timestamp DESC, status_event_id DESC
             LIMIT 10",
        )
        .map_err(|error| CliError::failure(format!("failed to load status events: {error}")))?;
    let events = statement
        .query_map([session_id], |row| {
            let timestamp: String = row.get(0)?;
            let workflow_status: String = row.get(1)?;
            let next_action: String = row.get(2)?;
            let event_text: String = row.get(3)?;
            let events = if event_text.trim().is_empty() {
                vec![format!(
                    "{timestamp} - status={workflow_status}; next={next_action}"
                )]
            } else {
                event_text
                    .lines()
                    .map(str::trim)
                    .filter(|line| !line.is_empty())
                    .map(str::to_string)
                    .collect()
            };
            Ok(events)
        })
        .map_err(|error| CliError::failure(format!("failed to load status events: {error}")))?
        .collect::<Result<Vec<_>, _>>()
        .map_err(|error| CliError::failure(format!("failed to read status events: {error}")))?;
    let mut events = events.into_iter().flatten().collect::<Vec<_>>();
    events.truncate(10);
    Ok(events)
}

fn load_export_audit_records(
    connection: &Connection,
    session_id: &str,
) -> CliResult<Vec<ExportedAuditRecord>> {
    let mut statement = connection
        .prepare(
            "SELECT audit_id, previous_audit_id, timestamp,
                    COALESCE(source_agent_id, 'unknown'), source_address,
                    COALESCE(target_agent_id, 'unknown'), target_address,
                    transport, workspace_id, session_id, mid, record_type,
                    command_origin, mode, ref, re, payload_hash,
                    payload_redaction_policy, content_size, delivery_status,
                    observed_by, verified_by, due
             FROM audit_records
             WHERE session_id = ?1
             ORDER BY timestamp, audit_id",
        )
        .map_err(|error| CliError::failure(format!("failed to load audit records: {error}")))?;
    let records = statement
        .query_map([session_id], |row| {
            Ok(ExportedAuditRecord {
                audit_id: row.get(0)?,
                previous_audit_id: row.get(1)?,
                timestamp: row.get(2)?,
                source_agent: row.get(3)?,
                source_address: row.get(4)?,
                target_agent: row.get(5)?,
                target_address: row.get(6)?,
                transport: row.get(7)?,
                workspace_id: row.get(8)?,
                session_id: row.get(9)?,
                mid: row.get(10)?,
                record_type: row.get(11)?,
                command_origin: row.get(12)?,
                mode: row.get(13)?,
                r#ref: row.get(14)?,
                re: row.get(15)?,
                payload_hash: row.get(16)?,
                payload_redaction_policy: row.get(17)?,
                content_size: row.get(18)?,
                delivery_status: row.get(19)?,
                observed_by: row.get(20)?,
                verified_by: row.get(21)?,
                due: row.get(22)?,
            })
        })
        .map_err(|error| CliError::failure(format!("failed to load audit records: {error}")))?
        .collect::<Result<Vec<_>, _>>()
        .map_err(|error| CliError::failure(format!("failed to read audit records: {error}")))?;
    Ok(order_export_audit_records(records))
}

fn order_export_audit_records(records: Vec<ExportedAuditRecord>) -> Vec<ExportedAuditRecord> {
    let mut roots = Vec::new();
    let mut children: HashMap<String, Vec<ExportedAuditRecord>> = HashMap::new();
    for record in records {
        if let Some(previous_audit_id) = &record.previous_audit_id {
            children
                .entry(previous_audit_id.clone())
                .or_default()
                .push(record);
        } else {
            roots.push(record);
        }
    }
    sort_audit_records(&mut roots);

    let mut ordered = Vec::new();
    let mut leftover = Vec::new();
    for root in roots {
        let mut current = Some(root);
        while let Some(record) = current {
            let audit_id = record.audit_id.clone();
            ordered.push(record);
            current = children.remove(&audit_id).and_then(|mut child_records| {
                sort_audit_records(&mut child_records);
                let mut child_records = child_records.into_iter();
                let next = child_records.next();
                leftover.extend(child_records);
                next
            });
        }
    }
    leftover.extend(children.into_values().flatten());
    sort_audit_records(&mut leftover);
    ordered.extend(leftover);
    ordered
}

fn sort_audit_records(records: &mut [ExportedAuditRecord]) {
    records.sort_by(|left, right| {
        left.timestamp
            .cmp(&right.timestamp)
            .then_with(|| left.audit_id.cmp(&right.audit_id))
    });
}

fn render_export_status(status: &ImportedStatus, events: &[String]) -> String {
    let event_lines = if events.is_empty() {
        "No events recorded.".to_string()
    } else {
        events
            .iter()
            .enumerate()
            .map(|(index, event)| format!("{}. {event}", index + 1))
            .collect::<Vec<_>>()
            .join("\n")
    };

    format!(
        "# Session Status: {session_id}\n\n\
session_id: {session_id}\n\
last_update: {timestamp}\n\
lead_agent: {lead_agent}\n\
status: {status}\n\n\
## Current State\n\n\
- phase: {phase}\n\
- mode: {mode}\n\
- artifact_ref: {artifact_ref}\n\
- completed_since_last_update: {completed}\n\
- in_progress: {in_progress}\n\
- next_action: {next_action}\n\
- blockers: {blockers}\n\
- asks_for_Zevs: {asks_for_zevs}\n\
- risk_or_residual_uncertainty: {risk}\n\
- expected_wait: {expected_wait}\n\n\
## Rolling Events\n\n\
{event_lines}\n",
        session_id = status.session_id,
        timestamp = status.last_update,
        lead_agent = status.lead_agent,
        status = status.workflow_status,
        phase = status.phase,
        mode = status.mode,
        artifact_ref = status.artifact_ref,
        completed = status.completed_since_last_update,
        in_progress = status.in_progress,
        next_action = status.next_action,
        blockers = status.blockers,
        asks_for_zevs = status.asks_for_zevs,
        risk = status.risk_or_residual_uncertainty,
        expected_wait = status.expected_wait,
    )
}

fn render_export_audit(session_id: &str, records: &[ExportedAuditRecord]) -> String {
    let record_text = records
        .iter()
        .map(render_export_audit_record)
        .collect::<Vec<_>>()
        .join("\n");
    format!(
        "# Audit Trail: {session_id}\n\nsession_id: {session_id}\n\n## Records\n\n{record_text}\n"
    )
}

fn render_export_audit_record(record: &ExportedAuditRecord) -> String {
    let mut fields = vec![
        ("audit_id", record.audit_id.clone()),
        (
            "previous_audit_id",
            record
                .previous_audit_id
                .clone()
                .unwrap_or_else(|| "none".to_string()),
        ),
        ("timestamp", record.timestamp.clone()),
        ("source_agent", record.source_agent.clone()),
        ("source_address", record.source_address.clone()),
        ("target_agent", record.target_agent.clone()),
        ("target_address", record.target_address.clone()),
        ("transport", record.transport.clone()),
        ("workspace_id", record.workspace_id.clone()),
        ("session_id", record.session_id.clone()),
        ("mid", record.mid.clone()),
        ("type", record.record_type.clone()),
        ("command_origin", record.command_origin.clone()),
        ("payload_hash", record.payload_hash.clone()),
        (
            "payload_redaction_policy",
            record.payload_redaction_policy.clone(),
        ),
        ("content_size", record.content_size.to_string()),
        ("delivery_status", record.delivery_status.clone()),
        ("observed_by", record.observed_by.clone()),
        ("verified_by", record.verified_by.clone()),
    ];
    for (key, value) in [
        ("mode", record.mode.as_ref()),
        ("ref", record.r#ref.as_ref()),
        ("re", record.re.as_ref()),
        ("due", record.due.as_ref()),
    ] {
        if let Some(value) = value {
            fields.push((key, value.clone()));
        }
    }
    let fields = fields
        .into_iter()
        .map(|(key, value)| format!("{key}={value}"))
        .collect::<Vec<_>>()
        .join("\n");
    format!("```text\n{fields}\n```")
}

fn write_if_changed(path: &Path, content: &str) -> CliResult<bool> {
    if path.exists() {
        let existing = fs::read_to_string(path).map_err(|error| {
            CliError::failure(format!("failed to read {}: {error}", path.display()))
        })?;
        if existing == content {
            return Ok(false);
        }
    }
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent).map_err(|error| {
            CliError::failure(format!("failed to create {}: {error}", parent.display()))
        })?;
    }
    fs::write(path, content).map_err(|error| {
        CliError::failure(format!("failed to write {}: {error}", path.display()))
    })?;
    Ok(true)
}

/// v0.2.2: opt-in artifact-follow import used by `db serve --auto-import`.
/// Reuses the idempotent import path (append-only audit, content-hash status
/// dedup) so re-importing before each render cannot duplicate. This is a
/// convenience for live dashboards; it does NOT change ADR 025's default
/// (serve stays DB-read-only unless `--auto-import` is set).
pub(crate) fn import_outputs_root(db_path: &Path, root: &Path) -> CliResult<()> {
    import_outputs(
        db_path,
        &DbImportOutputsArgs {
            root: root.to_path_buf(),
            session_id: None,
            timestamp: None,
        },
    )
    .map(|_summary| ())
}

fn import_outputs(path: &Path, args: &DbImportOutputsArgs) -> CliResult<ImportSummary> {
    let sessions_dir = args.root.join("sessions");
    if !sessions_dir.exists() {
        return Ok(ImportSummary::default());
    }

    let timestamp = match &args.timestamp {
        Some(value) => normalize_arg_timestamp(value)?,
        None => crate::timestamp::now_utc_seconds(),
    };
    let mut connection = open_database(path)?;
    let mut summary = ImportSummary::default();

    for entry in fs::read_dir(&sessions_dir).map_err(|error| {
        CliError::failure(format!(
            "failed to read {}: {error}",
            sessions_dir.display()
        ))
    })? {
        let entry = entry
            .map_err(|error| CliError::failure(format!("failed to read session entry: {error}")))?;
        let session_dir = entry.path();
        if !session_dir.is_dir() {
            continue;
        }
        let Some(session_id) = session_dir
            .file_name()
            .and_then(|name| name.to_str())
            .map(str::to_string)
        else {
            continue;
        };
        if args
            .session_id
            .as_ref()
            .is_some_and(|requested| requested != &session_id)
        {
            continue;
        }

        summary.sessions_seen += 1;
        let transaction = connection
            .transaction_with_behavior(TransactionBehavior::Immediate)
            .map_err(|error| {
                CliError::failure(format!(
                    "failed to start SQLite import transaction: {error}"
                ))
            })?;
        let warnings = import_outputs_session(&transaction, &args.root, &session_dir, &timestamp)?;
        summary.warning_count += warnings.len();
        insert_import_row(
            &transaction,
            &session_dir,
            &source_hash_for_session_dir(&session_dir)?,
            &timestamp,
            &warnings,
        )?;
        transaction.commit().map_err(|error| {
            CliError::failure(format!(
                "failed to commit outputs import transaction: {error}"
            ))
        })?;
    }

    Ok(summary)
}

fn import_outputs_session(
    transaction: &Transaction<'_>,
    root: &Path,
    session_dir: &Path,
    import_timestamp: &str,
) -> CliResult<Vec<String>> {
    let mut warnings = Vec::new();
    let fallback_session_id = session_dir
        .file_name()
        .and_then(|name| name.to_str())
        .unwrap_or("unknown")
        .to_string();
    let status_path = session_dir.join("status.md");
    let mut status = if status_path.exists() {
        Some(parse_status_artifact(&status_path, &fallback_session_id)?)
    } else {
        None
    };
    // V1-C4: validate the status timestamp with real RFC3339 parsing and fail
    // cleanly on garbage rather than letting it reach the DB / a shape-only check.
    if let Some(status) = status.as_mut() {
        status.last_update =
            crate::timestamp::canonicalize(&status.last_update).ok_or_else(|| {
                CliError::failure(format!(
                    "invalid status timestamp in {}: {}",
                    status_path.display(),
                    status.last_update
                ))
            })?;
    }
    let session_id = status
        .as_ref()
        .map(|status| status.session_id.clone())
        .unwrap_or(fallback_session_id);
    let project_id = import_project_id(root);

    ensure_project(transaction, &project_id, root, import_timestamp)?;
    if let Some(status) = &status {
        if status.lead_agent != "unknown" {
            ensure_agent(transaction, &status.lead_agent, import_timestamp)?;
        }
        let inserted = transaction
            .execute(
                "INSERT OR IGNORE INTO sessions (
                    session_id, project_id, title, phase, mode, workflow_status,
                    lead_agent_id, artifact_ref, created_at, updated_at
                 )
                 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?9)",
                params![
                    status.session_id,
                    project_id,
                    status.session_id,
                    status.phase,
                    status.mode,
                    status.workflow_status,
                    nullable_unknown(&status.lead_agent),
                    status.artifact_ref,
                    status.last_update,
                ],
            )
            .map_err(|error| CliError::failure(format!("failed to import session: {error}")))?;
        if inserted == 0 {
            warnings.push(format!("skipped existing session {}", status.session_id));
        }
        insert_status_event_if_missing(transaction, status)?;
    } else {
        transaction
            .execute(
                "INSERT OR IGNORE INTO sessions (
                    session_id, project_id, title, phase, mode, workflow_status,
                    created_at, updated_at
                 )
                 VALUES (?1, ?2, ?1, 'import', 'validate', 'idle', ?3, ?3)",
                params![session_id, project_id, import_timestamp],
            )
            .map_err(|error| CliError::failure(format!("failed to import session: {error}")))?;
    }

    // v1 M2a R2 P4 (Codex): accepted decision audit records, collected during the audit
    // loop but rebuilt into the typed `operator_decisions` table AFTER the work.md import
    // below — so a fully-file-first gate/conflict (work_event + decision both `--no-db`)
    // finds its referenced `work_events` row already present and the v7 FK is satisfied.
    // Rebuilding inline (R1 P1) ran before work events existed and FK-aborted the whole
    // session import. Still the SAME import transaction, just ordered after work events.
    let mut decision_records: Vec<ImportedAuditRecord> = Vec::new();
    // ADR 036 T9 (D10): `participant-overlay` proofs accepted in the audit loop are
    // collected here and rebuilt into the typed `participant_overlay` rows AFTER the
    // audit rows land (the FK target must exist first) — and in explicit-supersede
    // CHAIN order (a row that supersedes X is applied after X is inserted + closed),
    // NOT created_at order (ADR 027: created_at is display/sort, never conflict
    // authority). Mirrors the deferred `decision_records` rebuild below.
    let mut overlay_records: Vec<ImportedAuditRecord> = Vec::new();

    let audit_path = session_dir.join("audit.md");
    if audit_path.exists() {
        let mut new_messages = HashSet::new();
        for mut record in parse_audit_artifact(&audit_path, &session_id)? {
            // ADR 026 D2: fail loud rather than fabricate a dangerous `agent`
            // default for a missing verifier.
            if record.verified_by.is_empty() {
                warnings.push(format!(
                    "skipped audit_id {}: missing verified_by",
                    record.audit_id
                ));
                continue;
            }
            // V1-C4: validate the timestamp with real RFC3339 parsing BEFORE any
            // side-effecting insert (ensure_agent), so a bad value cannot pollute
            // agents or slip through the shape-only trigger.
            match crate::timestamp::canonicalize(&record.timestamp) {
                Some(canonical) => record.timestamp = canonical,
                None => {
                    warnings.push(format!(
                        "skipped audit_id {}: invalid timestamp {}",
                        record.audit_id, record.timestamp
                    ));
                    continue;
                }
            }
            // ADR 027 C4/R1 P2: due validation is fail-loud. Canonicalize when
            // present; on a malformed value SKIP the record with a warning rather
            // than silently losing the deadline by nulling due.
            if let Some(due) = record.due.clone() {
                match crate::timestamp::canonicalize(&due) {
                    Some(canonical) => record.due = Some(canonical),
                    None => {
                        warnings.push(format!(
                            "skipped audit_id {}: invalid due {due}",
                            record.audit_id
                        ));
                        continue;
                    }
                }
            }
            // V2-C1: create agents only for records the DB actually accepts.
            // ensure_agent used to run before the insert, so a record rejected by
            // the ADR 024 trigger (sent+agent) still polluted `agents`. Doing it
            // inside the accept arms means no side effects precede acceptance.
            // A decision audit row was ACCEPTED in any of the three accept arms below;
            // collect it for the deferred operator_decisions rebuild (after work.md).
            let is_decision =
                crate::decision::DECISION_RECORD_TYPES.contains(&record.record_type.as_str());
            // ADR 036 T9 (D10): a `participant-overlay` proof rebuilds into the typed
            // `participant_overlay` row in the deferred chain-ordered loop below.
            let is_overlay = record.record_type == crate::overlay::OVERLAY_RECORD_TYPE;
            // ADR 036 D7 (trackbrc1 P1b): for a `participant-overlay` proof, parse + validate
            // the overlay payload NOW — BEFORE inserting the audit row — so a missing /
            // unparseable / invalid overlay SKIPS the WHOLE record (no audit row), never leaves
            // an orphan audit row whose deferred typed rebuild later warn-skips. The valid case
            // falls through to the normal insert + deferred chain-ordered rebuild.
            if is_overlay {
                let parse = record
                    .payload_excerpt
                    .as_deref()
                    .ok_or_else(|| {
                        CliError::usage(format!(
                            "no overlay payload in artifact for audit_id {}",
                            record.audit_id
                        ))
                    })
                    .and_then(|payload| {
                        let overlay = crate::overlay::Overlay::from_storage(payload)?;
                        overlay.validate()?;
                        Ok(())
                    });
                if let Err(error) = parse {
                    warnings.push(format!(
                        "skipped participant-overlay audit_id {}: {}",
                        record.audit_id, error.message
                    ));
                    continue;
                }
            }
            match insert_imported_audit_record(transaction, &record) {
                Ok(ImportedAuditInsert::Inserted) => {
                    ensure_record_agents(transaction, &record)?;
                    // ADR 036 T5 no-leak invariant (D7): a `participant-overlay` proof is a
                    // control-plane record about a participant, NOT a conversation message —
                    // it must never enter the `messages` corpus/feed. Gate the import-path
                    // upsert exactly as the live path does (project_live_audit_record), so
                    // `db import` of an overlay proof cannot leak it into the chat. Every
                    // other record_type imports its message row as before.
                    if record.record_type != crate::overlay::OVERLAY_RECORD_TYPE {
                        insert_or_update_imported_message(transaction, &record, &mut new_messages)?;
                    }
                    if is_decision {
                        decision_records.push(record);
                    } else if is_overlay {
                        overlay_records.push(record);
                    }
                }
                Ok(ImportedAuditInsert::Existing) => {
                    warnings.push(format!("skipped existing audit_id {}", record.audit_id));
                    // The audit row already exists, but a prior file-first import (or a
                    // soft-degrade) may have left the typed operator_decisions /
                    // participant_overlay row absent. Still rebuild (deferred) — the
                    // decision rebuild is INSERT OR IGNORE (safe no-op when present); the
                    // overlay rebuild guards against a duplicate insert before re-inserting.
                    if is_decision {
                        decision_records.push(record);
                    } else if is_overlay {
                        overlay_records.push(record);
                    }
                }
                Ok(ImportedAuditInsert::RebasedToRoot { original_error }) => {
                    warnings.push(format!(
                        "rebased audit_id {} to chain root after insert failed: {}",
                        record.audit_id, original_error
                    ));
                    ensure_record_agents(transaction, &record)?;
                    // ADR 036 T5 no-leak invariant (D7): same overlay gate as the
                    // Inserted arm — a rebased-to-root overlay proof must also skip the
                    // messages upsert (never a chat/feed item).
                    if record.record_type != crate::overlay::OVERLAY_RECORD_TYPE {
                        insert_or_update_imported_message(transaction, &record, &mut new_messages)?;
                    }
                    if is_decision {
                        decision_records.push(record);
                    } else if is_overlay {
                        overlay_records.push(record);
                    }
                }
                Err(error) => {
                    warnings.push(format!("skipped audit_id {}: {error}", record.audit_id))
                }
            }
        }
    }

    // v1 M1 R1 P2: reconcile file-first work events from `work.md` back into
    // `work_events` (the `--no-db`/soft-degrade recovery gap ADR 027 promises). For
    // each parsed event: canonicalize the timestamp (warn+skip on None, exactly like
    // the audit import above), `validate()` (warn+skip on error), then project via
    // the SAME `project_work_event` the live path uses (INSERT OR IGNORE on the
    // event-identity content_hash → append-only + idempotent re-import). An
    // `Artifact` payload ALSO dual-projects one `artifacts` row per file, mirroring
    // exactly what `project_report` does — but inside this import transaction.
    let work_path = session_dir.join("work.md");
    if work_path.exists() {
        let (work_events, parse_warnings) = parse_work_artifact(&work_path, &session_id)?;
        warnings.extend(parse_warnings);
        for event in work_events {
            let canonical_ts = match crate::timestamp::canonicalize(&event.timestamp) {
                Some(value) => value,
                None => {
                    warnings.push(format!(
                        "skipped work event: invalid timestamp {}",
                        event.timestamp
                    ));
                    continue;
                }
            };
            if let Err(error) = event.payload.validate() {
                warnings.push(format!(
                    "skipped work event at {canonical_ts}: {}",
                    error.message
                ));
                continue;
            }
            project_work_event(
                transaction,
                &session_id,
                &event.actor,
                &canonical_ts,
                event.seq,
                &event.payload,
            )?;
            if let crate::work_event::WorkEventPayload::Artifact { files } = &event.payload {
                for file in files {
                    upsert_artifact(transaction, &session_id, &file.path, &canonical_ts)?;
                }
            }
        }
    }

    // v1 M2a R2 P4: rebuild the typed operator_decisions rows NOW — work_events from
    // work.md are in this transaction, so a gate/conflict ref resolves and the v7 FK is
    // satisfied. Each rebuild validates its ref against the in-transaction work_events
    // (warn+skip on missing/wrong-kind, no rollback); INSERT OR IGNORE keeps it
    // idempotent. Still atomic with the audit/work rows (same `transaction`).
    for record in &decision_records {
        if let Some(warning) = rebuild_imported_operator_decision(transaction, &session_id, record)?
        {
            warnings.push(warning);
        }
    }

    // ADR 036 T9 (D10): rebuild the typed `participant_overlay` rows from the imported
    // overlay proofs NOW — the audit rows above are in this transaction, so the
    // `participant_overlay.audit_id` FK is satisfied. Order by the EXPLICIT
    // `supersedes_audit_id` chain (NOT created_at; ADR 027) so a row that supersedes X
    // is applied after X is inserted + closed — otherwise the partial-unique current-slot
    // index would abort mid-import. A double-un-superseded slot makes that index ABORT,
    // which propagates as `Err` (fail-loud) and rolls back the whole session import.
    rebuild_imported_participant_overlays(transaction, &overlay_records, &mut warnings)?;

    Ok(warnings)
}

/// ADR 036 T9 (D10): rebuild the typed `participant_overlay` rows from the collected
/// `participant-overlay` audit proofs, ordered by the EXPLICIT `supersedes_audit_id`
/// pointers. Deterministic regardless of file/timestamp order: a proof that supersedes
/// X is emitted AFTER X (so the supersede UPDATE in `insert_participant_overlay` closes
/// X's current-slot pointer before the new current row lands, satisfying the
/// partial-unique index). A double-un-superseded slot is rejected by that index and
/// surfaces here as `Err` (fail-loud — never a silent drop).
fn rebuild_imported_participant_overlays(
    transaction: &Transaction<'_>,
    records: &[ImportedAuditRecord],
    warnings: &mut Vec<String>,
) -> CliResult<()> {
    // Parse each proof to its `Overlay` first (warn+skip on a missing/undeserializable
    // payload, exactly like the decision rebuild). A skipped proof drops out of the
    // ordering entirely — its supersede edge cannot be honored without the parsed row.
    let mut parsed: Vec<(&ImportedAuditRecord, crate::overlay::Overlay)> = Vec::new();
    for record in records {
        let Some(payload) = record.payload_excerpt.as_deref() else {
            warnings.push(format!(
                "skipped participant_overlay rebuild for audit_id {}: no overlay payload in artifact",
                record.audit_id
            ));
            continue;
        };
        let overlay = match crate::overlay::Overlay::from_storage(payload) {
            Ok(overlay) => overlay,
            Err(error) => {
                warnings.push(format!(
                    "skipped participant_overlay rebuild for audit_id {}: {}",
                    record.audit_id, error.message
                ));
                continue;
            }
        };
        if let Err(error) = overlay.validate() {
            warnings.push(format!(
                "skipped participant_overlay rebuild for audit_id {}: {}",
                record.audit_id, error.message
            ));
            continue;
        }
        parsed.push((record, overlay));
    }

    // Order by the explicit supersede chain. Build a forward map (audit_id ->
    // index-that-supersedes-it) and emit roots first (a proof whose `supersedes` names
    // no proof in THIS batch), then walk each chain forward. A chain whose root is
    // missing from the batch is itself a root (its earliest member supersedes nothing
    // in-batch) and gets walked; only a genuine supersede CYCLE leaves a proof unemitted,
    // which `chain_order` rejects (fail-loud Err, rolling back the whole import) rather
    // than an input-order append. The partial-unique index remains the final integrity
    // gate for a double-current slot. created_at is NEVER consulted (ADR 027).
    let order = chain_order(&parsed)?;
    for index in order {
        let (record, overlay) = &parsed[index];
        // A re-import re-presents already-projected proofs: the audit row is Existing and
        // the typed row already exists. Skip re-inserting it (idempotent) — re-running the
        // supersede UPDATE + INSERT would either be a harmless no-op or collide with the
        // unique index on a row this very import already closed. Mirrors the decision
        // rebuild's INSERT OR IGNORE idempotence.
        let already: bool = transaction
            .query_row(
                "SELECT 1 FROM participant_overlay WHERE audit_id = ?1",
                params![record.audit_id],
                |_| Ok(()),
            )
            .optional()
            .map_err(|error| {
                CliError::failure(format!(
                    "failed to read participant_overlay on rebuild: {error}"
                ))
            })?
            .is_some();
        if already {
            continue;
        }
        // Fail-loud: `insert_participant_overlay` propagates the partial-unique index
        // abort (a double-un-superseded slot) as `Err`, rolling back the whole import.
        insert_participant_overlay(transaction, record, overlay)?;
    }
    Ok(())
}

/// Deterministic chain order for a batch of parsed overlay proofs (ADR 036 D10): a proof
/// that supersedes X is emitted AFTER X. Roots (a proof whose `supersedes` names no proof
/// in this batch) come first, then each supersede edge is followed forward. The result is
/// a stable permutation of `0..parsed.len()` independent of the input/timestamp order.
///
/// A proof whose `supersedes` names an IN-BATCH predecessor but is never reached from any
/// root after the root-walk is part of a supersede CYCLE — `chain_order` FAILS LOUD (Err)
/// so a crafted cyclic import is rejected deterministically (never an input-order append
/// with a non-deterministic winner). A chain rooted OUTSIDE the batch is NOT a cycle: its
/// earliest in-batch member supersedes nothing in the batch, so it is itself a root and
/// gets walked. created_at is NEVER consulted.
fn chain_order(
    parsed: &[(&ImportedAuditRecord, crate::overlay::Overlay)],
) -> CliResult<Vec<usize>> {
    use std::collections::HashMap;
    // audit_id -> index in `parsed`.
    let mut index_by_audit: HashMap<&str, usize> = HashMap::new();
    for (index, (record, _)) in parsed.iter().enumerate() {
        index_by_audit.insert(record.audit_id.as_str(), index);
    }
    // For each proof, the index it supersedes WITHIN this batch (if present).
    let supersedes_index: Vec<Option<usize>> = parsed
        .iter()
        .map(|(_, overlay)| {
            overlay
                .supersedes()
                .and_then(|prev| index_by_audit.get(prev).copied())
        })
        .collect();
    // Forward edges: predecessor index -> the index that supersedes it.
    let mut superseded_by: Vec<Option<usize>> = vec![None; parsed.len()];
    for (index, prev) in supersedes_index.iter().enumerate() {
        if let Some(prev) = prev {
            // If two proofs claim the SAME predecessor, keep the first; the index will
            // still reject the resulting double-current slot. Order stays deterministic.
            if superseded_by[*prev].is_none() {
                superseded_by[*prev] = Some(index);
            }
        }
    }
    let mut order: Vec<usize> = Vec::with_capacity(parsed.len());
    let mut emitted = vec![false; parsed.len()];
    // Roots first (a proof that supersedes nothing in this batch), in input order so the
    // emission is stable.
    for (index, prev) in supersedes_index.iter().enumerate() {
        if prev.is_some() {
            continue;
        }
        // Walk this chain forward: root, then whoever supersedes it, and so on.
        let mut cursor = Some(index);
        while let Some(node) = cursor {
            if emitted[node] {
                break;
            }
            emitted[node] = true;
            order.push(node);
            cursor = superseded_by[node];
        }
    }
    // Anything still unemitted points at an in-batch predecessor (otherwise it would have
    // been a root and walked) yet is unreachable from any root — i.e. part of a supersede
    // CYCLE. Fail loud (ADR 036 D10): a crafted cyclic import is rejected deterministically,
    // never an input-order append with a non-deterministic winner.
    if let Some((index, _)) = emitted.iter().enumerate().find(|(_, done)| !**done) {
        return Err(CliError::failure(format!(
            "participant_overlay import has a supersede cycle (audit_id {} is unreachable from any chain root) — rejecting the import (ADR 036 D10)",
            parsed[index].0.audit_id
        )));
    }
    Ok(order)
}

fn parse_status_artifact(path: &Path, fallback_session_id: &str) -> CliResult<ImportedStatus> {
    let content = fs::read_to_string(path).map_err(|error| {
        CliError::failure(format!("failed to read {}: {error}", path.display()))
    })?;
    let values = parse_markdown_key_values(&content);
    Ok(ImportedStatus {
        session_id: value_or(&values, "session_id", fallback_session_id),
        last_update: value_or(&values, "last_update", "1970-01-01T00:00:00Z"),
        lead_agent: value_or(&values, "lead_agent", "unknown"),
        phase: value_or(&values, "phase", "import"),
        mode: value_or(&values, "mode", "validate"),
        artifact_ref: value_or(&values, "artifact_ref", "unknown"),
        workflow_status: value_or(&values, "status", "idle"),
        completed_since_last_update: value_or(&values, "completed_since_last_update", "unknown"),
        in_progress: value_or(&values, "in_progress", "unknown"),
        next_action: value_or(&values, "next_action", "unknown"),
        blockers: value_or(&values, "blockers", "unknown"),
        asks_for_zevs: value_or(&values, "asks_for_Zevs", "unknown"),
        risk_or_residual_uncertainty: value_or(&values, "risk_or_residual_uncertainty", "unknown"),
        expected_wait: value_or(&values, "expected_wait", "unknown"),
        rolling_events: parse_rolling_events(&content),
    })
}

fn parse_audit_artifact(
    path: &Path,
    fallback_session_id: &str,
) -> CliResult<Vec<ImportedAuditRecord>> {
    let content = fs::read_to_string(path).map_err(|error| {
        CliError::failure(format!("failed to read {}: {error}", path.display()))
    })?;
    let mut records = Vec::new();
    for values in parse_fenced_key_value_blocks(&content) {
        let audit_id = value_or(&values, "audit_id", "");
        if audit_id.is_empty() {
            continue;
        }
        records.push(ImportedAuditRecord {
            audit_id,
            previous_audit_id: optional_audit_id(&value_or(&values, "previous_audit_id", "none")),
            timestamp: value_or(&values, "timestamp", "1970-01-01T00:00:00Z"),
            source_agent_id: nullable_unknown(&value_or(&values, "source_agent", "unknown")),
            source_address: value_or(&values, "source_address", "unknown"),
            target_agent_id: nullable_unknown(&value_or(&values, "target_agent", "unknown")),
            target_address: value_or(&values, "target_address", "unknown"),
            transport: value_or(&values, "transport", "unknown"),
            workspace_id: value_or(&values, "workspace_id", "unknown"),
            session_id: value_or(&values, "session_id", fallback_session_id),
            mid: value_or(&values, "mid", "unknown"),
            record_type: value_or(&values, "type", "unknown"),
            command_origin: value_or(&values, "command_origin", "unknown"),
            mode: optional_text(&value_or(&values, "mode", "")),
            r#ref: optional_text(&value_or(&values, "ref", "")),
            re: optional_text(&value_or(&values, "re", "")),
            payload_hash: value_or(&values, "payload_hash", "sha256:unknown"),
            payload_redaction_policy: value_or(&values, "payload_redaction_policy", "hash-only"),
            content_size: value_or(&values, "content_size", "0").parse().unwrap_or(0),
            delivery_status: value_or(&values, "delivery_status", "unknown"),
            observed_by: value_or(&values, "observed_by", "unknown"),
            verified_by: value_or(&values, "verified_by", ""),
            due: optional_text(&value_or(&values, "due", "")),
            payload_excerpt: optional_text(&value_or(&values, "payload_excerpt", "")),
        });
    }
    Ok(records)
}

/// v1 M1 R1 P2 (+ R2 P4/P5): parse a session's `work.md` into typed
/// `ImportedWorkEvent`s. The file is a sequence of ```` ```work-event ```` … ```` ```
/// ```` fences (see `report::run`); blocks are split by the shared `split_work_blocks`
/// using EXACT column-0 fences (R2 P5), so an INDENTED payload fence is kept as payload,
/// not a false close. Inside each fence the block is written POSITIONALLY by the writer:
/// line 1 `kind={k}`, line 2 `actor={a}`, line 3 `timestamp={t}`, line 4 `seq={n}`, and
/// line 5 onward is the stored typed payload (serde_norway, possibly multiple lines).
/// The split is positional — NOT a per-line content heuristic — so a hand-edited /
/// corrupted block with a MISSING or reordered header (the import path is the ADR 027
/// file-as-authority recovery path and faces edited files) is a LOUD malformed skip,
/// never silently promoting a payload line into the header map. A block with fewer than
/// five inner lines, or whose first four lines do not start with the required
/// `kind=`/`actor=`/`timestamp=`/`seq=` prefixes in order (with `seq=` parsing as a
/// non-negative integer), or whose stored payload fails `from_storage`, or whose header
/// `kind` disagrees with the payload `kind()`, is a malformed record: it is collected as
/// a warning and SKIPPED, never silently dropped or imported as garbage — mirroring the
/// audit/status import discipline. An unterminated trailing block also warns (R2 P5).
/// The caller (`import_outputs_session`) canonicalizes the timestamp and validates the
/// payload before projecting, exactly as the audit import does.
fn parse_work_artifact(
    path: &Path,
    session_id: &str,
) -> CliResult<(Vec<ImportedWorkEvent>, Vec<String>)> {
    let content = fs::read_to_string(path).map_err(|error| {
        CliError::failure(format!("failed to read {}: {error}", path.display()))
    })?;
    let mut events = Vec::new();
    let mut warnings = Vec::new();
    // v1 M1 R2 P5: split on EXACT (untrimmed) column-0 fences via the shared
    // `split_work_blocks` so an INDENTED payload fence (a serde_norway block scalar
    // whose value itself contains a ```` ``` ````) is treated as payload, not a false
    // structural close. An unterminated trailing block warns (fail-loud) instead of
    // being silently dropped.
    let blocks = split_work_blocks(&content);
    for (index, block) in blocks.blocks.iter().enumerate() {
        let block_index = index + 1; // 1-based for the warning message
        match parse_work_block(block) {
            Ok(event) => events.push(event),
            Err(reason) => warnings.push(format!(
                "skipped work event in {} (block {block_index}, session {session_id}): {reason}",
                path.display()
            )),
        }
    }
    if blocks.unterminated {
        warnings.push(format!(
            "unterminated work-event block in {} (session {session_id}): \
             opening ```work-event fence at column 0 with no matching closing fence \
             before EOF — block skipped",
            path.display()
        ));
    }
    Ok((events, warnings))
}

/// The blocks recovered from a `work.md` content string by `split_work_blocks`.
struct WorkBlocks {
    /// Each terminated `work-event` block's inner lines (verbatim, fences excluded).
    blocks: Vec<Vec<String>>,
    /// True when an opening fence had no matching close before EOF (fail-loud).
    unterminated: bool,
}

/// v1 M1 R2 P5: split a `work.md` `content` into `work-event` blocks using EXACT
/// (untrimmed) COLUMN-0 fences. `report::run` always emits the structural fences at
/// column 0 (`\n```work-event\n…\n{stored}```\n`), and a serde_norway block-scalar
/// payload's content is always INDENTED (≥1 space) relative to its key — so a payload
/// line that happens to be a Markdown fence (e.g. `  ```` ```` `) can never appear at
/// column 0 and is correctly kept as payload. Detecting the fences by `.trim()` (the
/// old behavior) wrongly promoted such an indented fence to a structural close,
/// truncating the block. A line that is EXACTLY `` ```work-event `` opens a block; a
/// line that is EXACTLY `` ``` `` closes the open block; every other line (including an
/// indented fence) is block content. An opening fence with no matching close before EOF
/// is reported via `unterminated` so the caller can warn (fail-loud), not silently drop.
/// This is the single boundary authority shared by `parse_work_artifact` (import) and
/// the producer's `seq` count (`report::run`, via `count_work_blocks`), so both use
/// identical block boundaries.
fn split_work_blocks(content: &str) -> WorkBlocks {
    let mut blocks: Vec<Vec<String>> = Vec::new();
    let mut current: Option<Vec<String>> = None; // inner block lines, verbatim
    for line in content.lines() {
        if current.is_none() {
            if line == "```work-event" {
                current = Some(Vec::new());
            }
            // Lines outside any block (prose, blank separators) are ignored.
            continue;
        }
        // Inside an open block: only a column-0 exact ``` closes it.
        if line == "```" {
            blocks.push(current.take().expect("block is open"));
            continue;
        }
        current
            .as_mut()
            .expect("block is open")
            .push(line.to_string());
    }
    let unterminated = current.is_some();
    WorkBlocks {
        blocks,
        unterminated,
    }
}

/// v1 M1 R2 P4: count the existing `work-event` blocks in a session's `work.md`,
/// reusing the SAME `split_work_blocks` boundary authority so the producer's
/// file-rendered `seq` ordinal matches what the importer will re-derive. Returns 0
/// when the file is absent or empty. An unterminated trailing block (a partial prior
/// write) is NOT counted — it will not import as an event, so the next event's `seq`
/// must not reserve an ordinal for it.
pub(crate) fn count_work_blocks(content: &str) -> usize {
    split_work_blocks(content).blocks.len()
}

/// Parse one `work-event` block's inner lines into a typed `ImportedWorkEvent` via a
/// POSITIONAL split that mirrors the writer (`report::run`): line 0 `kind={k}`, line 1
/// `actor={a}`, line 2 `timestamp={t}`, line 3 `seq={n}`, then the stored payload from
/// line 4 on (v1 M1 R2 P4). A missing/reordered header (any of the first four lines not
/// starting with its required prefix), a `seq=` that is not a non-negative integer, or
/// fewer than five lines, is MALFORMED — returns a human-readable reason so the caller
/// can warn+skip rather than silently importing a corrupted event.
fn parse_work_block(lines: &[String]) -> Result<ImportedWorkEvent, String> {
    // Positional, strict-prefix split: the writer always emits the four headers
    // first, in order, then the payload — so a deviation is a corrupted/edited file.
    let header_kind = lines
        .first()
        .and_then(|l| l.strip_prefix("kind="))
        .ok_or_else(|| "missing or misplaced kind= header (expected line 1)".to_string())?
        .trim()
        .to_string();
    let actor = lines
        .get(1)
        .and_then(|l| l.strip_prefix("actor="))
        .ok_or_else(|| "missing or misplaced actor= header (expected line 2)".to_string())?
        .trim()
        .to_string();
    if actor.is_empty() {
        return Err("empty actor= header".to_string());
    }
    let timestamp = lines
        .get(2)
        .and_then(|l| l.strip_prefix("timestamp="))
        .ok_or_else(|| "missing or misplaced timestamp= header (expected line 3)".to_string())?
        .trim()
        .to_string();
    if timestamp.is_empty() {
        return Err("empty timestamp= header".to_string());
    }
    let seq_raw = lines
        .get(3)
        .and_then(|l| l.strip_prefix("seq="))
        .ok_or_else(|| "missing or misplaced seq= header (expected line 4)".to_string())?
        .trim();
    let seq: usize = seq_raw
        .parse()
        .map_err(|_| format!("seq= header must be a non-negative integer (got {seq_raw:?})"))?;
    if lines.len() < 5 {
        return Err("missing stored payload (block has no body after headers)".to_string());
    }
    // The stored payload is everything from line 4 on, reconstructed VERBATIM with the
    // trailing newline that `to_storage` (serde_norway) emits — so writer-produced
    // blocks round-trip identically through `from_storage`.
    let mut payload_body = String::new();
    for line in &lines[4..] {
        payload_body.push_str(line);
        payload_body.push('\n');
    }
    let payload = crate::work_event::WorkEventPayload::from_storage(&payload_body)
        .map_err(|error| format!("unparseable payload: {}", error.message))?;
    // The header `kind=` must agree with the typed payload kind — the same
    // typed-not-blob discipline the read-model enforces.
    if header_kind != payload.kind() {
        return Err(format!(
            "kind header {header_kind:?} disagrees with payload kind {:?}",
            payload.kind()
        ));
    }
    Ok(ImportedWorkEvent {
        actor,
        timestamp,
        seq,
        payload,
    })
}

fn parse_markdown_key_values(content: &str) -> BTreeMap<String, String> {
    let mut values = BTreeMap::new();
    for line in content.lines() {
        let line = line.trim();
        if let Some((key, value)) = line
            .strip_prefix("- ")
            .and_then(|line| line.split_once(": "))
        {
            values.insert(key.to_string(), value.to_string());
        } else if let Some((key, value)) = line.split_once(": ") {
            values.insert(key.to_string(), value.to_string());
        }
    }
    values
}

fn parse_rolling_events(content: &str) -> Vec<String> {
    let Some((_, events_text)) = content.split_once("## Rolling Events") else {
        return Vec::new();
    };
    events_text
        .lines()
        .filter_map(|line| {
            let line = line.trim();
            let (prefix, entry) = line.split_once(". ")?;
            prefix.parse::<usize>().ok()?;
            Some(entry.to_string())
        })
        .collect()
}

/// Parse the ```` ```text ```` `key=value` blocks of an audit artifact into per-record
/// maps. v1 M2a R1 P1 (approach A): `payload_excerpt` is a TERMINAL field — the writer
/// renders it LAST (`render_record`, src/audit.rs), so for `full` redaction a multi-line
/// serde_norway payload (e.g. a typed `Decision`) lands as `payload_excerpt=<line1>` plus
/// continuation lines with NO `key=`. The pre-fix single-line `split_once('=')` dropped
/// those continuation lines, truncating the payload to its first YAML line and breaking
/// `Decision::from_storage` on import. Now: once `payload_excerpt` is seen, its first-line
/// remainder PLUS every subsequent raw line up to the block's closing fence is captured
/// VERBATIM (no per-line trim — serde_norway needs the original indentation/blank lines)
/// and joined with `\n`. While capturing the terminal payload, the closing fence is matched
/// EXACTLY on the untrimmed column-0 `` ``` `` (the writer always emits the close at column
/// 0), so an INDENTED `` ``` `` that happens to appear inside the payload is kept as payload,
/// not mistaken for the block close — the same exact-fence discipline as the M1 work.md P5
/// fix. A column-0 `` ``` `` literally INSIDE a payload remains an accepted limitation (no
/// escaping); serde_norway block scalars indent their content so it cannot occur in
/// practice. Non-payload fields keep the trimmed `key=value` parse, so blocks without a
/// `payload_excerpt` (and single-line payload_excerpt blocks) parse identically to before.
fn parse_fenced_key_value_blocks(content: &str) -> Vec<BTreeMap<String, String>> {
    const PAYLOAD_KEY: &str = "payload_excerpt";
    let mut blocks = Vec::new();
    let mut current: Option<BTreeMap<String, String>> = None;
    // Some(lines) once the terminal `payload_excerpt` field is open: subsequent raw
    // lines are appended verbatim until the exact column-0 closing fence.
    let mut payload_capture: Option<Vec<String>> = None;
    for raw_line in content.lines() {
        // While capturing the terminal payload, ONLY an exact column-0 fence closes the
        // block (untrimmed). Check this before the trimmed/key-value handling below.
        if payload_capture.is_some() {
            if raw_line == "```" {
                if let (Some(values), Some(lines)) = (current.as_mut(), payload_capture.take()) {
                    values.insert(PAYLOAD_KEY.to_string(), lines.join("\n"));
                }
                if let Some(values) = current.take() {
                    blocks.push(values);
                }
                continue;
            }
            if let Some(lines) = payload_capture.as_mut() {
                lines.push(raw_line.to_string());
            }
            continue;
        }

        let line = raw_line.trim();
        if line == "```text" {
            current = Some(BTreeMap::new());
            continue;
        }
        if line == "```" {
            if let Some(values) = current.take() {
                blocks.push(values);
            }
            continue;
        }
        if current.is_some() {
            if let Some((key, value)) = line.split_once('=') {
                if key == PAYLOAD_KEY {
                    // Open the terminal capture with this line's remainder as line 1.
                    payload_capture = Some(vec![value.to_string()]);
                } else {
                    if let Some(values) = current.as_mut() {
                        values.insert(key.to_string(), value.to_string());
                    }
                }
            }
        }
    }
    blocks
}

fn ensure_project(
    transaction: &Transaction<'_>,
    project_id: &str,
    root: &Path,
    timestamp: &str,
) -> CliResult<()> {
    transaction
        .execute(
            "INSERT OR IGNORE INTO projects (project_id, name, root_path, created_at, updated_at)
             VALUES (?1, ?2, ?3, ?4, ?4)",
            params![
                project_id,
                root.file_name()
                    .and_then(|name| name.to_str())
                    .unwrap_or("outputs"),
                root.display().to_string(),
                timestamp,
            ],
        )
        .map_err(|error| CliError::failure(format!("failed to import project: {error}")))?;
    Ok(())
}

fn ensure_agent(transaction: &Transaction<'_>, agent_id: &str, timestamp: &str) -> CliResult<()> {
    transaction
        .execute(
            "INSERT OR IGNORE INTO agents (
                agent_id, display_name, agent_kind, created_at, updated_at
             )
             VALUES (?1, ?1, 'imported', ?2, ?2)",
            params![agent_id, timestamp],
        )
        .map_err(|error| CliError::failure(format!("failed to import agent: {error}")))?;
    Ok(())
}

/// Ensure the source/target agents of an accepted audit record exist. Called
/// only after the record is accepted (V2-C1), so rejected records leave no
/// agent rows behind.
fn ensure_record_agents(
    transaction: &Transaction<'_>,
    record: &ImportedAuditRecord,
) -> CliResult<()> {
    if let Some(agent_id) = &record.source_agent_id {
        ensure_agent(transaction, agent_id, &record.timestamp)?;
    }
    if let Some(agent_id) = &record.target_agent_id {
        ensure_agent(transaction, agent_id, &record.timestamp)?;
    }
    Ok(())
}

fn insert_status_event_if_missing(
    transaction: &Transaction<'_>,
    status: &ImportedStatus,
) -> CliResult<()> {
    // ADR 026 D3: dedup on content, not just (session, timestamp, phase, mode,
    // status). The 11-field order here MUST match backfill_status_content_hash.
    let event_text = status.rolling_events.join("\n");
    let content_hash = status_content_hash(&[
        &status.phase,
        &status.mode,
        &status.workflow_status,
        &status.completed_since_last_update,
        &status.in_progress,
        &status.next_action,
        &status.blockers,
        &status.asks_for_zevs,
        &status.risk_or_residual_uncertainty,
        &status.expected_wait,
        &event_text,
    ]);

    let exists: Option<i64> = transaction
        .query_row(
            "SELECT status_event_id
             FROM status_events
             WHERE session_id = ?1 AND timestamp = ?2 AND content_hash = ?3
             LIMIT 1",
            params![status.session_id, status.last_update, content_hash],
            |row| row.get(0),
        )
        .optional()
        .map_err(|error| CliError::failure(format!("failed to read status events: {error}")))?;
    if exists.is_some() {
        return Ok(());
    }

    transaction
        .execute(
            "INSERT INTO status_events (
                session_id, timestamp, phase, mode, workflow_status,
                completed_since_last_update, in_progress, next_action, blockers,
                asks_for_zevs, risk_or_residual_uncertainty, expected_wait, event_text,
                content_hash
             )
             VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14)",
            params![
                status.session_id,
                status.last_update,
                status.phase,
                status.mode,
                status.workflow_status,
                status.completed_since_last_update,
                status.in_progress,
                status.next_action,
                status.blockers,
                status.asks_for_zevs,
                status.risk_or_residual_uncertainty,
                status.expected_wait,
                event_text,
                content_hash,
            ],
        )
        .map_err(|error| CliError::failure(format!("failed to import status event: {error}")))?;
    Ok(())
}

fn insert_imported_audit_record(
    transaction: &Transaction<'_>,
    record: &ImportedAuditRecord,
) -> Result<ImportedAuditInsert, String> {
    let exists: Option<String> = transaction
        .query_row(
            "SELECT audit_id FROM audit_records WHERE audit_id = ?1",
            [&record.audit_id],
            |row| row.get(0),
        )
        .optional()
        .map_err(|error| error.to_string())?;
    if exists.is_some() {
        return Ok(ImportedAuditInsert::Existing);
    }

    match execute_imported_audit_insert(transaction, record, record.previous_audit_id.as_deref()) {
        Ok(_) => Ok(ImportedAuditInsert::Inserted),
        Err(error) if record.previous_audit_id.is_some() => {
            let original_error = error.to_string();
            match execute_imported_audit_insert(transaction, record, None) {
                Ok(_) => Ok(ImportedAuditInsert::RebasedToRoot { original_error }),
                Err(fallback_error) => Err(format!(
                    "{original_error}; root fallback failed: {fallback_error}"
                )),
            }
        }
        Err(error) => Err(error.to_string()),
    }
}

fn execute_imported_audit_insert(
    transaction: &Transaction<'_>,
    record: &ImportedAuditRecord,
    previous_audit_id: Option<&str>,
) -> rusqlite::Result<usize> {
    transaction.execute(
        "INSERT INTO audit_records (
            audit_id, previous_audit_id, session_id, source_agent_id, target_agent_id,
            source_address, target_address, transport, workspace_id, mid, record_type,
            command_origin, mode, ref, re, payload_hash, payload_redaction_policy,
            content_size, delivery_status, observed_by, verified_by, timestamp, due
         )
         VALUES (
            ?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11,
            ?12, ?13, ?14, ?15, ?16, ?17, ?18, ?19, ?20, ?21, ?22, ?23
         )",
        params![
            record.audit_id,
            previous_audit_id,
            record.session_id,
            record.source_agent_id,
            record.target_agent_id,
            record.source_address,
            record.target_address,
            record.transport,
            record.workspace_id,
            record.mid,
            record.record_type,
            record.command_origin,
            record.mode,
            record.r#ref,
            record.re,
            record.payload_hash,
            record.payload_redaction_policy,
            record.content_size,
            record.delivery_status,
            record.observed_by,
            record.verified_by,
            record.timestamp,
            record.due,
        ],
    )
}

fn insert_or_update_imported_message(
    transaction: &Transaction<'_>,
    record: &ImportedAuditRecord,
    new_messages: &mut HashSet<String>,
) -> CliResult<()> {
    let message_id = message_id(&record.session_id, &record.mid);
    let inserted = transaction
        .execute(
            "INSERT OR IGNORE INTO messages (
                message_id, session_id, mid, source_agent_id, target_agent_id, message_type,
                mode, ref, transport, payload_redaction_policy, payload_hash,
                latest_delivery_status, latest_verified_by, latest_audit_id, timestamp,
                payload_excerpt
             )
             VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16)",
            params![
                message_id,
                record.session_id,
                record.mid,
                record.source_agent_id,
                record.target_agent_id,
                record.record_type,
                record.mode,
                record.r#ref,
                record.transport,
                record.payload_redaction_policy,
                record.payload_hash,
                record.delivery_status,
                record.verified_by,
                record.audit_id,
                record.timestamp,
                corpus_payload_excerpt(record),
            ],
        )
        .map_err(|error| CliError::failure(format!("failed to import message: {error}")))?;
    if inserted == 1 {
        new_messages.insert(message_id);
        return Ok(());
    }
    if !new_messages.contains(&message_id) {
        return Ok(());
    }

    transaction
        .execute(
            "UPDATE messages
             SET source_agent_id = ?2,
                 target_agent_id = ?3,
                 message_type = ?4,
                 mode = ?5,
                 ref = ?6,
                 transport = ?7,
                 payload_redaction_policy = ?8,
                 payload_hash = ?9,
                 latest_delivery_status = ?10,
                 latest_verified_by = ?11,
                 latest_audit_id = ?12,
                 timestamp = ?13,
                 payload_excerpt = ?14
             WHERE message_id = ?1",
            params![
                message_id,
                record.source_agent_id,
                record.target_agent_id,
                record.record_type,
                record.mode,
                record.r#ref,
                record.transport,
                record.payload_redaction_policy,
                record.payload_hash,
                record.delivery_status,
                record.verified_by,
                record.audit_id,
                record.timestamp,
                corpus_payload_excerpt(record),
            ],
        )
        .map_err(|error| {
            CliError::failure(format!("failed to update imported message: {error}"))
        })?;
    Ok(())
}

// ===== ADR 027 + ADR 028: live DB projection (write path keeps the DB canonical) =====

/// Where a status/audit write should project (ADR 028).
pub(crate) enum ProjectionTarget {
    /// `--no-db`: file-only, never touch a DB.
    None,
    /// Default cwd DB: auto-create+migrate; a projection failure soft-degrades.
    Default(PathBuf),
    /// Explicit `--db <path>`: a projection failure hard-fails (file already written).
    Explicit(PathBuf),
}

impl ProjectionTarget {
    /// The path to project into and whether it was explicit (`--db`), or None for
    /// `--no-db`. Explicit targets hard-fail on projection error; default targets
    /// soft-degrade (the file is the durable record either way).
    pub(crate) fn into_path_and_mode(self) -> Option<(PathBuf, bool)> {
        match self {
            ProjectionTarget::None => None,
            ProjectionTarget::Default(path) => Some((path, false)),
            ProjectionTarget::Explicit(path) => Some((path, true)),
        }
    }

    /// Borrowing view of `into_path_and_mode` (the path + explicit flag) so a
    /// caller can consult the target without consuming it — `zynk decide` uses
    /// this for the pre-write ref-kind check, then `into_path_and_mode` for the
    /// post-write projection.
    pub(crate) fn path_and_mode(&self) -> Option<(&Path, bool)> {
        match self {
            ProjectionTarget::None => None,
            ProjectionTarget::Default(path) => Some((path.as_path(), false)),
            ProjectionTarget::Explicit(path) => Some((path.as_path(), true)),
        }
    }
}

/// Resolve the projection target from `--db`/`--no-db` (ADR 028): `--no-db` =>
/// None; `--db <p>` => Explicit(p); neither => Default(`<cwd>/.zynk/zynk.db`),
/// which is auto-created on use — no presence gate.
pub(crate) fn resolve_projection_target(db: Option<&Path>, no_db: bool) -> ProjectionTarget {
    if no_db {
        return ProjectionTarget::None;
    }
    match db {
        Some(path) => ProjectionTarget::Explicit(path.to_path_buf()),
        None => ProjectionTarget::Default(PathBuf::from(".zynk/zynk.db")),
    }
}

/// Path-keyed self-protection (ADR 028 C1/C7): if the DB lives in a `.zynk`
/// directory, ensure a `.zynk/.gitignore` of `*` so the runtime DB is never
/// accidentally committed, even in a repo that never configured zynk. Idempotent;
/// also protects a pre-existing v0.3 DB and `db init` at the default path.
fn ensure_zynk_gitignore(path: &Path) -> CliResult<()> {
    let in_zynk_dir = path
        .parent()
        .and_then(|parent| parent.file_name())
        .and_then(|name| name.to_str())
        == Some(".zynk");
    if !in_zynk_dir {
        return Ok(());
    }
    let Some(dir) = path.parent() else {
        return Ok(());
    };
    fs::create_dir_all(dir).map_err(|error| {
        CliError::failure(format!("failed to create {}: {error}", dir.display()))
    })?;
    let gitignore = dir.join(".gitignore");
    let has_star = |content: &str| content.lines().any(|line| line.trim() == "*");
    // ADR 028 R2 P4: this is FALLIBLE and the success condition is "a `*` rule is
    // actually present" — never claim self-ignore without proof, so the caller can
    // refuse to create/use the DB when protection can't be guaranteed.
    match fs::read_to_string(&gitignore) {
        Ok(content) if has_star(&content) => return Ok(()),
        Ok(content) => {
            // P1: append `*`, preserving existing content.
            let mut updated = content;
            if !updated.is_empty() && !updated.ends_with('\n') {
                updated.push('\n');
            }
            updated.push_str("*\n");
            fs::write(&gitignore, updated).map_err(|error| {
                CliError::failure(format!("failed to update {}: {error}", gitignore.display()))
            })?;
        }
        Err(_) => {
            // Missing or unreadable (e.g. `.gitignore` is itself a directory).
            fs::write(&gitignore, "*\n").map_err(|error| {
                CliError::failure(format!(
                    "failed to write {} (is it a directory?): {error}",
                    gitignore.display()
                ))
            })?;
        }
    }
    let final_content = fs::read_to_string(&gitignore).map_err(|error| {
        CliError::failure(format!("failed to verify {}: {error}", gitignore.display()))
    })?;
    if has_star(&final_content) {
        Ok(())
    } else {
        Err(CliError::failure(format!(
            "could not ensure a `*` rule in {}",
            gitignore.display()
        )))
    }
}

/// Open the projection DB, auto-creating + migrating it. Ensures the path-keyed
/// `.zynk/.gitignore` and, only on first creation of a `.zynk` DB, prints a
/// one-time notice. An explicit `--db` outside `.zynk/` is the user's path.
fn open_projection_database(path: &Path) -> CliResult<Connection> {
    let existed = path.exists();
    ensure_zynk_gitignore(path)?;
    let connection = open_database(path)?;
    let in_zynk_dir = path
        .parent()
        .and_then(|parent| parent.file_name())
        .and_then(|name| name.to_str())
        == Some(".zynk");
    if !existed && in_zynk_dir {
        eprintln!(
            "note: created {} for live state (+ .zynk/.gitignore); pass --no-db for file-only",
            path.display()
        );
    }
    Ok(connection)
}

/// Project a status write into the live DB (open + migrate + IMMEDIATE tx).
/// The status file remains the durable record; this keeps the DB current.
pub(crate) fn project_status(
    db_path: &Path,
    root: &Path,
    status: &ImportedStatus,
) -> CliResult<()> {
    let mut connection = open_projection_database(db_path)?;
    let transaction = connection
        .transaction_with_behavior(TransactionBehavior::Immediate)
        .map_err(|error| {
            CliError::failure(format!("failed to start status projection: {error}"))
        })?;
    project_live_status(&transaction, root, status)?;
    transaction.commit().map_err(|error| {
        CliError::failure(format!("failed to commit status projection: {error}"))
    })?;
    Ok(())
}

/// Live status projection: a status write OWNS the session's current state, so
/// UPSERT it (unlike import's INSERT OR IGNORE) and append the status event.
fn project_live_status(
    transaction: &Transaction<'_>,
    root: &Path,
    status: &ImportedStatus,
) -> CliResult<()> {
    let project_id = import_project_id(root);
    ensure_project(transaction, &project_id, root, &status.last_update)?;
    if status.lead_agent != "unknown" {
        ensure_agent(transaction, &status.lead_agent, &status.last_update)?;
    }
    transaction
        .execute(
            "INSERT INTO sessions (
                session_id, project_id, title, phase, mode, workflow_status,
                lead_agent_id, artifact_ref, created_at, updated_at
             )
             VALUES (?1, ?2, ?1, ?3, ?4, ?5, ?6, ?7, ?8, ?8)
             ON CONFLICT(session_id) DO UPDATE SET
                phase = excluded.phase,
                mode = excluded.mode,
                workflow_status = excluded.workflow_status,
                lead_agent_id = excluded.lead_agent_id,
                artifact_ref = excluded.artifact_ref,
                updated_at = excluded.updated_at",
            params![
                status.session_id,
                project_id,
                status.phase,
                status.mode,
                status.workflow_status,
                nullable_unknown(&status.lead_agent),
                status.artifact_ref,
                status.last_update,
            ],
        )
        .map_err(|error| CliError::failure(format!("failed to project session: {error}")))?;
    insert_status_event_if_missing(transaction, status)?;
    Ok(())
}

/// Outcome of projecting one audit record into the live DB (ADR 027 C6).
#[derive(Debug, PartialEq)]
pub(crate) enum LiveAuditProjection {
    Projected,
    AlreadyPresent,
    /// `previous_audit_id` is missing in the DB, or the insert otherwise
    /// conflicts (e.g. one-child-per-previous). The file is authoritative; we
    /// never live-rebase — `db import` reconciles the chain later.
    Gap {
        reason: String,
    },
}

/// Project an audit write into the live DB (open + migrate + IMMEDIATE tx).
pub(crate) fn project_audit(
    db_path: &Path,
    root: &Path,
    record: &ImportedAuditRecord,
) -> CliResult<LiveAuditProjection> {
    let mut connection = open_projection_database(db_path)?;
    let transaction = connection
        .transaction_with_behavior(TransactionBehavior::Immediate)
        .map_err(|error| CliError::failure(format!("failed to start audit projection: {error}")))?;
    // ADR 036 D7 (trackbrc1 P1a): the generic `zynk audit` / audited-send path has no
    // pre-parsed Overlay; when the record IS a participant-overlay the choke point parses it
    // from the payload and inserts the typed row in this tx (or fails loud — never an orphan).
    let outcome = project_live_audit_record(&transaction, root, record, None)?;
    transaction.commit().map_err(|error| {
        CliError::failure(format!("failed to commit audit projection: {error}"))
    })?;
    Ok(outcome)
}

/// v1 M2a R1 P1 / R2 P4: rebuild the typed `operator_decisions` row from an imported
/// decision audit, in the caller's import transaction (atomic with the audit row). The
/// ADR 027 file-first recovery path: a `decide --no-db` (or a default-projection
/// soft-degrade) leaves a durable decision audit but NO typed row; `db import outputs`
/// re-derives the audit row and must also reconstruct the typed query/effect surface —
/// the same class as the M1 work.md import gap.
///
/// R2 P4: this runs AFTER the work.md import (the caller defers it), so a fully-file-first
/// gate/conflict finds its `work_events` row already in the transaction. For a bound
/// gate/conflict the `--ref` is re-validated against the IN-TRANSACTION `work_events`
/// (`decide --no-db` had no DB to check it at write time): query the `transaction`
/// DIRECTLY — NOT `work_event_kind`, which opens a separate connection that cannot see the
/// uncommitted work rows. A missing ref or a kind mismatch (gate↔"gate", conflict↔"conflict")
/// is a warn+skip of the typed row, never an FK abort of the whole import.
///
/// Only decision record_types (`DECISION_RECORD_TYPES`) are decisions; for everything else
/// this is a no-op (`Ok(None)`). The full serde_norway `Decision` lives in the record's
/// `payload_excerpt` (the `decide` path writes `payload_redaction_policy=full`, so the
/// importer — with the P1 multi-line parser fix — carries it untruncated). On a missing or
/// undeserializable payload (e.g. a redacted/hand-edited/truncated artifact), a payload that
/// fails `validate()`, or a dangling/wrong-kind ref, this returns `Ok(Some(warning))`: the
/// caller warns and CONTINUES — it never fails the whole import and never inserts a garbage
/// row (fail-loud-consistent with the audit/work import skip discipline). A genuine DB error
/// from the typed insert propagates as `Err` so the import transaction rolls back.
/// `insert_operator_decision` uses INSERT OR IGNORE, so a re-import (or
/// accept-then-already-present) stays a clean no-op.
fn rebuild_imported_operator_decision(
    transaction: &Transaction<'_>,
    session_id: &str,
    record: &ImportedAuditRecord,
) -> CliResult<Option<String>> {
    use crate::decision::Decision;
    if !crate::decision::DECISION_RECORD_TYPES.contains(&record.record_type.as_str()) {
        return Ok(None);
    }
    let Some(payload) = record.payload_excerpt.as_deref() else {
        return Ok(Some(format!(
            "skipped operator_decisions rebuild for audit_id {}: no decision payload in artifact",
            record.audit_id
        )));
    };
    let decision = match Decision::from_storage(payload) {
        Ok(decision) => decision,
        Err(error) => {
            return Ok(Some(format!(
                "skipped operator_decisions rebuild for audit_id {}: {}",
                record.audit_id, error.message
            )));
        }
    };
    if let Err(error) = decision.validate() {
        return Ok(Some(format!(
            "skipped operator_decisions rebuild for audit_id {}: {}",
            record.audit_id, error.message
        )));
    }
    // For a bound gate/conflict, re-validate the ref against the in-transaction
    // work_events (the `decide --no-db` write path could not). Query the transaction
    // directly so it sees the work rows just imported above.
    let expected_kind = match &decision {
        Decision::Gate { .. } => Some("gate"),
        Decision::Conflict { .. } => Some("conflict"),
        Decision::Mode { .. } | Decision::Interrupt { .. } | Decision::Redirect { .. } => None,
    };
    if let (Some(expected_kind), Some(wid)) = (expected_kind, decision.target_work_event_id()) {
        let actual_kind: Option<String> = transaction
            .query_row(
                "SELECT kind FROM work_events WHERE work_event_id = ?1 AND session_id = ?2",
                params![wid, session_id],
                |row| row.get(0),
            )
            .optional()
            .map_err(|error| {
                CliError::failure(format!("failed to read work_event kind on import: {error}"))
            })?;
        match actual_kind.as_deref() {
            Some(kind) if kind == expected_kind => {}
            Some(other) => {
                return Ok(Some(format!(
                    "skipped operator_decisions rebuild for audit_id {}: --ref {wid} is a \
                     {other} work-event, not a {expected_kind}, in session",
                    record.audit_id
                )));
            }
            None => {
                return Ok(Some(format!(
                    "skipped operator_decisions rebuild for audit_id {}: --ref {wid} missing \
                     in session",
                    record.audit_id
                )));
            }
        }
    }
    insert_operator_decision(transaction, record, &decision)?;
    Ok(None)
}

/// Project an operator decision (ADR 033 D4 / M2a): the immutable audit proof row
/// AND the typed `operator_decisions` projection in ONE immediate transaction, so
/// the proof and the typed surface never diverge (they commit together or roll
/// back together). Mirrors `project_audit` but adds the decision insert. The audit
/// row keeps its file-rendered identity — `project_live_audit_record` never
/// live-rebases (ADR 027 C6). Because the audit row is inserted first in the same
/// transaction, the `operator_decisions.audit_id` FK is satisfied.
///
/// T4 (T3-review hardening): if the audit row GAPS (non-canonical timestamp, a
/// missing/conflicting `previous_audit_id`), `project_live_audit_record` returns
/// `Gap` WITHOUT inserting the row, so the typed insert below would otherwise hit
/// an opaque "FOREIGN KEY constraint failed" on `operator_decisions.audit_id`.
/// Capture the projection outcome and fail loud with the gap REASON before the
/// typed insert (the transaction is dropped → rolled back; no decision row leaks).
/// The normal `decide` path pins `previous_audit_id=None` + a canonical timestamp,
/// so it projects cleanly — this guard is for the edge.
pub(crate) fn project_decision(
    db_path: &Path,
    root: &Path,
    record: &ImportedAuditRecord,
    decision: &crate::decision::Decision,
) -> CliResult<()> {
    let mut connection = open_projection_database(db_path)?;
    let transaction = connection
        .transaction_with_behavior(TransactionBehavior::Immediate)
        .map_err(|error| {
            CliError::failure(format!("failed to start decision projection: {error}"))
        })?;
    // A decision record_type is never an overlay, so the choke point's overlay branch never
    // fires here; `None` for the pre-parsed overlay is correct. The typed decision row is
    // still inserted separately below (decisions are not part of the overlay choke point).
    match project_live_audit_record(&transaction, root, record, None)? {
        LiveAuditProjection::Projected | LiveAuditProjection::AlreadyPresent => {}
        // The audit row did NOT land — inserting the typed row would FK-fail on a
        // dangling audit_id. Surface the gap reason instead (tx rolls back on drop).
        LiveAuditProjection::Gap { reason } => {
            return Err(CliError::failure(format!(
                "decision audit did not project (gap): {reason}"
            )))
        }
    }
    insert_operator_decision(&transaction, record, decision)?;
    transaction.commit().map_err(|error| {
        CliError::failure(format!("failed to commit decision projection: {error}"))
    })?;
    Ok(())
}

/// Insert the typed `operator_decisions` row keyed by the audit_id. `decision_status`
/// is always 'decided'; `notification_status` starts 'not-requested' (a later
/// `update_decision_notification` records the notify outcome, M2a T5). The variant
/// determines which of the optional columns carry a value.
fn insert_operator_decision(
    transaction: &Transaction<'_>,
    record: &ImportedAuditRecord,
    decision: &crate::decision::Decision,
) -> CliResult<()> {
    use crate::decision::Decision;
    let (verdict, resolution, mode_to, target_agent, reason, note) = match decision {
        Decision::Gate { verdict, note, .. } => {
            (Some(verdict.clone()), None, None, None, None, note.clone())
        }
        Decision::Conflict {
            resolution, note, ..
        } => (
            None,
            Some(resolution.clone()),
            None,
            None,
            None,
            note.clone(),
        ),
        Decision::Mode { mode_to } => (None, None, Some(mode_to.clone()), None, None, None),
        Decision::Interrupt { reason } => (None, None, None, None, reason.clone(), None),
        Decision::Redirect {
            target_agent,
            reason,
        } => (
            None,
            None,
            None,
            Some(target_agent.clone()),
            reason.clone(),
            None,
        ),
    };
    // `created_at` must match the canonical UTC-`Z` form the audit proof row gets in
    // `project_live_audit_record`, so the typed decision row and its proof stay
    // consistent and `ORDER BY created_at` is chronological. `record.timestamp` is
    // already validated RFC3339 upstream, so canonicalize won't be None in practice;
    // the fallback is defensive only.
    let created_at = crate::timestamp::canonicalize(&record.timestamp)
        .unwrap_or_else(|| record.timestamp.clone());
    // INSERT OR IGNORE on the audit_id PK: idempotent so a re-import (or an
    // accept-then-already-present rebuild on `db import`, v1 M2a R1 P1) never errors
    // or duplicates the typed row. The live `project_decision` path is unaffected —
    // its audit_id is always freshly minted, so the IGNORE clause never fires there.
    transaction
        .execute(
            "INSERT OR IGNORE INTO operator_decisions
                (audit_id, session_id, decision_type, target_work_event_id,
                 verdict, resolution, mode_to, target_agent, reason, note,
                 decision_status, notification_status, created_at)
             VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, 'decided', 'not-requested', ?11)",
            params![
                record.audit_id,
                record.session_id,
                decision.record_type(),
                decision.target_work_event_id(),
                verdict,
                resolution,
                mode_to,
                target_agent,
                reason,
                note,
                created_at,
            ],
        )
        .map_err(|error| {
            CliError::failure(format!("failed to insert operator_decision: {error}"))
        })?;
    Ok(())
}

/// Project a participant overlay (ADR 036 Track B / T3): the immutable audit proof
/// row AND the typed `participant_overlay` projection in ONE immediate transaction,
/// so the proof and the typed surface never diverge (they commit together or roll
/// back together). Mirrors `project_decision` — same FK-gap guard, same
/// audit-first ordering so the `participant_overlay.audit_id` FK is satisfied. The
/// audit row keeps its file-rendered identity; `project_live_audit_record` never
/// live-rebases (ADR 027 C6).
///
/// No-leak invariant (T3): an overlay proof is a control-plane record about a
/// participant, NOT a conversation message — it must never upsert a `messages` row.
/// The gate lives in `project_live_audit_record` (the DB choke point), so this path
/// inherits it; `project_overlay` itself never touches `messages`.
// Consumed by `zynk assign` (assign.rs) — the Track B overlay producer.
pub(crate) fn project_overlay(
    db_path: &Path,
    root: &Path,
    record: &ImportedAuditRecord,
    overlay: &crate::overlay::Overlay,
) -> CliResult<()> {
    let mut connection = open_projection_database(db_path)?;
    let transaction = connection
        .transaction_with_behavior(TransactionBehavior::Immediate)
        .map_err(|error| {
            CliError::failure(format!("failed to start overlay projection: {error}"))
        })?;
    // ADR 036 D7 (trackbrc1 P1a): `project_live_audit_record` is now the SINGLE typed-insert
    // site (it inserts the audit row AND the typed participant_overlay row, in this tx, when
    // we thread the pre-parsed overlay in). We MUST NOT also call `insert_participant_overlay`
    // here — that would double-insert and collide on the PK / partial-unique index. A Gap
    // means the audit row did NOT land, so there is no typed row to surface; report it.
    match project_live_audit_record(&transaction, root, record, Some(overlay))? {
        LiveAuditProjection::Projected | LiveAuditProjection::AlreadyPresent => {}
        LiveAuditProjection::Gap { reason } => {
            return Err(CliError::failure(format!(
                "overlay audit did not project (gap): {reason}"
            )))
        }
    }
    transaction.commit().map_err(|error| {
        CliError::failure(format!("failed to commit overlay projection: {error}"))
    })?;
    Ok(())
}

/// Insert the typed `participant_overlay` row keyed by the audit_id, then (if this
/// overlay supersedes a prior one) close the prior row's `superseded_by_audit_id`
/// pointer IN THE SAME transaction. The provenance columns (session_id /
/// asserter_actor_id / created_at) are taken from the proof `record` so they match
/// the audit row the D3.1 binding trigger checks against; the typed fact columns
/// (subject / overlay_kind / actor_kind|role|trait) come from the `Overlay`.
fn insert_participant_overlay(
    transaction: &Transaction<'_>,
    record: &ImportedAuditRecord,
    overlay: &crate::overlay::Overlay,
) -> CliResult<()> {
    use crate::overlay::Overlay;
    // The producer always sets source_agent_id for an overlay (it IS the asserter).
    // Fail loud early on a missing asserter rather than inserting a NULL — the D3.1
    // binding trigger would also abort, but a clear message here is better.
    let asserter_actor_id = record.source_agent_id.as_deref().ok_or_else(|| {
        CliError::failure(format!(
            "overlay proof {} has no source_agent_id (asserter) — cannot project a typed row",
            record.audit_id
        ))
    })?;
    // Per-variant typed columns: exactly one of (actor_kind) / (role_id+role_label) /
    // (trait_id+trait_value) is non-NULL, matching the table's overlay_kind CHECK. Bind
    // each column from its own match so the others stay NULL (avoids one complex tuple).
    let actor_kind: Option<&str> = match overlay {
        Overlay::ActorKind { actor_kind, .. } => Some(actor_kind.as_str()),
        _ => None,
    };
    let role_id: Option<&str> = match overlay {
        Overlay::Role { role_id, .. } => Some(role_id.as_str()),
        _ => None,
    };
    let role_label: Option<&str> = match overlay {
        Overlay::Role { role_label, .. } => Some(role_label.as_str()),
        _ => None,
    };
    let trait_id: Option<&str> = match overlay {
        Overlay::Trait { trait_id, .. } => Some(trait_id.as_str()),
        _ => None,
    };
    let trait_value: Option<i64> = match overlay {
        Overlay::Trait { value, .. } => Some(i64::from(*value)),
        _ => None,
    };
    // `created_at` must match the canonical UTC-`Z` form the proof row gets in
    // `project_live_audit_record` (the D3.1 binding trigger compares them, and D3.4
    // requires the canonical GLOB). `record.timestamp` is validated RFC3339 upstream,
    // so canonicalize won't be None in practice; the fallback is defensive only.
    let created_at = crate::timestamp::canonicalize(&record.timestamp)
        .unwrap_or_else(|| record.timestamp.clone());
    // Close the superseded row's forward pointer FIRST, then insert the new current
    // row — in the SAME transaction (atomic). Order matters: the partial-unique index
    // (`...current_*` WHERE superseded_by_audit_id IS NULL) allows only one CURRENT
    // row per slot, so the prior row must stop being current BEFORE the new current
    // row lands or the second INSERT collides. The `superseded_by_audit_id` value is
    // the new audit_id, whose FK target already landed in `project_live_audit_record`
    // above. A `supersedes` naming no row updates 0 rows — harmless.
    if let Some(prev) = overlay.supersedes() {
        // SLOT-BIND the supersede UPDATE (ADR 036 D10 MAJOR): match the predecessor by
        // audit_id AND by the SAME (session_id, subject_actor_id, overlay_kind[, trait_id])
        // slot as the NEW row. A `supersedes` that mis-points at an UNRELATED slot's
        // current row must NOT close THAT row (silent corruption when the new row's own
        // slot is empty so the partial-unique index can't catch it). trait overlays bind
        // `trait_id = ?`; actor-kind/role bind `trait_id IS NULL`.
        let affected = transaction
            .execute(
                "UPDATE participant_overlay SET superseded_by_audit_id = ?1
                 WHERE audit_id = ?2
                   AND session_id = ?3
                   AND subject_actor_id = ?4
                   AND overlay_kind = ?5
                   AND (trait_id IS ?6)",
                params![
                    record.audit_id,
                    prev,
                    record.session_id,
                    overlay.subject(),
                    overlay.overlay_kind(),
                    trait_id,
                ],
            )
            .map_err(|error| {
                CliError::failure(format!(
                    "failed to mark superseded participant_overlay: {error}"
                ))
            })?;
        // A `supersedes` that named no row in THIS slot updates 0 rows — fail loud here
        // with a CLEAR message (rather than silently ignoring it and then colliding on
        // the partial-unique index with an opaque UNIQUE error).
        if affected != 1 {
            return Err(CliError::failure(format!(
                "supersedes {prev} is not the current row of this overlay slot \
                 (session={}, subject={}, kind={}) — a mis-pointed supersede is rejected (ADR 036 D10)",
                record.session_id,
                overlay.subject(),
                overlay.overlay_kind(),
            )));
        }
    }
    transaction
        .execute(
            "INSERT INTO participant_overlay (
                audit_id, session_id, subject_actor_id, overlay_kind,
                actor_kind, role_id, role_label, trait_id, trait_value,
                asserter_actor_id, asserter_kind, supersedes_audit_id,
                superseded_by_audit_id, created_at
             )
             VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, NULL, ?13)",
            params![
                record.audit_id,
                record.session_id,
                overlay.subject(),
                overlay.overlay_kind(),
                actor_kind,
                role_id,
                role_label,
                trait_id,
                trait_value,
                asserter_actor_id,
                // FIX 3b: bind the asserter grade from the Overlay (Track B's `assign`
                // always sets "operator"; ready for Track C's "profile") instead of a
                // hardcoded literal. The CHECK constrains it to operator/profile.
                overlay.asserter_kind(),
                overlay.supersedes(),
                created_at,
            ],
        )
        .map_err(|error| {
            CliError::failure(format!("failed to insert participant_overlay: {error}"))
        })?;
    Ok(())
}

/// Record the OPTIONAL notification outcome on a durable decision row (ADR 033 D4 /
/// C4=b, M2a T5). The decision is ALREADY durable; this only updates the
/// notification columns of its `operator_decisions` row.
///
/// On `status="sent"` with a `notification_mid`, resolve the REAL sent audit the
/// audited send (ADR 029) just wrote — the row keyed by that mid with
/// `delivery_status='sent'` — and link it as `notification_audit_id`. On `failed`,
/// `notification_audit_id` stays NULL and `notification_error` carries the reason:
/// the honesty core is that a failed notify NEVER fabricates a `sent` proof and
/// NEVER writes any audit row; the failure lives on the decision row alone.
pub(crate) fn update_decision_notification(
    db_path: &Path,
    decision_audit_id: &str,
    status: &str,
    notification_mid: Option<&str>,
    notification_error: Option<&str>,
) -> CliResult<()> {
    let connection = open_projection_database(db_path)?;
    // On success, resolve the audit_id of the sent notification the audited send
    // wrote (keyed by the notification mid). Most-recent sent row by that mid wins.
    let notification_audit_id: Option<String> = match (status, notification_mid) {
        ("sent", Some(mid)) => connection
            .query_row(
                "SELECT audit_id FROM audit_records
                 WHERE mid = ?1 AND delivery_status = 'sent'
                 ORDER BY rowid DESC LIMIT 1",
                params![mid],
                |row| row.get(0),
            )
            .optional()
            .map_err(|error| {
                CliError::failure(format!("failed to resolve notification audit: {error}"))
            })?,
        _ => None,
    };
    let updated = connection
        .execute(
            "UPDATE operator_decisions
                SET notification_status = ?1,
                    notification_mid = ?2,
                    notification_audit_id = ?3,
                    notification_error = ?4
              WHERE audit_id = ?5",
            params![
                status,
                notification_mid,
                notification_audit_id,
                notification_error,
                decision_audit_id,
            ],
        )
        .map_err(|error| {
            CliError::failure(format!("failed to update decision notification: {error}"))
        })?;
    if updated == 0 {
        return Err(CliError::failure(format!(
            "no operator_decisions row for audit_id {decision_audit_id} to record notification"
        )));
    }
    Ok(())
}

/// Read a `work_event`'s kind for ref validation (gate/conflict decisions bind a
/// target work-event). Returns None when the id is absent in the session. Consumed
/// by `zynk decide` ref validation in M2a T4.
pub(crate) fn work_event_kind(
    db_path: &Path,
    session_id: &str,
    work_event_id: i64,
) -> CliResult<Option<String>> {
    let connection = open_projection_database(db_path)?;
    let kind: Option<String> = connection
        .query_row(
            "SELECT kind FROM work_events WHERE work_event_id = ?1 AND session_id = ?2",
            params![work_event_id, session_id],
            |row| row.get(0),
        )
        .optional()
        .map_err(|error| CliError::failure(format!("failed to read work_event kind: {error}")))?;
    Ok(kind)
}

/// ADR 036 Track B T4: the audit_id of the CURRENT-slot `participant_overlay` row for
/// `(session_id, subject, overlay_kind[, trait_id])` — the row whose forward pointer
/// is still open (`superseded_by_audit_id IS NULL`). A re-assign / `--unset` supersedes
/// this row; a first assignment finds none (returns None). For traits the slot is keyed
/// by `trait_id` (one current row per trait); for actor-kind/role it is keyed by
/// `overlay_kind` (one current row per kind). The producer (`zynk assign`) consults this
/// BEFORE building the `Overlay`, so the new proof's `supersedes` names the row the
/// dual-write will close in the SAME transaction.
pub(crate) fn current_overlay_audit_id(
    db_path: &Path,
    session_id: &str,
    subject: &str,
    overlay_kind: &str,
    trait_id: Option<&str>,
) -> CliResult<Option<String>> {
    // Open the projection DB (auto-create+migrate), the same way `work_event_kind`
    // opens its own connection for the pre-write ref check — so the pre-read sees the
    // overlay table even on a default DB's first use.
    let connection = open_projection_database(db_path)?;
    // Traits are slotted by trait_id (one current row per trait); actor-kind/role are
    // slotted by overlay_kind. The partial-unique indexes guarantee at most one current
    // row per slot, so LIMIT 1 is exact.
    let audit_id: Option<String> = match trait_id {
        Some(trait_id) => connection
            .query_row(
                "SELECT audit_id FROM participant_overlay
                 WHERE session_id = ?1 AND subject_actor_id = ?2
                   AND overlay_kind = 'trait' AND trait_id = ?3
                   AND superseded_by_audit_id IS NULL
                 LIMIT 1",
                params![session_id, subject, trait_id],
                |row| row.get(0),
            )
            .optional(),
        None => connection
            .query_row(
                "SELECT audit_id FROM participant_overlay
                 WHERE session_id = ?1 AND subject_actor_id = ?2
                   AND overlay_kind = ?3
                   AND superseded_by_audit_id IS NULL
                 LIMIT 1",
                params![session_id, subject, overlay_kind],
                |row| row.get(0),
            )
            .optional(),
    }
    .map_err(|error| {
        CliError::failure(format!(
            "failed to read current participant_overlay: {error}"
        ))
    })?;
    Ok(audit_id)
}

/// ADR 033 M2b T3 (C3=b): the LATEST `mode-switch` operator decision for a session —
/// `(audit timestamp, mode_to)` of the most-recent decision by `audit_records.timestamp`,
/// or `None` if the session has no mode-switch.
///
/// This exists so the current-state read can make `mode` latest-writer across BOTH
/// the agent `status_events.mode` AND an operator `mode-switch` decision's `mode_to`.
/// Provenance stays clean: the operator decision keeps living in its typed
/// `operator_decisions` table joined to its `audit_records` proof row — it is NOT
/// synthesized into a fake `status_event` (the rejected alternative, which would
/// claim a phase/next-action/workflow_status the operator never authored). ONLY
/// `mode` participates cross-source; interrupt/redirect carry no `mode_to` and are
/// excluded by the `decision_type='mode-switch'` predicate, so they never touch the
/// current-state read. Takes a borrowed `&Connection` because the dashboard read
/// already holds one.
pub(crate) fn latest_mode_decision(
    connection: &Connection,
    session_id: &str,
) -> CliResult<Option<(String, String)>> {
    connection
        .query_row(
            "SELECT a.timestamp, od.mode_to
             FROM operator_decisions AS od
             JOIN audit_records AS a ON a.audit_id = od.audit_id
             WHERE od.session_id = ?1 AND od.decision_type = 'mode-switch'
             ORDER BY a.timestamp DESC, od.audit_id DESC
             LIMIT 1",
            [session_id],
            |row| Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?)),
        )
        .optional()
        .map_err(|error| {
            CliError::failure(format!(
                "failed to read latest mode-switch decision: {error}"
            ))
        })
}

/// Project a validated work event into the live DB (ADR 033 M1). Validate before
/// any write (ADR 029 discipline — never store-bad), serialize to the typed
/// storage form, then content-dedup via INSERT OR IGNORE on the
/// UNIQUE(session_id, kind, content_hash) key so re-projecting the same event is
/// a no-op.
pub(crate) fn project_work_event(
    connection: &Connection,
    session_id: &str,
    actor: &str,
    timestamp: &str,
    seq: usize,
    payload: &crate::work_event::WorkEventPayload,
) -> CliResult<()> {
    payload.validate()?; // never store-bad (ADR 029 discipline)
    let stored = payload.to_storage()?;
    // The content hash is the EVENT IDENTITY: seq + actor + timestamp + payload (NOT
    // the payload alone). `work_events` is an event log, so two genuinely distinct
    // events must stay distinct rows. The file-rendered per-session `seq` ordinal
    // (v1 M1 R2 P4) disambiguates events that share an actor + second-precision
    // timestamp + payload — wrappers legitimately emit repeated identical
    // tool/usage/system events within one second, and those are real distinct events,
    // not a dedup. `seq` is generated before the file write and imported VERBATIM from
    // work.md, so re-projecting / re-importing the SAME block (same seq+actor+ts+
    // payload) is still an INSERT OR IGNORE no-op (idempotent). Reuses the sha256
    // convention (see `status_content_hash`).
    let content_hash = format!(
        "sha256:{:x}",
        Sha256::digest(format!("{seq}\n{actor}\n{timestamp}\n{stored}").as_bytes())
    );
    connection
        .execute(
            "INSERT OR IGNORE INTO work_events
                (session_id, actor_agent_id, kind, timestamp, payload, content_hash, created_at)
             VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?4)",
            params![
                session_id,
                actor,
                payload.kind(),
                timestamp,
                stored,
                content_hash
            ],
        )
        .map_err(|error| CliError::failure(format!("failed to project work event: {error}")))?;
    Ok(())
}

/// Identity-preserving live audit projection (ADR 027 C6): insert the
/// file-rendered `audit_id`/`previous_audit_id` VERBATIM (never DB-tail-derived,
/// which is what `db audit append` does). A missing previous or other insert
/// conflict is a projection Gap, not a live rebase — rebasing is `db import`'s
/// job. The timestamp is canonicalized for the DB exactly as import does; the
/// file keeps the raw form.
fn project_live_audit_record(
    transaction: &Transaction<'_>,
    root: &Path,
    record: &ImportedAuditRecord,
    // ADR 036 D7 (trackbrc1 P1a): the choke point is now the SINGLE typed-insert site for
    // a `participant-overlay` proof on the file-first live path. When the caller has the
    // pre-parsed `Overlay` (project_overlay), it threads it in here; otherwise (project_audit,
    // project_decision — neither of which has it) this is None and the overlay is parsed from
    // the record's `payload_excerpt`. A non-overlay record_type ignores this argument.
    overlay: Option<&crate::overlay::Overlay>,
) -> CliResult<LiveAuditProjection> {
    let canonical_ts = match crate::timestamp::canonicalize(&record.timestamp) {
        Some(value) => value,
        None => {
            return Ok(LiveAuditProjection::Gap {
                reason: format!("non-canonical timestamp {}", record.timestamp),
            })
        }
    };

    // Idempotent: re-projecting the same audit_id is a no-op.
    let exists: Option<String> = transaction
        .query_row(
            "SELECT audit_id FROM audit_records WHERE audit_id = ?1",
            [&record.audit_id],
            |row| row.get(0),
        )
        .optional()
        .map_err(|error| CliError::failure(format!("failed to read audit_records: {error}")))?;
    if exists.is_some() {
        return Ok(LiveAuditProjection::AlreadyPresent);
    }

    // Ensure project + a minimal session row so the audit FK holds even when the
    // audit is the first DB write for this session (a later status projection
    // UPSERTs the real current-state; import never overwrites it).
    let project_id = import_project_id(root);
    ensure_project(transaction, &project_id, root, &canonical_ts)?;
    ensure_session_min(transaction, &project_id, &record.session_id, &canonical_ts)?;

    let mut canonical_record = record.clone();
    canonical_record.timestamp = canonical_ts;

    match execute_imported_audit_insert(
        transaction,
        &canonical_record,
        canonical_record.previous_audit_id.as_deref(),
    ) {
        Ok(_) => {
            // V2-C1: create agents only after the record is accepted.
            ensure_record_agents(transaction, &canonical_record)?;
            // ADR 036 T3 no-leak invariant + D7 typed-row atomicity: a `participant-overlay`
            // proof is a control-plane record about a participant, NOT a conversation message —
            // it must never appear in the `messages` corpus/feed AND it must create the typed
            // `participant_overlay` row in THIS same transaction. This DB choke point is the
            // SINGLE typed-insert site for the file-first live path, so NO producer
            // (project_overlay / project_audit / project_decision) can leave an orphan proof
            // or leak an overlay into the chat. A typed-insert FAILURE (Err — incl. a trigger
            // ABORT for self-grant / non-operator-grade) PROPAGATES so the caller's transaction
            // rolls back the audit row too (no orphan). Every other record_type upserts its
            // message row as before.
            if canonical_record.record_type == crate::overlay::OVERLAY_RECORD_TYPE {
                // Use the caller's pre-parsed overlay (project_overlay) when available; else
                // parse it from the proof's payload_excerpt (project_audit's path) and validate —
                // fail loud (Err → rollback) on an absent or malformed/invalid overlay, never
                // an accepted orphan.
                let parsed;
                let overlay = match overlay {
                    Some(overlay) => overlay,
                    None => {
                        let payload = canonical_record.payload_excerpt.as_deref().ok_or_else(|| {
                            CliError::failure(format!(
                                "participant-overlay proof {} has no payload to project a typed row (ADR 036 D7)",
                                canonical_record.audit_id
                            ))
                        })?;
                        parsed = crate::overlay::Overlay::from_storage(payload)?;
                        parsed.validate()?;
                        &parsed
                    }
                };
                insert_participant_overlay(transaction, &canonical_record, overlay)?;
            } else {
                upsert_message_latest(transaction, &canonical_record)?;
            }
            Ok(LiveAuditProjection::Projected)
        }
        // No live rebase (ADR 027 C6): leave the file authoritative.
        Err(error) => Ok(LiveAuditProjection::Gap {
            reason: error.to_string(),
        }),
    }
}

/// Ensure a minimal session row exists for FK integrity. Placeholder
/// current-state is corrected by a live status projection.
fn ensure_session_min(
    transaction: &Transaction<'_>,
    project_id: &str,
    session_id: &str,
    timestamp: &str,
) -> CliResult<()> {
    transaction
        .execute(
            "INSERT OR IGNORE INTO sessions (
                session_id, project_id, title, phase, mode, workflow_status, created_at, updated_at
             )
             VALUES (?1, ?2, ?1, 'live', 'unknown', 'idle', ?3, ?3)",
            params![session_id, project_id, timestamp],
        )
        .map_err(|error| CliError::failure(format!("failed to ensure session: {error}")))?;
    Ok(())
}

/// Project a `zynk report` work event into the live DB (ADR 027/028): open the
/// projection DB the SAME way `status`/`audit` do — through
/// `open_projection_database`, so the default `.zynk/` DB auto-creates WITH its
/// self-ignoring `.zynk/.gitignore` (+ one-time notice). One immediate
/// transaction seeds the project + session FK rows (mirroring the
/// `ensure_project`/`ensure_session_min` pair import uses) before inserting the
/// validated, content-deduped work-event row.
pub(crate) fn project_report(
    db_path: &Path,
    root: &Path,
    session_id: &str,
    actor: &str,
    timestamp: &str,
    seq: usize,
    payload: &crate::work_event::WorkEventPayload,
) -> CliResult<()> {
    let mut connection = open_projection_database(db_path)?;
    let transaction = connection
        .transaction_with_behavior(TransactionBehavior::Immediate)
        .map_err(|error| {
            CliError::failure(format!("failed to start report projection: {error}"))
        })?;
    let project_id = import_project_id(root);
    ensure_project(&transaction, &project_id, root, timestamp)?;
    ensure_session_min(&transaction, &project_id, session_id, timestamp)?;
    // `project_work_event` runs on the connection; a `Transaction` derefs to it,
    // so this insert participates in the same immediate transaction. The producer-
    // computed `seq` (v1 M1 R2 P4) matches what `db import` re-derives from work.md,
    // so the live and recovery paths agree on the event identity.
    project_work_event(&transaction, session_id, actor, timestamp, seq, payload)?;
    // T4 dual-projection: an `artifact` work event ALSO upserts one row per file
    // into the `artifacts` table — in the SAME immediate transaction as the
    // work_event insert, so the two views never diverge on a partial failure.
    if let crate::work_event::WorkEventPayload::Artifact { files } = payload {
        for file in files {
            upsert_artifact(&transaction, session_id, &file.path, timestamp)?;
        }
    }
    transaction.commit().map_err(|error| {
        CliError::failure(format!("failed to commit report projection: {error}"))
    })?;
    Ok(())
}

/// T4: upsert one `artifacts` row per reported file path. The artifacts table is
/// the live "what files moved" view (UNIQUE(session_id, path)); re-reporting the
/// same path is an idempotent `updated_at` bump, not a duplicate row. Called from
/// within `project_report`'s immediate transaction so it commits atomically with
/// the `work_events` insert.
pub(crate) fn upsert_artifact(
    connection: &Connection,
    session_id: &str,
    path: &str,
    ts: &str,
) -> CliResult<()> {
    connection
        .execute(
            "INSERT INTO artifacts (session_id, kind, path, updated_at) VALUES (?1, 'file', ?2, ?3)
             ON CONFLICT(session_id, path) DO UPDATE SET updated_at=excluded.updated_at",
            params![session_id, path, ts],
        )
        .map_err(|e| CliError::failure(format!("failed to upsert artifact: {e}")))?;
    Ok(())
}

/// Upsert the message row's latest delivery state for a live audit projection
/// (ON CONFLICT updates latest_*, mirroring `db audit append`).
/// ADR 029 C6 (R1 P1): the corpus excerpt to persist for a record. The redaction
/// policy is the authority — content is stored only for `full`/`excerpt`, never
/// for `hash-only`, regardless of what a parsed/imported artifact carries.
/// Enforcing this at the corpus-write boundary closes the import-trust leak where
/// a stale/forged `payload_excerpt=` line on a hash-only record could reach the
/// live corpus.
fn corpus_payload_excerpt(record: &ImportedAuditRecord) -> Option<&str> {
    if record.payload_redaction_policy == "hash-only" {
        None
    } else {
        record.payload_excerpt.as_deref()
    }
}

fn upsert_message_latest(
    transaction: &Transaction<'_>,
    record: &ImportedAuditRecord,
) -> CliResult<()> {
    let message_id = message_id(&record.session_id, &record.mid);
    transaction
        .execute(
            "INSERT INTO messages (
                message_id, session_id, mid, source_agent_id, target_agent_id, message_type,
                mode, ref, transport, payload_redaction_policy, payload_hash,
                latest_delivery_status, latest_verified_by, latest_audit_id, timestamp,
                payload_excerpt
             )
             VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16)
             ON CONFLICT(session_id, mid) DO UPDATE SET
                source_agent_id = excluded.source_agent_id,
                target_agent_id = excluded.target_agent_id,
                message_type = excluded.message_type,
                mode = excluded.mode,
                ref = excluded.ref,
                transport = excluded.transport,
                payload_redaction_policy = excluded.payload_redaction_policy,
                payload_hash = excluded.payload_hash,
                latest_delivery_status = excluded.latest_delivery_status,
                latest_verified_by = excluded.latest_verified_by,
                latest_audit_id = excluded.latest_audit_id,
                timestamp = excluded.timestamp,
                payload_excerpt = excluded.payload_excerpt",
            params![
                message_id,
                record.session_id,
                record.mid,
                record.source_agent_id,
                record.target_agent_id,
                record.record_type,
                record.mode,
                record.r#ref,
                record.transport,
                record.payload_redaction_policy,
                record.payload_hash,
                record.delivery_status,
                record.verified_by,
                record.audit_id,
                record.timestamp,
                corpus_payload_excerpt(record),
            ],
        )
        .map_err(|error| CliError::failure(format!("failed to project message: {error}")))?;
    Ok(())
}

fn insert_import_row(
    transaction: &Transaction<'_>,
    session_dir: &Path,
    source_hash: &str,
    imported_at: &str,
    warnings: &[String],
) -> CliResult<()> {
    let warning_summary = if warnings.is_empty() {
        "none".to_string()
    } else {
        warnings.join("; ")
    };
    let result = if warnings.is_empty() {
        "imported"
    } else {
        "imported-with-warnings"
    };
    transaction
        .execute(
            "INSERT INTO imports (
                source_kind, source_path, source_hash, imported_at, result, warning_summary
             )
             VALUES ('outputs', ?1, ?2, ?3, ?4, ?5)",
            params![
                session_dir.display().to_string(),
                source_hash,
                imported_at,
                result,
                warning_summary,
            ],
        )
        .map_err(|error| CliError::failure(format!("failed to record import: {error}")))?;
    Ok(())
}

/// Normalize an explicit CLI `--timestamp` argument to canonical UTC-`Z` before
/// it reaches the DB (ADR 026 D1 / Codex V1-C1). Valid RFC3339 offsets are
/// converted; invalid input fails cleanly here rather than as a trigger abort.
fn normalize_arg_timestamp(value: &str) -> CliResult<String> {
    crate::timestamp::canonicalize(value).ok_or_else(|| {
        CliError::usage(format!(
            "--timestamp must be RFC3339 (e.g. 2026-05-29T02:00:00Z): {value}"
        ))
    })
}

fn append_audit_record(path: &Path, args: &DbAuditAppendArgs) -> CliResult<String> {
    if args.payload.is_some() == args.payload_file.is_some() {
        return Err(CliError::usage(
            "exactly one of --payload or --payload-file is required",
        ));
    }
    if args.excerpt_chars < 1 {
        return Err(CliError::usage("--excerpt-chars must be >= 1"));
    }
    if !matches!(
        args.payload_redaction_policy.as_str(),
        "hash-only" | "excerpt" | "full"
    ) {
        return Err(CliError::usage(format!(
            "invalid redaction policy: {}",
            args.payload_redaction_policy
        )));
    }
    if !matches!(
        args.delivery_status.as_str(),
        "drafted" | "sent" | "observed" | "failed" | "unknown"
    ) {
        return Err(CliError::usage(format!(
            "invalid delivery status: {}",
            args.delivery_status
        )));
    }
    // ADR 024 §1a / ADR 034 D8 (v1 M3a R3 P4): `db audit append` is a SEPARATE audit
    // producer from `zynk audit` (it never calls `validate_audit_args`), so it needs
    // its OWN §1a guard. A non-transport operator proof — any decision record_type or
    // `reveal` — is observed/operator, never a delivered message. Fail fast with a
    // clear message; the v9 BEFORE INSERT trigger is the authoritative backstop for
    // producers that bypass this CLI path (import / direct insert).
    if crate::decision::is_non_transport_proof_record_type(&args.record_type)
        && args.delivery_status == "sent"
    {
        return Err(CliError::usage(
            "a non-transport operator proof (a decision record_type, `reveal`, or `participant-overlay`) must not be delivery_status=sent (ADR 024 §1a / ADR 034 D8 / ADR 036: an observed/operator event, not a delivered message)",
        ));
    }

    let timestamp = normalize_arg_timestamp(&args.timestamp)?;
    let payload = payload_from_args(args)?;
    let payload_bytes = payload.as_bytes();
    let payload_hash = format!("sha256:{:x}", Sha256::digest(payload_bytes));
    let payload_excerpt =
        payload_excerpt(&payload, args.excerpt_chars, &args.payload_redaction_policy);
    let message_id = message_id(&args.session_id, &args.mid);
    let mut connection = open_database(path)?;
    let transaction = connection
        .transaction_with_behavior(TransactionBehavior::Immediate)
        .map_err(|error| {
            CliError::failure(format!("failed to start SQLite audit transaction: {error}"))
        })?;
    let previous_audit_id = tail_audit_id(&transaction, &args.session_id)?;
    let audit_id = match &args.audit_id {
        Some(audit_id) => audit_id.clone(),
        None => generate_audit_id(&transaction)?,
    };

    transaction
        .execute(
            "INSERT INTO audit_records (
                audit_id, previous_audit_id, session_id, source_agent_id, target_agent_id,
                source_address, target_address, transport, workspace_id, mid, record_type,
                command_origin, mode, ref, re, payload_hash, payload_redaction_policy,
                content_size, delivery_status, observed_by, verified_by, timestamp
             )
             VALUES (
                ?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11,
                ?12, ?13, ?14, ?15, ?16, ?17, ?18, ?19, ?20, ?21, ?22
             )",
            params![
                audit_id,
                previous_audit_id,
                args.session_id,
                args.source_agent_id,
                args.target_agent_id,
                args.source_address,
                args.target_address,
                args.transport,
                args.workspace_id,
                args.mid,
                args.record_type,
                args.command_origin,
                args.mode,
                args.r#ref,
                args.re,
                payload_hash,
                args.payload_redaction_policy,
                payload_bytes.len() as i64,
                args.delivery_status,
                args.observed_by,
                args.verified_by,
                timestamp,
            ],
        )
        .map_err(|error| CliError::failure(format!("failed to append audit record: {error}")))?;

    // ADR 036 D7 (BLOCKER): `db audit append` is its OWN audit producer (it never calls
    // `project_overlay`). A `participant-overlay` proof is a control-plane record ABOUT a
    // participant, NOT a conversation message — so it must NOT upsert a `messages` row
    // (mirror the gate at project_live_audit_record / the import path) AND it must be
    // ROUTED through the typed projection (a typed `participant_overlay` row inserted in
    // THIS same transaction, so the no-self-grant / operator-grade / provenance triggers
    // FIRE — a bad overlay rolls back the WHOLE append atomically, never an accepted
    // orphan, never a feed leak). Every other record_type upserts its message row as before.
    if args.record_type == crate::overlay::OVERLAY_RECORD_TYPE {
        // Parse + validate the proof payload into a typed Overlay. Fail loud (REJECT the
        // append) if it is absent or not a valid Overlay — never an orphan proof.
        let overlay = crate::overlay::Overlay::from_storage(&payload)?;
        overlay.validate()?;
        // Mirror the audit row we just inserted so the D3.1 provenance-binding trigger
        // (session_id / asserter_actor_id / created_at) matches: the asserter is the
        // proof's source_agent_id; created_at is the NORMALIZED canonical timestamp the
        // audit row carries; `payload_excerpt` carries the overlay storage form (unused
        // by insert_participant_overlay, but kept consistent). `supersedes` is resolved
        // from the Overlay payload (overlay.supersedes()) inside insert_participant_overlay.
        let overlay_record = ImportedAuditRecord {
            audit_id: audit_id.clone(),
            previous_audit_id: previous_audit_id.clone(),
            timestamp: timestamp.clone(),
            source_agent_id: args.source_agent_id.clone(),
            source_address: args.source_address.clone(),
            target_agent_id: args.target_agent_id.clone(),
            target_address: args.target_address.clone(),
            transport: args.transport.clone(),
            workspace_id: args.workspace_id.clone(),
            session_id: args.session_id.clone(),
            mid: args.mid.clone(),
            record_type: args.record_type.clone(),
            command_origin: args.command_origin.clone(),
            mode: args.mode.clone(),
            r#ref: args.r#ref.clone(),
            re: args.re.clone(),
            payload_hash: payload_hash.clone(),
            payload_redaction_policy: args.payload_redaction_policy.clone(),
            content_size: payload_bytes.len() as i64,
            delivery_status: args.delivery_status.clone(),
            observed_by: args.observed_by.clone(),
            verified_by: args.verified_by.clone(),
            due: None,
            payload_excerpt: Some(payload.clone()),
        };
        insert_participant_overlay(&transaction, &overlay_record, &overlay)?;
    } else {
        transaction
            .execute(
                "INSERT INTO messages (
                message_id, session_id, mid, source_agent_id, target_agent_id, message_type,
                mode, ref, transport, transport_thread_id, payload_redaction_policy,
                payload_excerpt, payload_hash, latest_delivery_status, latest_verified_by,
                latest_audit_id, timestamp
             )
             VALUES (
                ?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17
             )
             ON CONFLICT(session_id, mid) DO UPDATE SET
                source_agent_id = excluded.source_agent_id,
                target_agent_id = excluded.target_agent_id,
                message_type = excluded.message_type,
                mode = excluded.mode,
                ref = excluded.ref,
                transport = excluded.transport,
                transport_thread_id = excluded.transport_thread_id,
                payload_redaction_policy = excluded.payload_redaction_policy,
                payload_excerpt = excluded.payload_excerpt,
                payload_hash = excluded.payload_hash,
                latest_delivery_status = excluded.latest_delivery_status,
                latest_verified_by = excluded.latest_verified_by,
                latest_audit_id = excluded.latest_audit_id,
                timestamp = excluded.timestamp",
                params![
                    message_id,
                    args.session_id,
                    args.mid,
                    args.source_agent_id,
                    args.target_agent_id,
                    args.record_type,
                    args.mode,
                    args.r#ref,
                    args.transport,
                    args.transport_thread_id,
                    args.payload_redaction_policy,
                    payload_excerpt,
                    payload_hash,
                    args.delivery_status,
                    args.verified_by,
                    audit_id,
                    timestamp,
                ],
            )
            .map_err(|error| {
                CliError::failure(format!("failed to update message state: {error}"))
            })?;
    }

    transaction.commit().map_err(|error| {
        CliError::failure(format!("failed to commit audit transaction: {error}"))
    })?;
    Ok(audit_id)
}

fn payload_from_args(args: &DbAuditAppendArgs) -> CliResult<String> {
    if let Some(path) = &args.payload_file {
        let mut payload = String::new();
        fs::File::open(path)
            .and_then(|mut file| file.read_to_string(&mut payload))
            .map_err(|error| {
                CliError::failure(format!(
                    "failed to read payload file {}: {error}",
                    path.display()
                ))
            })?;
        return Ok(payload);
    }
    Ok(args.payload.clone().unwrap_or_default())
}

fn payload_excerpt(payload: &str, chars: usize, policy: &str) -> Option<String> {
    match policy {
        "hash-only" => None,
        "full" => Some(payload.to_string()),
        _ => {
            let count = payload.chars().count();
            if count <= chars * 2 {
                Some(payload.to_string())
            } else {
                let start = payload.chars().take(chars).collect::<String>();
                let end = payload
                    .chars()
                    .rev()
                    .take(chars)
                    .collect::<String>()
                    .chars()
                    .rev()
                    .collect::<String>();
                Some(format!("{start}...{end}"))
            }
        }
    }
}

fn tail_audit_id(transaction: &Transaction<'_>, session_id: &str) -> CliResult<Option<String>> {
    transaction
        .query_row(
            "SELECT record.audit_id
             FROM audit_records AS record
             WHERE record.session_id = ?1
               AND NOT EXISTS (
                 SELECT 1
                 FROM audit_records AS child
                 WHERE child.session_id = record.session_id
                   AND child.previous_audit_id = record.audit_id
               )
             ORDER BY record.timestamp DESC, record.audit_id DESC
             LIMIT 1",
            [session_id],
            |row| row.get(0),
        )
        .optional()
        .map_err(|error| CliError::failure(format!("failed to read audit chain tail: {error}")))
}

fn generate_audit_id(transaction: &Transaction<'_>) -> CliResult<String> {
    let mut statement = transaction
        .prepare("SELECT audit_id FROM audit_records")
        .map_err(|error| CliError::failure(format!("failed to read audit ids: {error}")))?;
    let existing_ids = statement
        .query_map([], |row| row.get::<_, String>(0))
        .map_err(|error| CliError::failure(format!("failed to read audit ids: {error}")))?
        .collect::<Result<HashSet<_>, _>>()
        .map_err(|error| CliError::failure(format!("failed to read audit ids: {error}")))?;

    const ALPHABET: &[u8] = b"abcdefghijklmnopqrstuvwxyz0123456789";
    let mut rng = OsRng;
    for _ in 0..100 {
        let audit_id = (0..6)
            .map(|_| {
                let index = rng.gen_range(0..ALPHABET.len());
                ALPHABET[index] as char
            })
            .collect::<String>();
        if !existing_ids.contains(&audit_id) {
            return Ok(audit_id);
        }
    }
    Err(CliError::usage(
        "could not generate unique audit_id after 100 attempts",
    ))
}

fn message_id(session_id: &str, mid: &str) -> String {
    let digest = Sha256::digest(format!("{session_id}\0{mid}").as_bytes());
    format!("msg-{digest:x}")
}

fn import_project_id(root: &Path) -> String {
    let digest = Sha256::digest(root.display().to_string().as_bytes());
    let hex = format!("{digest:x}");
    format!("project-{}", &hex[..16])
}

fn source_hash_for_session_dir(session_dir: &Path) -> CliResult<String> {
    let mut hasher = Sha256::new();
    for file_name in ["status.md", "audit.md", "summary.md"] {
        let path = session_dir.join(file_name);
        if path.exists() {
            hasher.update(file_name.as_bytes());
            let content = fs::read(&path).map_err(|error| {
                CliError::failure(format!("failed to read {}: {error}", path.display()))
            })?;
            hasher.update(content);
        }
    }
    Ok(format!("sha256:{:x}", hasher.finalize()))
}

fn value_or(values: &BTreeMap<String, String>, key: &str, fallback: &str) -> String {
    values
        .get(key)
        .filter(|value| !value.is_empty())
        .cloned()
        .unwrap_or_else(|| fallback.to_string())
}

fn optional_text(value: &str) -> Option<String> {
    if value.is_empty() || value == "unknown" {
        None
    } else {
        Some(value.to_string())
    }
}

fn optional_audit_id(value: &str) -> Option<String> {
    if matches!(value, "" | "none" | "unknown") {
        None
    } else {
        Some(value.to_string())
    }
}

fn nullable_unknown(value: &str) -> Option<String> {
    if value.is_empty() || value == "unknown" {
        None
    } else {
        Some(value.to_string())
    }
}

fn table_has_column(connection: &Connection, table: &str, column: &str) -> CliResult<bool> {
    let mut statement = connection
        .prepare(&format!("PRAGMA table_info({table})"))
        .map_err(|error| {
            CliError::failure(format!("failed to inspect SQLite table {table}: {error}"))
        })?;
    let columns = statement
        .query_map([], |row| row.get::<_, String>(1))
        .map_err(|error| {
            CliError::failure(format!("failed to inspect SQLite table {table}: {error}"))
        })?
        .collect::<Result<Vec<_>, _>>()
        .map_err(|error| {
            CliError::failure(format!("failed to inspect SQLite table {table}: {error}"))
        })?;
    Ok(columns.iter().any(|name| name == column))
}

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

    // Build a v3-state database (pre-content_hash) the way a v0.2.0 binary would.
    fn open_v3(connection: &Connection) {
        create_schema_migrations(connection).unwrap();
        apply_v1(connection).unwrap();
        apply_v2(connection).unwrap();
        apply_v3(connection).unwrap();
        connection.pragma_update(None, "user_version", 3).unwrap();
    }

    // ADR 033 M1: a freshly opened DB is at schema v6 with a work_events table,
    // and project_work_event inserts a row that reads back as the typed payload.
    #[test]
    fn v6_work_events_insert_and_read() {
        let dir = tempfile::tempdir().unwrap();
        let db = dir.path().join("z.db");
        let conn = open_database(&db).unwrap();
        // seed a session row (FK). Timestamps must be canonical RFC3339 UTC-Z to
        // satisfy the v4 sessions_ts_canonical trigger.
        let ts = "2026-05-31T00:00:00Z";
        conn.execute(
            "INSERT INTO projects (project_id,name,root_path,created_at,updated_at) VALUES ('p','p','/tmp',?1,?1)",
            params![ts],
        )
        .unwrap();
        conn.execute(
            "INSERT INTO sessions (session_id,project_id,title,phase,mode,workflow_status,created_at,updated_at) VALUES ('s1','p','s1','live','unknown','idle',?1,?1)",
            params![ts],
        )
        .unwrap();
        let payload = crate::work_event::WorkEventPayload::Think {
            text: "weighing options".into(),
        };
        project_work_event(&conn, "s1", "claude", "2026-05-31T00:00:00Z", 0, &payload).unwrap();
        let (kind, stored): (String, String) = conn
            .query_row(
                "SELECT kind, payload FROM work_events WHERE session_id='s1'",
                [],
                |r| Ok((r.get(0)?, r.get(1)?)),
            )
            .unwrap();
        assert_eq!(kind, "think");
        assert_eq!(
            crate::work_event::WorkEventPayload::from_storage(&stored).unwrap(),
            payload
        );
    }

    // ADR 026 C5: a legacy status_events row predating content_hash must be
    // backfilled by apply_v4 with the same hash the import path computes, so a
    // later re-import dedups instead of inserting a duplicate.
    #[test]
    fn v4_backfills_content_hash_for_legacy_status_event() {
        let connection = Connection::open_in_memory().unwrap();
        open_v3(&connection);
        connection
            .execute(
                "INSERT INTO projects (project_id, name, root_path, created_at, updated_at)
                 VALUES ('p', 'p', '/p', '2026-05-29T00:00:00Z', '2026-05-29T00:00:00Z')",
                [],
            )
            .unwrap();
        connection
            .execute(
                "INSERT INTO sessions (session_id, project_id, title, phase, mode, workflow_status, created_at, updated_at)
                 VALUES ('s', 'p', 's', 'tooling', 'review', 'working', '2026-05-29T00:00:00Z', '2026-05-29T00:00:00Z')",
                [],
            )
            .unwrap();
        // v3 status_events has no content_hash column yet.
        connection
            .execute(
                "INSERT INTO status_events (session_id, timestamp, phase, mode, workflow_status,
                    completed_since_last_update, in_progress, next_action, blockers,
                    asks_for_zevs, risk_or_residual_uncertainty, expected_wait, event_text)
                 VALUES ('s', '2026-05-29T01:00:00Z', 'tooling', 'review', 'working',
                    'c', 'p', 'next-A', 'none', 'none', 'none', 'unknown', 'event one')",
                [],
            )
            .unwrap();

        apply_v4(&connection).unwrap();

        let stored: String = connection
            .query_row(
                "SELECT content_hash FROM status_events WHERE session_id='s'",
                [],
                |row| row.get(0),
            )
            .unwrap();
        let expected = status_content_hash(&[
            "tooling",
            "review",
            "working",
            "c",
            "p",
            "next-A",
            "none",
            "none",
            "none",
            "unknown",
            "event one",
        ]);
        assert_eq!(
            stored, expected,
            "legacy row must be backfilled with the canonical hash"
        );
        assert!(stored.starts_with("sha256:"));
    }

    // ADR 026 C3: scan counts pre-existing non-canonical timestamps so migrate()
    // can warn. Rows inserted before the v4 triggers exist can be non-canonical.
    #[test]
    fn noncanonical_scan_counts_legacy_offset_rows() {
        let connection = Connection::open_in_memory().unwrap();
        open_v3(&connection);
        connection
            .execute(
                "INSERT INTO projects (project_id, name, root_path, created_at, updated_at)
                 VALUES ('p', 'p', '/p', '2026-05-29T00:00:00Z', '2026-05-29T00:00:00Z')",
                [],
            )
            .unwrap();
        // sessions.updated_at carries a legacy offset form (pre-v4, no trigger).
        connection
            .execute(
                "INSERT INTO sessions (session_id, project_id, title, phase, mode, workflow_status, created_at, updated_at)
                 VALUES ('s', 'p', 's', 'x', 'review', 'working', '2026-05-29T00:00:00Z', '2026-05-28T18:00:00+07:00')",
                [],
            )
            .unwrap();
        assert_eq!(noncanonical_timestamp_count(&connection).unwrap(), 1);

        apply_v4(&connection).unwrap();
        // apply_v4 does not rewrite existing rows, so the legacy row is still counted.
        assert_eq!(noncanonical_timestamp_count(&connection).unwrap(), 1);
    }

    // ADR 026 C5 / Codex V1-C2: the full migrated path — a v3 legacy row with
    // content_hash='' is backfilled by v4, and a re-import of the SAME content
    // must dedup (not duplicate) because backfill and import share the helper.
    #[test]
    fn migrated_legacy_status_row_dedups_on_reimport() {
        let mut connection = Connection::open_in_memory().unwrap();
        open_v3(&connection);
        connection
            .execute(
                "INSERT INTO projects (project_id, name, root_path, created_at, updated_at)
                 VALUES ('p', 'p', '/p', '2026-05-29T00:00:00Z', '2026-05-29T00:00:00Z')",
                [],
            )
            .unwrap();
        connection
            .execute(
                "INSERT INTO sessions (session_id, project_id, title, phase, mode, workflow_status, created_at, updated_at)
                 VALUES ('s', 'p', 's', 'tooling', 'review', 'working', '2026-05-29T00:00:00Z', '2026-05-29T00:00:00Z')",
                [],
            )
            .unwrap();
        // legacy v3 row: content_hash column does not exist yet
        connection
            .execute(
                "INSERT INTO status_events (session_id, timestamp, phase, mode, workflow_status,
                    completed_since_last_update, in_progress, next_action, blockers,
                    asks_for_zevs, risk_or_residual_uncertainty, expected_wait, event_text)
                 VALUES ('s', '2026-05-29T01:00:00Z', 'tooling', 'review', 'working',
                    'c', 'p', 'next-A', 'none', 'none', 'none', 'unknown', 'event one')",
                [],
            )
            .unwrap();

        apply_v4(&connection).unwrap();

        // Re-import the identical content through the importer dedup path.
        let status = ImportedStatus {
            session_id: "s".to_string(),
            last_update: "2026-05-29T01:00:00Z".to_string(),
            lead_agent: "codex".to_string(),
            phase: "tooling".to_string(),
            mode: "review".to_string(),
            artifact_ref: "tools/x".to_string(),
            workflow_status: "working".to_string(),
            completed_since_last_update: "c".to_string(),
            in_progress: "p".to_string(),
            next_action: "next-A".to_string(),
            blockers: "none".to_string(),
            asks_for_zevs: "none".to_string(),
            risk_or_residual_uncertainty: "none".to_string(),
            expected_wait: "unknown".to_string(),
            rolling_events: vec!["event one".to_string()],
        };
        let tx = connection.transaction().unwrap();
        insert_status_event_if_missing(&tx, &status).unwrap();
        tx.commit().unwrap();

        let count: i64 = connection
            .query_row(
                "SELECT COUNT(*) FROM status_events WHERE session_id='s' AND timestamp='2026-05-29T01:00:00Z'",
                [],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(
            count, 1,
            "re-import of a backfilled legacy row must dedup, not duplicate"
        );
    }

    // ADR 026 D5 (+ Codex V2-C2): the schema CHECK enums must EXACTLY match the
    // canonical per-column value lists. Asserting the exact `col IN (...)` literal
    // (one line in the schema) catches missing values, EXTRA values, reordering,
    // and column-specific drift (a value in the wrong column's CHECK) — not just
    // presence somewhere in the table. The fragments here are the spec.
    #[test]
    fn schema_check_enums_match_canonical_values() {
        let connection = Connection::open_in_memory().unwrap();
        open_v3(&connection);
        apply_v4(&connection).unwrap();
        let table_sql = |name: &str| -> String {
            connection
                .query_row(
                    "SELECT sql FROM sqlite_master WHERE type='table' AND name=?1",
                    [name],
                    |row| row.get(0),
                )
                .unwrap()
        };
        // (table, exact CHECK IN-list fragment as it appears on one schema line)
        let expectations: &[(&str, &str)] = &[
            (
                "sessions",
                "workflow_status IN ('idle', 'working', 'blocked', 'waiting-for-operator', 'done')",
            ),
            (
                "status_events",
                "workflow_status IN ('idle', 'working', 'blocked', 'waiting-for-operator', 'done')",
            ),
            (
                "agents",
                "current_agent_status IN ('idle', 'working', 'blocked', 'done', 'unknown')",
            ),
            (
                "session_agents",
                "agent_status IN ('idle', 'working', 'blocked', 'done', 'unknown')",
            ),
            (
                "audit_records",
                "command_origin IN ('agent', 'operator', 'helper-tool', 'unknown')",
            ),
            (
                "audit_records",
                "payload_redaction_policy IN ('hash-only', 'excerpt', 'full')",
            ),
            (
                "audit_records",
                "delivery_status IN ('drafted', 'sent', 'observed', 'failed', 'unknown')",
            ),
            (
                "audit_records",
                "verified_by IN ('transport', 'agent', 'operator', 'helper-tool')",
            ),
            (
                "messages",
                "payload_redaction_policy IN ('hash-only', 'excerpt', 'full')",
            ),
            (
                "messages",
                "latest_delivery_status IN ('drafted', 'sent', 'observed', 'failed', 'unknown')",
            ),
            (
                "messages",
                "latest_verified_by IN ('transport', 'agent', 'operator', 'helper-tool')",
            ),
        ];
        for (table, fragment) in expectations {
            let sql = table_sql(table);
            assert!(
                sql.contains(fragment),
                "{table} CHECK drifted from canonical enum; expected exact fragment: {fragment}"
            );
        }
    }

    // ===== ADR 027 schema v5: audit_records.due =====

    // Build a v4-state database (pre-`due`) the way a v0.2.2 binary would.
    fn open_v4(connection: &Connection) {
        create_schema_migrations(connection).unwrap();
        apply_v1(connection).unwrap();
        apply_v2(connection).unwrap();
        apply_v3(connection).unwrap();
        apply_v4(connection).unwrap();
        connection.pragma_update(None, "user_version", 4).unwrap();
    }

    fn seed_audit_session(connection: &Connection) {
        connection
            .execute(
                "INSERT INTO projects (project_id, name, root_path, created_at, updated_at)
                 VALUES ('p', 'p', '/p', '2026-05-29T00:00:00Z', '2026-05-29T00:00:00Z')",
                [],
            )
            .unwrap();
        connection
            .execute(
                "INSERT INTO sessions (session_id, project_id, title, phase, mode, workflow_status, created_at, updated_at)
                 VALUES ('s', 'p', 's', 'x', 'review', 'working', '2026-05-29T00:00:00Z', '2026-05-29T00:00:00Z')",
                [],
            )
            .unwrap();
    }

    // Insert an audit row carrying an explicit `due` (None => SQL NULL). Requires v5.
    fn insert_audit_with_due(
        connection: &Connection,
        audit_id: &str,
        due: Option<&str>,
    ) -> rusqlite::Result<usize> {
        connection.execute(
            "INSERT INTO audit_records (audit_id, previous_audit_id, session_id, source_address,
                target_address, transport, workspace_id, mid, record_type, command_origin,
                payload_hash, payload_redaction_policy, content_size, delivery_status, observed_by,
                verified_by, timestamp, due)
             VALUES (?1, NULL, 's', 'src', 'tgt', 'herdr', 'w', ?1, 'status-update', 'agent',
                'sha256:x', 'hash-only', 0, 'observed', 'codex', 'helper-tool',
                '2026-05-29T01:00:00Z', ?2)",
            params![audit_id, due],
        )
    }

    // v5 adds the column and does not disturb existing rows (new column reads NULL).
    #[test]
    fn v5_adds_due_column_and_preserves_existing_audit_rows() {
        let connection = Connection::open_in_memory().unwrap();
        open_v4(&connection);
        seed_audit_session(&connection);
        connection
            .execute(
                "INSERT INTO audit_records (audit_id, previous_audit_id, session_id, source_address,
                    target_address, transport, workspace_id, mid, record_type, command_origin,
                    payload_hash, payload_redaction_policy, content_size, delivery_status,
                    observed_by, verified_by, timestamp)
                 VALUES ('a1', NULL, 's', 'src', 'tgt', 'herdr', 'w', 'm1', 'status-update',
                    'agent', 'sha256:x', 'hash-only', 0, 'observed', 'codex', 'helper-tool',
                    '2026-05-29T01:00:00Z')",
                [],
            )
            .unwrap();
        assert!(!table_has_column(&connection, "audit_records", "due").unwrap());

        apply_v5(&connection).unwrap();

        assert!(table_has_column(&connection, "audit_records", "due").unwrap());
        let due: Option<String> = connection
            .query_row(
                "SELECT due FROM audit_records WHERE audit_id='a1'",
                [],
                |row| row.get(0),
            )
            .unwrap();
        assert!(
            due.is_none(),
            "existing audit row must read due=NULL after v5"
        );
    }

    // The v5 shape trigger is defense-in-depth: NULL and canonical `due` are
    // accepted; a shape-violating `due` is rejected at insert.
    #[test]
    fn v5_due_shape_trigger_accepts_null_and_canonical_rejects_malformed() {
        let connection = Connection::open_in_memory().unwrap();
        open_v4(&connection);
        apply_v5(&connection).unwrap();
        seed_audit_session(&connection);

        insert_audit_with_due(&connection, "a1", None).expect("NULL due must be accepted");
        insert_audit_with_due(&connection, "a2", Some("2026-06-01T12:00:00Z"))
            .expect("canonical due must be accepted");
        assert!(
            insert_audit_with_due(&connection, "a3", Some("2026-06-01 12:00:00")).is_err(),
            "shape-violating due (no T/Z) must be rejected by the trigger"
        );
    }

    // End-to-end: migrate() advances a v4 DB to the current head (>= v5), adds the
    // v5 due column, and re-open is a no-op. The terminal version tracks
    // CURRENT_SCHEMA_VERSION (now v8 after the additive operator_decisions (v7) and
    // custody_vault (v8) migrations); the v5 behavior (due column present) is unchanged.
    #[test]
    fn migrate_advances_v4_db_to_v5_with_due_column() {
        let mut connection = Connection::open_in_memory().unwrap();
        open_v4(&connection);
        assert!(!table_has_column(&connection, "audit_records", "due").unwrap());

        migrate(&mut connection).unwrap();

        let version: i64 = connection
            .pragma_query_value(None, "user_version", |row| row.get(0))
            .unwrap();
        assert_eq!(version, CURRENT_SCHEMA_VERSION);
        assert!(table_has_column(&connection, "audit_records", "due").unwrap());

        // The v7->v8 step creates the custody_vault table; assert it exists post-migration
        // so the v4->v8 ladder's terminal step has explicit coverage (matches the
        // `v8_custody_vault_table_present` integration check).
        let custody_vault_present: i64 = connection
            .query_row(
                "SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = ?1",
                ["custody_vault"],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(
            custody_vault_present, 1,
            "custody_vault table must exist after a v4->v8 migration"
        );

        // v1 M3a R3 P4: the v8->v9 step adds the non-transport-proof sent-guard
        // trigger; assert it exists after the v4->v9 migration so an upgraded
        // legacy DB rejects forged `sent` decision/reveal rows (ADR 024 / ADR 034 D8).
        let nontransport_trigger_present: i64 = connection
            .query_row(
                "SELECT count(*) FROM sqlite_master
                 WHERE type = 'trigger' AND name = ?1",
                ["audit_records_no_sent_nontransport_proof_insert"],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(
            nontransport_trigger_present, 1,
            "audit_records_no_sent_nontransport_proof_insert trigger must exist after a v4->v9 migration"
        );

        // T9: re-running migrate at the current version is a no-op.
        migrate(&mut connection).unwrap();
        let version_again: i64 = connection
            .pragma_query_value(None, "user_version", |row| row.get(0))
            .unwrap();
        assert_eq!(version_again, CURRENT_SCHEMA_VERSION);
    }

    // ADR 027 slice 4a: a live status projection OWNS session current-state, so a
    // second write UPDATEs the session row (unlike import's INSERT OR IGNORE) and
    // appends a distinct status event.
    #[test]
    fn live_status_projection_upserts_session_current_state() {
        let mut connection = Connection::open_in_memory().unwrap();
        open_v4(&connection);
        apply_v5(&connection).unwrap();
        let root = Path::new("outputs");
        let make =
            |phase: &str, status: &str, lead: &str, artifact: &str, ts: &str| ImportedStatus {
                session_id: "s".to_string(),
                last_update: ts.to_string(),
                lead_agent: lead.to_string(),
                phase: phase.to_string(),
                mode: "build".to_string(),
                artifact_ref: artifact.to_string(),
                workflow_status: status.to_string(),
                completed_since_last_update: "c".to_string(),
                in_progress: "p".to_string(),
                next_action: "n".to_string(),
                blockers: "none".to_string(),
                asks_for_zevs: "none".to_string(),
                risk_or_residual_uncertainty: "none".to_string(),
                expected_wait: "unknown".to_string(),
                rolling_events: vec![format!("event-{phase}")],
            };
        {
            let tx = connection.transaction().unwrap();
            project_live_status(
                &tx,
                root,
                &make("p1", "working", "claude", "a1", "2026-05-29T01:00:00Z"),
            )
            .unwrap();
            tx.commit().unwrap();
        }
        {
            let tx = connection.transaction().unwrap();
            project_live_status(
                &tx,
                root,
                &make("p2", "blocked", "codex", "a2", "2026-05-29T02:00:00Z"),
            )
            .unwrap();
            tx.commit().unwrap();
        }

        let (phase, status, lead, artifact): (String, String, Option<String>, Option<String>) =
            connection
                .query_row(
                    "SELECT phase, workflow_status, lead_agent_id, artifact_ref
                     FROM sessions WHERE session_id='s'",
                    [],
                    |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?)),
                )
                .unwrap();
        assert_eq!(phase, "p2", "session phase must reflect the latest write");
        assert_eq!(status, "blocked");
        assert_eq!(lead.as_deref(), Some("codex"));
        assert_eq!(artifact.as_deref(), Some("a2"));

        let events: i64 = connection
            .query_row(
                "SELECT COUNT(*) FROM status_events WHERE session_id='s'",
                [],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(events, 2, "two distinct status writes append two events");
    }

    // v5 with foreign keys ON, matching how open_database configures a real DB —
    // required for the missing-previous FK gap to fire.
    fn open_v5(connection: &Connection) {
        open_v4(connection);
        apply_v5(connection).unwrap();
        connection
            .pragma_update(None, "foreign_keys", "ON")
            .unwrap();
    }

    fn live_audit_record(audit_id: &str, previous: Option<&str>, ts: &str) -> ImportedAuditRecord {
        ImportedAuditRecord {
            audit_id: audit_id.to_string(),
            previous_audit_id: previous.map(str::to_string),
            timestamp: ts.to_string(),
            source_agent_id: Some("claude".to_string()),
            source_address: "w-1".to_string(),
            target_agent_id: Some("codex".to_string()),
            target_address: "w-2".to_string(),
            transport: "herdr".to_string(),
            workspace_id: "w".to_string(),
            session_id: "s".to_string(),
            mid: audit_id.to_string(),
            record_type: "status-update".to_string(),
            command_origin: "agent".to_string(),
            mode: None,
            r#ref: None,
            re: None,
            payload_hash: "sha256:x".to_string(),
            payload_redaction_policy: "hash-only".to_string(),
            content_size: 0,
            delivery_status: "observed".to_string(),
            observed_by: "codex".to_string(),
            verified_by: "helper-tool".to_string(),
            due: None,
            payload_excerpt: None,
        }
    }

    fn project_one_audit(
        connection: &mut Connection,
        record: &ImportedAuditRecord,
    ) -> LiveAuditProjection {
        let tx = connection.transaction().unwrap();
        let outcome = project_live_audit_record(&tx, Path::new("outputs"), record, None).unwrap();
        tx.commit().unwrap();
        outcome
    }

    // ADR 027 C6: the live audit projection inserts the file-rendered chain
    // identity verbatim — previous is the file value, NOT DB-tail-derived.
    #[test]
    fn live_audit_projection_preserves_file_chain_identity() {
        let mut connection = Connection::open_in_memory().unwrap();
        open_v5(&connection);
        assert_eq!(
            project_one_audit(
                &mut connection,
                &live_audit_record("a1", None, "2026-05-29T01:00:00Z")
            ),
            LiveAuditProjection::Projected
        );
        assert_eq!(
            project_one_audit(
                &mut connection,
                &live_audit_record("a2", Some("a1"), "2026-05-29T02:00:00Z")
            ),
            LiveAuditProjection::Projected
        );
        let previous: Option<String> = connection
            .query_row(
                "SELECT previous_audit_id FROM audit_records WHERE audit_id='a2'",
                [],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(
            previous.as_deref(),
            Some("a1"),
            "previous must be the file value verbatim, not DB-tail-derived"
        );
    }

    // ADR 027 C6: a missing previous is a projection Gap — the record is NOT
    // inserted and NOT rebased to root. db import reconciles later.
    #[test]
    fn live_audit_projection_gap_on_missing_previous_without_rebase() {
        let mut connection = Connection::open_in_memory().unwrap();
        open_v5(&connection);
        let outcome = project_one_audit(
            &mut connection,
            &live_audit_record("a9", Some("ghost"), "2026-05-29T03:00:00Z"),
        );
        assert!(
            matches!(outcome, LiveAuditProjection::Gap { .. }),
            "missing previous must be a Gap, got {outcome:?}"
        );
        let count: i64 = connection
            .query_row(
                "SELECT COUNT(*) FROM audit_records WHERE audit_id='a9'",
                [],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(
            count, 0,
            "a gapped record must not be inserted (no live rebase)"
        );
    }

    #[test]
    fn live_audit_projection_is_idempotent_on_reprojection() {
        let mut connection = Connection::open_in_memory().unwrap();
        open_v5(&connection);
        assert_eq!(
            project_one_audit(
                &mut connection,
                &live_audit_record("a1", None, "2026-05-29T01:00:00Z")
            ),
            LiveAuditProjection::Projected
        );
        assert_eq!(
            project_one_audit(
                &mut connection,
                &live_audit_record("a1", None, "2026-05-29T01:00:00Z")
            ),
            LiveAuditProjection::AlreadyPresent
        );
        let count: i64 = connection
            .query_row(
                "SELECT COUNT(*) FROM audit_records WHERE audit_id='a1'",
                [],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(count, 1);
    }

    /// Seed a project + session + one `gate` work_event in a freshly migrated DB.
    /// The first inserted `work_events` row gets `work_event_id = 1` (INTEGER
    /// PRIMARY KEY), so the returned gate decision can reference it via FK.
    fn seed_session_and_gate_work_event(db: &Path, session_id: &str) {
        let connection = open_projection_database(db).unwrap();
        let ts = "2026-05-31T00:00:00Z";
        connection
            .execute(
                "INSERT INTO projects (project_id, name, root_path, created_at, updated_at)
                 VALUES ('p', 'p', '/tmp', ?1, ?1)",
                params![ts],
            )
            .unwrap();
        connection
            .execute(
                "INSERT INTO sessions (session_id, project_id, title, phase, mode, workflow_status, created_at, updated_at)
                 VALUES (?1, 'p', ?1, 'live', 'unknown', 'idle', ?2, ?2)",
                params![session_id, ts],
            )
            .unwrap();
        let payload = crate::work_event::WorkEventPayload::Gate {
            title: "merge?".into(),
            summary: "approve the merge".into(),
            proposer: "claude".into(),
            actions: vec!["merge".into()],
        };
        project_work_event(&connection, session_id, "claude", ts, 0, &payload).unwrap();
    }

    /// An `ImportedAuditRecord` carrying the decision conventions (ADR 033 D4):
    /// operator-originated, observed + operator-verified, transport=none, the
    /// `gate-decision` record_type, and `ref` pointing at the target work-event.
    /// `previous_audit_id: None` makes this a clean chain root (projects, not Gap).
    fn decision_audit_record_fixture(session_id: &str, audit_id: &str) -> ImportedAuditRecord {
        ImportedAuditRecord {
            audit_id: audit_id.to_string(),
            previous_audit_id: None,
            timestamp: "2026-05-31T01:00:00Z".to_string(),
            source_agent_id: Some("operator".to_string()),
            source_address: "operator".to_string(),
            target_agent_id: None,
            target_address: "none".to_string(),
            transport: "none".to_string(),
            workspace_id: "w".to_string(),
            session_id: session_id.to_string(),
            mid: audit_id.to_string(),
            record_type: "gate-decision".to_string(),
            command_origin: "operator".to_string(),
            mode: None,
            r#ref: Some("1".to_string()),
            re: None,
            payload_hash: "sha256:x".to_string(),
            payload_redaction_policy: "hash-only".to_string(),
            content_size: 0,
            delivery_status: "observed".to_string(),
            observed_by: "operator".to_string(),
            verified_by: "operator".to_string(),
            due: None,
            payload_excerpt: None,
        }
    }

    // ADR 033 D4 / M2a T3: project_decision writes the immutable audit proof row
    // AND the typed operator_decisions row in ONE immediate transaction (atomic).
    #[test]
    fn project_decision_writes_audit_and_typed_row() {
        let dir = tempfile::tempdir().unwrap();
        let db = dir.path().join("zynk.db");
        open_projection_database(&db).unwrap(); // auto-creates at CURRENT_SCHEMA_VERSION (v7)
        seed_session_and_gate_work_event(&db, "s1");
        let record = decision_audit_record_fixture("s1", "dec-aud-1");
        let decision = crate::decision::Decision::Gate {
            target_work_event_id: 1,
            verdict: "approve".into(),
            note: None,
        };
        project_decision(&db, Path::new("outputs"), &record, &decision).unwrap();

        let connection = open_database(&db).unwrap();
        let audit_rows: i64 = connection
            .query_row(
                "SELECT COUNT(*) FROM audit_records WHERE audit_id='dec-aud-1'",
                [],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(
            audit_rows, 1,
            "the decision audit proof row must be present"
        );

        let (dt, st, ns, twe, verdict): (String, String, String, i64, String) = connection
            .query_row(
                "SELECT decision_type, decision_status, notification_status,
                        target_work_event_id, verdict
                 FROM operator_decisions WHERE audit_id='dec-aud-1'",
                [],
                |row| {
                    Ok((
                        row.get(0)?,
                        row.get(1)?,
                        row.get(2)?,
                        row.get(3)?,
                        row.get(4)?,
                    ))
                },
            )
            .unwrap();
        assert_eq!(dt, "gate-decision");
        assert_eq!(st, "decided");
        assert_eq!(ns, "not-requested");
        assert_eq!(twe, 1, "the gate decision binds the target work-event");
        assert_eq!(verdict, "approve");
    }

    // ADR 033 D4 / M2a T3: the audit row and the typed row are ONE transaction. If
    // the typed insert fails (here: a dangling target_work_event_id FK), the whole
    // transaction rolls back — the audit proof row must NOT be left committed alone.
    #[test]
    fn project_decision_rolls_back_audit_row_when_typed_insert_fails() {
        let dir = tempfile::tempdir().unwrap();
        let db = dir.path().join("zynk.db");
        open_projection_database(&db).unwrap();
        // Seed session ONLY — no work_events, so target_work_event_id=1 dangles.
        let connection = open_projection_database(&db).unwrap();
        let ts = "2026-05-31T00:00:00Z";
        connection
            .execute(
                "INSERT INTO projects (project_id, name, root_path, created_at, updated_at)
                 VALUES ('p', 'p', '/tmp', ?1, ?1)",
                params![ts],
            )
            .unwrap();
        connection
            .execute(
                "INSERT INTO sessions (session_id, project_id, title, phase, mode, workflow_status, created_at, updated_at)
                 VALUES ('s1', 'p', 's1', 'live', 'unknown', 'idle', ?1, ?1)",
                params![ts],
            )
            .unwrap();
        drop(connection);

        let record = decision_audit_record_fixture("s1", "dec-aud-2");
        let decision = crate::decision::Decision::Gate {
            target_work_event_id: 1, // no such work_event -> FK violation
            verdict: "approve".into(),
            note: None,
        };
        let result = project_decision(&db, Path::new("outputs"), &record, &decision);
        assert!(
            result.is_err(),
            "a dangling target_work_event_id FK must fail the projection"
        );

        let connection = open_database(&db).unwrap();
        let audit_rows: i64 = connection
            .query_row(
                "SELECT COUNT(*) FROM audit_records WHERE audit_id='dec-aud-2'",
                [],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(
            audit_rows, 0,
            "the audit proof row must roll back with the failed typed insert (atomic)"
        );
    }

    // ADR 033 D4 / M2a T4 (T3-review hardening): if the decision audit row GAPS
    // (e.g. a non-canonical timestamp), `project_decision` must surface a CLEAR
    // error naming the gap reason BEFORE attempting the typed insert — never an
    // opaque "FOREIGN KEY constraint failed" — and write NO operator_decisions row.
    #[test]
    fn project_decision_gap_audit_yields_clear_error_no_typed_row() {
        let dir = tempfile::tempdir().unwrap();
        let db = dir.path().join("zynk.db");
        open_projection_database(&db).unwrap();
        seed_session_and_gate_work_event(&db, "s1");

        // A deliberately non-canonical timestamp forces project_live_audit_record
        // to return Gap (the normal decide path uses a canonical ts, so it projects).
        let mut record = decision_audit_record_fixture("s1", "dec-aud-gap");
        record.timestamp = "not-a-timestamp".to_string();
        let decision = crate::decision::Decision::Gate {
            target_work_event_id: 1,
            verdict: "approve".into(),
            note: None,
        };
        let err = project_decision(&db, Path::new("outputs"), &record, &decision)
            .expect_err("a gapping decision audit must fail the projection");
        assert!(
            err.message.contains("gap"),
            "the error must name the gap, not surface an opaque FK error: {}",
            err.message
        );

        let connection = open_database(&db).unwrap();
        let decisions: i64 = connection
            .query_row("SELECT COUNT(*) FROM operator_decisions", [], |row| {
                row.get(0)
            })
            .unwrap();
        assert_eq!(
            decisions, 0,
            "no operator_decisions row may be written when the audit gaps"
        );
        let audit_rows: i64 = connection
            .query_row(
                "SELECT COUNT(*) FROM audit_records WHERE audit_id='dec-aud-gap'",
                [],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(audit_rows, 0, "a gapping audit row is not projected");
    }

    /// Seed a minimal, valid `audit_records` row for custody tests: a project + a
    /// session (the FK chain) then a NON-sent, NON-decision audit row inserted via a
    /// direct parameterized INSERT. `delivery_status='drafted'` + `verified_by='agent'`
    /// deliberately does NOT trip the ADR 024 sent+agent trigger (which fires only on
    /// `delivery_status='sent'`), so the fixture lands without any decision/work-event.
    fn seed_session_and_audit_record(
        db: &Path,
        session_id: &str,
        audit_id: &str,
        payload_hash: &str,
    ) {
        let connection = open_projection_database(db).unwrap();
        let ts = "2026-05-31T00:00:00Z";
        connection
            .execute(
                "INSERT INTO projects (project_id, name, root_path, created_at, updated_at)
                 VALUES ('p', 'p', '/tmp', ?1, ?1)",
                params![ts],
            )
            .unwrap();
        connection
            .execute(
                "INSERT INTO sessions (session_id, project_id, title, phase, mode, workflow_status, created_at, updated_at)
                 VALUES (?1, 'p', ?1, 'live', 'unknown', 'idle', ?2, ?2)",
                params![session_id, ts],
            )
            .unwrap();
        connection
            .execute(
                "INSERT INTO audit_records (
                    audit_id, previous_audit_id, session_id, source_agent_id,
                    target_agent_id, source_address, target_address, transport,
                    workspace_id, mid, record_type, command_origin, mode, ref, re,
                    payload_hash, payload_redaction_policy, content_size,
                    delivery_status, observed_by, verified_by, timestamp
                 )
                 VALUES (?1, NULL, ?2, 'claude', NULL, 'claude', 'none', 'none',
                         'w', ?1, 'note', 'agent', NULL, NULL, NULL,
                         ?3, 'hash-only', 0, 'drafted', 'none', 'agent', ?4)",
                params![audit_id, session_id, payload_hash, ts],
            )
            .unwrap();
    }

    // ADR 034 M3a T3: the custody_vault projection helpers round-trip a ciphertext
    // BLOB keyed by audit_id, and `read_reveal_target` reads the audit record's
    // (session_id, payload_hash) — the reveal proof's session + the disclosure-contract
    // hash that the decrypted plaintext is re-verified against in T5 (one read so the
    // two can never diverge).
    #[test]
    fn custody_vault_insert_and_read() {
        let dir = tempfile::tempdir().unwrap();
        let db = dir.path().join("zynk.db");
        open_projection_database(&db).unwrap();
        seed_session_and_audit_record(&db, "s1", "aud-1", "sha256:ab");

        let conn = open_projection_database(&db).unwrap();
        insert_custody_vault(
            &conn,
            "aud-1",
            b"CIPHER",
            b"NONCE-24-BYTES-FILLER-XX",
            "xchacha20poly1305",
            1,
            "2026-05-31T00:00:00Z",
        )
        .unwrap();

        let row = read_custody_vault(&conn, "aud-1")
            .unwrap()
            .expect("vault row");
        assert_eq!(row.ciphertext, b"CIPHER");
        assert_eq!(row.nonce, b"NONCE-24-BYTES-FILLER-XX");
        assert_eq!(row.cipher_id, "xchacha20poly1305");
        assert_eq!(row.key_version, 1);

        // read_reveal_target returns BOTH the session_id and the payload_hash for a
        // present row (T5 reveal consumes this exact pair).
        assert_eq!(
            read_reveal_target(&conn, "aud-1").unwrap(),
            Some(("s1".to_string(), "sha256:ab".to_string()))
        );

        // Idempotent on the audit_id PK: a second insert with DIFFERENT bytes is
        // ignored (INSERT OR IGNORE), leaving the original row intact.
        insert_custody_vault(
            &conn,
            "aud-1",
            b"DIFFERENT",
            b"OTHER-NONCE-24-BYTES-FILL",
            "xchacha20poly1305",
            1,
            "2026-05-31T01:00:00Z",
        )
        .unwrap();
        let again = read_custody_vault(&conn, "aud-1").unwrap().expect("row");
        assert_eq!(
            again.ciphertext, b"CIPHER",
            "INSERT OR IGNORE keeps the original"
        );

        // Absent audit_id -> None for both reads.
        assert!(read_custody_vault(&conn, "missing").unwrap().is_none());
        assert!(read_reveal_target(&conn, "missing").unwrap().is_none());
    }

    // ===== ADR 036 Track B schema v10: participant_overlay =====

    // A migrated temp DB (runs migrate -> v10) that holds a minimal `sessions` row plus
    // a `participant-overlay` `audit_records` proof row carrying the given provenance
    // fields. Returns the open connection so a test can then attempt a direct
    // `participant_overlay` INSERT and assert the v10 triggers fire.
    #[allow(clippy::too_many_arguments)]
    fn migrated_db_with_overlay_proof(
        audit_id: &str,
        verified_by: &str,
        command_origin: &str,
        transport: &str,
        session: &str,
        source_agent: &str,
    ) -> Connection {
        let connection = Connection::open_in_memory().unwrap();
        // open_database/migrate require a mutable connection; do the same dance here.
        let mut connection = connection;
        configure_connection(&connection).unwrap();
        migrate(&mut connection).unwrap();
        let ts = "2026-06-02T00:00:00Z";
        connection
            .execute(
                "INSERT INTO projects (project_id, name, root_path, created_at, updated_at)
                 VALUES ('p', 'p', '/tmp', ?1, ?1)",
                params![ts],
            )
            .unwrap();
        connection
            .execute(
                "INSERT OR IGNORE INTO sessions (session_id, project_id, title, phase, mode, workflow_status, created_at, updated_at)
                 VALUES (?1, 'p', ?1, 'live', 'unknown', 'idle', ?2, ?2)",
                params![session, ts],
            )
            .unwrap();
        connection
            .execute(
                "INSERT INTO audit_records (
                    audit_id, previous_audit_id, session_id, source_agent_id,
                    target_agent_id, source_address, target_address, transport,
                    workspace_id, mid, record_type, command_origin, mode, ref, re,
                    payload_hash, payload_redaction_policy, content_size,
                    delivery_status, observed_by, verified_by, timestamp
                 )
                 VALUES (?1, NULL, ?2, ?3, NULL, 'cli', 'none:none', ?4,
                         'w', ?1, 'participant-overlay', ?5, NULL, NULL, NULL,
                         'sha256:x', 'full', 0, 'observed', 'operator', ?6, ?7)",
                params![
                    audit_id,
                    session,
                    source_agent,
                    transport,
                    command_origin,
                    verified_by,
                    ts
                ],
            )
            .unwrap();
        connection
    }

    // A canonical operator-grade trait proof (verified_by=operator, command_origin=operator,
    // transport=none) is the only proof that may grant a trait (D3.3).
    // A test-only seeding helper that mirrors the full `participant_overlay` row shape, so it
    // legitimately binds all the trait + provenance columns positionally.
    #[allow(clippy::too_many_arguments)]
    fn insert_overlay_trait_row(
        connection: &Connection,
        audit_id: &str,
        session: &str,
        subject: &str,
        asserter: &str,
        trait_id: &str,
        trait_value: i64,
        created_at: &str,
    ) -> rusqlite::Result<usize> {
        connection.execute(
            "INSERT INTO participant_overlay (
                audit_id, session_id, subject_actor_id, overlay_kind,
                actor_kind, role_id, role_label, trait_id, trait_value,
                asserter_actor_id, asserter_kind, supersedes_audit_id,
                superseded_by_audit_id, created_at
             )
             VALUES (?1, ?2, ?3, 'trait',
                     NULL, NULL, NULL, ?4, ?5,
                     ?6, 'operator', NULL, NULL, ?7)",
            params![
                audit_id,
                session,
                subject,
                trait_id,
                trait_value,
                asserter,
                created_at
            ],
        )
    }

    // migrate() -> v10 creates the participant_overlay table and bumps user_version to 10.
    #[test]
    fn v10_participant_overlay_table_and_triggers() {
        let connection = Connection::open_in_memory().unwrap();
        let mut connection = connection;
        configure_connection(&connection).unwrap();
        migrate(&mut connection).unwrap();

        let table_present: i64 = connection
            .query_row(
                "SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = ?1",
                ["participant_overlay"],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(
            table_present, 1,
            "participant_overlay table must exist after migrate -> v10"
        );

        let version: i64 = connection
            .pragma_query_value(None, "user_version", |row| row.get(0))
            .unwrap();
        assert_eq!(version, 10, "PRAGMA user_version must be 10 after migrate");
        assert_eq!(CURRENT_SCHEMA_VERSION, 10);
    }

    // D3.2: a trait whose asserter == subject (self-grant) is ABORTed by the trigger.
    #[test]
    fn v10_trait_self_grant_aborts() {
        let connection = migrated_db_with_overlay_proof(
            "aud-self", "operator", "operator", "none", "s1", "claude",
        );
        let res = insert_overlay_trait_row(
            &connection,
            "aud-self",
            "s1",
            "claude", // subject
            "claude", // asserter == subject => self-grant
            "independent",
            1,
            "2026-06-02T00:00:00Z",
        );
        let err = res.expect_err("a self-granted trait must abort");
        assert!(
            err.to_string().contains("self-grant"),
            "abort message must name the self-grant rule: {err}"
        );
    }

    // D3.3: a trait proof that is NOT operator-grade (e.g. verified_by='helper-tool')
    // is ABORTed — helper-tool/transport are not authority to grant a trait.
    #[test]
    fn v10_trait_non_operator_grade_proof_aborts() {
        // proof: verified_by='helper-tool' (NOT operator-grade) but command_origin/transport ok.
        let connection = migrated_db_with_overlay_proof(
            "aud-helper",
            "helper-tool",
            "operator",
            "none",
            "s1",
            "operator",
        );
        let res = insert_overlay_trait_row(
            &connection,
            "aud-helper",
            "s1",
            "claude",
            "operator",
            "independent",
            1,
            "2026-06-02T00:00:00Z",
        );
        let err = res.expect_err("a non-operator-grade trait proof must abort");
        assert!(
            err.to_string().contains("operator-grade"),
            "abort message must name the operator-grade rule: {err}"
        );

        // FIX 3d: command_origin != 'operator' (otherwise operator-grade) also aborts —
        // command_origin is part of the D3.3 operator-grade triple.
        let conn_cmd = migrated_db_with_overlay_proof(
            "aud-cmd", "operator", "agent", "none", "s1", "operator",
        );
        let res_cmd = insert_overlay_trait_row(
            &conn_cmd,
            "aud-cmd",
            "s1",
            "claude",
            "operator",
            "independent",
            1,
            "2026-06-02T00:00:00Z",
        );
        let err_cmd = res_cmd.expect_err("a non-operator command_origin trait proof must abort");
        assert!(
            err_cmd.to_string().contains("operator-grade"),
            "abort must name the operator-grade rule on a non-operator command_origin: {err_cmd}"
        );

        // FIX 3d: transport != 'none' (otherwise operator-grade) also aborts — transport
        // is part of the D3.3 operator-grade triple (an overlay is non-transport).
        let conn_tr = migrated_db_with_overlay_proof(
            "aud-tr", "operator", "operator", "herdr", "s1", "operator",
        );
        let res_tr = insert_overlay_trait_row(
            &conn_tr,
            "aud-tr",
            "s1",
            "claude",
            "operator",
            "independent",
            1,
            "2026-06-02T00:00:00Z",
        );
        let err_tr = res_tr.expect_err("a transported trait proof must abort");
        assert!(
            err_tr.to_string().contains("operator-grade"),
            "abort must name the operator-grade rule on a transported proof: {err_tr}"
        );
    }

    // D3.1: a row whose session_id / asserter_actor_id / created_at disagree with its
    // proof is ABORTed (provenance binding, ALL kinds — tested here on a trait row).
    #[test]
    fn v10_provenance_binding_mismatch_aborts() {
        let connection = migrated_db_with_overlay_proof(
            "aud-prov", "operator", "operator", "none", "s1", "operator",
        );

        // asserter_actor_id disagrees with the proof's source_agent_id ('operator').
        let res = insert_overlay_trait_row(
            &connection,
            "aud-prov",
            "s1",
            "claude",
            "mallory", // != proof.source_agent_id
            "independent",
            1,
            "2026-06-02T00:00:00Z",
        );
        let err = res.expect_err("an asserter disagreeing with the proof must abort");
        assert!(
            err.to_string().contains("provenance"),
            "abort message must name the provenance-binding rule: {err}"
        );

        // created_at disagrees with the proof's timestamp.
        let res = insert_overlay_trait_row(
            &connection,
            "aud-prov",
            "s1",
            "claude",
            "operator",
            "independent",
            1,
            "2026-06-02T09:99:99Z", // not even canonical AND != proof.timestamp
        );
        assert!(
            res.is_err(),
            "a created_at disagreeing with the proof must abort"
        );

        // session_id disagrees with the proof's session_id.
        let res = insert_overlay_trait_row(
            &connection,
            "aud-prov",
            "other-session",
            "claude",
            "operator",
            "independent",
            1,
            "2026-06-02T00:00:00Z",
        );
        assert!(
            res.is_err(),
            "a session_id disagreeing with the proof must abort"
        );
    }

    // D3.1 (NULL-safe): audit_records.source_agent_id is nullable. A proof row with
    // source_agent_id = NULL must NOT let an overlay bypass the asserter binding — a
    // `<>` comparison yields NULL (no abort); the trigger uses NULL-safe `IS NOT` so a
    // non-NULL NEW.asserter_actor_id over a NULL proof source still ABORTs. Uses
    // overlay_kind='actor-kind' so the trait-only triggers (D3.2/D3.3) cannot mask it.
    #[test]
    fn v10_provenance_binding_aborts_on_null_source_proof() {
        let connection = Connection::open_in_memory().unwrap();
        let mut connection = connection;
        configure_connection(&connection).unwrap();
        migrate(&mut connection).unwrap();
        let ts = "2026-06-02T00:00:00Z";
        connection
            .execute(
                "INSERT INTO projects (project_id, name, root_path, created_at, updated_at)
                 VALUES ('p', 'p', '/tmp', ?1, ?1)",
                params![ts],
            )
            .unwrap();
        connection
            .execute(
                "INSERT INTO sessions (session_id, project_id, title, phase, mode, workflow_status, created_at, updated_at)
                 VALUES ('s1', 'p', 's1', 'live', 'unknown', 'idle', ?1, ?1)",
                params![ts],
            )
            .unwrap();
        // Proof row with source_agent_id = NULL (a real, non-sent participant-overlay proof).
        connection
            .execute(
                "INSERT INTO audit_records (
                    audit_id, previous_audit_id, session_id, source_agent_id,
                    target_agent_id, source_address, target_address, transport,
                    workspace_id, mid, record_type, command_origin, mode, ref, re,
                    payload_hash, payload_redaction_policy, content_size,
                    delivery_status, observed_by, verified_by, timestamp
                 )
                 VALUES ('aud-null', NULL, 's1', NULL, NULL, 'cli', 'none:none', 'none',
                         'w', 'aud-null', 'participant-overlay', 'operator', NULL, NULL, NULL,
                         'sha256:x', 'full', 0, 'observed', 'operator', 'operator', ?1)",
                params![ts],
            )
            .unwrap();
        // actor-kind overlay row: asserter_actor_id='operator' (NOT NULL) over a NULL proof source.
        let res = connection.execute(
            "INSERT INTO participant_overlay (
                audit_id, session_id, subject_actor_id, overlay_kind,
                actor_kind, role_id, role_label, trait_id, trait_value,
                asserter_actor_id, asserter_kind, supersedes_audit_id,
                superseded_by_audit_id, created_at
             )
             VALUES ('aud-null', 's1', 'operator', 'actor-kind',
                     'human', NULL, NULL, NULL, NULL,
                     'operator', 'operator', NULL, NULL, ?1)",
            params![ts],
        );
        let err = res.expect_err(
            "an overlay over a NULL-source proof must abort (NULL-safe provenance binding)",
        );
        assert!(
            err.to_string().contains("provenance"),
            "abort message must name the provenance-binding rule: {err}"
        );
    }

    // D3.5 (v10 sent-guard): a `participant-overlay` audit_records row with
    // delivery_status='sent' is ABORTed (overlay is non-transport operator proof).
    #[test]
    fn v10_sent_participant_overlay_audit_aborts() {
        let connection = Connection::open_in_memory().unwrap();
        let mut connection = connection;
        configure_connection(&connection).unwrap();
        migrate(&mut connection).unwrap();
        let ts = "2026-06-02T00:00:00Z";
        connection
            .execute(
                "INSERT INTO projects (project_id, name, root_path, created_at, updated_at)
                 VALUES ('p', 'p', '/tmp', ?1, ?1)",
                params![ts],
            )
            .unwrap();
        connection
            .execute(
                "INSERT INTO sessions (session_id, project_id, title, phase, mode, workflow_status, created_at, updated_at)
                 VALUES ('s1', 'p', 's1', 'live', 'unknown', 'idle', ?1, ?1)",
                params![ts],
            )
            .unwrap();
        let res = connection.execute(
            "INSERT INTO audit_records (
                audit_id, previous_audit_id, session_id, source_agent_id,
                target_agent_id, source_address, target_address, transport,
                workspace_id, mid, record_type, command_origin, mode, ref, re,
                payload_hash, payload_redaction_policy, content_size,
                delivery_status, observed_by, verified_by, timestamp
             )
             VALUES ('aud-sent', NULL, 's1', 'operator', NULL, 'cli', 'none:none', 'none',
                     'w', 'aud-sent', 'participant-overlay', 'operator', NULL, NULL, NULL,
                     'sha256:x', 'full', 0, 'sent', 'operator', 'operator', ?1)",
            params![ts],
        );
        let err = res.expect_err("a sent participant-overlay proof must abort");
        assert!(
            err.to_string().contains("participant-overlay") || err.to_string().contains("sent"),
            "abort message must name the sent participant-overlay rule: {err}"
        );
    }

    // D2 partial-unique index: two CURRENT rows in one trait slot (same
    // session/subject/trait_id, both superseded_by_audit_id NULL) — the second
    // INSERT errors.
    #[test]
    fn v10_two_current_trait_rows_one_slot_aborts() {
        let connection = migrated_db_with_overlay_proof(
            "aud-one", "operator", "operator", "none", "s1", "operator",
        );
        // A second proof row (distinct audit_id) for the same slot.
        connection
            .execute(
                "INSERT INTO audit_records (
                    audit_id, previous_audit_id, session_id, source_agent_id,
                    target_agent_id, source_address, target_address, transport,
                    workspace_id, mid, record_type, command_origin, mode, ref, re,
                    payload_hash, payload_redaction_policy, content_size,
                    delivery_status, observed_by, verified_by, timestamp
                 )
                 VALUES ('aud-two', NULL, 's1', 'operator', NULL, 'cli', 'none:none', 'none',
                         'w', 'aud-two', 'participant-overlay', 'operator', NULL, NULL, NULL,
                         'sha256:y', 'full', 0, 'observed', 'operator', 'operator', '2026-06-02T00:00:00Z')",
                [],
            )
            .unwrap();

        insert_overlay_trait_row(
            &connection,
            "aud-one",
            "s1",
            "claude",
            "operator",
            "independent",
            1,
            "2026-06-02T00:00:00Z",
        )
        .expect("the first current trait row inserts");

        let res = insert_overlay_trait_row(
            &connection,
            "aud-two",
            "s1",
            "claude",
            "operator",
            "independent",
            1,
            "2026-06-02T00:00:00Z",
        );
        assert!(
            res.is_err(),
            "a second CURRENT row in the same trait slot must be rejected by the partial-unique index"
        );
    }

    // FIX 3d (D3.4): the v10 canonical-timestamp trigger #4 ABORTs a non-canonical
    // participant_overlay.created_at. Isolated from D3.1 (provenance binding) by DROPping
    // the other three participant_overlay triggers first — the proof timestamp must be
    // canonical (the audit_records ts trigger enforces it), so D3.1 would otherwise also
    // fire on the mismatched created_at; dropping it leaves ONLY trigger #4 to abort.
    #[test]
    fn v10_canonical_ts_trigger_aborts_noncanonical_created_at() {
        let connection = migrated_db_with_overlay_proof(
            "aud-ts", "operator", "operator", "none", "s1", "operator",
        );
        // Isolate trigger #4: drop the provenance/self-grant/operator-grade triggers.
        connection
            .execute_batch(
                "DROP TRIGGER participant_overlay_provenance_binding_insert;
                 DROP TRIGGER participant_overlay_no_self_grant_trait_insert;
                 DROP TRIGGER participant_overlay_operator_grade_trait_insert;",
            )
            .unwrap();
        // An actor-kind row with a non-canonical created_at (no `Z`, with an offset) —
        // fails the canonical GLOB. Only trigger #4 remains to catch it.
        let res = connection.execute(
            "INSERT INTO participant_overlay (
                audit_id, session_id, subject_actor_id, overlay_kind,
                actor_kind, role_id, role_label, trait_id, trait_value,
                asserter_actor_id, asserter_kind, supersedes_audit_id,
                superseded_by_audit_id, created_at
             )
             VALUES ('aud-ts', 's1', 'claude', 'actor-kind',
                     'human', NULL, NULL, NULL, NULL,
                     'operator', 'operator', NULL, NULL, '2026-06-02T00:00:00+07:00')",
            [],
        );
        let err = res.expect_err("a non-canonical created_at must abort (D3.4)");
        assert!(
            err.to_string().contains("RFC3339 UTC seconds") || err.to_string().contains("D3.4"),
            "the abort must name the canonical-timestamp rule (D3.4): {err}"
        );
    }

    // FIX 3d (D2 partial-unique index, actor-kind/role slot): two CURRENT actor-kind rows
    // in one (session, subject) slot (both superseded_by_audit_id NULL) — the second
    // INSERT is rejected by `participant_overlay_current_kindrole`. Mirrors the trait-slot
    // test above for the actor-kind/role index.
    #[test]
    fn v10_two_current_kindrole_rows_one_slot_aborts() {
        let connection = migrated_db_with_overlay_proof(
            "aud-k1", "operator", "operator", "none", "s1", "operator",
        );
        // A second proof row (distinct audit_id) for the same actor-kind slot.
        connection
            .execute(
                "INSERT INTO audit_records (
                    audit_id, previous_audit_id, session_id, source_agent_id,
                    target_agent_id, source_address, target_address, transport,
                    workspace_id, mid, record_type, command_origin, mode, ref, re,
                    payload_hash, payload_redaction_policy, content_size,
                    delivery_status, observed_by, verified_by, timestamp
                 )
                 VALUES ('aud-k2', NULL, 's1', 'operator', NULL, 'cli', 'none:none', 'none',
                         'w', 'aud-k2', 'participant-overlay', 'operator', NULL, NULL, NULL,
                         'sha256:y', 'full', 0, 'observed', 'operator', 'operator', '2026-06-02T00:00:00Z')",
                [],
            )
            .unwrap();

        let insert_ak = |audit_id: &str| {
            connection.execute(
                "INSERT INTO participant_overlay (
                    audit_id, session_id, subject_actor_id, overlay_kind,
                    actor_kind, role_id, role_label, trait_id, trait_value,
                    asserter_actor_id, asserter_kind, supersedes_audit_id,
                    superseded_by_audit_id, created_at
                 )
                 VALUES (?1, 's1', 'claude', 'actor-kind',
                         'agent', NULL, NULL, NULL, NULL,
                         'operator', 'operator', NULL, NULL, '2026-06-02T00:00:00Z')",
                params![audit_id],
            )
        };
        insert_ak("aud-k1").expect("the first current actor-kind row inserts");
        let res = insert_ak("aud-k2");
        assert!(
            res.is_err(),
            "a second CURRENT actor-kind row in the same slot must be rejected by the partial-unique index"
        );
    }

    // ===== ADR 036 (trackbrc1 P2): the v10 row-shape CHECK must enforce EXACT per-kind
    // shape — every OTHER kind's columns NULL. The pre-fix CHECK nulled only a SUBSET, so a
    // cross-kind smuggle (e.g. an actor-kind row carrying role_label + trait_value) inserted.
    // These tests do DIRECT INSERTs (bypassing app validation) and assert the CHECK aborts.
    // The proof provenance matches the helper (session/asserter/created_at) so the binding
    // trigger passes and the CHECK is the only gate under test.

    // actor-kind row that ALSO sets role_label (and trait_value) must be rejected: the strict
    // CHECK requires role_id/role_label/trait_id/trait_value all NULL for an actor-kind row.
    #[test]
    fn v10_row_shape_check_rejects_mixed_actor_kind() {
        let connection = migrated_db_with_overlay_proof(
            "aud-mix-ak",
            "operator",
            "operator",
            "none",
            "s1",
            "operator",
        );
        let res = connection.execute(
            "INSERT INTO participant_overlay (
                audit_id, session_id, subject_actor_id, overlay_kind,
                actor_kind, role_id, role_label, trait_id, trait_value,
                asserter_actor_id, asserter_kind, supersedes_audit_id,
                superseded_by_audit_id, created_at
             )
             VALUES ('aud-mix-ak', 's1', 'claude', 'actor-kind',
                     'agent', NULL, 'Smuggled Role', NULL, 1,
                     'operator', 'operator', NULL, NULL, '2026-06-02T00:00:00Z')",
            [],
        );
        assert!(
            res.is_err(),
            "an actor-kind row carrying role_label/trait_value must be rejected by the row-shape CHECK"
        );
    }

    // role row that ALSO sets trait_value must be rejected: the strict CHECK requires
    // actor_kind/trait_id/trait_value all NULL for a role row.
    #[test]
    fn v10_row_shape_check_rejects_mixed_role() {
        let connection = migrated_db_with_overlay_proof(
            "aud-mix-role",
            "operator",
            "operator",
            "none",
            "s1",
            "operator",
        );
        let res = connection.execute(
            "INSERT INTO participant_overlay (
                audit_id, session_id, subject_actor_id, overlay_kind,
                actor_kind, role_id, role_label, trait_id, trait_value,
                asserter_actor_id, asserter_kind, supersedes_audit_id,
                superseded_by_audit_id, created_at
             )
             VALUES ('aud-mix-role', 's1', 'claude', 'role',
                     NULL, 'reviewer', 'Reviewer', NULL, 1,
                     'operator', 'operator', NULL, NULL, '2026-06-02T00:00:00Z')",
            [],
        );
        assert!(
            res.is_err(),
            "a role row carrying trait_value must be rejected by the row-shape CHECK"
        );
    }

    // trait row that ALSO sets role_label must be rejected: the strict CHECK requires
    // actor_kind/role_id/role_label all NULL for a trait row. (asserter 'operator' != subject
    // 'claude', operator-grade proof — so the self-grant/operator-grade triggers pass and the
    // row-shape CHECK is the gate under test.)
    #[test]
    fn v10_row_shape_check_rejects_mixed_trait() {
        let connection = migrated_db_with_overlay_proof(
            "aud-mix-trait",
            "operator",
            "operator",
            "none",
            "s1",
            "operator",
        );
        let res = connection.execute(
            "INSERT INTO participant_overlay (
                audit_id, session_id, subject_actor_id, overlay_kind,
                actor_kind, role_id, role_label, trait_id, trait_value,
                asserter_actor_id, asserter_kind, supersedes_audit_id,
                superseded_by_audit_id, created_at
             )
             VALUES ('aud-mix-trait', 's1', 'claude', 'trait',
                     NULL, NULL, 'Smuggled Role', 'independent', 1,
                     'operator', 'operator', NULL, NULL, '2026-06-02T00:00:00Z')",
            [],
        );
        assert!(
            res.is_err(),
            "a trait row carrying role_label must be rejected by the row-shape CHECK"
        );
    }

    // ===== ADR 036 Track B T3: project_overlay dual-write (proof + typed row) =====

    /// An `ImportedAuditRecord` carrying the overlay conventions (ADR 036):
    /// record_type='participant-overlay', operator-originated + operator-verified,
    /// transport=none, a canonical timestamp, `previous_audit_id: None` (clean chain
    /// root → projects, not Gap). Mirrors `decision_audit_record_fixture`.
    fn overlay_audit_record_fixture(session_id: &str, audit_id: &str) -> ImportedAuditRecord {
        ImportedAuditRecord {
            audit_id: audit_id.to_string(),
            previous_audit_id: None,
            timestamp: "2026-06-02T01:00:00Z".to_string(),
            source_agent_id: Some("operator".to_string()),
            source_address: "operator".to_string(),
            target_agent_id: None,
            target_address: "none".to_string(),
            transport: "none".to_string(),
            workspace_id: "w".to_string(),
            session_id: session_id.to_string(),
            mid: audit_id.to_string(),
            record_type: crate::overlay::OVERLAY_RECORD_TYPE.to_string(),
            command_origin: "operator".to_string(),
            mode: None,
            r#ref: None,
            re: None,
            payload_hash: "sha256:x".to_string(),
            payload_redaction_policy: "full".to_string(),
            content_size: 0,
            delivery_status: "observed".to_string(),
            observed_by: "operator".to_string(),
            verified_by: "operator".to_string(),
            due: None,
            payload_excerpt: None,
        }
    }

    // ADR 036 T3: project_overlay writes the immutable audit proof row AND the typed
    // participant_overlay row in ONE immediate transaction (atomic).
    #[test]
    fn project_overlay_writes_audit_and_typed_row() {
        let dir = tempfile::tempdir().unwrap();
        let db = dir.path().join("zynk.db");
        open_projection_database(&db).unwrap(); // auto-creates at CURRENT_SCHEMA_VERSION (v10)
        let record = overlay_audit_record_fixture("s1", "ovl-aud-1");
        let overlay = crate::overlay::Overlay::Trait {
            subject: "claude".into(),
            asserter: "operator".into(),
            asserter_kind: "operator".into(),
            trait_id: "independent".into(),
            value: true,
            supersedes: None,
        };
        project_overlay(&db, Path::new("outputs"), &record, &overlay).unwrap();

        let connection = open_database(&db).unwrap();
        let audit_rows: i64 = connection
            .query_row(
                "SELECT COUNT(*) FROM audit_records WHERE audit_id='ovl-aud-1'",
                [],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(audit_rows, 1, "the overlay audit proof row must be present");

        let (subject, kind, trait_id, trait_value, asserter, created_at): (
            String,
            String,
            String,
            i64,
            String,
            String,
        ) = connection
            .query_row(
                "SELECT subject_actor_id, overlay_kind, trait_id, trait_value,
                        asserter_actor_id, created_at
                 FROM participant_overlay WHERE audit_id='ovl-aud-1'",
                [],
                |row| {
                    Ok((
                        row.get(0)?,
                        row.get(1)?,
                        row.get(2)?,
                        row.get(3)?,
                        row.get(4)?,
                        row.get(5)?,
                    ))
                },
            )
            .unwrap();
        assert_eq!(subject, "claude");
        assert_eq!(kind, "trait");
        assert_eq!(trait_id, "independent");
        assert_eq!(trait_value, 1);
        assert_eq!(asserter, "operator");
        assert_eq!(
            created_at, "2026-06-02T01:00:00Z",
            "created_at must equal the proof timestamp (D3.1 provenance binding)"
        );
    }

    // ADR 036 T3: if the overlay audit row GAPS (here: a non-canonical timestamp),
    // project_overlay surfaces a CLEAR error naming the gap BEFORE the typed insert —
    // never an opaque FK error — and writes NO participant_overlay row.
    #[test]
    fn project_overlay_gap_yields_clear_error_no_typed_row() {
        let dir = tempfile::tempdir().unwrap();
        let db = dir.path().join("zynk.db");
        open_projection_database(&db).unwrap();

        let mut record = overlay_audit_record_fixture("s1", "ovl-aud-gap");
        record.timestamp = "not-a-timestamp".to_string();
        let overlay = crate::overlay::Overlay::Trait {
            subject: "claude".into(),
            asserter: "operator".into(),
            asserter_kind: "operator".into(),
            trait_id: "independent".into(),
            value: true,
            supersedes: None,
        };
        let err = project_overlay(&db, Path::new("outputs"), &record, &overlay)
            .expect_err("a gapping overlay audit must fail the projection");
        assert!(
            err.message.contains("gap"),
            "the error must name the gap, not surface an opaque FK error: {}",
            err.message
        );

        let connection = open_database(&db).unwrap();
        let overlays: i64 = connection
            .query_row("SELECT COUNT(*) FROM participant_overlay", [], |row| {
                row.get(0)
            })
            .unwrap();
        assert_eq!(
            overlays, 0,
            "no participant_overlay row may be written when the audit gaps"
        );
    }

    // ADR 036 T3: superseding an earlier overlay sets the prior row's
    // superseded_by_audit_id pointer and leaves the new row CURRENT (NULL pointer),
    // in the SAME transaction as the new typed insert.
    #[test]
    fn project_overlay_supersede_sets_pointer() {
        let dir = tempfile::tempdir().unwrap();
        let db = dir.path().join("zynk.db");
        open_projection_database(&db).unwrap();

        let first = overlay_audit_record_fixture("s1", "ovl-a1");
        let overlay1 = crate::overlay::Overlay::Trait {
            subject: "claude".into(),
            asserter: "operator".into(),
            asserter_kind: "operator".into(),
            trait_id: "independent".into(),
            value: true,
            supersedes: None,
        };
        project_overlay(&db, Path::new("outputs"), &first, &overlay1).unwrap();

        let mut second = overlay_audit_record_fixture("s1", "ovl-a2");
        // A distinct canonical timestamp keeps the proof rows ordered.
        second.timestamp = "2026-06-02T02:00:00Z".to_string();
        let overlay2 = crate::overlay::Overlay::Trait {
            subject: "claude".into(),
            asserter: "operator".into(),
            asserter_kind: "operator".into(),
            trait_id: "independent".into(),
            value: false,
            supersedes: Some("ovl-a1".into()),
        };
        project_overlay(&db, Path::new("outputs"), &second, &overlay2).unwrap();

        let connection = open_database(&db).unwrap();
        let a1_superseded_by: Option<String> = connection
            .query_row(
                "SELECT superseded_by_audit_id FROM participant_overlay WHERE audit_id='ovl-a1'",
                [],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(
            a1_superseded_by.as_deref(),
            Some("ovl-a2"),
            "the prior row must point at the superseding audit"
        );
        let a2_superseded_by: Option<String> = connection
            .query_row(
                "SELECT superseded_by_audit_id FROM participant_overlay WHERE audit_id='ovl-a2'",
                [],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(
            a2_superseded_by, None,
            "the superseding row is CURRENT (superseded_by NULL)"
        );
    }

    // ADR 036 T3 no-leak invariant: an overlay proof must NOT upsert a messages row.
    // project_overlay must not call any messages insert (project_live_audit_record's
    // upsert_message_latest is gated to message record_types, NOT participant-overlay).
    #[test]
    fn project_overlay_creates_no_messages_row() {
        let dir = tempfile::tempdir().unwrap();
        let db = dir.path().join("zynk.db");
        open_projection_database(&db).unwrap();
        let record = overlay_audit_record_fixture("s1", "ovl-aud-nomsg");
        let overlay = crate::overlay::Overlay::ActorKind {
            subject: "zevs".into(),
            asserter: "operator".into(),
            asserter_kind: "operator".into(),
            actor_kind: "human".into(),
            supersedes: None,
        };
        project_overlay(&db, Path::new("outputs"), &record, &overlay).unwrap();

        let connection = open_database(&db).unwrap();
        let messages: i64 = connection
            .query_row(
                "SELECT COUNT(*) FROM messages WHERE session_id='s1'",
                [],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(
            messages, 0,
            "an overlay proof must NOT create a messages row (no-leak invariant)"
        );
    }

    // ADR 036 D10 (MAJOR hardening): the supersede UPDATE must be SLOT-BOUND. A new
    // trait row whose `supersedes` points at an UNRELATED slot's current row (here the
    // actor-kind row for the same subject) must FAIL LOUD — never silently close THAT
    // unrelated row. Without the slot binding the UPDATE matches by audit_id alone and
    // wrongly closes the actor-kind row (silent corruption, since the new trait slot is
    // empty so the partial-unique index can't catch it). RED before the slot binding:
    // the actor-kind row gets closed and the insert succeeds.
    #[test]
    fn supersede_rejects_cross_slot_predecessor() {
        let dir = tempfile::tempdir().unwrap();
        let db = dir.path().join("zynk.db");
        open_projection_database(&db).unwrap();

        // Current trait row for (s1, codex, independent).
        let trait_rec = overlay_audit_record_fixture("s1", "ovl-trait");
        let trait_overlay = crate::overlay::Overlay::Trait {
            subject: "codex".into(),
            asserter: "operator".into(),
            asserter_kind: "operator".into(),
            trait_id: "independent".into(),
            value: true,
            supersedes: None,
        };
        project_overlay(&db, Path::new("outputs"), &trait_rec, &trait_overlay).unwrap();

        // Current actor-kind row for (s1, codex) — an UNRELATED slot.
        let mut ak_rec = overlay_audit_record_fixture("s1", "ovl-actorkind");
        ak_rec.timestamp = "2026-06-02T02:00:00Z".to_string();
        let ak_overlay = crate::overlay::Overlay::ActorKind {
            subject: "codex".into(),
            asserter: "operator".into(),
            asserter_kind: "operator".into(),
            actor_kind: "agent".into(),
            supersedes: None,
        };
        project_overlay(&db, Path::new("outputs"), &ak_rec, &ak_overlay).unwrap();

        // A NEW trait row whose `supersedes` mis-points at the ACTOR-KIND row's audit_id.
        let mut bad_rec = overlay_audit_record_fixture("s1", "ovl-trait-2");
        bad_rec.timestamp = "2026-06-02T03:00:00Z".to_string();
        let bad_overlay = crate::overlay::Overlay::Trait {
            subject: "codex".into(),
            asserter: "operator".into(),
            asserter_kind: "operator".into(),
            trait_id: "independent".into(),
            value: false,
            supersedes: Some("ovl-actorkind".into()), // wrong slot
        };
        let err = project_overlay(&db, Path::new("outputs"), &bad_rec, &bad_overlay)
            .expect_err("a cross-slot supersede must fail loud (not close the actor-kind row)");
        assert!(
            err.message.contains("not the current row")
                || err.message.contains("slot")
                || err.message.contains("supersede"),
            "the error must name the mis-pointed supersede: {}",
            err.message
        );

        // The actor-kind row must STAY current (its forward pointer is still NULL).
        let connection = open_database(&db).unwrap();
        let ak_superseded_by: Option<String> = connection
            .query_row(
                "SELECT superseded_by_audit_id FROM participant_overlay WHERE audit_id='ovl-actorkind'",
                [],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(
            ak_superseded_by, None,
            "the unrelated actor-kind row must NOT be closed by a cross-slot supersede"
        );
    }

    // A parsed (record, overlay) pair for chain_order tests: a trait overlay whose
    // audit_id is `audit_id` and that supersedes `supersedes` (if Some). chain_order only
    // reads record.audit_id + overlay.supersedes(), so the rest of the record is filler.
    fn chain_pair(
        audit_id: &str,
        supersedes: Option<&str>,
    ) -> (ImportedAuditRecord, crate::overlay::Overlay) {
        let record = overlay_audit_record_fixture("s1", audit_id);
        let overlay = crate::overlay::Overlay::Trait {
            subject: "codex".into(),
            asserter: "operator".into(),
            asserter_kind: "operator".into(),
            trait_id: "independent".into(),
            value: true,
            supersedes: supersedes.map(|s| s.to_string()),
        };
        (record, overlay)
    }

    // ADR 036 D10 (FIX 3a): chain_order FAILS LOUD on a supersede cycle (A supersedes B,
    // B supersedes A) — both are unreachable from any root, so neither is a root and the
    // whole import is rejected deterministically (never an input-order append).
    #[test]
    fn chain_order_fails_loud_on_cycle() {
        let a = chain_pair("A", Some("B"));
        let b = chain_pair("B", Some("A"));
        let parsed: Vec<(&ImportedAuditRecord, crate::overlay::Overlay)> =
            vec![(&a.0, a.1.clone()), (&b.0, b.1.clone())];
        let err = chain_order(&parsed).expect_err("a supersede cycle must fail loud");
        assert!(
            err.message.contains("cycle"),
            "the error must name the supersede cycle: {}",
            err.message
        );
    }

    // ADR 036 D10 (FIX 3a): a reverse-input-order chain (the superseding proof appears
    // FIRST in input) still emits root-first — the root B (supersedes nothing in-batch)
    // before A (which supersedes B), regardless of input order.
    #[test]
    fn chain_order_orders_by_supersede_not_input() {
        // Input order: A first (supersedes B), then B (the root). Emission must be B, A.
        let a = chain_pair("A", Some("B"));
        let b = chain_pair("B", None);
        let parsed: Vec<(&ImportedAuditRecord, crate::overlay::Overlay)> =
            vec![(&a.0, a.1.clone()), (&b.0, b.1.clone())];
        let order = chain_order(&parsed).expect("a clean chain must order");
        // index 0 == A, index 1 == B; root-first means B (index 1) precedes A (index 0).
        assert_eq!(
            order,
            vec![1, 0],
            "the root (B) must be emitted before the proof that supersedes it (A)"
        );
    }
}