decapod 0.38.12

Decapod is the daemonless, local-first control plane that agents call on demand to align intent, enforce boundaries, and produce proof-backed completion across concurrent multi-agent work. 🦀
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
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
//! Intent-driven methodology validation harness.
//!
//! This module implements the comprehensive validation suite that enforces
//! Decapod's contracts, invariants, and methodology gates.

use crate::core::broker::DbBroker;
use crate::core::context_capsule::DeterministicContextCapsule;
use crate::core::error;
use crate::core::output;
use crate::core::plan_governance;
use crate::core::store::{Store, StoreKind};
use crate::core::workunit::{self, WorkUnitManifest, WorkUnitStatus};
use crate::{db, primitives, todo};
use regex::Regex;
use serde_json;
use std::collections::HashSet;
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use std::sync::atomic::{AtomicU32, Ordering};
use std::time::{Duration, Instant};
use ulid::Ulid;

struct ValidationContext {
    pass_count: AtomicU32,
    fail_count: AtomicU32,
    warn_count: AtomicU32,
    fails: Mutex<Vec<String>>,
    warns: Mutex<Vec<String>>,
    repo_files_cache: Mutex<Vec<(PathBuf, Vec<PathBuf>)>>,
}

impl ValidationContext {
    fn new() -> Self {
        Self {
            pass_count: AtomicU32::new(0),
            fail_count: AtomicU32::new(0),
            warn_count: AtomicU32::new(0),
            fails: Mutex::new(Vec::new()),
            warns: Mutex::new(Vec::new()),
            repo_files_cache: Mutex::new(Vec::new()),
        }
    }
}

fn collect_repo_files(
    root: &Path,
    out: &mut Vec<PathBuf>,
    ctx: &ValidationContext,
) -> Result<(), error::DecapodError> {
    // Check cache first — this is called 3 times on the same root during validation.
    let cached = {
        let cache = ctx.repo_files_cache.lock().unwrap();
        cache
            .iter()
            .find(|(k, _)| k == root)
            .map(|(_, v)| v.clone())
    };
    if let Some(files) = cached {
        out.extend(files);
        return Ok(());
    }

    fn recurse(dir: &Path, out: &mut Vec<PathBuf>) -> Result<(), error::DecapodError> {
        if !dir.is_dir() {
            return Ok(());
        }

        let name = dir.file_name().and_then(|s| s.to_str()).unwrap_or("");
        // Skip VCS/build/runtime directories that are not authoritative sources
        // for validation rules and can be very large in active agent workspaces.
        if matches!(
            name,
            ".git"
                | "target"
                | ".decapod"
                | "artifacts"
                | "node_modules"
                | ".venv"
                | ".mypy_cache"
                | ".pytest_cache"
        ) {
            return Ok(());
        }

        for entry in fs::read_dir(dir).map_err(error::DecapodError::IoError)? {
            let entry = entry.map_err(error::DecapodError::IoError)?;
            let path = entry.path();
            if path.is_dir() {
                recurse(&path, out)?;
            } else if path.is_file() {
                out.push(path);
            }
        }
        Ok(())
    }

    let start = out.len();
    recurse(root, out)?;
    // Cache the result for subsequent calls with the same root.
    ctx.repo_files_cache
        .lock()
        .unwrap()
        .push((root.to_path_buf(), out[start..].to_vec()));
    Ok(())
}

fn validate_no_legacy_namespaces(
    ctx: &ValidationContext,
    decapod_dir: &Path,
) -> Result<(), error::DecapodError> {
    info("Namespace Purge Gate");

    let mut files = Vec::new();
    collect_repo_files(decapod_dir, &mut files, ctx)?;

    let needles = [
        [".".to_string(), "globex".to_string()].concat(),
        [".".to_string(), "codex".to_string()].concat(),
    ];
    let mut offenders: Vec<(PathBuf, String)> = Vec::new();

    for path in files {
        // Skip obvious binaries.
        if path.extension().is_some_and(|e| e == "db") {
            continue;
        }
        let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");
        let is_texty = matches!(
            ext,
            "md" | "rs" | "toml" | "json" | "jsonl" | "yml" | "yaml" | "sh" | "lock"
        );
        if !is_texty {
            continue;
        }
        let content = match fs::read_to_string(&path) {
            Ok(c) => c,
            Err(_) => continue,
        };
        for n in needles.iter() {
            if content.contains(n) {
                offenders.push((path.clone(), n.clone()));
            }
        }
    }

    if offenders.is_empty() {
        pass(
            "No legacy namespace references found in repo text sources",
            ctx,
        );
    } else {
        let mut msg = String::from("Forbidden legacy namespace references found:");
        for (p, n) in offenders.iter().take(12) {
            msg.push_str(&format!(" {}({})", p.display(), n));
        }
        if offenders.len() > 12 {
            msg.push_str(&format!(" ... ({} total)", offenders.len()));
        }
        fail(&msg, ctx);
    }
    Ok(())
}

fn validate_embedded_self_contained(
    ctx: &ValidationContext,
    repo_root: &Path,
) -> Result<(), error::DecapodError> {
    info("Embedded Self-Contained Gate");

    let constitution_dir = repo_root.join("constitution");
    if !constitution_dir.exists() {
        // This is a decapod repo, not a project with embedded docs
        skip("No constitution/ directory found (decapod repo)", ctx);
        return Ok(());
    }

    let mut files = Vec::new();
    collect_repo_files(&constitution_dir, &mut files, ctx)?;

    let mut offenders: Vec<PathBuf> = Vec::new();

    for path in files {
        if path.extension().and_then(|e| e.to_str()) != Some("md") {
            continue;
        }

        let content = match fs::read_to_string(&path) {
            Ok(c) => c,
            Err(_) => continue,
        };

        // Check for .decapod/ references that aren't documenting override behavior
        if content.contains(".decapod/") {
            // Allow legitimate documentation patterns, counting legitimate references (not just lines).
            let mut legitimate_ref_count = 0usize;
            for line in content.lines() {
                let refs_on_line = line.matches(".decapod/").count();
                if refs_on_line == 0 {
                    continue;
                }
                let is_legitimate_line = line.contains("<repo>")
                    || line.contains("store:")
                    || line.contains("directory")
                    || line.contains("override")
                    || line.contains("Override")
                    || line.contains("OVERRIDE.md")
                    || line.contains("Location:")
                    || line.contains("primarily contain")
                    || line.contains(".decapod/context/")
                    || line.contains(".decapod/memory/")
                    || line.contains("intended as")
                    || line.contains(".decapod/knowledge/")
                    || line.contains(".decapod/data/")
                    || line.contains(".decapod/workspaces/")
                    || line.contains("repo-scoped");
                if is_legitimate_line {
                    legitimate_ref_count += refs_on_line;
                }
            }

            let total_decapod_refs = content.matches(".decapod/").count();
            if total_decapod_refs > legitimate_ref_count {
                offenders.push(path);
            }
        }
    }

    if offenders.is_empty() {
        pass(
            "Embedded constitution files contain no invalid .decapod/ references",
            ctx,
        );
    } else {
        let mut msg =
            String::from("Embedded constitution files contain invalid .decapod/ references:");
        for p in offenders.iter().take(8) {
            msg.push_str(&format!(" {}", p.display()));
        }
        if offenders.len() > 8 {
            msg.push_str(&format!(" ... ({} total)", offenders.len()));
        }
        fail(&msg, ctx);
    }
    Ok(())
}

fn pass(_message: &str, ctx: &ValidationContext) {
    ctx.pass_count.fetch_add(1, Ordering::Relaxed);
}

fn fail(message: &str, ctx: &ValidationContext) {
    ctx.fail_count.fetch_add(1, Ordering::Relaxed);
    ctx.fails.lock().unwrap().push(message.to_string());
}

fn skip(_message: &str, ctx: &ValidationContext) {
    ctx.pass_count.fetch_add(1, Ordering::Relaxed);
}

fn warn(message: &str, ctx: &ValidationContext) {
    ctx.warn_count.fetch_add(1, Ordering::Relaxed);
    ctx.warns.lock().unwrap().push(message.to_string());
}

fn info(_message: &str) {}

fn count_tasks_in_db(db_path: &Path) -> Result<i64, error::DecapodError> {
    let conn = db::db_connect_for_validate(&db_path.to_string_lossy())?;
    let count: i64 = conn
        .query_row("SELECT COUNT(*) FROM tasks", [], |row| row.get(0))
        .map_err(error::DecapodError::RusqliteError)?;
    Ok(count)
}

fn fetch_tasks_fingerprint(db_path: &Path) -> Result<String, error::DecapodError> {
    let conn = db::db_connect_for_validate(&db_path.to_string_lossy())?;
    let mut stmt = conn
        .prepare("SELECT id,title,status,updated_at,dir_path,scope,priority FROM tasks ORDER BY id")
        .map_err(error::DecapodError::RusqliteError)?;
    let rows = stmt
        .query_map([], |row| {
            Ok(serde_json::json!({
                "id": row.get::<_, String>(0)?,
                "title": row.get::<_, String>(1)?,
                "status": row.get::<_, String>(2)?,
                "updated_at": row.get::<_, String>(3)?,
                "dir_path": row.get::<_, String>(4)?,
                "scope": row.get::<_, String>(5)?,
                "priority": row.get::<_, String>(6)?,
            }))
        })
        .map_err(error::DecapodError::RusqliteError)?;

    let mut out = Vec::new();
    for r in rows {
        out.push(r.map_err(error::DecapodError::RusqliteError)?);
    }
    Ok(serde_json::to_string(&out).unwrap())
}

fn validate_user_store_blank_slate(ctx: &ValidationContext) -> Result<(), error::DecapodError> {
    info("Store: user (blank-slate semantics)");
    let tmp_root = std::env::temp_dir().join(format!("decapod_validate_user_{}", Ulid::new()));
    fs::create_dir_all(&tmp_root).map_err(error::DecapodError::IoError)?;

    todo::initialize_todo_db(&tmp_root)?;
    let db_path = tmp_root.join("todo.db");
    let n = count_tasks_in_db(&db_path)?;

    if n == 0 {
        pass("User store starts empty (no automatic seeding)", ctx);
    } else {
        fail(
            &format!(
                "User store is not empty on fresh init ({} task(s) found)",
                n
            ),
            ctx,
        );
    }
    Ok(())
}

fn validate_repo_store_dogfood(
    store: &Store,
    ctx: &ValidationContext,
    _decapod_dir: &Path,
) -> Result<(), error::DecapodError> {
    info("Store: repo (dogfood backlog semantics)");

    let events = store.root.join("todo.events.jsonl");
    if !events.is_file() {
        fail("Repo store missing todo.events.jsonl", ctx);
        return Ok(());
    }
    let content = fs::read_to_string(&events).map_err(error::DecapodError::IoError)?;
    let add_count = content
        .lines()
        .filter(|l| l.contains("\"event_type\":\"task.add\""))
        .count();

    // Fresh setup has 0 events but is valid.
    pass(
        &format!(
            "Repo backlog event log present ({} task.add events)",
            add_count
        ),
        ctx,
    );

    let db_path = store.root.join("todo.db");
    if !db_path.is_file() {
        fail("Repo store missing todo.db", ctx);
        return Ok(());
    }

    // Broker log integrity check
    let broker = DbBroker::new(&store.root);
    let replay_report = broker.verify_replay()?;
    if replay_report.divergences.is_empty() {
        pass("Audit log integrity verified (no pending event gaps)", ctx);
    } else {
        warn(
            &format!(
                "Audit log contains {} potential crash divergence(s); historical pending entries detected. Run `decapod data broker verify` for details.",
                replay_report.divergences.len(),
            ),
            ctx,
        );
    }

    let tmp_root = std::env::temp_dir().join(format!("decapod_validate_repo_{}", Ulid::new()));
    fs::create_dir_all(&tmp_root).map_err(error::DecapodError::IoError)?;
    let tmp_db = tmp_root.join("todo.db");
    let _events = todo::rebuild_db_from_events(&events, &tmp_db)?;

    let fp_a = fetch_tasks_fingerprint(&db_path)?;
    let fp_b = fetch_tasks_fingerprint(&tmp_db)?;
    if fp_a == fp_b {
        pass(
            "Repo todo.db matches deterministic rebuild from todo.events.jsonl",
            ctx,
        );
    } else {
        fail(
            "Repo todo.db does NOT match rebuild from todo.events.jsonl",
            ctx,
        );
    }

    Ok(())
}

fn validate_repo_map(
    ctx: &ValidationContext,
    _decapod_dir: &Path, // decapod_dir is no longer used for filesystem constitution checks
) -> Result<(), error::DecapodError> {
    info("Repo Map");

    // We no longer check for a filesystem directory for constitution.
    // Instead, we verify embedded docs.
    pass(
        "Methodology constitution checks will verify embedded docs.",
        ctx,
    );

    let required_specs = ["specs/INTENT.md", "specs/SYSTEM.md"];
    let required_methodology = ["methodology/ARCHITECTURE.md"];
    for r in required_specs {
        if crate::core::assets::get_doc(r).is_some() {
            pass(&format!("Constitution doc {} present (embedded)", r), ctx);
        } else {
            fail(&format!("Constitution doc {} missing (embedded)", r), ctx);
        }
    }
    for r in required_methodology {
        if crate::core::assets::get_doc(r).is_some() {
            pass(&format!("Constitution doc {} present (embedded)", r), ctx);
        } else {
            fail(&format!("Constitution doc {} missing (embedded)", r), ctx);
        }
    }
    Ok(())
}

fn validate_docs_templates_bucket(
    ctx: &ValidationContext,
    decapod_dir: &Path,
) -> Result<(), error::DecapodError> {
    info("Entrypoint Gate");

    // Entrypoints MUST be in the project root
    let required = ["AGENTS.md", "CLAUDE.md", "GEMINI.md", "CODEX.md"];
    for a in required {
        let p = decapod_dir.join(a);
        if p.is_file() {
            pass(&format!("Root entrypoint {} present", a), ctx);
        } else {
            fail(
                &format!("Root entrypoint {} missing from project root", a),
                ctx,
            );
        }
    }

    if decapod_dir.join(".decapod").join("README.md").is_file() {
        pass(".decapod/README.md present", ctx);
    } else {
        fail(".decapod/README.md missing", ctx);
    }

    // NEGATIVE GATE: Decapod docs MUST NOT be copied into the project
    let forbidden_docs = decapod_dir.join(".decapod").join("docs");
    if forbidden_docs.exists() {
        fail(
            "Decapod internal docs were copied into .decapod/docs/ (Forbidden)",
            ctx,
        );
    } else {
        pass(
            "Decapod internal docs correctly excluded from project repo",
            ctx,
        );
    }

    // NEGATIVE GATE: projects/<id> MUST NOT exist
    let forbidden_projects = decapod_dir.join(".decapod").join("projects");
    if forbidden_projects.exists() {
        fail("Legacy .decapod/projects/ directory found (Forbidden)", ctx);
    } else {
        pass(".decapod/projects/ correctly absent", ctx);
    }

    Ok(())
}

fn validate_entrypoint_invariants(
    ctx: &ValidationContext,
    decapod_dir: &Path,
) -> Result<(), error::DecapodError> {
    info("Four Invariants Gate");

    // Check AGENTS.md for the four invariants
    let agents_path = decapod_dir.join("AGENTS.md");
    if !agents_path.is_file() {
        fail("AGENTS.md missing, cannot check invariants", ctx);
        return Ok(());
    }

    let content = fs::read_to_string(&agents_path).map_err(error::DecapodError::IoError)?;

    // Exact invariant strings (tamper detection)
    let exact_invariants = [
        ("core/DECAPOD.md", "Router pointer to core/DECAPOD.md"),
        ("cargo install decapod", "Version update gate language"),
        ("decapod validate", "Validation gate language"),
        (
            "decapod docs ingest",
            "Core constitution ingestion mandate language",
        ),
        ("Stop if", "Stop-if-missing behavior"),
        ("Docker git workspaces", "Docker workspace mandate language"),
        (
            "decapod todo claim --id <task-id>",
            "Task claim-before-work mandate language",
        ),
        (
            "request elevated permissions before Docker/container workspace commands",
            "Elevated-permissions mandate language",
        ),
        (
            "DECAPOD_SESSION_PASSWORD",
            "Per-agent session password mandate language",
        ),
        (
            ".decapod files are accessed only via decapod CLI",
            "Jail rule: .decapod access is CLI-only",
        ),
        (
            "Interface abstraction boundary",
            "Control-plane opacity language",
        ),
        (
            "Strict Dependency: You are strictly bound to the Decapod control plane",
            "Agent dependency enforcement language",
        ),
        ("✅", "Four invariants checklist format"),
    ];

    let mut all_present = true;
    for (marker, description) in exact_invariants {
        if content.contains(marker) {
            pass(&format!("Invariant present: {}", description), ctx);
        } else {
            fail(&format!("Invariant missing: {}", description), ctx);
            all_present = false;
        }
    }

    // Check for legacy router names (must not exist)
    let legacy_routers = ["MAESTRO.md", "GLOBEX.md", "CODEX.md\" as router"];
    for legacy in legacy_routers {
        if content.contains(legacy) {
            fail(
                &format!("AGENTS.md contains legacy router reference: {}", legacy),
                ctx,
            );
            all_present = false;
        }
    }

    // Line count check (AGENTS.md should be thin: max 100 lines for universal contract)
    let line_count = content.lines().count();
    const MAX_AGENTS_LINES: usize = 100;
    if line_count <= MAX_AGENTS_LINES {
        pass(
            &format!(
                "AGENTS.md is thin ({} lines ≤ {})",
                line_count, MAX_AGENTS_LINES
            ),
            ctx,
        );
    } else {
        fail(
            &format!(
                "AGENTS.md exceeds line limit ({} lines > {})",
                line_count, MAX_AGENTS_LINES
            ),
            ctx,
        );
        all_present = false;
    }

    // Check that agent-specific files defer to AGENTS.md and are thin
    const MAX_AGENT_SPECIFIC_LINES: usize = 70;
    for agent_file in ["CLAUDE.md", "GEMINI.md", "CODEX.md"] {
        let agent_path = decapod_dir.join(agent_file);
        if !agent_path.is_file() {
            fail(&format!("{} missing from project root", agent_file), ctx);
            all_present = false;
            continue;
        }

        let agent_content =
            fs::read_to_string(&agent_path).map_err(error::DecapodError::IoError)?;

        // Must defer to AGENTS.md
        if agent_content.contains("See `AGENTS.md`") || agent_content.contains("AGENTS.md") {
            pass(&format!("{} defers to AGENTS.md", agent_file), ctx);
        } else {
            fail(&format!("{} does not reference AGENTS.md", agent_file), ctx);
            all_present = false;
        }

        // Must reference canonical router
        if agent_content.contains("core/DECAPOD.md") {
            pass(&format!("{} references canonical router", agent_file), ctx);
        } else {
            fail(
                &format!("{} missing canonical router reference", agent_file),
                ctx,
            );
            all_present = false;
        }

        // Must use embedded doc paths via CLI, never direct constitution/* file paths.
        if agent_content.contains("decapod docs show constitution/")
            || agent_content.contains("(constitution/")
        {
            fail(
                &format!(
                    "{} references direct constitution filesystem paths; use embedded doc paths (e.g. core/*, specs/*, docs/*)",
                    agent_file
                ),
                ctx,
            );
            all_present = false;
        } else if agent_content.contains("decapod docs show docs/") {
            pass(
                &format!("{} references embedded docs path convention", agent_file),
                ctx,
            );
        } else {
            fail(
                &format!(
                    "{} missing embedded docs path reference (`decapod docs show docs/...`)",
                    agent_file
                ),
                ctx,
            );
            all_present = false;
        }

        // Must include explicit jail rule for .decapod access
        if agent_content.contains(".decapod files are accessed only via decapod CLI") {
            pass(
                &format!("{} includes .decapod CLI-only jail rule", agent_file),
                ctx,
            );
        } else {
            fail(
                &format!("{} missing .decapod CLI-only jail rule marker", agent_file),
                ctx,
            );
            all_present = false;
        }

        // Must include Docker git workspace mandate
        if agent_content.contains("Docker git workspaces") {
            pass(
                &format!("{} includes Docker workspace mandate", agent_file),
                ctx,
            );
        } else {
            fail(
                &format!("{} missing Docker workspace mandate marker", agent_file),
                ctx,
            );
            all_present = false;
        }

        // Must include elevated-permissions mandate for container workspace commands
        if agent_content
            .contains("request elevated permissions before Docker/container workspace commands")
        {
            pass(
                &format!("{} includes elevated-permissions mandate", agent_file),
                ctx,
            );
        } else {
            fail(
                &format!("{} missing elevated-permissions mandate marker", agent_file),
                ctx,
            );
            all_present = false;
        }

        // Must include per-agent session password mandate
        if agent_content.contains("DECAPOD_SESSION_PASSWORD") {
            pass(
                &format!("{} includes per-agent session password mandate", agent_file),
                ctx,
            );
        } else {
            fail(
                &format!(
                    "{} missing per-agent session password mandate marker",
                    agent_file
                ),
                ctx,
            );
            all_present = false;
        }

        // Must include claim-before-work mandate
        if agent_content.contains("decapod todo claim --id <task-id>") {
            pass(
                &format!("{} includes claim-before-work mandate", agent_file),
                ctx,
            );
        } else {
            fail(
                &format!("{} missing claim-before-work mandate marker", agent_file),
                ctx,
            );
            all_present = false;
        }

        // Must include task creation before claim mandate
        if agent_content.contains("decapod todo add \"<task>\"") {
            pass(
                &format!("{} includes task creation mandate", agent_file),
                ctx,
            );
        } else {
            fail(
                &format!("{} missing task creation mandate marker", agent_file),
                ctx,
            );
            all_present = false;
        }

        // Must include canonical Decapod workspace path mandate
        if agent_content.contains(".decapod/workspaces") {
            pass(
                &format!("{} includes canonical workspace path mandate", agent_file),
                ctx,
            );
        } else {
            fail(
                &format!(
                    "{} missing canonical workspace path marker (`.decapod/workspaces`)",
                    agent_file
                ),
                ctx,
            );
            all_present = false;
        }

        if agent_content.contains(".claude/worktrees") {
            let mut has_forbidden_positive_reference = false;
            for line in agent_content.lines() {
                if !line.contains(".claude/worktrees") {
                    continue;
                }
                let lower = line.to_ascii_lowercase();
                let is_negative_context = lower.contains("never")
                    || lower.contains("forbid")
                    || lower.contains("non-canonical")
                    || lower.contains("must not")
                    || lower.contains("do not");
                if !is_negative_context {
                    has_forbidden_positive_reference = true;
                    break;
                }
            }
            if has_forbidden_positive_reference {
                fail(
                    &format!(
                        "{} references forbidden non-canonical worktree path `.claude/worktrees`",
                        agent_file
                    ),
                    ctx,
                );
                all_present = false;
            } else {
                pass(
                    &format!(
                        "{} explicitly forbids `.claude/worktrees` non-canonical path",
                        agent_file
                    ),
                    ctx,
                );
            }
        }

        // Must include core constitution ingestion mandate
        if agent_content.contains("decapod docs ingest") {
            pass(
                &format!(
                    "{} includes core constitution ingestion mandate",
                    agent_file
                ),
                ctx,
            );
        } else {
            fail(
                &format!(
                    "{} missing core constitution ingestion mandate marker",
                    agent_file
                ),
                ctx,
            );
            all_present = false;
        }

        // Must include explicit update command in startup sequence
        if agent_content.contains("cargo install decapod") {
            pass(&format!("{} includes version update step", agent_file), ctx);
        } else {
            fail(
                &format!(
                    "{} missing version update step (`cargo install decapod`)",
                    agent_file
                ),
                ctx,
            );
            all_present = false;
        }

        // Must be thin (max 50 lines for agent-specific shims)
        let agent_lines = agent_content.lines().count();
        if agent_lines <= MAX_AGENT_SPECIFIC_LINES {
            pass(
                &format!(
                    "{} is thin ({} lines ≤ {})",
                    agent_file, agent_lines, MAX_AGENT_SPECIFIC_LINES
                ),
                ctx,
            );
        } else {
            fail(
                &format!(
                    "{} exceeds line limit ({} lines > {})",
                    agent_file, agent_lines, MAX_AGENT_SPECIFIC_LINES
                ),
                ctx,
            );
            all_present = false;
        }

        // Must not contain duplicated contracts (check for common duplication markers)
        let duplication_markers = [
            "## Lifecycle States", // Contract details belong in constitution
            "## Validation Rules", // Contract details belong in constitution
            "### Proof Gates",     // Contract details belong in constitution
            "## Store Model",      // Contract details belong in constitution
        ];
        for marker in duplication_markers {
            if agent_content.contains(marker) {
                fail(
                    &format!(
                        "{} contains duplicated contract details ({})",
                        agent_file, marker
                    ),
                    ctx,
                );
                all_present = false;
            }
        }
    }

    if all_present {
        pass("All entrypoint files follow thin waist architecture", ctx);
    }

    Ok(())
}

fn validate_interface_contract_bootstrap(
    ctx: &ValidationContext,
    repo_root: &Path,
) -> Result<(), error::DecapodError> {
    info("Interface Contract Bootstrap Gate");

    // This gate applies to the decapod repository where constitution/* is present.
    // Project repos initialized by `decapod init` should not fail on missing embedded docs.
    let constitution_dir = repo_root.join("constitution");
    if !constitution_dir.exists() {
        skip(
            "No constitution/ directory found (project repo); skipping interface bootstrap checks",
            ctx,
        );
        return Ok(());
    }

    let risk_policy_doc = repo_root.join("constitution/interfaces/RISK_POLICY_GATE.md");
    let context_pack_doc = repo_root.join("constitution/interfaces/AGENT_CONTEXT_PACK.md");
    for (path, label) in [
        (&risk_policy_doc, "RISK_POLICY_GATE interface"),
        (&context_pack_doc, "AGENT_CONTEXT_PACK interface"),
    ] {
        if path.is_file() {
            pass(&format!("{} present at {}", label, path.display()), ctx);
        } else {
            fail(&format!("{} missing at {}", label, path.display()), ctx);
        }
    }

    if risk_policy_doc.is_file() {
        let content = fs::read_to_string(&risk_policy_doc).map_err(error::DecapodError::IoError)?;
        for marker in [
            "**Authority:**",
            "**Layer:** Interfaces",
            "**Binding:** Yes",
            "**Scope:**",
            "**Non-goals:**",
            "## 3. Current-Head SHA Discipline",
            "## 6. Browser Evidence Manifest (UI/Critical Flows)",
            "## 8. Truth Labels and Upgrade Path",
            "## 10. Contract Example (JSON)",
            "## Links",
        ] {
            if content.contains(marker) {
                pass(
                    &format!("RISK_POLICY_GATE includes marker: {}", marker),
                    ctx,
                );
            } else {
                fail(&format!("RISK_POLICY_GATE missing marker: {}", marker), ctx);
            }
        }
    }

    if context_pack_doc.is_file() {
        let content =
            fs::read_to_string(&context_pack_doc).map_err(error::DecapodError::IoError)?;
        for marker in [
            "**Authority:**",
            "**Layer:** Interfaces",
            "**Binding:** Yes",
            "**Scope:**",
            "**Non-goals:**",
            "## 2. Deterministic Load Order",
            "## 3. Mutation Authority",
            "## 4. Memory Distillation Contract",
            "## 8. Truth Labels and Upgrade Path",
            "## Links",
        ] {
            if content.contains(marker) {
                pass(
                    &format!("AGENT_CONTEXT_PACK includes marker: {}", marker),
                    ctx,
                );
            } else {
                fail(
                    &format!("AGENT_CONTEXT_PACK missing marker: {}", marker),
                    ctx,
                );
            }
        }
    }

    Ok(())
}

fn extract_md_version(content: &str) -> Option<String> {
    for line in content.lines() {
        let line = line.trim();
        if let Some(rest) = line.strip_prefix("- v") {
            let v_and_rest = rest.trim();
            if !v_and_rest.is_empty() {
                // Extract version number, assuming it's the first word before the colon
                return v_and_rest.split(':').next().map(|s| s.trim().to_string());
            }
        }
    }
    None
}

fn validate_health_purity(
    ctx: &ValidationContext,
    decapod_dir: &Path,
) -> Result<(), error::DecapodError> {
    info("Health Purity Gate");
    let mut files = Vec::new();
    collect_repo_files(decapod_dir, &mut files, ctx)?;

    let forbidden =
        Regex::new(r"(?i)\(health:\s*(VERIFIED|ASSERTED|STALE|CONTRADICTED)\)").unwrap();
    let mut offenders = Vec::new();

    let generated_path = decapod_dir.join(".decapod").join("generated");

    for path in files {
        if path.extension().is_some_and(|e| e == "md") {
            // Skip files in the generated artifacts directory
            if path.starts_with(&generated_path) {
                continue;
            }

            let content = fs::read_to_string(&path).unwrap_or_default();
            if forbidden.is_match(&content) {
                offenders.push(path);
            }
        }
    }

    if offenders.is_empty() {
        pass(
            "No manual health status values found in authoritative docs",
            ctx,
        );
    } else {
        fail(
            &format!(
                "Manual health values found in non-generated files: {:?}",
                offenders
            ),
            ctx,
        );
    }
    Ok(())
}

fn validate_project_scoped_state(
    store: &Store,
    ctx: &ValidationContext,
    decapod_dir: &Path,
) -> Result<(), error::DecapodError> {
    info("Project-Scoped State Gate");
    if store.kind != StoreKind::Repo {
        skip("Not in repo mode; skipping state scoping check", ctx);
        return Ok(());
    }

    // Check if any .db or .jsonl files exist outside .decapod/ in the project root
    let mut offenders = Vec::new();
    for entry in fs::read_dir(decapod_dir).map_err(error::DecapodError::IoError)? {
        let entry = entry.map_err(error::DecapodError::IoError)?;
        let path = entry.path();
        if path.is_file() {
            let ext = path.extension().and_then(|s| s.to_str()).unwrap_or("");
            if matches!(ext, "db" | "jsonl") {
                offenders.push(path);
            }
        }
    }

    if offenders.is_empty() {
        pass("All state is correctly scoped within .decapod/", ctx);
    } else {
        fail(
            &format!(
                "Found Decapod state files outside .decapod/: {:?}",
                offenders
            ),
            ctx,
        );
    }
    Ok(())
}

fn validate_generated_artifact_whitelist(
    store: &Store,
    ctx: &ValidationContext,
    decapod_dir: &Path,
) -> Result<(), error::DecapodError> {
    info("Generated Artifact Whitelist Gate");

    if store.kind != StoreKind::Repo {
        skip(
            "Not in repo mode; skipping generated artifact whitelist check",
            ctx,
        );
        return Ok(());
    }

    let gitignore_path = decapod_dir.join(".gitignore");
    let gitignore = fs::read_to_string(&gitignore_path).map_err(error::DecapodError::IoError)?;
    let required_rules = [
        ".decapod/generated/*",
        "!.decapod/generated/Dockerfile",
        "!.decapod/generated/context/",
        "!.decapod/generated/context/*.json",
        ".decapod/data",
        "!.decapod/data/",
        ".decapod/data/*",
        "!.decapod/data/knowledge.promotions.jsonl",
    ];

    for rule in required_rules {
        if gitignore.lines().any(|line| line.trim() == rule) {
            pass(&format!("Gitignore contains required rule '{}'", rule), ctx);
        } else {
            fail(
                &format!(
                    "Missing .gitignore rule '{}' for generated/data whitelist enforcement",
                    rule
                ),
                ctx,
            );
        }
    }

    let output = std::process::Command::new("git")
        .arg("-C")
        .arg(decapod_dir)
        .args(["ls-files", ".decapod/generated", ".decapod/data"])
        .output();

    let output = match output {
        Ok(o) if o.status.success() => o,
        Ok(_) | Err(_) => {
            warn(
                "Unable to evaluate tracked generated artifacts via git ls-files; skipping tracked whitelist check",
                ctx,
            );
            return Ok(());
        }
    };

    let allowed_tracked = [
        ".decapod/generated/Dockerfile",
        ".decapod/data/knowledge.promotions.jsonl",
    ];
    let mut offenders = Vec::new();
    for line in String::from_utf8_lossy(&output.stdout).lines() {
        let path = line.trim();
        if path.is_empty() {
            continue;
        }
        let is_allowed_exact = allowed_tracked.iter().any(|allowed| allowed == &path);
        let is_allowed_context_json = path.starts_with(".decapod/generated/context/")
            && path.ends_with(".json")
            && !path.contains("/../");
        if !is_allowed_exact && !is_allowed_context_json {
            offenders.push(path.to_string());
        }
    }

    if offenders.is_empty() {
        pass(
            "Tracked generated artifacts are restricted to the whitelist",
            ctx,
        );
    } else {
        fail(
            &format!(
                "Tracked non-whitelisted generated artifacts found: {:?}. Keep generated files ignored unless explicitly allowlisted.",
                offenders
            ),
            ctx,
        );
    }

    Ok(())
}

fn validate_workunit_manifests_if_present(
    ctx: &ValidationContext,
    repo_root: &Path,
) -> Result<(), error::DecapodError> {
    info("Work Unit Manifest Gate");

    let workunits_dir = repo_root
        .join(".decapod")
        .join("governance")
        .join("workunits");
    if !workunits_dir.exists() {
        skip("No workunit manifests found; skipping workunit gate", ctx);
        return Ok(());
    }

    let mut files = 0usize;
    for entry in fs::read_dir(&workunits_dir).map_err(error::DecapodError::IoError)? {
        let entry = entry.map_err(error::DecapodError::IoError)?;
        let path = entry.path();
        if path.extension().and_then(|s| s.to_str()) != Some("json") {
            continue;
        }
        files += 1;
        let raw = fs::read_to_string(&path).map_err(error::DecapodError::IoError)?;
        let parsed: WorkUnitManifest = serde_json::from_str(&raw).map_err(|e| {
            error::DecapodError::ValidationError(format!(
                "invalid workunit manifest {}: {}",
                path.display(),
                e
            ))
        })?;
        let _ = parsed.canonical_json_bytes().map_err(|e| {
            error::DecapodError::ValidationError(format!(
                "workunit canonicalization failed for {}: {}",
                path.display(),
                e
            ))
        })?;
        if parsed.status == WorkUnitStatus::Verified {
            workunit::validate_verified_manifest(&parsed).map_err(|e| {
                error::DecapodError::ValidationError(format!(
                    "invalid VERIFIED workunit manifest {}: {}",
                    path.display(),
                    e
                ))
            })?;
        }
    }

    pass(
        &format!(
            "Workunit manifest schema check passed for {} file(s)",
            files
        ),
        ctx,
    );
    Ok(())
}

fn validate_context_capsules_if_present(
    ctx: &ValidationContext,
    repo_root: &Path,
) -> Result<(), error::DecapodError> {
    info("Context Capsule Gate");

    let capsules_dir = repo_root.join(".decapod").join("generated").join("context");
    if !capsules_dir.exists() {
        skip(
            "No context capsules found; skipping context capsule gate",
            ctx,
        );
        return Ok(());
    }

    let mut files = 0usize;
    for entry in fs::read_dir(&capsules_dir).map_err(error::DecapodError::IoError)? {
        let entry = entry.map_err(error::DecapodError::IoError)?;
        let path = entry.path();
        if path.extension().and_then(|s| s.to_str()) != Some("json") {
            continue;
        }
        files += 1;
        let raw = fs::read_to_string(&path).map_err(error::DecapodError::IoError)?;
        let parsed: DeterministicContextCapsule = serde_json::from_str(&raw).map_err(|e| {
            error::DecapodError::ValidationError(format!(
                "invalid context capsule {}: {}",
                path.display(),
                e
            ))
        })?;
        let expected = parsed.computed_hash_hex().map_err(|e| {
            error::DecapodError::ValidationError(format!(
                "context capsule hash computation failed for {}: {}",
                path.display(),
                e
            ))
        })?;
        if parsed.capsule_hash != expected {
            fail(
                &format!(
                    "Context capsule hash mismatch in {} (expected {}, got {})",
                    path.display(),
                    expected,
                    parsed.capsule_hash
                ),
                ctx,
            );
        }
    }

    pass(
        &format!("Context capsule integrity checked for {} file(s)", files),
        ctx,
    );
    Ok(())
}

fn validate_knowledge_promotions_if_present(
    ctx: &ValidationContext,
    repo_root: &Path,
) -> Result<(), error::DecapodError> {
    info("Knowledge Promotion Ledger Gate");

    let ledger = repo_root
        .join(".decapod")
        .join("data")
        .join("knowledge.promotions.jsonl");
    if !ledger.exists() {
        skip(
            "No knowledge promotion ledger found; skipping promotion ledger gate",
            ctx,
        );
        return Ok(());
    }

    let raw = fs::read_to_string(&ledger).map_err(error::DecapodError::IoError)?;
    for (idx, line) in raw.lines().enumerate() {
        if line.trim().is_empty() {
            continue;
        }
        let v: serde_json::Value = serde_json::from_str(line).map_err(|e| {
            error::DecapodError::ValidationError(format!(
                "invalid promotion ledger line {} in {}: {}",
                idx + 1,
                ledger.display(),
                e
            ))
        })?;
        for key in [
            "event_id",
            "ts",
            "source_entry_id",
            "target_class",
            "evidence_refs",
            "approved_by",
            "actor",
            "reason",
        ] {
            if v.get(key).is_none() {
                fail(
                    &format!(
                        "Knowledge promotion ledger missing '{}' on line {} ({})",
                        key,
                        idx + 1,
                        ledger.display()
                    ),
                    ctx,
                );
            }
        }

        if v.get("target_class").and_then(|x| x.as_str()) != Some("procedural") {
            fail(
                &format!(
                    "Knowledge promotion ledger requires target_class='procedural' on line {} ({})",
                    idx + 1,
                    ledger.display()
                ),
                ctx,
            );
        }

        let evidence_ok = v
            .get("evidence_refs")
            .and_then(|x| x.as_array())
            .map(|arr| {
                !arr.is_empty()
                    && arr
                        .iter()
                        .all(|item| item.as_str().map(|s| !s.trim().is_empty()).unwrap_or(false))
            })
            .unwrap_or(false);
        if !evidence_ok {
            fail(
                &format!(
                    "Knowledge promotion ledger evidence_refs must be a non-empty string array on line {} ({})",
                    idx + 1,
                    ledger.display()
                ),
                ctx,
            );
        }

        for key in ["approved_by", "actor", "reason"] {
            let non_empty = v
                .get(key)
                .and_then(|x| x.as_str())
                .map(|s| !s.trim().is_empty())
                .unwrap_or(false);
            if !non_empty {
                fail(
                    &format!(
                        "Knowledge promotion ledger '{}' must be a non-empty string on line {} ({})",
                        key,
                        idx + 1,
                        ledger.display()
                    ),
                    ctx,
                );
            }
        }
    }

    pass("Knowledge promotion ledger schema check passed", ctx);
    Ok(())
}

fn validate_schema_determinism(
    ctx: &ValidationContext,
    _decapod_dir: &Path,
) -> Result<(), error::DecapodError> {
    info("Schema Determinism Gate");
    let run_schema = || -> Result<String, error::DecapodError> {
        let snapshot = crate::deterministic_schema_envelope();
        serde_json::to_string(&snapshot).map_err(|e| {
            error::DecapodError::ValidationError(format!(
                "schema determinism serialization failed: {}",
                e
            ))
        })
    };

    // Run sequentially: parallel execution causes non-determinism due to shared state
    let s1 = run_schema()?;
    let s2 = run_schema()?;

    if s1 == s2 && !s1.is_empty() {
        pass("Schema output is deterministic", ctx);
    } else {
        fail("Schema output is non-deterministic or empty", ctx);
    }
    Ok(())
}

fn validate_eval_gate_if_required(
    store: &Store,
    ctx: &ValidationContext,
) -> Result<(), error::DecapodError> {
    info("Eval Gate Requirement");
    let failures = crate::plugins::eval::validate_eval_gate_if_required(&store.root)?;
    if failures.is_empty() {
        pass("Eval gate requirement satisfied or not configured", ctx);
    } else {
        for failure in failures {
            fail(&failure, ctx);
        }
    }
    Ok(())
}

fn validate_health_cache_integrity(
    store: &Store,
    ctx: &ValidationContext,
) -> Result<(), error::DecapodError> {
    info("Health Cache Non-Authoritative Gate");
    let db_path = store.root.join("health.db");
    if !db_path.exists() {
        skip("health.db not found; skipping health integrity check", ctx);
        return Ok(());
    }

    let conn = db::db_connect_for_validate(&db_path.to_string_lossy())?;

    // Check if any health_cache entries exist without corresponding proof_events
    let orphaned: i64 = conn.query_row(
        "SELECT COUNT(*) FROM health_cache hc LEFT JOIN proof_events pe ON hc.claim_id = pe.claim_id WHERE pe.event_id IS NULL",
        [],
        |row| row.get(0),
    ).map_err(error::DecapodError::RusqliteError)?;

    if orphaned == 0 {
        pass("No orphaned health cache entries (integrity pass)", ctx);
    } else {
        warn(
            &format!(
                "Found {} health cache entries without proof events (might be manual writes)",
                orphaned
            ),
            ctx,
        );
    }
    Ok(())
}

fn validate_risk_map(store: &Store, ctx: &ValidationContext) -> Result<(), error::DecapodError> {
    info("Risk Map Gate");
    let map_path = store.root.join("RISKMAP.json");
    if map_path.exists() {
        pass("Risk map (blast-radius) is present", ctx);
    } else {
        warn("Risk map missing (run `decapod riskmap init`)", ctx);
    }
    Ok(())
}

fn validate_risk_map_violations(
    store: &Store,
    ctx: &ValidationContext,
    pre_read_broker: Option<&str>,
) -> Result<(), error::DecapodError> {
    info("Zone Violation Gate");
    let fallback;
    let content = match pre_read_broker {
        Some(c) => c,
        None => {
            let audit_log = store.root.join("broker.events.jsonl");
            if !audit_log.exists() {
                return Ok(());
            }
            fallback = fs::read_to_string(audit_log)?;
            &fallback
        }
    };
    {
        let mut offenders = Vec::new();
        for line in content.lines() {
            if line.contains("\".decapod/\"") && line.contains("\"op\":\"todo.add\"") {
                offenders.push(line.to_string());
            }
        }
        if offenders.is_empty() {
            pass("No risk zone violations detected in audit log", ctx);
        } else {
            fail(
                &format!("Detected operations in protected zones: {:?}", offenders),
                ctx,
            );
        }
    }
    Ok(())
}

fn validate_policy_integrity(
    store: &Store,
    ctx: &ValidationContext,
    pre_read_broker: Option<&str>,
) -> Result<(), error::DecapodError> {
    info("Policy Integrity Gates");
    let db_path = store.root.join("policy.db");
    if !db_path.exists() {
        skip("policy.db not found; skipping policy check", ctx);
        return Ok(());
    }

    let _conn = db::db_connect_for_validate(&db_path.to_string_lossy())?;

    let fallback;
    let content_opt = match pre_read_broker {
        Some(c) => Some(c),
        None => {
            let audit_log = store.root.join("broker.events.jsonl");
            if audit_log.exists() {
                fallback = fs::read_to_string(audit_log)?;
                Some(fallback.as_str())
            } else {
                None
            }
        }
    };
    if let Some(content) = content_opt {
        let mut offenders = Vec::new();
        for line in content.lines() {
            if line.contains("\"op\":\"policy.approve\"")
                && line.contains("\"db_id\":\"health.db\"")
            {
                offenders.push(line.to_string());
            }
        }
        if offenders.is_empty() {
            pass(
                "Approval isolation verified (no direct health mutations)",
                ctx,
            );
        } else {
            fail(
                &format!(
                    "Policy approval directly mutated health state: {:?}",
                    offenders
                ),
                ctx,
            );
        }
    }

    Ok(())
}

fn validate_knowledge_integrity(
    store: &Store,
    ctx: &ValidationContext,
    pre_read_broker: Option<&str>,
) -> Result<(), error::DecapodError> {
    info("Knowledge Integrity Gate");
    let db_path = store.root.join("knowledge.db");
    if !db_path.exists() {
        skip(
            "knowledge.db not found; skipping knowledge integrity check",
            ctx,
        );
        return Ok(());
    }

    let query_missing_provenance = |conn: &rusqlite::Connection| -> Result<i64, rusqlite::Error> {
        conn.query_row(
            "SELECT COUNT(*) FROM knowledge WHERE provenance IS NULL OR provenance = ''",
            [],
            |row| row.get(0),
        )
    };

    let mut conn = db::db_connect_for_validate(&db_path.to_string_lossy())?;
    let missing_provenance: i64 = match query_missing_provenance(&conn) {
        Ok(v) => v,
        Err(rusqlite::Error::SqliteFailure(_, Some(msg)))
            if msg.contains("no such table: knowledge") =>
        {
            // Self-heal schema drift/partial bootstrap before validating integrity.
            db::initialize_knowledge_db(&store.root)?;
            conn = db::db_connect_for_validate(&db_path.to_string_lossy())?;
            query_missing_provenance(&conn).map_err(error::DecapodError::RusqliteError)?
        }
        Err(e) => return Err(error::DecapodError::RusqliteError(e)),
    };

    if missing_provenance == 0 {
        pass(
            "Knowledge provenance verified (all entries have pointers)",
            ctx,
        );
    } else {
        fail(
            &format!(
                "Found {} knowledge entries missing mandatory provenance",
                missing_provenance
            ),
            ctx,
        );
    }

    let procedural_missing_event_provenance: i64 = conn
        .query_row(
            "SELECT COUNT(*) FROM knowledge
             WHERE id LIKE 'procedural/%'
               AND (provenance IS NULL OR provenance = '' OR provenance NOT LIKE 'event:%')",
            [],
            |row| row.get(0),
        )
        .map_err(error::DecapodError::RusqliteError)?;
    if procedural_missing_event_provenance == 0 {
        pass(
            "Knowledge promotion firewall verified (procedural entries carry event provenance)",
            ctx,
        );
    } else {
        fail(
            &format!(
                "Found {} procedural knowledge entries without event-backed provenance",
                procedural_missing_event_provenance
            ),
            ctx,
        );
    }

    let event_ids = load_knowledge_promotion_event_ids(&store.root)?;
    let mut stmt = conn
        .prepare(
            "SELECT provenance FROM knowledge
             WHERE id LIKE 'procedural/%' AND provenance LIKE 'event:%'",
        )
        .map_err(error::DecapodError::RusqliteError)?;
    let rows = stmt
        .query_map([], |row| row.get::<_, String>(0))
        .map_err(error::DecapodError::RusqliteError)?;
    let mut missing_event_refs = 0usize;
    for row in rows {
        let prov = row.map_err(error::DecapodError::RusqliteError)?;
        let event_id = prov.trim_start_matches("event:");
        if !event_ids.contains(event_id) {
            missing_event_refs += 1;
        }
    }
    if missing_event_refs == 0 {
        pass("Knowledge promotion firewall ledger linkage verified", ctx);
    } else {
        fail(
            &format!(
                "Found {} procedural knowledge entries referencing missing promotion events",
                missing_event_refs
            ),
            ctx,
        );
    }

    let fallback;
    let content_opt = match pre_read_broker {
        Some(c) => Some(c),
        None => {
            let audit_log = store.root.join("broker.events.jsonl");
            if audit_log.exists() {
                fallback = fs::read_to_string(audit_log)?;
                Some(fallback.as_str())
            } else {
                None
            }
        }
    };
    if let Some(content) = content_opt {
        let mut offenders = Vec::new();
        for line in content.lines() {
            if line.contains("\"op\":\"knowledge.add\"") && line.contains("\"db_id\":\"health.db\"")
            {
                offenders.push(line.to_string());
            }
        }
        if offenders.is_empty() {
            pass("No direct health promotion from knowledge detected", ctx);
        } else {
            fail(
                &format!(
                    "Knowledge system directly mutated health state: {:?}",
                    offenders
                ),
                ctx,
            );
        }
    }

    Ok(())
}

fn load_knowledge_promotion_event_ids(
    store_root: &Path,
) -> Result<HashSet<String>, error::DecapodError> {
    let ledger = store_root.join("knowledge.promotions.jsonl");
    if !ledger.exists() {
        return Ok(HashSet::new());
    }

    let raw = fs::read_to_string(&ledger).map_err(error::DecapodError::IoError)?;
    let mut ids = HashSet::new();
    for (idx, line) in raw.lines().enumerate() {
        if line.trim().is_empty() {
            continue;
        }
        let v: serde_json::Value = serde_json::from_str(line).map_err(|e| {
            error::DecapodError::ValidationError(format!(
                "invalid promotion ledger line {} in {}: {}",
                idx + 1,
                ledger.display(),
                e
            ))
        })?;
        if let Some(id) = v.get("event_id").and_then(|x| x.as_str()) {
            ids.insert(id.to_string());
        }
    }
    Ok(ids)
}

fn validate_lineage_hard_gate(
    store: &Store,
    ctx: &ValidationContext,
) -> Result<(), error::DecapodError> {
    info("Lineage Hard Gate");
    let todo_events = store.root.join("todo.events.jsonl");
    let federation_db = store.root.join("federation.db");
    let todo_db = store.root.join("todo.db");

    // Fast path: if any required file is missing, skip entirely
    if !todo_events.exists() || !federation_db.exists() || !todo_db.exists() {
        skip("lineage inputs missing; skipping", ctx);
        return Ok(());
    }

    // Quick check: if todo events is empty or very small, skip
    if let Ok(metadata) = fs::metadata(&todo_events) {
        if metadata.len() < 100 {
            skip("todo.events.jsonl too small; skipping", ctx);
            return Ok(());
        }
    }

    let content = match fs::read_to_string(&todo_events) {
        Ok(c) => c,
        Err(_) => {
            skip("cannot read todo.events.jsonl; skipping", ctx);
            return Ok(());
        }
    };

    // Fast path: if no intent: prefix events, skip the expensive part
    if !content.contains("intent:") {
        pass("no intent-tagged events found; skipping", ctx);
        return Ok(());
    }

    let mut add_candidates = Vec::new();
    let mut done_candidates = Vec::new();
    for line in content.lines() {
        let Ok(v) = serde_json::from_str::<serde_json::Value>(line) else {
            continue;
        };
        let event_type = v.get("event_type").and_then(|x| x.as_str()).unwrap_or("");
        let task_id = v.get("task_id").and_then(|x| x.as_str()).unwrap_or("");
        if task_id.is_empty() {
            continue;
        }
        let intent_ref = v
            .get("payload")
            .and_then(|p| p.get("intent_ref"))
            .and_then(|x| x.as_str())
            .unwrap_or("");
        // Hard gate only applies to new intent-tagged events.
        if !intent_ref.starts_with("intent:") {
            continue;
        }
        if event_type == "task.add" {
            add_candidates.push(task_id.to_string());
        } else if event_type == "task.done" {
            done_candidates.push(task_id.to_string());
        }
    }

    // Fast path: no candidates to check
    if add_candidates.is_empty() && done_candidates.is_empty() {
        pass("no intent-tagged task events to validate", ctx);
        return Ok(());
    }

    let conn = db::db_connect_for_validate(&federation_db.to_string_lossy())?;
    let todo_conn = db::db_connect_for_validate(&todo_db.to_string_lossy())?;
    let mut violations = Vec::new();

    for task_id in add_candidates {
        let exists: i64 = todo_conn
            .query_row(
                "SELECT COUNT(*) FROM tasks WHERE id = ?1",
                rusqlite::params![task_id.clone()],
                |row| row.get(0),
            )
            .map_err(error::DecapodError::RusqliteError)?;
        if exists == 0 {
            continue;
        }
        let source = format!("event:{}", task_id);
        let commitment_count: i64 = conn
            .query_row(
                "SELECT COUNT(*) FROM nodes n JOIN sources s ON s.node_id = n.id WHERE s.source = ?1 AND n.node_type = 'commitment'",
                rusqlite::params![source],
                |row| row.get(0),
            )
            .map_err(error::DecapodError::RusqliteError)?;
        if commitment_count == 0 {
            violations.push(format!(
                "task.add {} missing commitment lineage node",
                task_id
            ));
        }
    }

    for task_id in done_candidates {
        let exists: i64 = todo_conn
            .query_row(
                "SELECT COUNT(*) FROM tasks WHERE id = ?1",
                rusqlite::params![task_id.clone()],
                |row| row.get(0),
            )
            .map_err(error::DecapodError::RusqliteError)?;
        if exists == 0 {
            continue;
        }
        let source = format!("event:{}", task_id);
        let commitment_count: i64 = conn
            .query_row(
                "SELECT COUNT(*) FROM nodes n JOIN sources s ON s.node_id = n.id WHERE s.source = ?1 AND n.node_type = 'commitment'",
                rusqlite::params![source.clone()],
                |row| row.get(0),
            )
            .map_err(error::DecapodError::RusqliteError)?;
        let decision_count: i64 = conn
            .query_row(
                "SELECT COUNT(*) FROM nodes n JOIN sources s ON s.node_id = n.id WHERE s.source = ?1 AND n.node_type = 'decision'",
                rusqlite::params![source],
                |row| row.get(0),
            )
            .map_err(error::DecapodError::RusqliteError)?;
        if commitment_count == 0 || decision_count == 0 {
            violations.push(format!(
                "task.done {} missing commitment/decision lineage nodes",
                task_id
            ));
        }
    }

    if violations.is_empty() {
        pass(
            "Intent-tagged task.add/task.done events have commitment+proof lineage",
            ctx,
        );
    } else {
        fail(&format!("Lineage gate violations: {:?}", violations), ctx);
    }
    Ok(())
}

fn validate_repomap_determinism(
    ctx: &ValidationContext,
    decapod_dir: &Path,
) -> Result<(), error::DecapodError> {
    info("Repo Map Determinism Gate");
    use crate::core::repomap;
    let dir1 = decapod_dir.to_path_buf();
    let dir2 = decapod_dir.to_path_buf();
    let h1 =
        std::thread::spawn(move || serde_json::to_string(&repomap::generate_map(&dir1)).unwrap());
    let h2 =
        std::thread::spawn(move || serde_json::to_string(&repomap::generate_map(&dir2)).unwrap());

    let m1 = h1
        .join()
        .map_err(|_| error::DecapodError::ValidationError("repomap thread panicked".into()))?;
    let m2 = h2
        .join()
        .map_err(|_| error::DecapodError::ValidationError("repomap thread panicked".into()))?;

    if m1 == m2 && !m1.is_empty() {
        pass("Repo map output is deterministic", ctx);
    } else {
        fail("Repo map output is non-deterministic or empty", ctx);
    }
    Ok(())
}

fn validate_watcher_audit(
    store: &Store,
    ctx: &ValidationContext,
) -> Result<(), error::DecapodError> {
    info("Watcher Audit Gate");
    let audit_log = store.root.join("watcher.events.jsonl");
    if audit_log.exists() {
        pass("Watcher audit trail present", ctx);
    } else {
        warn(
            "Watcher audit trail missing (run `decapod govern watcher run`)",
            ctx,
        );
    }
    Ok(())
}

fn validate_watcher_purity(
    store: &Store,
    ctx: &ValidationContext,
    pre_read_broker: Option<&str>,
) -> Result<(), error::DecapodError> {
    info("Watcher Purity Gate");
    let fallback;
    let content_opt = match pre_read_broker {
        Some(c) => Some(c),
        None => {
            let audit_log = store.root.join("broker.events.jsonl");
            if audit_log.exists() {
                fallback = fs::read_to_string(audit_log)?;
                Some(fallback.as_str())
            } else {
                None
            }
        }
    };
    if let Some(content) = content_opt {
        let mut offenders = Vec::new();
        for line in content.lines() {
            if line.contains("\"actor\":\"watcher\"") {
                offenders.push(line.to_string());
            }
        }
        if offenders.is_empty() {
            pass("Watcher purity verified (read-only checks only)", ctx);
        } else {
            fail(
                &format!(
                    "Watcher subsystem attempted brokered mutations: {:?}",
                    offenders
                ),
                ctx,
            );
        }
    }
    Ok(())
}

fn validate_archive_integrity(
    store: &Store,
    ctx: &ValidationContext,
) -> Result<(), error::DecapodError> {
    info("Archive Integrity Gate");
    let db_path = store.root.join("archive.db");
    if !db_path.exists() {
        skip("archive.db not found; skipping archive check", ctx);
        return Ok(());
    }

    use crate::archive;
    let failures = archive::verify_archives(store)?;
    if failures.is_empty() {
        pass(
            "All session archives verified (content and hash match)",
            ctx,
        );
    } else {
        fail(
            &format!("Archive integrity failures detected: {:?}", failures),
            ctx,
        );
    }
    Ok(())
}

fn validate_control_plane_contract(
    store: &Store,
    ctx: &ValidationContext,
) -> Result<(), error::DecapodError> {
    info("Control Plane Contract Gate");

    // Check that all database mutations went through the broker
    // by verifying event log consistency
    let data_dir = &store.root;
    let mut violations = Vec::new();

    // Check for broker audit trail presence
    let broker_log = data_dir.join("broker.events.jsonl");
    if !broker_log.exists() {
        // First run - no broker log yet, this is OK
        pass("No broker events yet (first run)", ctx);
        return Ok(());
    }

    // Check that critical databases have corresponding broker events
    let todo_db = data_dir.join("todo.db");
    if todo_db.exists() {
        let todo_events = data_dir.join("todo.events.jsonl");
        if !todo_events.exists() {
            violations.push("todo.db exists but todo.events.jsonl is missing".to_string());
        }
    }

    let federation_db = data_dir.join("federation.db");
    if federation_db.exists() {
        let federation_events = data_dir.join("federation.events.jsonl");
        if !federation_events.exists() {
            violations
                .push("federation.db exists but federation.events.jsonl is missing".to_string());
        }
    }

    // Check for direct SQLite write patterns in process list (best effort).
    // Bound the probe to keep validate responsive in active workspaces.
    #[cfg(target_os = "linux")]
    {
        use std::process::Command;
        if let Ok(output) = Command::new("timeout")
            .args(["3s", "lsof", "+D", data_dir.to_string_lossy().as_ref()])
            .output()
        {
            if output.status.success() {
                let stdout = String::from_utf8_lossy(&output.stdout);
                for line in stdout.lines() {
                    if line.contains("sqlite") && !line.contains("decapod") {
                        violations
                            .push(format!("External SQLite process accessing store: {}", line));
                    }
                }
            }
        }
    }

    if violations.is_empty() {
        pass(
            "Control plane contract honored (all mutations brokered)",
            ctx,
        );
    } else {
        fail(
            &format!(
                "Control plane contract violations detected: {:?}",
                violations
            ),
            ctx,
        );
    }

    Ok(())
}

fn validate_canon_mutation(
    store: &Store,
    ctx: &ValidationContext,
    pre_read_broker: Option<&str>,
) -> Result<(), error::DecapodError> {
    info("Canon Mutation Gate");
    let fallback;
    let content_opt = match pre_read_broker {
        Some(c) => Some(c),
        None => {
            let audit_log = store.root.join("broker.events.jsonl");
            if audit_log.exists() {
                fallback = fs::read_to_string(audit_log)?;
                Some(fallback.as_str())
            } else {
                None
            }
        }
    };
    if let Some(content) = content_opt {
        let mut offenders = Vec::new();
        for line in content.lines() {
            if line.contains("\"op\":\"write\"")
                && (line.contains(".md\"") || line.contains(".json\""))
                && !line.contains("\"actor\":\"decapod\"")
                && !line.contains("\"actor\":\"scaffold\"")
            {
                offenders.push(line.to_string());
            }
        }
        if offenders.is_empty() {
            pass("No unauthorized canon mutations detected", ctx);
        } else {
            warn(
                &format!(
                    "Detected direct mutations to canonical documents: {:?}",
                    offenders
                ),
                ctx,
            );
        }
    }
    Ok(())
}

fn validate_heartbeat_invocation_gate(
    ctx: &ValidationContext,
    decapod_dir: &Path,
) -> Result<(), error::DecapodError> {
    info("Heartbeat Invocation Gate");

    let lib_rs = decapod_dir.join("src").join("lib.rs");
    let todo_rs = decapod_dir.join("src").join("plugins").join("todo.rs");
    if lib_rs.exists() && todo_rs.exists() {
        let lib_content = fs::read_to_string(&lib_rs).unwrap_or_default();
        let todo_content = fs::read_to_string(&todo_rs).unwrap_or_default();

        let code_markers = [
            (
                lib_content.contains("should_auto_clock_in(&cli.command)")
                    && lib_content.contains("todo::clock_in_agent_presence(&project_store)?"),
                "Top-level command dispatch auto-clocks heartbeat",
            ),
            (
                lib_content
                    .contains("Command::Todo(todo_cli) => !todo::is_heartbeat_command(todo_cli)"),
                "Decorator excludes explicit todo heartbeat to prevent duplicates",
            ),
            (
                todo_content.contains("pub fn clock_in_agent_presence")
                    && todo_content.contains("record_heartbeat"),
                "TODO plugin exposes reusable clock-in helper",
            ),
        ];

        for (ok, msg) in code_markers {
            if ok {
                pass(msg, ctx);
            } else {
                fail(msg, ctx);
            }
        }
    } else {
        skip(
            "Heartbeat wiring source files absent; skipping code-level heartbeat checks",
            ctx,
        );
    }

    let doc_markers = [
        (
            crate::core::assets::get_doc("core/DECAPOD.md")
                .unwrap_or_default()
                .contains("invocation heartbeat"),
            "Router documents invocation heartbeat contract",
        ),
        (
            crate::core::assets::get_doc("interfaces/CONTROL_PLANE.md")
                .unwrap_or_default()
                .contains("invocation heartbeat"),
            "Control-plane interface documents invocation heartbeat",
        ),
        (
            crate::core::assets::get_doc("plugins/TODO.md")
                .unwrap_or_default()
                .contains("auto-clocks liveness"),
            "TODO plugin documents automatic liveness clock-in",
        ),
        (
            crate::core::assets::get_doc("plugins/REFLEX.md")
                .unwrap_or_default()
                .contains("todo.heartbeat.autoclaim"),
            "REFLEX plugin documents heartbeat autoclaim action",
        ),
    ];

    for (ok, msg) in doc_markers {
        if ok {
            pass(msg, ctx);
        } else {
            fail(msg, ctx);
        }
    }

    Ok(())
}

fn validate_federation_gates(
    store: &Store,
    ctx: &ValidationContext,
) -> Result<(), error::DecapodError> {
    info("Federation Gates");

    let results = crate::plugins::federation::validate_federation(&store.root)?;

    for (gate_name, passed, message) in results {
        if passed {
            pass(&format!("[{}] {}", gate_name, message), ctx);
        } else {
            // Federation gates are advisory (warn) rather than hard-fail because the
            // two-phase DB+JSONL write design can produce transient drift that does
            // not indicate data loss.
            warn(&format!("[{}] {}", gate_name, message), ctx);
        }
    }

    Ok(())
}

fn validate_markdown_primitives_roundtrip_gate(
    store: &Store,
    ctx: &ValidationContext,
) -> Result<(), error::DecapodError> {
    info("Markdown Primitive Round-Trip Gate");
    match primitives::validate_roundtrip_gate(store) {
        Ok(()) => {
            pass(
                "Markdown primitives export and round-trip validation pass",
                ctx,
            );
        }
        Err(err) => {
            fail(
                &format!("Markdown primitive round-trip failed: {}", err),
                ctx,
            );
        }
    }
    Ok(())
}

/// Validates that tooling requirements are satisfied.
/// This gate ensures formatting, linting, and type checking pass before promotion.
fn validate_git_workspace_context(
    ctx: &ValidationContext,
    repo_root: &Path,
) -> Result<(), error::DecapodError> {
    info("Git Workspace Context Gate");

    // Allow bypass for testing/CI environments
    if std::env::var("DECAPOD_VALIDATE_SKIP_GIT_GATES").is_ok() {
        skip(
            "Git workspace gates skipped (DECAPOD_VALIDATE_SKIP_GIT_GATES set)",
            ctx,
        );
        return Ok(());
    }

    // Exempt read-only schema commands (data schema, lcm schema, map schema)
    let args: Vec<String> = std::env::args().collect();
    let is_schema_command = args.iter().any(|a| {
        a == "schema"
            || (a == "lcm"
                && args
                    .iter()
                    .skip_while(|x| *x != "lcm")
                    .nth(1)
                    .is_some_and(|x| x == "schema"))
            || (a == "map"
                && args
                    .iter()
                    .skip_while(|x| *x != "map")
                    .nth(1)
                    .is_some_and(|x| x == "schema"))
    });
    if is_schema_command {
        skip(
            "Schema command exempted from workspace requirement (read-only)",
            ctx,
        );
        return Ok(());
    }

    let signals_container = [
        (
            std::env::var("DECAPOD_CONTAINER").ok().as_deref() == Some("1"),
            "DECAPOD_CONTAINER=1",
        ),
        (repo_root.join(".dockerenv").exists(), ".dockerenv marker"),
        (
            repo_root.join(".devcontainer").exists(),
            ".devcontainer marker",
        ),
        (
            std::env::var("DOCKER_CONTAINER").is_ok(),
            "DOCKER_CONTAINER env",
        ),
    ];

    let in_container = signals_container.iter().any(|(signal, _)| *signal);

    if in_container {
        let reasons: Vec<&str> = signals_container
            .iter()
            .filter(|(signal, _)| *signal)
            .map(|(_, name)| *name)
            .collect();
        pass(
            &format!(
                "Running in container workspace (signals: {})",
                reasons.join(", ")
            ),
            ctx,
        );
    } else {
        fail(
            "Not running in container workspace - git-tracked work must execute in Docker-isolated workspace (claim.git.container_workspace_required)",
            ctx,
        );
    }

    let git_dir = repo_root.join(".git");
    let is_worktree = git_dir.is_file() && {
        let content = fs::read_to_string(&git_dir).unwrap_or_default();
        content.contains("gitdir:")
    };

    if is_worktree {
        pass("Running in git worktree (isolated branch)", ctx);
    } else if in_container {
        pass(
            "Container workspace detected (worktree check informational)",
            ctx,
        );
    } else {
        fail(
            "Not running in isolated git worktree - must use container workspace for implementation work",
            ctx,
        );
    }

    validate_commit_often_gate(ctx, repo_root)?;

    Ok(())
}

fn validate_commit_often_gate(
    ctx: &ValidationContext,
    repo_root: &Path,
) -> Result<(), error::DecapodError> {
    let max_dirty_files = std::env::var("DECAPOD_COMMIT_OFTEN_MAX_DIRTY_FILES")
        .ok()
        .and_then(|v| v.parse::<usize>().ok())
        .filter(|v| *v > 0)
        .unwrap_or(6);

    let status_output = std::process::Command::new("git")
        .args(["status", "--porcelain"])
        .current_dir(repo_root)
        .output()
        .map_err(error::DecapodError::IoError)?;

    if !status_output.status.success() {
        warn("Commit-often gate skipped: unable to read git status", ctx);
        return Ok(());
    }

    let dirty_count = String::from_utf8_lossy(&status_output.stdout)
        .lines()
        .filter(|line| !line.trim().is_empty())
        .count();

    if dirty_count == 0 {
        pass("Commit-often gate: working tree is clean", ctx);
        return Ok(());
    }

    if dirty_count > max_dirty_files {
        fail(
            &format!(
                "Commit-often mandate violation: {} dirty file(s) exceed limit {}. Commit incremental changes before continuing.",
                dirty_count, max_dirty_files
            ),
            ctx,
        );
    } else {
        pass(
            &format!(
                "Commit-often gate: {} dirty file(s) within limit {}",
                dirty_count, max_dirty_files
            ),
            ctx,
        );
    }

    Ok(())
}

fn validate_plan_governed_execution_gate(
    store: &Store,
    ctx: &ValidationContext,
    repo_root: &Path,
) -> Result<(), error::DecapodError> {
    info("Plan-Governed Execution Gate");

    // Test harnesses and isolated fixture repos explicitly bypass git gates.
    // Keep plan-governed promotion checks out of that mode to preserve stable
    // verification replay fixtures that are not modeled as full workspaces.
    if std::env::var("DECAPOD_VALIDATE_SKIP_GIT_GATES").is_ok() {
        skip(
            "Plan-governed execution gate skipped (DECAPOD_VALIDATE_SKIP_GIT_GATES set)",
            ctx,
        );
        return Ok(());
    }

    let plan = plan_governance::load_plan(repo_root)?;
    if let Some(plan) = plan {
        if plan.state != plan_governance::PlanState::Approved
            && plan.state != plan_governance::PlanState::Done
        {
            fail(
                &format!(
                    "NEEDS_PLAN_APPROVAL: plan state is {:?}; execution/promotion requires APPROVED or DONE",
                    plan.state
                ),
                ctx,
            );
        } else {
            pass("Plan artifact state allows governed execution", ctx);
        }

        if plan.intent.trim().is_empty()
            || !plan.unknowns.is_empty()
            || !plan.human_questions.is_empty()
        {
            fail(
                "NEEDS_HUMAN_INPUT: governed plan has unresolved intent/unknowns/questions",
                ctx,
            );
        } else {
            pass("Plan intent and unknowns are resolved", ctx);
        }
    } else {
        let done_count = plan_governance::count_done_todos(&store.root)?;
        if done_count > 0 {
            fail(
                &format!(
                    "NEEDS_PLAN_APPROVAL: {} done TODO(s) exist but governed PLAN artifact is missing",
                    done_count
                ),
                ctx,
            );
        } else {
            pass(
                "No governed plan artifact present; gate is advisory until first done TODO",
                ctx,
            );
        }
    }

    let unverified = plan_governance::collect_unverified_done_todos(&store.root)?;
    if !unverified.is_empty() {
        fail(
            &format!(
                "PROOF_HOOK_FAILED: {} done TODO(s) are CLAIMED but not VERIFIED: {}",
                unverified.len(),
                output::preview_messages(&unverified, 4, 80)
            ),
            ctx,
        );
    } else {
        pass("Done TODOs are proof-verified", ctx);
    }

    Ok(())
}

fn validate_git_protected_branch(
    ctx: &ValidationContext,
    repo_root: &Path,
) -> Result<(), error::DecapodError> {
    info("Git Protected Branch Gate");

    // Allow bypass for testing/CI environments
    if std::env::var("DECAPOD_VALIDATE_SKIP_GIT_GATES").is_ok() {
        skip(
            "Git protected branch gate skipped (DECAPOD_VALIDATE_SKIP_GIT_GATES set)",
            ctx,
        );
        return Ok(());
    }

    let protected_patterns = ["master", "main", "production", "stable"];

    let current_branch = {
        let output = std::process::Command::new("git")
            .args(["rev-parse", "--abbrev-ref", "HEAD"])
            .current_dir(repo_root)
            .output();
        output
            .ok()
            .and_then(|o| {
                if o.status.success() {
                    Some(String::from_utf8_lossy(&o.stdout).trim().to_string())
                } else {
                    None
                }
            })
            .unwrap_or_else(|| "unknown".to_string())
    };

    let is_protected = protected_patterns
        .iter()
        .any(|p| current_branch == *p || current_branch.starts_with("release/"));

    if is_protected {
        fail(
            &format!(
                "Currently on protected branch '{}' - implementation work must happen in working branch, not directly on protected refs (claim.git.no_direct_main_push)",
                current_branch
            ),
            ctx,
        );
    } else {
        pass(
            &format!("On working branch '{}' (not protected)", current_branch),
            ctx,
        );
    }

    let has_remote = std::process::Command::new("git")
        .args(["remote", "get-url", "origin"])
        .current_dir(repo_root)
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false);

    if has_remote {
        let ahead_behind = std::process::Command::new("git")
            .args(["rev-list", "--left-right", "--count", "HEAD...origin/HEAD"])
            .current_dir(repo_root)
            .output();

        if let Ok(out) = ahead_behind {
            if out.status.success() {
                let counts = String::from_utf8_lossy(&out.stdout);
                let parts: Vec<&str> = counts.split_whitespace().collect();
                if parts.len() >= 2 {
                    let ahead: u32 = parts[0].parse().unwrap_or(0);
                    if ahead > 0 {
                        let output = std::process::Command::new("git")
                            .args(["rev-list", "--format=%s", "-n1", "HEAD"])
                            .current_dir(repo_root)
                            .output();
                        let commit_msg = output
                            .ok()
                            .and_then(|o| {
                                if o.status.success() {
                                    Some(String::from_utf8_lossy(&o.stdout).trim().to_string())
                                } else {
                                    None
                                }
                            })
                            .unwrap_or_else(|| "unknown".to_string());

                        fail(
                            &format!(
                                "Protected branch has {} unpushed commit(s) - direct push to protected branch detected (commit: {})",
                                ahead, commit_msg
                            ),
                            ctx,
                        );
                    } else {
                        pass("No unpushed commits to protected branches", ctx);
                    }
                }
            }
        }
    }

    Ok(())
}

fn validate_tooling_gate(
    ctx: &ValidationContext,
    repo_root: &Path,
) -> Result<(), error::DecapodError> {
    info("Tooling Validation Gate");

    let tooling_enabled = std::env::var("DECAPOD_VALIDATE_ENABLE_TOOLING_GATES")
        .ok()
        .map(|v| matches!(v.as_str(), "1" | "true" | "TRUE" | "yes" | "YES"))
        .unwrap_or(false);
    if !tooling_enabled {
        skip(
            "Tooling validation gates disabled by default (set DECAPOD_VALIDATE_ENABLE_TOOLING_GATES=1 to enable)",
            ctx,
        );
        return Ok(());
    }

    if std::env::var("DECAPOD_VALIDATE_SKIP_TOOLING_GATES").is_ok() {
        skip(
            "Tooling validation gates skipped (DECAPOD_VALIDATE_SKIP_TOOLING_GATES set)",
            ctx,
        );
        return Ok(());
    }

    let mut has_failures = false;
    let mut has_tooling = false;

    let cargo_toml = repo_root.join("Cargo.toml");
    if cargo_toml.exists() {
        has_tooling = true;
        let root_fmt = repo_root.to_path_buf();
        let root_clippy = repo_root.to_path_buf();

        let fmt_handle = std::thread::spawn(move || {
            std::process::Command::new("cargo")
                .args(["fmt", "--all", "--", "--check"])
                .current_dir(&root_fmt)
                .output()
        });

        let clippy_handle = std::thread::spawn(move || {
            std::process::Command::new("cargo")
                .args([
                    "clippy",
                    "--all-targets",
                    "--all-features",
                    "--",
                    "-D",
                    "warnings",
                ])
                .current_dir(&root_clippy)
                .output()
        });

        match fmt_handle.join().expect("fmt thread panicked") {
            Ok(output) => {
                if output.status.success() {
                    pass("Rust code formatting passes (cargo fmt)", ctx);
                } else {
                    fail("Rust code formatting failed - run `cargo fmt --all`", ctx);
                    has_failures = true;
                }
            }
            Err(e) => {
                fail(&format!("Failed to run cargo fmt: {}", e), ctx);
                has_failures = true;
            }
        }

        match clippy_handle.join().expect("clippy thread panicked") {
            Ok(output) => {
                if output.status.success() {
                    pass("Rust linting passes (cargo clippy)", ctx);
                } else {
                    fail(
                        "Rust linting failed - run `cargo clippy --all-targets --all-features`",
                        ctx,
                    );
                    has_failures = true;
                }
            }
            Err(e) => {
                fail(&format!("Failed to run cargo clippy: {}", e), ctx);
                has_failures = true;
            }
        }
    }

    let pyproject = repo_root.join("pyproject.toml");
    let requirements = repo_root.join("requirements.txt");
    if pyproject.exists() || requirements.exists() {
        has_tooling = true;

        if std::process::Command::new("which")
            .arg("ruff")
            .output()
            .map(|o| o.status.success())
            .unwrap_or(false)
        {
            let root_ruff = repo_root.to_path_buf();
            let ruff_handle = std::thread::spawn(move || {
                std::process::Command::new("ruff")
                    .args(["check", ".", "--output-format=concise"])
                    .current_dir(&root_ruff)
                    .output()
            });

            match ruff_handle.join().expect("ruff thread panicked") {
                Ok(output) => {
                    if output.status.success() {
                        pass("Python linting passes (ruff)", ctx);
                    } else {
                        fail("Python linting failed - fix ruff violations", ctx);
                        has_failures = true;
                    }
                }
                Err(e) => {
                    warn(&format!("ruff not available: {}", e), ctx);
                }
            }
        } else {
            skip("ruff not installed; skipping Python linting", ctx);
        }
    }

    let shell_check = repo_root.join(".shellcheckrc");
    let shell_files_exist = std::fs::read_dir(repo_root)
        .into_iter()
        .flatten()
        .filter_map(|e| e.ok())
        .any(|e| {
            let p = e.path();
            p.is_file() && p.extension().map(|s| s == "sh").unwrap_or(false)
        });

    if shell_check.exists() || shell_files_exist {
        has_tooling = true;

        if std::process::Command::new("which")
            .arg("shellcheck")
            .output()
            .map(|o| o.status.success())
            .unwrap_or(false)
        {
            let repo_root_clone = repo_root.to_path_buf();
            let shellcheck_handle = std::thread::spawn(move || {
                std::process::Command::new("shellcheck")
                    .args(["--enable=all"])
                    .current_dir(repo_root_clone)
                    .output()
            });

            match shellcheck_handle
                .join()
                .expect("shellcheck thread panicked")
            {
                Ok(output) => {
                    if output.status.success() {
                        pass("Shell script linting passes (shellcheck)", ctx);
                    } else {
                        fail(
                            "Shell script linting failed - fix shellcheck violations",
                            ctx,
                        );
                        has_failures = true;
                    }
                }
                Err(e) => {
                    warn(&format!("shellcheck failed: {}", e), ctx);
                }
            }
        } else {
            skip("shellcheck not installed; skipping shell linting", ctx);
        }
    }

    let yaml_check = repo_root.join(".yamllint");
    let yaml_files_exist = std::fs::read_dir(repo_root)
        .into_iter()
        .flatten()
        .filter_map(|e| e.ok())
        .any(|e| {
            let p = e.path();
            p.is_file()
                && p.extension()
                    .map(|s| s == "yaml" || s == "yml")
                    .unwrap_or(false)
        });

    if yaml_check.exists() || yaml_files_exist {
        has_tooling = true;

        if std::process::Command::new("which")
            .arg("yamllint")
            .output()
            .map(|o| o.status.success())
            .unwrap_or(false)
        {
            let repo_root_clone = repo_root.to_path_buf();
            let yamllint_handle = std::thread::spawn(move || {
                std::process::Command::new("yamllint")
                    .arg(".")
                    .current_dir(repo_root_clone)
                    .output()
            });

            match yamllint_handle.join().expect("yamllint thread panicked") {
                Ok(output) => {
                    if output.status.success() {
                        pass("YAML linting passes (yamllint)", ctx);
                    } else {
                        fail("YAML linting failed - fix yamllint violations", ctx);
                        has_failures = true;
                    }
                }
                Err(e) => {
                    warn(&format!("yamllint failed: {}", e), ctx);
                }
            }
        } else {
            skip("yamllint not installed; skipping YAML linting", ctx);
        }
    }

    let dockerfile_exists = std::fs::read_dir(repo_root)
        .into_iter()
        .flatten()
        .filter_map(|e| e.ok())
        .any(|e| {
            e.path()
                .file_name()
                .and_then(|n| n.to_str())
                .map(|n| n.to_lowercase() == "dockerfile")
                .unwrap_or(false)
        });

    if dockerfile_exists {
        has_tooling = true;

        if std::process::Command::new("which")
            .arg("hadolint")
            .output()
            .map(|o| o.status.success())
            .unwrap_or(false)
        {
            let repo_root_clone = repo_root.to_path_buf();
            let hadolint_handle = std::thread::spawn(move || {
                std::process::Command::new("hadolint")
                    .args(["Dockerfile"])
                    .current_dir(repo_root_clone)
                    .output()
            });

            match hadolint_handle.join().expect("hadolint thread panicked") {
                Ok(output) => {
                    if output.status.success() {
                        pass("Dockerfile linting passes (hadolint)", ctx);
                    } else {
                        fail("Dockerfile linting failed - fix hadolint violations", ctx);
                        has_failures = true;
                    }
                }
                Err(e) => {
                    warn(&format!("hadolint failed: {}", e), ctx);
                }
            }
        } else {
            skip("hadolint not installed; skipping Dockerfile linting", ctx);
        }
    }

    if !has_tooling {
        skip(
            "No recognized project files found; skipping tooling validation",
            ctx,
        );
    } else if !has_failures {
        pass(
            "All toolchain validations pass - project is ready for promotion",
            ctx,
        );
    }

    Ok(())
}

fn validate_state_commit_gate(
    ctx: &ValidationContext,
    repo_root: &Path,
) -> Result<(), error::DecapodError> {
    info("STATE_COMMIT Validation Gate");

    // Policy knob: configurable CI job name (can be set via env var)
    let required_ci_job = std::env::var("DECAPOD_STATE_COMMIT_CI_JOB")
        .unwrap_or_else(|_| "state_commit_golden_vectors".to_string());

    info(&format!(
        "STATE_COMMIT: required_ci_job = {}",
        required_ci_job
    ));

    // Check for v1 golden directory (versioned)
    let golden_v1_dir = repo_root
        .join("tests")
        .join("golden")
        .join("state_commit")
        .join("v1");
    if !golden_v1_dir.exists() {
        skip(
            "No tests/golden/state_commit/v1 directory found; skipping STATE_COMMIT validation",
            ctx,
        );
        return Ok(());
    }

    // Check for required v1 golden files
    let required_files = ["scope_record_hash.txt", "state_commit_root.txt"];
    let mut has_golden = true;
    for file in &required_files {
        if !golden_v1_dir.join(file).exists() {
            fail(
                &format!("Missing golden file: tests/golden/state_commit/v1/{}", file),
                ctx,
            );
            has_golden = false;
        }
    }

    // Immutability check: v1 files should not change
    // In v1, these are the canonical golden vectors
    if has_golden {
        pass("STATE_COMMIT v1 golden vectors present", ctx);

        // Verify the expected hashes match v1 protocol
        let expected_scope_hash =
            "41d7e3729b6f4512887fb3cb6f10140942b600041e0d88308b0177e06ebb4b93";
        let expected_root = "28591ac86e52ffac76d5fc3aceeceda5d8592708a8d7fcb75371567fdc481492";

        if let Ok(actual_hash) =
            std::fs::read_to_string(golden_v1_dir.join("scope_record_hash.txt"))
        {
            if actual_hash.trim() != expected_scope_hash {
                fail(
                    &format!(
                        "STATE_COMMIT v1 scope_record_hash changed! Expected {}, got {}. This requires a SPEC_VERSION bump to v2.",
                        expected_scope_hash,
                        actual_hash.trim()
                    ),
                    ctx,
                );
            }
        }

        if let Ok(actual_root) =
            std::fs::read_to_string(golden_v1_dir.join("state_commit_root.txt"))
        {
            if actual_root.trim() != expected_root {
                fail(
                    &format!(
                        "STATE_COMMIT v1 state_commit_root changed! Expected {}, got {}. This requires a SPEC_VERSION bump to v2.",
                        expected_root,
                        actual_root.trim()
                    ),
                    ctx,
                );
            }
        }
    }

    Ok(())
}

fn validate_obligations(store: &Store, ctx: &ValidationContext) -> Result<(), error::DecapodError> {
    // Initialize the DB to ensure tables exist
    crate::core::obligation::initialize_obligation_db(&store.root)?;

    let obligations = crate::core::obligation::list_obligations(store)?;
    let mut met_count = 0;
    for ob in obligations {
        // If an obligation is marked Met, we MUST verify it still holds
        if ob.status == crate::core::obligation::ObligationStatus::Met {
            let (status, reason) = crate::core::obligation::verify_obligation(store, &ob.id)?;
            if status != crate::core::obligation::ObligationStatus::Met {
                fail(
                    &format!("Obligation {} failed verification: {}", ob.id, reason),
                    ctx,
                );
            } else {
                met_count += 1;
            }
        }
    }
    pass(
        &format!(
            "Obligation Graph Validation Gate ({} met nodes verified)",
            met_count
        ),
        ctx,
    );
    Ok(())
}

fn validate_lcm_immutability(
    store: &Store,
    ctx: &ValidationContext,
) -> Result<(), error::DecapodError> {
    info("LCM Immutability Gate");
    let ledger_path = store.root.join(crate::core::schemas::LCM_EVENTS_NAME);
    if !ledger_path.exists() {
        pass("No LCM ledger yet; gate trivially passes", ctx);
        return Ok(());
    }

    let failures = crate::plugins::lcm::validate_ledger_integrity(&store.root)?;
    if failures.is_empty() {
        pass("LCM ledger integrity verified", ctx);
    } else {
        for f in &failures {
            fail(&format!("LCM immutability: {}", f), ctx);
        }
    }
    Ok(())
}

fn validate_lcm_rebuild_gate(
    store: &Store,
    ctx: &ValidationContext,
) -> Result<(), error::DecapodError> {
    info("LCM Rebuild Gate");
    let ledger_path = store.root.join(crate::core::schemas::LCM_EVENTS_NAME);
    if !ledger_path.exists() {
        pass("No LCM ledger yet; rebuild gate trivially passes", ctx);
        return Ok(());
    }

    let result = crate::plugins::lcm::rebuild_index(store, true)?;
    if result.get("status").and_then(|v| v.as_str()) == Some("success") {
        pass("LCM index rebuild successful", ctx);
    } else {
        let errors = result
            .get("errors")
            .and_then(|v| v.as_array())
            .map(|a| {
                a.iter()
                    .filter_map(|e| e.as_str())
                    .collect::<Vec<_>>()
                    .join(", ")
            })
            .unwrap_or_default();
        fail(&format!("LCM rebuild failed: {}", errors), ctx);
    }
    Ok(())
}

fn validate_gatekeeper_gate(
    ctx: &ValidationContext,
    decapod_dir: &Path,
) -> Result<(), error::DecapodError> {
    info("Gatekeeper Safety Gate");

    // Get staged files from git (if in a git repo)
    let output = std::process::Command::new("git")
        .args(["diff", "--cached", "--name-only"])
        .current_dir(decapod_dir)
        .output();

    let staged_paths: Vec<PathBuf> = match output {
        Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout)
            .lines()
            .filter(|l| !l.is_empty())
            .map(PathBuf::from)
            .collect(),
        _ => {
            skip(
                "Git not available or not in a repo; skipping gatekeeper gate",
                ctx,
            );
            return Ok(());
        }
    };

    if staged_paths.is_empty() {
        pass("No staged files; gatekeeper gate trivially passes", ctx);
        return Ok(());
    }

    let config = crate::core::gatekeeper::GatekeeperConfig::default();
    let result = crate::core::gatekeeper::run_gatekeeper(decapod_dir, &staged_paths, 0, &config)?;

    if result.passed {
        pass(
            &format!(
                "Gatekeeper: {} staged file(s) passed safety checks",
                staged_paths.len()
            ),
            ctx,
        );
    } else {
        let secret_count = result
            .violations
            .iter()
            .filter(|v| v.kind == crate::core::gatekeeper::ViolationKind::SecretDetected)
            .count();
        let blocked_count = result
            .violations
            .iter()
            .filter(|v| v.kind == crate::core::gatekeeper::ViolationKind::PathBlocked)
            .count();
        let dangerous_count = result
            .violations
            .iter()
            .filter(|v| v.kind == crate::core::gatekeeper::ViolationKind::DangerousPattern)
            .count();

        let mut parts = Vec::new();
        if secret_count > 0 {
            parts.push(format!("{} secret(s)", secret_count));
        }
        if blocked_count > 0 {
            parts.push(format!("{} blocked path(s)", blocked_count));
        }
        if dangerous_count > 0 {
            parts.push(format!("{} dangerous pattern(s)", dangerous_count));
        }
        fail(&format!("Gatekeeper violations: {}", parts.join(", ")), ctx);
    }

    Ok(())
}

/// Evaluates a set of mandates and returns any active blockers.
pub fn evaluate_mandates(
    project_root: &Path,
    store: &Store,
    mandates: &[crate::core::docs::Mandate],
) -> Vec<crate::core::rpc::Blocker> {
    use crate::core::rpc::{Blocker, BlockerKind};
    let mut blockers = Vec::new();

    for mandate in mandates {
        match mandate.check_tag.as_str() {
            "gate.worktree.no_master" => {
                let status = crate::core::workspace::get_workspace_status(project_root);
                if let Ok(s) = status {
                    if s.git.is_protected {
                        blockers.push(Blocker {
                            kind: BlockerKind::ProtectedBranch,
                            message: format!("Mandate Violation: {}", mandate.fragment.title),
                            resolve_hint:
                                "Run `decapod workspace ensure` to create a working branch."
                                    .to_string(),
                        });
                    }
                }
            }
            "gate.worktree.isolated" => {
                let status = crate::core::workspace::get_workspace_status(project_root);
                if let Ok(s) = status {
                    if !s.git.in_worktree {
                        blockers.push(Blocker {
                            kind: BlockerKind::WorkspaceRequired,
                            message: format!("Mandate Violation: {}", mandate.fragment.title),
                            resolve_hint:
                                "Run `decapod workspace ensure` to create an isolated git worktree."
                                    .to_string(),
                        });
                    }
                }
            }
            "gate.session.active" => {
                // This is usually handled by the RPC kernel session check,
                // but we can add a blocker if we want more detail.
            }
            "gate.todo.active_task" => {
                let agent_id =
                    std::env::var("DECAPOD_AGENT_ID").unwrap_or_else(|_| "unknown".to_string());
                if agent_id != "unknown" {
                    let mut active_tasks = crate::core::todo::list_tasks(
                        &store.root,
                        Some("open".to_string()),
                        None,
                        None,
                        None,
                        None,
                    );
                    if let Ok(ref mut tasks) = active_tasks {
                        let pre_filter_count = tasks.len();
                        let debug_info = if !tasks.is_empty() {
                            format!(
                                "First task assigned to: '{}', My ID: '{}'",
                                tasks[0].assigned_to, agent_id
                            )
                        } else {
                            format!(
                                "No tasks found. My ID: '{}', Root: '{}'",
                                agent_id,
                                project_root.display()
                            )
                        };

                        tasks.retain(|t| t.assigned_to == agent_id);
                        if tasks.is_empty() {
                            blockers.push(Blocker {
                                kind: BlockerKind::MissingProof,
                                message: format!("Mandate Violation: {} (Pre-filter: {}, {})", mandate.fragment.title, pre_filter_count, debug_info),
                                resolve_hint: "You MUST create and claim a `todo` before starting work. Run `decapod todo add \"...\"` then `decapod todo claim --id <id>`.".to_string(),
                            });
                        }
                    }
                }
            }
            "gate.validation.pass" => {
                // Future: check a 'last_validated' marker in the store
            }
            _ => {}
        }
    }

    blockers
}

/// Co-Player Policy Tightening Gate
///
/// Validates that the coplayer policy derivation function only tightens
/// constraints as reliability decreases. This is a structural invariant:
/// no snapshot should produce a policy that is looser than a less-reliable one.
fn validate_coplayer_policy_tightening(
    ctx: &ValidationContext,
    _decapod_dir: &Path,
) -> Result<(), error::DecapodError> {
    info("Co-Player Policy Tightening Gate");

    use crate::core::coplayer::{CoPlayerSnapshot, derive_policy};

    // Test the invariant: unknown → high → medium → low reliability
    // Each step must be equal or tighter than the next.
    let profiles = vec![
        ("unknown", 0.0, 0),
        ("high", 0.5, 20),
        ("medium", 0.8, 20),
        ("low", 0.95, 100),
    ];

    let mut prev_policy = None;
    let mut all_valid = true;

    for (risk, reliability, total) in &profiles {
        let snap = CoPlayerSnapshot {
            agent_id: format!("gate-test-{}", risk),
            reliability_score: *reliability,
            total_ops: *total,
            successful_ops: (*total as f64 * reliability) as usize,
            failed_ops: *total - (*total as f64 * reliability) as usize,
            last_active: "gate-test".to_string(),
            common_ops: vec![],
            risk_profile: risk.to_string(),
        };

        let policy = derive_policy(&snap);

        // Validation is ALWAYS required
        if !policy.require_validation {
            fail(
                &format!(
                    "Co-player policy for '{}' does not require validation (MUST always be true)",
                    risk
                ),
                ctx,
            );
            all_valid = false;
        }

        // Check tightening: diff limits must be <= previous (less reliable) agent's limits
        if let Some(prev) = &prev_policy {
            let prev: &crate::core::coplayer::CoPlayerPolicy = prev;
            // More reliable agents may have larger diff limits, never smaller
            if policy.max_diff_lines < prev.max_diff_lines {
                // This is expected: more reliable = looser (larger diff limit)
                // The INVARIANT is the reverse must not happen:
                // less reliable must not have LARGER limits than more reliable
            }
        }

        prev_policy = Some(policy);
    }

    if all_valid {
        pass("Co-player policies only tighten constraints", ctx);
    }

    Ok(())
}

pub fn run_validation(
    store: &Store,
    decapod_dir: &Path,
    _home_dir: &Path,
    verbose: bool,
) -> Result<(), error::DecapodError> {
    let total_start = Instant::now();
    use colored::Colorize;
    println!(
        "{} {}",
        "â–¶".bright_green().bold(),
        "validate:".bright_cyan().bold()
    );

    // Directly get content from embedded assets
    let intent_content = crate::core::assets::get_doc("specs/INTENT.md").unwrap_or_default();
    let intent_version =
        extract_md_version(&intent_content).unwrap_or_else(|| "unknown".to_string());
    println!(
        "  {} intent_version={}",
        "spec:".bright_cyan(),
        intent_version.bright_white()
    );

    let ctx = ValidationContext::new();

    // Pre-read broker.events.jsonl once for gates that need it
    let broker_events_path = store.root.join("broker.events.jsonl");
    let broker_content: Option<String> = if broker_events_path.exists() {
        fs::read_to_string(&broker_events_path).ok()
    } else {
        None
    };

    // Store validations — run sequentially since they set up state
    match store.kind {
        StoreKind::User => {
            let start = Instant::now();
            validate_user_store_blank_slate(&ctx)?;
            if verbose {
                println!(
                    "  {} [validate_user_store_blank_slate] {} ({:.2?})",
                    "✓".bright_green(),
                    "done".bright_white(),
                    start.elapsed()
                );
            }
        }
        StoreKind::Repo => {
            let start = Instant::now();
            validate_repo_store_dogfood(store, &ctx, decapod_dir)?;
            if verbose {
                println!(
                    "  {} [validate_repo_store_dogfood] {} ({:.2?})",
                    "✓".bright_green(),
                    "done".bright_white(),
                    start.elapsed()
                );
            }
        }
    }

    println!(
        "  {} {}",
        "gate:".bright_magenta().bold(),
        "Four Invariants Gate".bright_white()
    );

    // Run remaining gates in parallel for bounded wall-clock validation time.
    let timings: Mutex<Vec<(&str, Duration)>> = Mutex::new(Vec::new());
    rayon::scope(|s| {
        let ctx = &ctx;
        let timings = &timings;
        let broker = broker_content.as_deref();

        s.spawn(move |_| {
            let start = Instant::now();
            if let Err(e) = validate_repo_map(ctx, decapod_dir) {
                fail(&format!("gate error: {e}"), ctx);
            }
            timings
                .lock()
                .unwrap()
                .push(("validate_repo_map", start.elapsed()));
        });
        s.spawn(move |_| {
            let start = Instant::now();
            if let Err(e) = validate_no_legacy_namespaces(ctx, decapod_dir) {
                fail(&format!("gate error: {e}"), ctx);
            }
            timings
                .lock()
                .unwrap()
                .push(("validate_no_legacy_namespaces", start.elapsed()));
        });
        s.spawn(move |_| {
            let start = Instant::now();
            if let Err(e) = validate_embedded_self_contained(ctx, decapod_dir) {
                fail(&format!("gate error: {e}"), ctx);
            }
            timings
                .lock()
                .unwrap()
                .push(("validate_embedded_self_contained", start.elapsed()));
        });
        s.spawn(move |_| {
            let start = Instant::now();
            if let Err(e) = validate_docs_templates_bucket(ctx, decapod_dir) {
                fail(&format!("gate error: {e}"), ctx);
            }
            timings
                .lock()
                .unwrap()
                .push(("validate_docs_templates_bucket", start.elapsed()));
        });
        s.spawn(move |_| {
            let start = Instant::now();
            if let Err(e) = validate_entrypoint_invariants(ctx, decapod_dir) {
                fail(&format!("gate error: {e}"), ctx);
            }
            timings
                .lock()
                .unwrap()
                .push(("validate_entrypoint_invariants", start.elapsed()));
        });
        s.spawn(move |_| {
            let start = Instant::now();
            if let Err(e) = validate_interface_contract_bootstrap(ctx, decapod_dir) {
                fail(&format!("gate error: {e}"), ctx);
            }
            timings
                .lock()
                .unwrap()
                .push(("validate_interface_contract_bootstrap", start.elapsed()));
        });
        s.spawn(move |_| {
            let start = Instant::now();
            if let Err(e) = validate_health_purity(ctx, decapod_dir) {
                fail(&format!("gate error: {e}"), ctx);
            }
            timings
                .lock()
                .unwrap()
                .push(("validate_health_purity", start.elapsed()));
        });
        s.spawn(move |_| {
            let start = Instant::now();
            if let Err(e) = validate_project_scoped_state(store, ctx, decapod_dir) {
                fail(&format!("gate error: {e}"), ctx);
            }
            timings
                .lock()
                .unwrap()
                .push(("validate_project_scoped_state", start.elapsed()));
        });
        s.spawn(move |_| {
            let start = Instant::now();
            if let Err(e) = validate_generated_artifact_whitelist(store, ctx, decapod_dir) {
                fail(&format!("gate error: {e}"), ctx);
            }
            timings
                .lock()
                .unwrap()
                .push(("validate_generated_artifact_whitelist", start.elapsed()));
        });
        s.spawn(move |_| {
            let start = Instant::now();
            if let Err(e) = validate_workunit_manifests_if_present(ctx, decapod_dir) {
                fail(&format!("gate error: {e}"), ctx);
            }
            timings
                .lock()
                .unwrap()
                .push(("validate_workunit_manifests_if_present", start.elapsed()));
        });
        s.spawn(move |_| {
            let start = Instant::now();
            if let Err(e) = validate_context_capsules_if_present(ctx, decapod_dir) {
                fail(&format!("gate error: {e}"), ctx);
            }
            timings
                .lock()
                .unwrap()
                .push(("validate_context_capsules_if_present", start.elapsed()));
        });
        s.spawn(move |_| {
            let start = Instant::now();
            if let Err(e) = validate_knowledge_promotions_if_present(ctx, decapod_dir) {
                fail(&format!("gate error: {e}"), ctx);
            }
            timings
                .lock()
                .unwrap()
                .push(("validate_knowledge_promotions_if_present", start.elapsed()));
        });
        s.spawn(move |_| {
            let start = Instant::now();
            if let Err(e) = validate_eval_gate_if_required(store, ctx) {
                fail(&format!("gate error: {e}"), ctx);
            }
            timings
                .lock()
                .unwrap()
                .push(("validate_eval_gate_if_required", start.elapsed()));
        });
        s.spawn(move |_| {
            let start = Instant::now();
            if let Err(e) = validate_schema_determinism(ctx, decapod_dir) {
                fail(&format!("gate error: {e}"), ctx);
            }
            timings
                .lock()
                .unwrap()
                .push(("validate_schema_determinism", start.elapsed()));
        });
        s.spawn(move |_| {
            let start = Instant::now();
            if let Err(e) = validate_health_cache_integrity(store, ctx) {
                fail(&format!("gate error: {e}"), ctx);
            }
            timings
                .lock()
                .unwrap()
                .push(("validate_health_cache_integrity", start.elapsed()));
        });
        s.spawn(move |_| {
            let start = Instant::now();
            if let Err(e) = validate_risk_map(store, ctx) {
                fail(&format!("gate error: {e}"), ctx);
            }
            timings
                .lock()
                .unwrap()
                .push(("validate_risk_map", start.elapsed()));
        });
        s.spawn(move |_| {
            let start = Instant::now();
            if let Err(e) = validate_risk_map_violations(store, ctx, broker) {
                fail(&format!("gate error: {e}"), ctx);
            }
            timings
                .lock()
                .unwrap()
                .push(("validate_risk_map_violations", start.elapsed()));
        });
        s.spawn(move |_| {
            let start = Instant::now();
            if let Err(e) = validate_policy_integrity(store, ctx, broker) {
                fail(&format!("gate error: {e}"), ctx);
            }
            timings
                .lock()
                .unwrap()
                .push(("validate_policy_integrity", start.elapsed()));
        });
        s.spawn(move |_| {
            let start = Instant::now();
            if let Err(e) = validate_knowledge_integrity(store, ctx, broker) {
                fail(&format!("gate error: {e}"), ctx);
            }
            timings
                .lock()
                .unwrap()
                .push(("validate_knowledge_integrity", start.elapsed()));
        });
        s.spawn(move |_| {
            let start = Instant::now();
            if let Err(e) = validate_lineage_hard_gate(store, ctx) {
                fail(&format!("gate error: {e}"), ctx);
            }
            timings
                .lock()
                .unwrap()
                .push(("validate_lineage_hard_gate", start.elapsed()));
        });
        s.spawn(move |_| {
            let start = Instant::now();
            if let Err(e) = validate_repomap_determinism(ctx, decapod_dir) {
                fail(&format!("gate error: {e}"), ctx);
            }
            timings
                .lock()
                .unwrap()
                .push(("validate_repomap_determinism", start.elapsed()));
        });
        s.spawn(move |_| {
            let start = Instant::now();
            if let Err(e) = validate_watcher_audit(store, ctx) {
                fail(&format!("gate error: {e}"), ctx);
            }
            timings
                .lock()
                .unwrap()
                .push(("validate_watcher_audit", start.elapsed()));
        });
        s.spawn(move |_| {
            let start = Instant::now();
            if let Err(e) = validate_watcher_purity(store, ctx, broker) {
                fail(&format!("gate error: {e}"), ctx);
            }
            timings
                .lock()
                .unwrap()
                .push(("validate_watcher_purity", start.elapsed()));
        });
        s.spawn(move |_| {
            let start = Instant::now();
            if let Err(e) = validate_archive_integrity(store, ctx) {
                fail(&format!("gate error: {e}"), ctx);
            }
            timings
                .lock()
                .unwrap()
                .push(("validate_archive_integrity", start.elapsed()));
        });
        s.spawn(move |_| {
            let start = Instant::now();
            if let Err(e) = validate_control_plane_contract(store, ctx) {
                fail(&format!("gate error: {e}"), ctx);
            }
            timings
                .lock()
                .unwrap()
                .push(("validate_control_plane_contract", start.elapsed()));
        });
        s.spawn(move |_| {
            let start = Instant::now();
            if let Err(e) = validate_canon_mutation(store, ctx, broker) {
                fail(&format!("gate error: {e}"), ctx);
            }
            timings
                .lock()
                .unwrap()
                .push(("validate_canon_mutation", start.elapsed()));
        });
        s.spawn(move |_| {
            let start = Instant::now();
            if let Err(e) = validate_heartbeat_invocation_gate(ctx, decapod_dir) {
                fail(&format!("gate error: {e}"), ctx);
            }
            timings
                .lock()
                .unwrap()
                .push(("validate_heartbeat_invocation_gate", start.elapsed()));
        });
        s.spawn(move |_| {
            let start = Instant::now();
            if let Err(e) = validate_markdown_primitives_roundtrip_gate(store, ctx) {
                fail(&format!("gate error: {e}"), ctx);
            }
            timings.lock().unwrap().push((
                "validate_markdown_primitives_roundtrip_gate",
                start.elapsed(),
            ));
        });
        s.spawn(move |_| {
            let start = Instant::now();
            if let Err(e) = validate_federation_gates(store, ctx) {
                fail(&format!("gate error: {e}"), ctx);
            }
            timings
                .lock()
                .unwrap()
                .push(("validate_federation_gates", start.elapsed()));
        });
        s.spawn(move |_| {
            let start = Instant::now();
            if let Err(e) = validate_git_workspace_context(ctx, decapod_dir) {
                fail(&format!("gate error: {e}"), ctx);
            }
            timings
                .lock()
                .unwrap()
                .push(("validate_git_workspace_context", start.elapsed()));
        });
        s.spawn(move |_| {
            let start = Instant::now();
            if let Err(e) = validate_git_protected_branch(ctx, decapod_dir) {
                fail(&format!("gate error: {e}"), ctx);
            }
            timings
                .lock()
                .unwrap()
                .push(("validate_git_protected_branch", start.elapsed()));
        });
        s.spawn(move |_| {
            let start = Instant::now();
            if let Err(e) = validate_tooling_gate(ctx, decapod_dir) {
                fail(&format!("gate error: {e}"), ctx);
            }
            timings
                .lock()
                .unwrap()
                .push(("validate_tooling_gate", start.elapsed()));
        });
        s.spawn(move |_| {
            let start = Instant::now();
            if let Err(e) = validate_state_commit_gate(ctx, decapod_dir) {
                fail(&format!("gate error: {e}"), ctx);
            }
            timings
                .lock()
                .unwrap()
                .push(("validate_state_commit_gate", start.elapsed()));
        });
        s.spawn(move |_| {
            let start = Instant::now();
            if let Err(e) = validate_obligations(store, ctx) {
                fail(&format!("gate error: {e}"), ctx);
            }
            timings
                .lock()
                .unwrap()
                .push(("validate_obligations", start.elapsed()));
        });

        s.spawn(move |_| {
            let start = Instant::now();
            if let Err(e) = validate_gatekeeper_gate(ctx, decapod_dir) {
                fail(&format!("gate error: {e}"), ctx);
            }
            timings
                .lock()
                .unwrap()
                .push(("validate_gatekeeper_gate", start.elapsed()));
        });
        s.spawn(move |_| {
            let start = Instant::now();
            if let Err(e) = validate_coplayer_policy_tightening(ctx, decapod_dir) {
                fail(&format!("gate error: {e}"), ctx);
            }
            timings
                .lock()
                .unwrap()
                .push(("validate_coplayer_policy_tightening", start.elapsed()));
        });
        s.spawn(move |_| {
            let start = Instant::now();
            if let Err(e) = validate_lcm_immutability(store, ctx) {
                fail(&format!("gate error: {e}"), ctx);
            }
            timings
                .lock()
                .unwrap()
                .push(("validate_lcm_immutability", start.elapsed()));
        });
        s.spawn(move |_| {
            let start = Instant::now();
            if let Err(e) = validate_lcm_rebuild_gate(store, ctx) {
                fail(&format!("gate error: {e}"), ctx);
            }
            timings
                .lock()
                .unwrap()
                .push(("validate_lcm_rebuild_gate", start.elapsed()));
        });
        s.spawn(move |_| {
            let start = Instant::now();
            if let Err(e) = validate_plan_governed_execution_gate(store, ctx, decapod_dir) {
                fail(&format!("gate error: {e}"), ctx);
            }
            timings
                .lock()
                .unwrap()
                .push(("validate_plan_governed_execution_gate", start.elapsed()));
        });
    });

    // Print per-gate timings in verbose mode
    if verbose {
        let mut gate_timings = timings.into_inner().unwrap();
        gate_timings.sort_by(|a, b| b.1.cmp(&a.1));
        for (name, elapsed) in &gate_timings {
            println!(
                "  {} [{}] {} ({:.2?})",
                "✓".bright_green(),
                name.bright_cyan(),
                "done".bright_white(),
                elapsed
            );
        }
    }

    let elapsed = total_start.elapsed();
    let pass_count = ctx.pass_count.load(Ordering::Relaxed);
    let fail_count = ctx.fail_count.load(Ordering::Relaxed);
    let warn_count = ctx.warn_count.load(Ordering::Relaxed);
    let fails = ctx.fails.lock().unwrap();
    let warns = ctx.warns.lock().unwrap();
    let fail_total = (fails.len() as u32).max(fail_count);
    let warn_total = (warns.len() as u32).max(warn_count);

    println!(
        "  {} pass={} fail={} warn={} {}",
        "summary:".bright_cyan(),
        pass_count.to_string().bright_green(),
        fail_total.to_string().bright_red(),
        warn_total.to_string().bright_yellow(),
        format!("({:.2?})", elapsed).bright_white()
    );

    if !fails.is_empty() {
        println!(
            "  {} {}: {}",
            "✗".bright_red().bold(),
            "failures".bright_red(),
            output::preview_messages(&fails, 2, 110)
        );
    }

    if !warns.is_empty() {
        println!(
            "  {} {}: {}",
            "âš ".bright_yellow().bold(),
            "warnings".bright_yellow(),
            output::preview_messages(&warns, 2, 110)
        );
    }

    if fail_total > 0 {
        Err(error::DecapodError::ValidationError(format!(
            "{} test(s) failed.",
            fail_total
        )))
    } else {
        println!(
            "{} {}",
            "✓".bright_green().bold(),
            "validation passed".bright_green().bold()
        );
        Ok(())
    }
}