xchecker 1.2.0

Spec pipeline with receipts and gateable JSON contracts
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
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
//! Command-line interface for xchecker
//!
//! This module provides the CLI commands and argument parsing for the
//! xchecker tool, starting with basic spec generation functionality.

use anyhow::{Context, Result};
use clap::{Parser, Subcommand};
use crossterm::style::{Color, Stylize};
use std::collections::HashMap;
use std::io::{IsTerminal, Write};
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::thread;
use std::time::Duration;

// Stable public API imports from crate root
// _Requirements: FR-CLI-2_
use crate::{
    CliArgs, Config, ExitCode, OrchestratorConfig, OrchestratorHandle, PhaseId, XCheckerError,
    emit_jcs,
};

// Internal module imports (not part of stable public API)
use crate::atomic_write::write_file_atomic;
use crate::error::{ConfigError, PhaseError};
use crate::error_reporter::{ErrorReport, utils as error_utils};
use crate::logging::Logger;
use crate::redaction::SecretRedactor;
use crate::source::SourceResolver;
use crate::spec_id::sanitize_spec_id;

/// Check if colored output should be used.
///
/// Returns true only if:
/// - stdout is a terminal (TTY)
/// - NO_COLOR environment variable is not set
fn use_color() -> bool {
    std::io::stdout().is_terminal() && std::env::var_os("NO_COLOR").is_none()
}

/// Return a styled check mark (✓) if colors are enabled, otherwise plain.
fn styled_check() -> String {
    if use_color() {
        format!("{}", "".with(Color::Green).bold())
    } else {
        "".to_string()
    }
}

/// Return a styled warning mark (⚠) if colors are enabled, otherwise plain.
fn styled_warning() -> String {
    if use_color() {
        format!("{}", "".with(Color::Yellow).bold())
    } else {
        "".to_string()
    }
}

/// Return styled success text if colors are enabled, otherwise plain.
fn styled_success(text: &str) -> String {
    if use_color() {
        format!("{}", text.with(Color::Green).bold())
    } else {
        text.to_string()
    }
}

/// Return styled info text (cyan) if colors are enabled, otherwise plain.
fn styled_info(text: &str) -> String {
    if use_color() {
        format!("{}", text.with(Color::Cyan).bold())
    } else {
        text.to_string()
    }
}

/// xchecker - Claude orchestration tool for spec generation
#[derive(Parser)]
#[command(name = "xchecker")]
#[command(about = "A CLI tool for orchestrating spec generation workflows using LLM providers")]
#[command(long_about = r#"
xchecker is a deterministic, token-efficient pipeline that transforms rough ideas
into detailed implementation plans through a structured phase-based approach.

EXAMPLES:
  # Generate a spec from stdin input
  echo "Create a REST API for user management" | xchecker spec user-api

  # Generate a spec from a GitHub issue
  xchecker spec issue-123 --source gh --gh owner/repo

  # Generate a spec from local filesystem context
  xchecker spec my-feature --source fs --repo /path/to/project

  # Run in dry-run mode to see what would be executed
  xchecker spec test-spec --dry-run --verbose

  # Check status of a spec
  xchecker status user-api

  # Resume from a specific phase
  xchecker resume user-api --phase design

  # Clean up spec artifacts
  xchecker clean user-api

  # Run performance benchmarks
  xchecker benchmark --file-count 50 --iterations 3

  # Run integration tests
  xchecker test --components --smoke

CONFIGURATION:
  Configuration is loaded with precedence: CLI flags > config file > defaults
  Config file is discovered by searching upward from CWD for .xchecker/config.toml
  Use --config to specify an explicit config file path

PHASES:
  Requirements → Design → Tasks → Review → Fixup → Final
  Each phase produces artifacts and receipts for auditability
  Use --dry-run to see planned execution without making LLM calls

For more information, see: https://github.com/your-org/xchecker
"#)]
#[command(version)]
pub struct Cli {
    /// Path to configuration file (overrides discovery)
    #[arg(long, global = true)]
    pub config: Option<PathBuf>,

    /// Model to use for LLM provider calls
    #[arg(long, global = true)]
    pub model: Option<String>,

    /// Maximum number of turns for Claude interactions
    #[arg(long, global = true)]
    pub max_turns: Option<u32>,

    /// Maximum bytes for packet content
    #[arg(long, global = true)]
    pub packet_max_bytes: Option<usize>,

    /// Maximum lines for packet content
    #[arg(long, global = true)]
    pub packet_max_lines: Option<usize>,

    /// Output format for Claude CLI (stream-json or text)
    #[arg(long, global = true)]
    pub output_format: Option<String>,

    /// Runner mode: native (direct), wsl (Windows only), or auto (detect best option)
    #[arg(long, global = true)]
    pub runner_mode: Option<String>,

    /// WSL distribution to use (when `runner_mode` is wsl)
    #[arg(long, global = true)]
    pub runner_distro: Option<String>,

    /// Path to Claude CLI binary in WSL
    #[arg(long, global = true)]
    pub claude_path: Option<String>,

    /// Enable verbose output
    #[arg(short, long, global = true)]
    pub verbose: bool,

    /// Tool patterns to allow (passed to Claude as allowedTools)
    #[arg(long, global = true)]
    pub allow: Vec<String>,

    /// Tool patterns to deny (passed to Claude as disallowedTools)
    #[arg(long, global = true)]
    pub deny: Vec<String>,

    /// Skip permission checks (passed to Claude)
    #[arg(long, global = true)]
    pub dangerously_skip_permissions: bool,

    /// Ignore specific secret patterns by pattern ID (e.g. github_pat, aws_access_key)
    #[arg(long, global = true)]
    pub ignore_secret_pattern: Vec<String>,

    /// Add extra secret patterns to detect (regex)
    #[arg(long, global = true)]
    pub extra_secret_pattern: Vec<String>,

    /// Phase timeout in seconds (default: 600, min: 5)
    #[arg(long, global = true)]
    pub phase_timeout: Option<u64>,

    /// Maximum bytes for stdout ring buffer (default: 2097152 = 2 MiB)
    #[arg(long, global = true)]
    pub stdout_cap_bytes: Option<usize>,

    /// Maximum bytes for stderr ring buffer (default: 262144 = 256 KiB)
    #[arg(long, global = true)]
    pub stderr_cap_bytes: Option<usize>,

    /// Lock TTL in seconds (default: 900 = 15 minutes)
    #[arg(long, global = true)]
    pub lock_ttl_seconds: Option<u64>,

    /// Write full packet to `context/<phase>-packet.txt` after secret scan passes
    #[arg(long, global = true)]
    pub debug_packet: bool,

    /// Allow symlinks and hardlinks in fixup targets
    #[arg(long, global = true)]
    pub allow_links: bool,

    /// Enable strict validation (validation failures fail phases)
    /// Use --no-strict-validation to disable strict mode
    #[arg(long, global = true, overrides_with = "no_strict_validation")]
    pub strict_validation: bool,

    /// Disable strict validation (validation failures log warnings only)
    /// Use --strict-validation to enable strict mode
    #[arg(long, global = true, overrides_with = "strict_validation")]
    pub no_strict_validation: bool,

    /// LLM provider to use (claude-cli)
    #[arg(long, global = true)]
    pub llm_provider: Option<String>,

    /// Fallback LLM provider to use if primary provider fails to initialize
    #[arg(long, global = true)]
    pub llm_fallback_provider: Option<String>,

    /// Prompt template to use for LLM interactions
    #[arg(long, global = true)]
    pub prompt_template: Option<String>,

    /// Path to Claude CLI binary (for claude-cli provider)
    #[arg(long, global = true)]
    pub llm_claude_binary: Option<String>,

    /// Path to Gemini CLI binary (for gemini-cli provider)
    #[arg(long, global = true)]
    pub llm_gemini_binary: Option<String>,

    /// Default Gemini model to use when no per-phase override is set
    #[arg(long, global = true)]
    pub llm_gemini_default_model: Option<String>,

    /// Execution strategy: controlled (default, LLMs cannot write directly)
    #[arg(long, global = true)]
    pub execution_strategy: Option<String>,

    #[command(subcommand)]
    pub command: Commands,
}

/// Available CLI commands
#[derive(Subcommand)]
pub enum Commands {
    /// Generate a complete spec flow (Requirements → Design → Tasks)
    ///
    /// This command executes the full spec generation workflow, transforming
    /// a rough idea into detailed requirements, design, and implementation tasks.
    ///
    /// EXAMPLES:
    ///   echo "Build a calculator app" | xchecker spec calc-app
    ///   xchecker spec issue-42 --source gh --gh myorg/myrepo
    ///   xchecker spec new-feature --source fs --repo ./project --dry-run
    Spec {
        /// Unique identifier for the spec
        id: String,

        /// Source type: 'gh' (GitHub issue), 'fs' (filesystem), 'stdin' (standard input)
        #[arg(long, default_value = "stdin", value_parser = ["gh", "fs", "stdin"])]
        source: String,

        /// GitHub repository in format 'owner/repo' (required when --source gh)
        #[arg(long, help = "GitHub repository (e.g., 'myorg/myrepo')")]
        gh: Option<String>,

        /// Local repository path (required when --source fs)
        #[arg(long, help = "Path to local repository directory")]
        repo: Option<String>,

        /// Run in dry-run mode (show what would be executed without making LLM calls)
        #[arg(long)]
        dry_run: bool,

        /// Force override of stale locks
        #[arg(long)]
        force: bool,

        /// Apply fixups to files (default is preview mode)
        #[arg(long)]
        apply_fixups: bool,

        /// Hard fail on lockfile drift (exit with error if model/CLI version differs)
        #[arg(long)]
        strict_lock: bool,

        /// Output spec information as JSON (for Claude Code integration)
        #[arg(long)]
        json: bool,
    },

    /// Show status of a spec
    ///
    /// Displays the current state of a spec including completed phases,
    /// artifacts with BLAKE3 hashes, receipts, and configuration.
    ///
    /// EXAMPLES:
    ///   xchecker status my-spec
    ///   xchecker status my-spec --json
    Status {
        /// Spec ID to check status for
        id: String,

        /// Output status as JSON
        #[arg(long)]
        json: bool,
    },

    /// Resume execution from a specific phase
    ///
    /// Continues spec generation from a specific phase, useful for recovery
    /// from failures or re-running phases with different parameters.
    ///
    /// EXAMPLES:
    ///   xchecker resume my-spec --phase design
    ///   xchecker resume my-spec --phase requirements --dry-run
    ///   xchecker resume my-spec --phase design --json
    Resume {
        /// Spec ID to resume
        id: String,

        /// Phase to resume from: requirements, design, tasks, review, fixup, final
        #[arg(long, value_parser = ["requirements", "design", "tasks", "review", "fixup", "final"])]
        phase: String,

        /// Run in dry-run mode (show what would be executed without making LLM calls)
        #[arg(long)]
        dry_run: bool,

        /// Force override of stale locks
        #[arg(long)]
        force: bool,

        /// Apply fixups to files (default is preview mode)
        #[arg(long)]
        apply_fixups: bool,

        /// Hard fail on lockfile drift (exit with error if model/CLI version differs)
        #[arg(long)]
        strict_lock: bool,

        /// Output resume information as JSON (for Claude Code integration)
        #[arg(long)]
        json: bool,
    },

    /// Clean up spec artifacts and receipts
    ///
    /// Removes all artifacts, receipts, and context files for a spec.
    /// Use --hard to skip confirmation prompts.
    ///
    /// EXAMPLES:
    ///   xchecker clean my-spec
    ///   xchecker clean my-spec --hard --force
    Clean {
        /// Spec ID to clean
        id: String,

        /// Remove artifacts without confirmation
        #[arg(long)]
        hard: bool,

        /// Force removal even if lock is present
        #[arg(long)]
        force: bool,
    },

    /// Run performance benchmarks (NFR1 validation)
    ///
    /// Validates performance targets: empty run ≤ 5s, packetization ≤ 200ms for 100 files.
    /// Useful for regression testing and performance validation.
    ///
    /// EXAMPLES:
    ///   xchecker benchmark
    ///   xchecker benchmark --file-count 50 --iterations 10 --verbose
    ///   xchecker benchmark --json
    ///   xchecker benchmark --max-empty-run-secs 3.0 --max-packetization-ms 150.0
    Benchmark {
        /// Number of files to create for packetization benchmark
        #[arg(long, default_value = "100")]
        file_count: usize,

        /// Size of each test file in bytes
        #[arg(long, default_value = "1024")]
        file_size: usize,

        /// Number of benchmark iterations
        #[arg(long, default_value = "5")]
        iterations: usize,

        /// Output benchmark results as JSON
        #[arg(long)]
        json: bool,

        /// Maximum allowed empty run time in seconds (default: 5.0)
        #[arg(long)]
        max_empty_run_secs: Option<f64>,

        /// Maximum allowed packetization time in milliseconds per 100 files (default: 200.0)
        #[arg(long)]
        max_packetization_ms: Option<f64>,

        /// Maximum allowed RSS memory in MB (optional)
        #[arg(long)]
        max_rss_mb: Option<f64>,

        /// Maximum allowed commit memory in MB (Windows only, optional)
        #[arg(long)]
        max_commit_mb: Option<f64>,
    },

    /// Run integration smoke tests to validate all components
    ///
    /// Validates that all systems are properly integrated and working.
    /// Useful for development and CI/CD validation.
    ///
    /// EXAMPLES:
    ///   xchecker test
    ///   xchecker test --components --smoke --verbose
    Test {
        /// Run component validation tests
        #[arg(long)]
        components: bool,

        /// Run smoke tests
        #[arg(long)]
        smoke: bool,
    },

    /// Run environment health checks
    ///
    /// Validates that Claude CLI is installed, runner configuration is correct,
    /// write permissions are available, and configuration is valid.
    ///
    /// EXAMPLES:
    ///   xchecker doctor
    ///   xchecker doctor --json
    ///   xchecker doctor --strict-exit  # Treat warnings as failures
    Doctor {
        /// Output doctor results as JSON
        #[arg(long)]
        json: bool,

        /// Treat warnings as failures (exit non-zero on any warn or fail)
        #[arg(long)]
        strict_exit: bool,
    },

    /// Initialize a new spec with optional lockfile creation
    ///
    /// Creates the spec directory structure and optionally pins the model
    /// and Claude CLI version for reproducibility tracking.
    ///
    /// EXAMPLES:
    ///   xchecker init my-spec
    ///   xchecker init my-spec --create-lock
    ///   xchecker init my-spec --create-lock --model haiku
    Init {
        /// Spec ID to initialize
        id: String,

        /// Create a lockfile to pin model and CLI version
        #[arg(long)]
        create_lock: bool,
    },

    /// Manage workspace and multi-spec projects
    ///
    /// Workspace commands allow managing multiple specs within a project.
    /// A workspace is defined by a `workspace.yaml` file that contains
    /// metadata about registered specs.
    ///
    /// EXAMPLES:
    ///   xchecker project init my-project
    ///   xchecker project add-spec feature-auth --tag backend
    ///   xchecker project list
    #[command(subcommand)]
    Project(ProjectCommands),

    /// Gate merges on xchecker receipts/status
    ///
    /// Evaluates a spec against a configurable policy to determine if it
    /// meets requirements for CI/CD gates. Returns exit code 0 on policy
    /// success, 1 on policy violation.
    ///
    /// EXAMPLES:
    ///   xchecker gate my-spec
    ///   xchecker gate my-spec --min-phase design
    ///   xchecker gate my-spec --fail-on-pending-fixups
    ///   xchecker gate my-spec --max-phase-age 7d
    ///   xchecker gate my-spec --policy .xchecker/policy.toml
    ///   xchecker gate my-spec --json
    ///
    /// Per FR-GATE (Requirements 4.5.1, 4.5.2, 4.5.3, 4.5.4)
    Gate {
        /// Spec ID to evaluate
        id: String,

        /// Policy file path (TOML)
        /// Defaults to .xchecker/policy.toml in the repo or ~/.config/xchecker/policy.toml
        #[arg(long)]
        policy: Option<PathBuf>,

        /// Minimum phase that must be completed (default: tasks)
        /// Valid phases: requirements, design, tasks, review, fixup, final
        #[arg(long)]
        min_phase: Option<String>,

        /// Fail if any pending fixups exist
        #[arg(long)]
        fail_on_pending_fixups: bool,

        /// Maximum age of the latest successful phase run (e.g., "7d", "24h", "30m")
        /// Failed receipts do not count towards age (prevents flapping phases from appearing fresh)
        #[arg(long)]
        max_phase_age: Option<String>,

        /// Output gate results as JSON (gate-json.v1 schema)
        #[arg(long)]
        json: bool,
    },

    /// Manage spec templates
    ///
    /// Templates provide predefined configurations and problem statements
    /// for common use cases, allowing you to bootstrap specs quickly.
    ///
    /// EXAMPLES:
    ///   xchecker template list
    ///   xchecker template init fullstack-nextjs my-app
    ///   xchecker template init rust-microservice my-service
    ///
    /// Per FR-TEMPLATES (Requirements 4.7.1, 4.7.2, 4.7.3)
    #[command(subcommand)]
    Template(TemplateCommands),
}

/// Project/workspace management subcommands
#[derive(Subcommand)]
pub enum ProjectCommands {
    /// Initialize a new workspace in the current directory
    ///
    /// Creates a `workspace.yaml` file that marks this directory as a project root.
    /// The workspace can then be used to manage multiple specs.
    ///
    /// EXAMPLES:
    ///   xchecker project init my-project
    Init {
        /// Name for the workspace
        name: String,
    },

    /// Add a spec to the workspace
    ///
    /// Registers a spec in the workspace registry with optional tags.
    ///
    /// EXAMPLES:
    ///   xchecker project add-spec feature-auth
    ///   xchecker project add-spec feature-auth --tag backend --tag security
    AddSpec {
        /// Spec ID to add
        spec_id: String,

        /// Tags for categorization (can be specified multiple times)
        #[arg(long, short)]
        tag: Vec<String>,

        /// Force override if spec already exists
        #[arg(long)]
        force: bool,
    },

    /// List all specs in the workspace
    ///
    /// Shows all registered specs with their tags and status.
    ///
    /// EXAMPLES:
    ///   xchecker project list
    List {
        /// Path to workspace file (overrides discovery)
        #[arg(long)]
        workspace: Option<PathBuf>,
    },

    /// Show aggregated status for all specs in the workspace
    ///
    /// Displays status summary for all registered specs including phase summaries,
    /// counts of failed/pending/stale specs, and overall workspace health.
    ///
    /// EXAMPLES:
    ///   xchecker project status
    ///   xchecker project status --json
    Status {
        /// Path to workspace file (overrides discovery)
        #[arg(long)]
        workspace: Option<PathBuf>,

        /// Output status as JSON (workspace-status-json.v1 schema)
        #[arg(long)]
        json: bool,
    },

    /// Show history timeline for a spec
    ///
    /// Displays timeline of phase progression, timestamps, and selected metrics
    /// including LLM token usage and fixup counts.
    ///
    /// EXAMPLES:
    ///   xchecker project history feature-auth
    ///   xchecker project history feature-auth --json
    ///
    /// Per FR-WORKSPACE (Requirements 4.3.5): Emits timeline of phase progression
    History {
        /// Spec ID to show history for
        spec_id: String,

        /// Output history as JSON (workspace-history-json.v1 schema)
        #[arg(long)]
        json: bool,
    },

    /// Launch interactive terminal UI for workspace overview
    ///
    /// Displays an interactive TUI showing specs list with tags and status,
    /// latest receipt summary per selected spec, pending fixups, error counts,
    /// and stale specs. The TUI is read-only (no destructive operations).
    ///
    /// Navigation:
    ///   - Arrow keys or j/k: Move selection up/down
    ///   - Enter: View details for selected spec
    ///   - Esc: Go back / close details
    ///   - q: Quit
    ///
    /// EXAMPLES:
    ///   xchecker project tui
    ///
    /// Per FR-WORKSPACE-TUI (Requirements 4.4.1, 4.4.2, 4.4.3)
    Tui {
        /// Path to workspace file (overrides discovery)
        #[arg(long)]
        workspace: Option<PathBuf>,
    },
}

/// Template management subcommands
#[derive(Subcommand)]
pub enum TemplateCommands {
    /// List available built-in templates
    ///
    /// Shows all available templates with their descriptions and use cases.
    ///
    /// EXAMPLES:
    ///   xchecker template list
    ///
    /// Per FR-TEMPLATES (Requirements 4.7.1)
    List,

    /// Initialize a spec from a template
    ///
    /// Creates a new spec with predefined problem statement, configuration,
    /// and example partial spec flow based on the selected template.
    ///
    /// Available templates:
    ///   - fullstack-nextjs: Full-stack web applications with Next.js
    ///   - rust-microservice: Rust microservices and CLI tools
    ///   - python-fastapi: Python REST APIs with FastAPI
    ///   - docs-refactor: Documentation improvements and refactoring
    ///
    /// EXAMPLES:
    ///   xchecker template init fullstack-nextjs my-app
    ///   xchecker template init rust-microservice my-service
    ///   xchecker template init python-fastapi my-api
    ///   xchecker template init docs-refactor docs-v2
    ///
    /// Per FR-TEMPLATES (Requirements 4.7.2, 4.7.3)
    Init {
        /// Template to use (fullstack-nextjs, rust-microservice, python-fastapi, docs-refactor)
        template: String,

        /// Spec ID to create
        spec_id: String,
    },
}

/// Build the CLI command structure without parsing arguments
/// This is used for introspection in tests and documentation validation
#[must_use]
pub fn build_cli() -> clap::Command {
    <Cli as clap::CommandFactory>::command()
}

/// Main CLI execution function.
///
/// This function handles ALL output including errors. It returns `Result<(), ExitCode>`:
/// - On success: returns `Ok(())` after printing any output
/// - On error: prints error message via contextual reporting, returns `Err(ExitCode)`
///
/// main.rs only calls `std::process::exit(code.as_i32())` on error - it does NOT print.
///
/// _Requirements: FR-CLI-3, FR-CLI-4_
pub fn run() -> Result<(), ExitCode> {
    let cli = Cli::parse();

    // Build CLI args for configuration system (wired through build_cli)
    let cli_args = CliArgs {
        config_path: cli.config.clone(),
        model: cli.model.clone(),
        max_turns: cli.max_turns,
        packet_max_bytes: cli.packet_max_bytes,
        packet_max_lines: cli.packet_max_lines,
        output_format: cli.output_format.clone(),
        verbose: Some(cli.verbose),
        runner_mode: cli.runner_mode.clone(),
        runner_distro: cli.runner_distro.clone(),
        claude_path: cli.claude_path.clone(),
        allow: cli.allow.clone(),
        deny: cli.deny.clone(),
        dangerously_skip_permissions: cli.dangerously_skip_permissions,
        ignore_secret_pattern: cli.ignore_secret_pattern.clone(),
        extra_secret_pattern: cli.extra_secret_pattern.clone(),
        phase_timeout: cli.phase_timeout,
        stdout_cap_bytes: cli.stdout_cap_bytes,
        stderr_cap_bytes: cli.stderr_cap_bytes,
        lock_ttl_seconds: cli.lock_ttl_seconds,
        debug_packet: cli.debug_packet,
        allow_links: cli.allow_links,
        strict_validation: if cli.strict_validation {
            Some(true)
        } else if cli.no_strict_validation {
            Some(false)
        } else {
            None
        },
        llm_provider: cli.llm_provider.clone(),
        llm_fallback_provider: cli.llm_fallback_provider.clone(),
        prompt_template: cli.prompt_template.clone(),
        llm_claude_binary: cli.llm_claude_binary.clone(),
        llm_gemini_binary: cli.llm_gemini_binary.clone(),
        llm_gemini_default_model: cli.llm_gemini_default_model.clone(),
        execution_strategy: cli.execution_strategy.clone(),
    };

    // Discover and load configuration
    let config = match Config::discover(&cli_args) {
        Ok(config) => config,
        Err(err) => {
            let contextual_report = error_utils::create_contextual_report(&err, "config");
            eprintln!("{contextual_report}");
            return Err(err.to_exit_code());
        }
    };

    // Build a configured redactor once from the effective config so all output surfaces
    // respect extra/ignore patterns (FR-SEC-19).
    let redactor = match SecretRedactor::from_config(&config) {
        Ok(redactor) => Arc::new(redactor),
        Err(e) => {
            let err = XCheckerError::Config(ConfigError::InvalidValue {
                key: "security".to_string(),
                value: e.to_string(),
            });
            let contextual_report = error_utils::create_contextual_report(&err, "config");
            eprintln!("{contextual_report}");
            return Err(err.to_exit_code());
        }
    };

    // Create tokio runtime for async operations
    let rt = match tokio::runtime::Runtime::new() {
        Ok(rt) => rt,
        Err(e) => {
            eprintln!("✗ Failed to create async runtime: {e}");
            return Err(ExitCode::INTERNAL);
        }
    };

    // Determine operation context for better error reporting before moving cli.command
    let operation = match &cli.command {
        Commands::Spec { .. } => "spec",
        Commands::Status { .. } => "status",
        Commands::Resume { .. } => "resume",
        Commands::Clean { .. } => "clean",
        Commands::Benchmark { .. } => "benchmark",
        Commands::Test { .. } => "test",
        Commands::Doctor { .. } => "doctor",
        Commands::Init { .. } => "init",
        Commands::Project(_) => "project",
        Commands::Gate { .. } => "gate",
        Commands::Template(_) => "template",
    };

    let result = rt.block_on(async {
        match cli.command {
            Commands::Spec {
                id,
                source,
                gh,
                repo,
                dry_run,
                force,
                apply_fixups,
                strict_lock,
                json,
            } => {
                // Sanitize spec ID (R5.7)
                let sanitized_id = sanitize_spec_id(&id).map_err(|e| {
                    XCheckerError::Config(ConfigError::InvalidValue {
                        key: "spec_id".to_string(),
                        value: format!("{e}"),
                    })
                })?;

                // If --json flag is set, output spec info as JSON and return
                if json {
                    return execute_spec_json_command(&sanitized_id, &config);
                }

                execute_spec_command(
                    &sanitized_id,
                    &source,
                    gh.as_deref(),
                    repo.as_deref(),
                    dry_run,
                    cli.verbose,
                    force,
                    apply_fixups,
                    strict_lock,
                    &config,
                    &cli_args,
                    &redactor,
                )
                .await
            }
            Commands::Status { id, json } => {
                // Sanitize spec ID (R5.7)
                let sanitized_id = sanitize_spec_id(&id).map_err(|e| {
                    XCheckerError::Config(ConfigError::InvalidValue {
                        key: "spec_id".to_string(),
                        value: format!("{e}"),
                    })
                })?;
                execute_status_command(&sanitized_id, json, &config)
            }
            Commands::Resume {
                id,
                phase,
                dry_run,
                force,
                apply_fixups,
                strict_lock,
                json,
            } => {
                // Sanitize spec ID (R5.7)
                let sanitized_id = sanitize_spec_id(&id).map_err(|e| {
                    XCheckerError::Config(ConfigError::InvalidValue {
                        key: "spec_id".to_string(),
                        value: format!("{e}"),
                    })
                })?;

                // If --json flag is set, output resume info as JSON and return
                if json {
                    return execute_resume_json_command(&sanitized_id, &phase, &config);
                }

                execute_resume_command(
                    &sanitized_id,
                    &phase,
                    dry_run,
                    cli.verbose,
                    force,
                    apply_fixups,
                    strict_lock,
                    &config,
                    &cli_args,
                    &redactor,
                )
                .await
            }
            Commands::Clean { id, hard, force } => {
                // Sanitize spec ID (R5.7)
                let sanitized_id = sanitize_spec_id(&id).map_err(|e| {
                    XCheckerError::Config(ConfigError::InvalidValue {
                        key: "spec_id".to_string(),
                        value: format!("{e}"),
                    })
                })?;
                execute_clean_command(&sanitized_id, hard, force, &config)
            }
            Commands::Benchmark {
                file_count,
                file_size,
                iterations,
                json,
                max_empty_run_secs,
                max_packetization_ms,
                max_rss_mb,
                max_commit_mb,
            } => execute_benchmark_command(
                file_count,
                file_size,
                iterations,
                json,
                max_empty_run_secs,
                max_packetization_ms,
                max_rss_mb,
                max_commit_mb,
                cli.verbose,
            ),
            Commands::Test { components, smoke } => {
                execute_test_command(components, smoke, cli.verbose)
            }
            Commands::Doctor { json, strict_exit } => {
                execute_doctor_command(json, strict_exit, &config)
            }
            Commands::Init { id, create_lock } => {
                // Sanitize spec ID (R5.7)
                let sanitized_id = sanitize_spec_id(&id).map_err(|e| {
                    XCheckerError::Config(ConfigError::InvalidValue {
                        key: "spec_id".to_string(),
                        value: format!("{e}"),
                    })
                })?;
                execute_init_command(&sanitized_id, create_lock, &config)
            }
            Commands::Project(project_cmd) => execute_project_command(project_cmd),
            Commands::Gate {
                id,
                policy,
                min_phase,
                fail_on_pending_fixups,
                max_phase_age,
                json,
            } => {
                // Sanitize spec ID (R5.7)
                let sanitized_id = sanitize_spec_id(&id).map_err(|e| {
                    XCheckerError::Config(ConfigError::InvalidValue {
                        key: "spec_id".to_string(),
                        value: format!("{e}"),
                    })
                })?;
                execute_gate_command(
                    &sanitized_id,
                    policy.as_deref(),
                    min_phase.as_deref(),
                    fail_on_pending_fixups,
                    max_phase_age.as_deref(),
                    json,
                )
            }
            Commands::Template(template_cmd) => execute_template_command(template_cmd),
        }
    });

    // Handle errors with structured reporting (R1.3, R6.4, R6.8, R6.9)
    // cli::run() handles ALL output including errors (FR-CLI-3, FR-CLI-6)
    // Error messages are displayed via contextual reporting which extends display_for_user()
    // with operation-specific context for better user experience
    if let Err(error) = result {
        // Try to downcast to XCheckerError for better reporting
        if let Some(xchecker_error) = error.downcast_ref::<XCheckerError>() {
            // Use contextual error reporting which builds on display_for_user() (FR-CLI-3)
            // This provides user_message(), context(), suggestions() plus operation-specific help
            let contextual_report = error_utils::create_contextual_report_with_redactor(
                xchecker_error,
                operation,
                redactor.as_ref(),
            );
            eprintln!("{contextual_report}");

            // Return the appropriate exit code - main.rs will call std::process::exit()
            return Err(xchecker_error.to_exit_code());
        } else {
            // Fallback for other error types with enhanced context
            let redacted_error = redactor.redact_string(&error.to_string());
            eprintln!("✗ Unexpected error: {redacted_error}");

            // Provide enhanced context and suggestions for common anyhow errors
            if let Some(suggestions) = enhance_error_context(&error) {
                eprintln!("\n  Suggestions:");
                for (i, suggestion) in suggestions.iter().enumerate() {
                    eprintln!("    {}. {}", i + 1, suggestion);
                }
            }

            // Provide general troubleshooting steps
            eprintln!("\n  General troubleshooting:");
            eprintln!("    - Run with --verbose for more detailed output");
            eprintln!("    - Check the xchecker documentation for common issues");
            eprintln!("    - Ensure all dependencies are properly installed");

            return Err(ExitCode::INTERNAL);
        }
    }

    Ok(())
}

/// Execute the spec generation command
#[allow(clippy::too_many_arguments)]
async fn execute_spec_command(
    spec_id: &str,
    source_type: &str,
    gh_repo: Option<&str>,
    fs_repo: Option<&str>,
    dry_run: bool,
    verbose: bool,
    force: bool,
    apply_fixups: bool,
    strict_lock: bool,
    config: &Config,
    cli_args: &CliArgs,
    redactor: &Arc<SecretRedactor>,
) -> Result<()> {
    // Create logger for verbose output and timing (R7.5, NFR5)
    let mut logger = Logger::new(verbose);
    logger.start_timing("total_execution");

    logger.verbose(&format!("Starting spec generation for ID: {spec_id}"));
    if dry_run {
        logger.verbose("Running in dry-run mode (no Claude calls will be made)");
    }

    // Resolve source input (R6.4)
    logger.start_timing("source_resolution");
    let source_content = match source_type {
        "gh" => {
            let gh_repo = gh_repo.ok_or_else(|| {
                XCheckerError::Config(ConfigError::MissingRequired("--gh owner/repo".to_string()))
            })?;

            let parts: Vec<&str> = gh_repo.split('/').collect();
            if parts.len() != 2 {
                return Err(XCheckerError::Config(ConfigError::InvalidValue {
                    key: "gh".to_string(),
                    value: gh_repo.to_string(),
                })
                .into());
            }

            SourceResolver::resolve_github(parts[0], parts[1], spec_id).map_err(|_e| {
                // Convert SourceError to XCheckerError for consistent reporting (R6.4)
                XCheckerError::Source(crate::error::SourceError::GitHubRepoNotFound {
                    owner: parts[0].to_string(),
                    repo: parts[1].to_string(),
                })
            })?
        }
        "fs" => {
            let fs_repo = fs_repo.ok_or_else(|| {
                XCheckerError::Config(ConfigError::MissingRequired("--repo <path>".to_string()))
            })?;

            let path = PathBuf::from(fs_repo);
            SourceResolver::resolve_filesystem(&path).map_err(|e| {
                // Enhanced error reporting for filesystem source resolution (R6.4)
                if path.exists() {
                    if path.is_dir() {
                        // Check if it's a permission issue or other access problem
                        match std::fs::read_dir(&path) {
                            Err(io_err)
                                if io_err.kind() == std::io::ErrorKind::PermissionDenied =>
                            {
                                XCheckerError::Source(
                                    crate::error::SourceError::FileSystemAccessDenied {
                                        path: fs_repo.to_string(),
                                    },
                                )
                            }
                            Err(_) => {
                                XCheckerError::Source(crate::error::SourceError::InvalidFormat {
                                    reason: format!("Directory exists but cannot be read: {e}"),
                                })
                            }
                            Ok(_) => {
                                // Directory is readable, so it's some other issue
                                XCheckerError::Source(crate::error::SourceError::InvalidFormat {
                                    reason: format!("Failed to resolve filesystem source: {e}"),
                                })
                            }
                        }
                    } else {
                        XCheckerError::Source(crate::error::SourceError::FileSystemNotDirectory {
                            path: fs_repo.to_string(),
                        })
                    }
                } else {
                    XCheckerError::Source(crate::error::SourceError::FileSystemNotFound {
                        path: fs_repo.to_string(),
                    })
                }
            })?
        }
        "stdin" => {
            SourceResolver::resolve_stdin().map_err(|e| {
                // Enhanced error reporting for stdin source resolution (R6.4)
                let error_msg = e.to_string();
                if error_msg.contains("empty") || error_msg.contains("EOF") {
                    XCheckerError::Source(crate::error::SourceError::EmptyInput)
                } else if error_msg.contains("permission") || error_msg.contains("access") {
                    XCheckerError::Source(crate::error::SourceError::StdinReadFailed {
                        reason: "Permission denied or stdin not accessible".to_string(),
                    })
                } else {
                    XCheckerError::Source(crate::error::SourceError::StdinReadFailed {
                        reason: error_msg,
                    })
                }
            })?
        }
        _ => {
            return Err(XCheckerError::Config(ConfigError::InvalidValue {
                key: "source".to_string(),
                value: format!("Unknown source type '{source_type}'. Valid options: 'gh' (GitHub), 'fs' (filesystem), 'stdin' (standard input)"),
            }).into());
        }
    };
    logger.end_timing("source_resolution");

    // Extract problem statement from resolved source
    let problem_statement = source_content.content.clone();
    logger.verbose(&format!("Source resolved successfully from: {source_type}"));

    // Persist problem statement to spec directory (FR-PKT: problem statement in packet)
    // This ensures the problem statement is available for packet building
    let spec_root = crate::paths::spec_root(spec_id);
    let source_dir = spec_root.join("source");
    crate::paths::ensure_dir_all(&source_dir)
        .with_context(|| format!("Failed to create source directory: {}", source_dir))?;

    let problem_path = source_dir.join("00-problem-statement.md");
    write_file_atomic(
        &problem_path,
        &format!("# Problem Statement\n\n{}\n", problem_statement.trim()),
    )
    .with_context(|| format!("Failed to write problem statement: {}", problem_path))?;

    logger.verbose(&format!("Problem statement written to: {}", problem_path));

    // Check for lockfile drift (R10.2, R10.4)
    let model_full_name = config.defaults.model.as_deref().unwrap_or("haiku");
    let claude_cli_version = detect_claude_cli_version().unwrap_or_else(|_| "unknown".to_string());
    let _lock_drift =
        check_lockfile_drift(spec_id, strict_lock, model_full_name, &claude_cli_version)?;

    // Configure execution using shared helper, passing problem statement for prompt construction
    let orchestrator_config = build_orchestrator_config(
        dry_run,
        verbose,
        apply_fixups,
        config,
        cli_args,
        Some(&problem_statement),
        redactor.clone(),
    );

    // Create orchestrator handle (this will acquire the file lock)
    logger.start_timing("orchestrator_setup");
    let mut handle = OrchestratorHandle::with_config_and_force(spec_id, orchestrator_config, force)
        .with_context(|| format!("Failed to create orchestrator for spec: {spec_id}"))?;
    logger.end_timing("orchestrator_setup");

    logger.verbose("Executing Requirements phase...");

    // Execute Requirements phase
    logger.start_timing("requirements_phase");
    let result = handle
        .run_phase(PhaseId::Requirements)
        .await
        .with_context(|| "Failed to execute Requirements phase")?;
    logger.end_timing("requirements_phase");

    // Report results
    logger.end_timing("total_execution");

    if result.success {
        println!("✓ Requirements phase completed successfully");

        logger.verbose(&format!("Phase: {}", result.phase.as_str()));
        logger.verbose(&format!("Exit code: {}", result.exit_code));
        logger.verbose(&format!(
            "Artifacts created: {}",
            result.artifact_paths.len()
        ));

        for (i, path) in result.artifact_paths.iter().enumerate() {
            logger.verbose(&format!("  {}: {}", i + 1, path.display()));
        }

        if let Some(receipt_path) = &result.receipt_path {
            logger.verbose(&format!("Receipt: {}", receipt_path.display()));
        }

        // Print performance summary if verbose (R7.5, NFR5)
        logger.print_performance_summary();

        // Show next steps
        println!("\nNext steps:");
        println!("  - Review the generated requirements in .xchecker/specs/{spec_id}/artifacts/");
        println!("  - Check status with: xchecker status {spec_id}");
        println!("  - Continue to Design phase: xchecker resume {spec_id} --phase design");
    } else {
        // Create structured error for phase failure (R1.3, R4.3)
        let phase_error = PhaseError::ExecutionFailed {
            phase: result.phase.as_str().to_string(),
            code: result.exit_code,
        };
        let xchecker_error = XCheckerError::Phase(phase_error);

        // Report with full context and suggestions
        let report = ErrorReport::new(&xchecker_error);
        eprintln!("{}", report.format_with_redactor(redactor.as_ref()));

        // Enhanced error reporting for phase failures (R1.3, R4.3)
        if let Some(error_msg) = &result.error {
            let redacted_error_msg = redactor.redact_string(error_msg);
            eprintln!("\n  Phase failure details: {redacted_error_msg}");

            // Try to parse the error for enhanced reporting
            if error_msg.contains("ExecutionFailedWithStderr") {
                eprintln!("  ↳ Claude CLI produced error output (see receipt for full stderr)");
            } else if error_msg.contains("PartialOutputSaved") {
                eprintln!("  ↳ Partial output was saved for debugging");
            }
        }

        // Show partial artifacts location (R4.3)
        eprintln!("\n  Debugging information:");
        if !result.artifact_paths.is_empty() {
            eprintln!("    Partial artifacts:");
            for path in &result.artifact_paths {
                eprintln!("      - {}", path.display());
            }
        }
        eprintln!("    Spec directory: .xchecker/specs/{spec_id}/");

        if let Some(receipt_path) = &result.receipt_path {
            eprintln!("    Execution receipt: {}", receipt_path.display());
            eprintln!("      ↳ Contains stderr output, warnings, and execution metadata");
        }

        // Provide recovery suggestions
        eprintln!("\n  Recovery options:");
        eprintln!("    - Review partial outputs and receipt for error details");
        eprintln!("    - Fix any configuration or connectivity issues");
        eprintln!("    - Retry with: xchecker spec {spec_id}");
        eprintln!("    - Test configuration with: xchecker spec {spec_id} --dry-run");

        std::process::exit(result.exit_code);
    }

    Ok(())
}

/// Execute the spec --json command (FR-Claude Code-CLI: Claude Code CLI Surfaces)
/// Returns JSON with schema_version, spec_id, phases, config_summary
/// Excludes full artifacts and packet contents per Requirements 4.1.1, 4.1.4
fn execute_spec_json_command(spec_id: &str, config: &Config) -> Result<()> {
    use crate::types::{PhaseId, PhaseInfo, SpecConfigSummary, SpecOutput};

    // Create read-only handle to access managers (no lock needed for JSON output)
    let handle = OrchestratorHandle::readonly(spec_id)
        .with_context(|| format!("Failed to create orchestrator for spec: {spec_id}"))?;

    // Check if spec directory exists
    let base_path = handle.artifact_manager().base_path();
    if !base_path.exists() {
        // Return minimal JSON for non-existent spec
        let output = SpecOutput {
            schema_version: "spec-json.v1".to_string(),
            spec_id: spec_id.to_string(),
            phases: vec![],
            config_summary: SpecConfigSummary {
                execution_strategy: config
                    .llm
                    .execution_strategy
                    .clone()
                    .unwrap_or_else(|| "controlled".to_string()),
                provider: config.llm.provider.clone(),
                spec_path: base_path.to_string(),
            },
        };
        let json_output = emit_spec_json(&output)?;
        println!("{json_output}");
        return Ok(());
    }

    // Get phase information
    let all_phases = [
        PhaseId::Requirements,
        PhaseId::Design,
        PhaseId::Tasks,
        PhaseId::Review,
        PhaseId::Fixup,
        PhaseId::Final,
    ];

    // Get receipts to determine phase status and last run times
    // Handle case where receipts directory doesn't exist yet
    let receipts = handle.receipt_manager().list_receipts().unwrap_or_default();

    // Build phase info list
    let mut phases = Vec::new();
    for phase_id in &all_phases {
        let phase_completed = handle.artifact_manager().phase_completed(*phase_id);

        // Find the latest receipt for this phase
        let latest_receipt = receipts
            .iter()
            .filter(|r| r.phase == phase_id.as_str())
            .max_by_key(|r| r.emitted_at);

        let status = if phase_completed {
            "completed".to_string()
        } else if latest_receipt.is_some() {
            "pending".to_string()
        } else {
            "not_started".to_string()
        };

        let last_run = latest_receipt.map(|r| r.emitted_at);

        phases.push(PhaseInfo {
            phase_id: phase_id.as_str().to_string(),
            status,
            last_run,
        });
    }

    // Build config summary (excludes full artifacts and packet contents)
    let config_summary = SpecConfigSummary {
        execution_strategy: config
            .llm
            .execution_strategy
            .clone()
            .unwrap_or_else(|| "controlled".to_string()),
        provider: config.llm.provider.clone(),
        spec_path: base_path.to_string(),
    };

    let output = SpecOutput {
        schema_version: "spec-json.v1".to_string(),
        spec_id: spec_id.to_string(),
        phases,
        config_summary,
    };

    let json_output = emit_spec_json(&output)?;
    println!("{json_output}");

    Ok(())
}

/// Emit spec output as canonical JSON using JCS (RFC 8785)
fn emit_spec_json(output: &crate::types::SpecOutput) -> Result<String> {
    // Use emit_jcs from crate root for JCS canonicalization
    emit_jcs(output).context("Failed to emit spec JSON")
}

/// Emit status output as canonical JSON using JCS (RFC 8785)
/// Per FR-Claude Code-CLI (Requirements 4.1.2): Returns compact status summary
fn emit_status_json(output: &crate::types::StatusJsonOutput) -> Result<String> {
    // Use emit_jcs from crate root for JCS canonicalization
    emit_jcs(output).context("Failed to emit status JSON")
}

/// Execute the resume --json command (FR-Claude Code-CLI: Claude Code CLI Surfaces)
/// Returns JSON with schema_version, spec_id, phase, current_inputs, next_steps
/// Excludes full packet and raw artifacts per Requirements 4.1.3, 4.1.4
fn execute_resume_json_command(spec_id: &str, phase_name: &str, config: &Config) -> Result<()> {
    use crate::types::{CurrentInputs, PhaseId, ResumeJsonOutput};

    // Parse phase name
    let phase_id = match phase_name.to_lowercase().as_str() {
        "requirements" => PhaseId::Requirements,
        "design" => PhaseId::Design,
        "tasks" => PhaseId::Tasks,
        "review" => PhaseId::Review,
        "fixup" => PhaseId::Fixup,
        "final" => PhaseId::Final,
        _ => {
            return Err(XCheckerError::Config(ConfigError::InvalidValue {
                key: "phase".to_string(),
                value: format!("Unknown phase '{phase_name}'. Valid phases: requirements, design, tasks, review, fixup, final"),
            }).into());
        }
    };

    // Create read-only handle to access managers (no lock needed for JSON output)
    let handle = OrchestratorHandle::readonly(spec_id)
        .with_context(|| format!("Failed to create orchestrator for spec: {spec_id}"))?;

    // Check if spec directory exists
    let base_path = handle.artifact_manager().base_path();
    let spec_exists = base_path.exists();

    // Get available artifacts (names only, not contents)
    let available_artifacts = if spec_exists {
        handle
            .artifact_manager()
            .list_artifacts()
            .unwrap_or_default()
    } else {
        vec![]
    };

    // Get latest completed phase
    let latest_completed_phase = if spec_exists {
        handle
            .artifact_manager()
            .get_latest_completed_phase()
            .map(|p| p.as_str().to_string())
    } else {
        None
    };

    // Build current inputs (high-level metadata only, no full contents)
    let current_inputs = CurrentInputs {
        available_artifacts,
        spec_exists,
        latest_completed_phase,
    };

    // Generate next steps hint based on phase and current state
    let next_steps = generate_next_steps_hint(spec_id, phase_id, &current_inputs, config);

    let output = ResumeJsonOutput {
        schema_version: "resume-json.v1".to_string(),
        spec_id: spec_id.to_string(),
        phase: phase_id.as_str().to_string(),
        current_inputs,
        next_steps,
    };

    let json_output = emit_resume_json(&output)?;
    println!("{json_output}");

    Ok(())
}

/// Generate next steps hint for resume JSON output
fn generate_next_steps_hint(
    spec_id: &str,
    phase_id: PhaseId,
    current_inputs: &crate::types::CurrentInputs,
    _config: &Config,
) -> String {
    if !current_inputs.spec_exists {
        return format!(
            "Spec '{}' does not exist. Run 'xchecker spec {}' to create it first.",
            spec_id, spec_id
        );
    }

    // Check if we have the required inputs for this phase
    let has_requirements = current_inputs
        .available_artifacts
        .iter()
        .any(|a| a.contains("requirements"));
    let has_design = current_inputs
        .available_artifacts
        .iter()
        .any(|a| a.contains("design"));
    let has_tasks = current_inputs
        .available_artifacts
        .iter()
        .any(|a| a.contains("tasks"));
    let has_review = current_inputs
        .available_artifacts
        .iter()
        .any(|a| a.contains("review"));

    match phase_id {
        PhaseId::Requirements => {
            "Run requirements phase to generate initial requirements from the problem statement."
                .to_string()
        }
        PhaseId::Design => {
            if has_requirements {
                "Run design phase to generate architecture and design from requirements."
                    .to_string()
            } else {
                format!(
                    "Requirements phase not completed. Run 'xchecker resume {} --phase requirements' first.",
                    spec_id
                )
            }
        }
        PhaseId::Tasks => {
            if has_design {
                "Run tasks phase to generate implementation tasks from design.".to_string()
            } else {
                format!(
                    "Design phase not completed. Run 'xchecker resume {} --phase design' first.",
                    spec_id
                )
            }
        }
        PhaseId::Review => {
            if has_tasks {
                "Run review phase to review and validate the generated spec.".to_string()
            } else {
                format!(
                    "Tasks phase not completed. Run 'xchecker resume {} --phase tasks' first.",
                    spec_id
                )
            }
        }
        PhaseId::Fixup => {
            if has_review {
                "Run fixup phase to apply any suggested changes from review.".to_string()
            } else {
                format!(
                    "Review phase not completed. Run 'xchecker resume {} --phase review' first.",
                    spec_id
                )
            }
        }
        PhaseId::Final => "Run final phase to complete the spec generation workflow.".to_string(),
    }
}

/// Emit resume output as canonical JSON using JCS (RFC 8785)
/// Per FR-Claude Code-CLI (Requirements 4.1.3): Returns resume context without full packet/artifacts
fn emit_resume_json(output: &crate::types::ResumeJsonOutput) -> Result<String> {
    // Use emit_jcs from crate root for JCS canonicalization
    emit_jcs(output).context("Failed to emit resume JSON")
}

/// Execute the status command
fn execute_status_command(spec_id: &str, json: bool, config: &Config) -> Result<()> {
    // Create read-only handle to access managers (no lock needed for status)
    let handle = OrchestratorHandle::readonly(spec_id)
        .with_context(|| format!("Failed to create orchestrator for spec: {spec_id}"))?;

    // Check if spec directory exists
    let base_path = handle.artifact_manager().base_path();
    if !base_path.exists() {
        if json {
            // Return empty JSON for non-existent spec
            println!("{{}}");
        } else {
            println!("Status for spec: {spec_id}");
            println!("  Status: No spec found");
            println!("  Directory: {base_path} (does not exist)");
        }
        return Ok(());
    }

    // If JSON output is requested, use status-json.v2 format with full details
    // Includes artifacts with blake3_first8, effective_config, and lock_drift
    if json {
        use crate::lock::{RunContext, XCheckerLock};
        use crate::types::{
            ArtifactInfo, ConfigSource, ConfigValue, PhaseStatusInfo, StatusJsonOutput,
        };
        use std::collections::BTreeMap;

        // Get all phases
        let all_phases = [
            PhaseId::Requirements,
            PhaseId::Design,
            PhaseId::Tasks,
            PhaseId::Review,
            PhaseId::Fixup,
            PhaseId::Final,
        ];

        // Get receipts to determine phase status and receipt IDs
        let receipts = handle.receipt_manager().list_receipts().unwrap_or_default();

        // Build phase status list
        let mut phase_statuses = Vec::new();
        let mut has_errors = false;

        for phase_id in &all_phases {
            // Find the latest receipt for this phase
            let latest_receipt = receipts
                .iter()
                .filter(|r| r.phase == phase_id.as_str())
                .max_by_key(|r| r.emitted_at);

            let (status, receipt_id) = if let Some(receipt) = latest_receipt {
                // Check if the phase succeeded or failed
                if receipt.exit_code == 0 {
                    (
                        "success".to_string(),
                        Some(format!(
                            "{}-{}",
                            receipt.phase,
                            receipt.emitted_at.format("%Y%m%d_%H%M%S")
                        )),
                    )
                } else {
                    has_errors = true;
                    (
                        "failed".to_string(),
                        Some(format!(
                            "{}-{}",
                            receipt.phase,
                            receipt.emitted_at.format("%Y%m%d_%H%M%S")
                        )),
                    )
                }
            } else {
                ("not_started".to_string(), None)
            };

            phase_statuses.push(PhaseStatusInfo {
                phase_id: phase_id.as_str().to_string(),
                status,
                receipt_id,
            });
        }

        // Count pending fixups
        let pending_fixups = count_pending_fixups_for_spec(spec_id);

        // Collect artifacts with blake3_first8 from receipts
        let mut artifact_hashes: BTreeMap<String, String> = BTreeMap::new();
        for receipt in &receipts {
            for output in &receipt.outputs {
                // Extract just the filename from the path for matching
                if let Some(filename) = output.path.split('/').next_back() {
                    let short_hash = if output.blake3_canonicalized.len() >= 8 {
                        &output.blake3_canonicalized[..8]
                    } else {
                        &output.blake3_canonicalized
                    };
                    artifact_hashes.insert(filename.to_string(), short_hash.to_string());
                }
            }
        }

        // Build artifact info list
        let artifact_files = handle
            .artifact_manager()
            .list_artifacts()
            .unwrap_or_default();

        let mut artifacts: Vec<ArtifactInfo> = artifact_files
            .iter()
            .filter_map(|filename| {
                artifact_hashes.get(filename).map(|hash| ArtifactInfo {
                    path: format!("artifacts/{filename}"),
                    blake3_first8: hash.clone(),
                })
            })
            .collect();
        artifacts.sort_by(|a, b| a.path.cmp(&b.path));

        // Build effective_config from config with source attribution
        let mut effective_config: BTreeMap<String, ConfigValue> = BTreeMap::new();

        // Add key configuration values with their sources
        // Provider
        if let Some(ref provider) = config.llm.provider {
            let source = config
                .source_attribution
                .get("provider")
                .cloned()
                .unwrap_or(ConfigSource::Config);
            effective_config.insert(
                "provider".to_string(),
                ConfigValue {
                    value: serde_json::Value::String(provider.clone()),
                    source,
                },
            );
        }

        // Model
        if let Some(ref model) = config.defaults.model {
            let source = config
                .source_attribution
                .get("model")
                .cloned()
                .unwrap_or(ConfigSource::Config);
            effective_config.insert(
                "model".to_string(),
                ConfigValue {
                    value: serde_json::Value::String(model.clone()),
                    source,
                },
            );
        }

        // Max turns
        if let Some(max_turns) = config.defaults.max_turns {
            let source = config
                .source_attribution
                .get("max_turns")
                .cloned()
                .unwrap_or(ConfigSource::Config);
            effective_config.insert(
                "max_turns".to_string(),
                ConfigValue {
                    value: serde_json::Value::Number(max_turns.into()),
                    source,
                },
            );
        }

        // Phase timeout
        if let Some(timeout) = config.defaults.phase_timeout {
            let source = config
                .source_attribution
                .get("phase_timeout")
                .cloned()
                .unwrap_or(ConfigSource::Config);
            effective_config.insert(
                "phase_timeout".to_string(),
                ConfigValue {
                    value: serde_json::Value::Number(timeout.into()),
                    source,
                },
            );
        }

        // Execution strategy
        if let Some(ref strategy) = config.llm.execution_strategy {
            let source = config
                .source_attribution
                .get("execution_strategy")
                .cloned()
                .unwrap_or(ConfigSource::Config);
            effective_config.insert(
                "execution_strategy".to_string(),
                ConfigValue {
                    value: serde_json::Value::String(strategy.clone()),
                    source,
                },
            );
        }

        // Load lockfile and detect drift
        let lock_drift = if let Ok(Some(lock)) = XCheckerLock::load(spec_id) {
            // Get current run context from latest receipt or config
            let model_full_name = receipts
                .last()
                .map(|r| r.model_full_name.clone())
                .unwrap_or_else(|| config.defaults.model.clone().unwrap_or_default());

            let claude_cli_version = receipts
                .last()
                .map(|r| r.claude_cli_version.clone())
                .unwrap_or_else(|| env!("CARGO_PKG_VERSION").to_string());

            let context = RunContext {
                model_full_name,
                claude_cli_version,
                schema_version: "1".to_string(),
            };

            lock.detect_drift(&context)
        } else {
            None
        };

        let output = StatusJsonOutput {
            schema_version: "status-json.v2".to_string(),
            spec_id: spec_id.to_string(),
            phase_statuses,
            pending_fixups,
            has_errors,
            strict_validation: config.strict_validation(),
            artifacts,
            effective_config,
            lock_drift,
        };

        // Emit as canonical JSON using JCS (RFC 8785)
        let json_output =
            emit_status_json(&output).with_context(|| "Failed to emit status JSON")?;

        println!("{json_output}");
        return Ok(());
    }

    // Human-readable output
    println!("Status for spec: {spec_id}");
    println!("  Directory: {base_path}");

    // Get latest completed phase and show phase progression (R2.6)
    let latest_completed = handle.artifact_manager().get_latest_completed_phase();
    match latest_completed {
        Some(phase) => {
            println!("  Latest completed phase: {}", phase.as_str());
        }
        None => {
            println!("  Latest completed phase: None");
        }
    }

    // List artifacts with first-8 BLAKE3 hashes (R2.6, R8.1)
    let artifacts = handle
        .artifact_manager()
        .list_artifacts()
        .with_context(|| "Failed to list artifacts")?;

    if artifacts.is_empty() {
        println!("  Artifacts: None");
    } else {
        println!("  Artifacts: {} found", artifacts.len());

        // Get receipts to extract hashes for artifacts
        let receipts = handle
            .receipt_manager()
            .list_receipts()
            .with_context(|| "Failed to list receipts")?;

        // Create a map of artifact paths to their hashes from receipts
        let mut artifact_hashes: HashMap<String, String> = HashMap::new();
        for receipt in &receipts {
            for output in &receipt.outputs {
                // Extract just the filename from the path for matching
                if let Some(filename) = output.path.split('/').next_back() {
                    let short_hash = if output.blake3_canonicalized.len() >= 8 {
                        &output.blake3_canonicalized[..8]
                    } else {
                        &output.blake3_canonicalized
                    };
                    artifact_hashes.insert(filename.to_string(), short_hash.to_string());
                }
            }
        }

        for artifact in &artifacts {
            if let Some(hash) = artifact_hashes.get(artifact) {
                println!("    - {artifact} -> {hash}");
            } else {
                println!("    - {artifact} -> <no hash>");
            }
        }
    }

    // Display last receipt path and key information (R2.6, R8.2)
    let receipts = handle
        .receipt_manager()
        .list_receipts()
        .with_context(|| "Failed to list receipts")?;

    if receipts.is_empty() {
        println!("  Last receipt: None");
    } else {
        let latest_receipt = receipts.last().unwrap();

        // Show receipt path
        let receipt_filename = format!(
            "{}-{}.json",
            latest_receipt.phase,
            latest_receipt.emitted_at.format("%Y%m%d_%H%M%S")
        );
        let receipt_path = base_path.join("receipts").join(receipt_filename);
        println!("  Last receipt: {receipt_path}");

        // Show key receipt information
        println!("    Phase: {}", latest_receipt.phase);
        println!(
            "    Emitted at: {}",
            latest_receipt.emitted_at.format("%Y-%m-%d %H:%M:%S UTC")
        );
        println!("    Exit code: {}", latest_receipt.exit_code);
        println!("    Model: {}", latest_receipt.model_full_name);
        if let Some(alias) = &latest_receipt.model_alias {
            println!("    Model alias: {alias}");
        }
        println!("    Runner: {}", latest_receipt.runner);
        if let Some(distro) = &latest_receipt.runner_distro {
            println!("    Runner distro: {distro}");
        }
        println!(
            "    Canonicalization: {}",
            latest_receipt.canonicalization_version
        );

        if !latest_receipt.warnings.is_empty() {
            println!("    Warnings: {}", latest_receipt.warnings.len());
            for warning in &latest_receipt.warnings {
                println!("      - {warning}");
            }
        }

        if latest_receipt.fallback_used == Some(true) {
            println!("    Output format fallback: Used (stream-json → text)");
        }
    }

    // Show effective configuration with source attribution (R11.3)
    println!("\n  Effective configuration:");
    let effective_config = config.effective_config();
    for (key, (value, source)) in effective_config {
        println!("    {key} = {value} (from {source})");
    }

    // Check for partial artifacts and resume capabilities
    let phases = [
        PhaseId::Requirements,
        PhaseId::Design,
        PhaseId::Tasks,
        PhaseId::Review,
        PhaseId::Fixup,
        PhaseId::Final,
    ];
    let mut partial_phases = Vec::new();
    let mut completed_phases = Vec::new();

    for phase in phases {
        if handle.artifact_manager().has_partial_artifact(phase) {
            partial_phases.push(phase);
        }
        if handle.artifact_manager().phase_completed(phase) {
            completed_phases.push(phase);
        }
    }

    if !partial_phases.is_empty() {
        println!("\n  Partial artifacts found:");
        for phase in partial_phases {
            println!("    - {} (from failed execution)", phase.as_str());
        }
    }

    if !completed_phases.is_empty() {
        println!("\n  Completed phases:");
        for phase in completed_phases {
            println!("    - {}", phase.as_str());
        }
    }

    // Check for pending fixups and show intended targets (R5.6)
    check_and_display_fixup_targets(spec_id)?;

    // Show resume suggestions
    match latest_completed {
        Some(PhaseId::Requirements) => {
            println!("\n  Resume options:");
            println!("    - Continue to Design: xchecker resume {spec_id} --phase design");
            println!("    - Re-run Requirements: xchecker resume {spec_id} --phase requirements");
        }
        Some(PhaseId::Design) => {
            println!("\n  Resume options:");
            println!("    - Continue to Tasks: xchecker resume {spec_id} --phase tasks");
            println!("    - Re-run Design: xchecker resume {spec_id} --phase design");
        }
        Some(PhaseId::Tasks) => {
            println!("\n  Resume options:");
            println!("    - Continue to Review: xchecker resume {spec_id} --phase review");
            println!("    - Re-run Tasks: xchecker resume {spec_id} --phase tasks");
        }
        Some(PhaseId::Review) => {
            println!("\n  Resume options:");
            println!("    - Continue to Fixup: xchecker resume {spec_id} --phase fixup");
            println!("    - Re-run Review: xchecker resume {spec_id} --phase review");
        }
        Some(_) => {
            println!("\n  Resume options:");
            println!("    - Re-run any phase: xchecker resume {spec_id} --phase <phase_name>");
        }
        None => {
            println!("\n  Resume options:");
            println!(
                "    - Start from Requirements: xchecker resume {spec_id} --phase requirements"
            );
        }
    }

    Ok(())
}

/// Check for pending fixups and display intended targets (R5.6)
fn check_and_display_fixup_targets(spec_id: &str) -> Result<()> {
    use crate::fixup::{FixupMode, FixupParser};

    // Check if Review phase is completed and has fixup markers
    let base_path = crate::paths::spec_root(spec_id);
    let review_md_path = base_path.join("artifacts").join("30-review.md");

    if !review_md_path.exists() {
        return Ok(()); // No review phase completed yet
    }

    // Read the review content
    let review_content = match std::fs::read_to_string(&review_md_path) {
        Ok(content) => content,
        Err(_) => return Ok(()), // Can't read review file, skip fixup check
    };

    // Create fixup parser in preview mode to check for targets
    let fixup_parser = FixupParser::new(FixupMode::Preview, base_path.clone().into())?;

    // Check if there are fixup markers
    if !fixup_parser.has_fixup_markers(&review_content) {
        return Ok(()); // No fixups needed
    }

    // Parse diffs to get intended targets
    match fixup_parser.parse_diffs(&review_content) {
        Ok(diffs) => {
            if !diffs.is_empty() {
                println!("\n  Pending fixups detected:");
                println!("    Fixup markers found in review phase");
                println!("    Intended targets ({} files):", diffs.len());

                for diff in &diffs {
                    println!("      - {}", diff.target_file);
                }

                // Show preview information
                match fixup_parser.preview_changes(&diffs) {
                    Ok(preview) => {
                        if !preview.all_valid {
                            println!("    ⚠ Warning: Some diffs failed validation");
                        }

                        if !preview.warnings.is_empty() {
                            println!("    Validation warnings:");
                            for warning in &preview.warnings {
                                println!("      - {warning}");
                            }
                        }

                        // Show change summary
                        let mut total_added = 0;
                        let mut total_removed = 0;
                        for (file, summary) in &preview.change_summary {
                            total_added += summary.lines_added;
                            total_removed += summary.lines_removed;
                            if !summary.validation_passed {
                                println!("{file}: validation failed");
                            }
                        }

                        if total_added > 0 || total_removed > 0 {
                            println!(
                                "    Estimated changes: +{total_added} lines, -{total_removed} lines"
                            );
                        }
                    }
                    Err(e) => {
                        println!("    ⚠ Warning: Failed to preview changes: {e}");
                    }
                }

                println!("\n    To apply fixups:");
                println!("      xchecker resume {spec_id} --phase fixup --apply-fixups");
                println!("    To preview only (default):");
                println!("      xchecker resume {spec_id} --phase fixup");
            }
        }
        Err(e) => {
            println!("\n  Fixup parsing error: {e}");
            println!("    Review phase contains fixup markers but diffs could not be parsed");
        }
    }

    Ok(())
}

/// Execute the resume command
#[allow(clippy::too_many_arguments)]
async fn execute_resume_command(
    spec_id: &str,
    phase_name: &str,
    dry_run: bool,
    verbose: bool,
    force: bool,
    apply_fixups: bool,
    strict_lock: bool,
    config: &Config,
    cli_args: &CliArgs,
    redactor: &Arc<SecretRedactor>,
) -> Result<()> {
    // Create logger for verbose output and timing (R7.5, NFR5)
    let mut logger = Logger::new(verbose);
    logger.start_timing("total_execution");

    // Parse phase name
    let phase_id = match phase_name.to_lowercase().as_str() {
        "requirements" => PhaseId::Requirements,
        "design" => PhaseId::Design,
        "tasks" => PhaseId::Tasks,
        "review" => PhaseId::Review,
        "fixup" => PhaseId::Fixup,
        "final" => PhaseId::Final,
        _ => {
            return Err(XCheckerError::Config(ConfigError::InvalidValue {
                key: "phase".to_string(),
                value: format!("Unknown phase '{phase_name}'. Valid phases: requirements, design, tasks, review, fixup, final"),
            }).into());
        }
    };

    logger.verbose(&format!(
        "Resuming spec {} from {} phase",
        spec_id,
        phase_id.as_str()
    ));
    if dry_run {
        logger.verbose("Running in dry-run mode (no Claude calls will be made)");
    }

    // Check for lockfile drift (R10.2, R10.4)
    let model_full_name = config.defaults.model.as_deref().unwrap_or("haiku");
    let claude_cli_version = detect_claude_cli_version().unwrap_or_else(|_| "unknown".to_string());
    let _lock_drift =
        check_lockfile_drift(spec_id, strict_lock, model_full_name, &claude_cli_version)?;

    // Configure execution using shared helper
    // Note: Problem statement is not passed for resume - it's already persisted in spec dir
    let orchestrator_config = build_orchestrator_config(
        dry_run,
        verbose,
        apply_fixups,
        config,
        cli_args,
        None,
        redactor.clone(),
    );

    // Create orchestrator handle (this will acquire the file lock)
    logger.start_timing("orchestrator_setup");
    let mut handle = OrchestratorHandle::with_config_and_force(spec_id, orchestrator_config, force)
        .with_context(|| format!("Failed to create orchestrator for spec: {spec_id}"))?;
    logger.end_timing("orchestrator_setup");

    // Check if spec exists
    let base_path = handle.artifact_manager().base_path();
    if !base_path.exists() {
        return Err(XCheckerError::Config(ConfigError::NotFound {
            path: format!("Spec directory: {base_path}"),
        })
        .into());
    }

    logger.verbose(&format!(
        "Checking dependencies for {} phase...",
        phase_id.as_str()
    ));

    // Execute resume
    logger.start_timing(&format!("{}_phase", phase_id.as_str()));
    let result = handle
        .run_phase(phase_id)
        .await
        .with_context(|| format!("Failed to resume {} phase", phase_id.as_str()))?;
    logger.end_timing(&format!("{}_phase", phase_id.as_str()));

    // Report results
    logger.end_timing("total_execution");

    if result.success {
        println!("{} phase completed successfully", phase_id.as_str());

        logger.verbose(&format!("Phase: {}", result.phase.as_str()));
        logger.verbose(&format!("Exit code: {}", result.exit_code));
        logger.verbose(&format!(
            "Artifacts created: {}",
            result.artifact_paths.len()
        ));

        for (i, path) in result.artifact_paths.iter().enumerate() {
            logger.verbose(&format!("  {}: {}", i + 1, path.display()));
        }

        if let Some(receipt_path) = &result.receipt_path {
            logger.verbose(&format!("Receipt: {}", receipt_path.display()));
        }

        // Print performance summary if verbose (R7.5, NFR5)
        logger.print_performance_summary();

        // Show next steps based on completed phase
        println!("\nNext steps:");
        match phase_id {
            PhaseId::Requirements => {
                println!(
                    "  - Review the generated requirements in .xchecker/specs/{spec_id}/artifacts/"
                );
                println!("  - Continue to Design phase: xchecker resume {spec_id} --phase design");
            }
            PhaseId::Design => {
                println!("  - Review the generated design in .xchecker/specs/{spec_id}/artifacts/");
                println!("  - Continue to Tasks phase: xchecker resume {spec_id} --phase tasks");
            }
            PhaseId::Tasks => {
                println!("  - Review the generated tasks in .xchecker/specs/{spec_id}/artifacts/");
                println!("  - Continue to Review phase: xchecker resume {spec_id} --phase review");
            }
            _ => {
                println!("  - Check status with: xchecker status {spec_id}");
            }
        }
    } else {
        // Create structured error for phase failure (R1.3, R4.3)
        let phase_error = PhaseError::ExecutionFailed {
            phase: result.phase.as_str().to_string(),
            code: result.exit_code,
        };
        let xchecker_error = XCheckerError::Phase(phase_error);

        // Report with full context and suggestions
        let report = ErrorReport::new(&xchecker_error);
        eprintln!("{}", report.format_with_redactor(redactor.as_ref()));

        // Enhanced error reporting for phase failures (R1.3, R4.3)
        if let Some(error_msg) = &result.error {
            let redacted_error_msg = redactor.redact_string(error_msg);
            eprintln!("\n  Phase failure details: {redacted_error_msg}");
        }

        // Show partial artifacts location (R4.3)
        eprintln!("\n  Debugging information:");
        if !result.artifact_paths.is_empty() {
            eprintln!("    Partial artifacts:");
            for path in &result.artifact_paths {
                eprintln!("      - {}", path.display());
            }
        }
        eprintln!("    Spec directory: .xchecker/specs/{spec_id}/");

        if let Some(receipt_path) = &result.receipt_path {
            eprintln!("    Execution receipt: {}", receipt_path.display());
        }

        // Provide recovery suggestions
        eprintln!("\n  Recovery options:");
        eprintln!("    - Review partial outputs and receipt for error details");
        eprintln!("    - Fix any configuration or connectivity issues");
        eprintln!("    - Retry with: xchecker resume {spec_id} --phase {phase_name}");
        eprintln!(
            "    - Test configuration with: xchecker resume {spec_id} --phase {phase_name} --dry-run"
        );

        std::process::exit(result.exit_code);
    }

    Ok(())
}

/// Execute the clean command
fn execute_clean_command(spec_id: &str, hard: bool, force: bool, _config: &Config) -> Result<()> {
    use crate::lock::utils;

    // Check if clean operation is allowed (no active locks unless forced)
    if let Err(lock_error) = utils::can_clean(spec_id, force, None) {
        return Err(anyhow::anyhow!(
            "Cannot clean spec '{spec_id}': {lock_error}"
        ));
    }

    // Collect information we need before dropping the handle
    let (base_path, artifacts_path, receipts_path, context_path, artifacts, receipts) = {
        // Create handle to access managers (this will acquire a lock)
        let handle = OrchestratorHandle::with_force(spec_id, force)
            .with_context(|| format!("Failed to create orchestrator for spec: {spec_id}"))?;

        // Check if spec directory exists
        let base_path = handle.artifact_manager().base_path();
        if !base_path.exists() {
            println!("No spec found for ID: {spec_id}");
            println!("Directory: {base_path} (does not exist)");
            return Ok(());
        }

        // Show what will be cleaned
        println!("Clean spec: {spec_id}");
        println!("  Directory: {base_path}");

        // List what will be removed
        let artifacts = handle
            .artifact_manager()
            .list_artifacts()
            .with_context(|| "Failed to list artifacts")?;
        let receipts = handle
            .receipt_manager()
            .list_receipts()
            .with_context(|| "Failed to list receipts")?;

        if artifacts.is_empty() && receipts.is_empty() {
            println!("  Nothing to clean (no artifacts or receipts found)");
            // Still need to remove the directory if --hard is specified
            if !hard {
                return Ok(());
            }
        }

        println!("  Will remove:");
        if !artifacts.is_empty() {
            println!("    Artifacts: {} files", artifacts.len());
            for artifact in &artifacts {
                println!("      - {artifact}");
            }
        }

        if !receipts.is_empty() {
            println!("    Receipts: {} files", receipts.len());
            for receipt in &receipts {
                let receipt_filename = format!(
                    "{}-{}.json",
                    receipt.phase,
                    receipt.emitted_at.format("%Y%m%d_%H%M%S")
                );
                println!("      - {receipt_filename}");
            }
        }

        // Get paths before dropping handle (clone to own the data)
        let artifacts_path = handle.artifact_manager().artifacts_path().to_path_buf();
        let receipts_path = base_path.join("receipts");
        let context_path = base_path.join("context");
        let base_path_owned = base_path.to_path_buf();

        (
            base_path_owned,
            artifacts_path,
            receipts_path,
            context_path,
            artifacts,
            receipts,
        )
        // Handle is dropped here, releasing the lock
    };

    // Confirmation prompt (R8.1)
    if !hard {
        println!("\nThis will permanently delete all artifacts and receipts for spec '{spec_id}'.");
        print!("Are you sure? (y/N): ");
        // Flush stdout, logging a warning if it fails (non-fatal)
        if let Err(e) = std::io::stdout().flush() {
            tracing::warn!("Failed to flush stdout: {}", e);
        }

        let mut input = String::new();
        std::io::stdin().read_line(&mut input)?;
        let input = input.trim().to_lowercase();

        if input != "y" && input != "yes" {
            println!("Clean cancelled.");
            return Ok(());
        }
    }

    // Perform cleanup (R8.2) - orchestrator lock is now released

    let mut removed_count = 0;

    // Remove artifacts directory
    if artifacts_path.exists() {
        std::fs::remove_dir_all(&artifacts_path)
            .with_context(|| format!("Failed to remove artifacts directory: {artifacts_path}"))?;
        removed_count += artifacts.len();
        println!("{} Removed artifacts directory", styled_check());
    }

    // Remove receipts directory
    if receipts_path.exists() {
        std::fs::remove_dir_all(&receipts_path)
            .with_context(|| format!("Failed to remove receipts directory: {receipts_path}"))?;
        removed_count += receipts.len();
        println!("{} Removed receipts directory", styled_check());
    }

    // Remove context directory
    if context_path.exists() {
        std::fs::remove_dir_all(&context_path)
            .with_context(|| format!("Failed to remove context directory: {context_path}"))?;
        println!("{} Removed context directory", styled_check());
    }

    // Remove the spec directory
    if base_path.exists() {
        if hard {
            // With --hard, remove the entire spec directory including any remaining files
            std::fs::remove_dir_all(&base_path)
                .with_context(|| format!("Failed to remove spec directory: {base_path}"))?;
            println!("{} Removed spec directory completely", styled_check());
        } else {
            // Without --hard, only remove if empty
            match std::fs::remove_dir(&base_path) {
                Ok(()) => {
                    println!("{} Removed empty spec directory", styled_check());
                }
                Err(_) => {
                    // Directory not empty, that's fine
                    println!(
                        "{} Spec directory retained (contains other files)",
                        styled_check()
                    );
                }
            }
        }
    }

    println!("\n{}", styled_success("Clean completed successfully."));
    println!("  Removed {removed_count} files total");

    Ok(())
}

/// Create default configuration from Config struct and CLI args
fn create_default_config(
    verbose: bool,
    config: &Config,
    cli_args: &CliArgs,
) -> HashMap<String, String> {
    let mut config_map = HashMap::new();

    if verbose {
        config_map.insert("verbose".to_string(), "true".to_string());
    }

    // Use values from the configuration system
    if let Some(packet_max_bytes) = config.defaults.packet_max_bytes {
        config_map.insert("packet_max_bytes".to_string(), packet_max_bytes.to_string());
    }

    if let Some(packet_max_lines) = config.defaults.packet_max_lines {
        config_map.insert("packet_max_lines".to_string(), packet_max_lines.to_string());
    }

    if let Some(max_turns) = config.defaults.max_turns {
        config_map.insert("max_turns".to_string(), max_turns.to_string());
    }

    if let Some(model) = &config.defaults.model {
        config_map.insert("model".to_string(), model.clone());
    }

    if let Some(output_format) = &config.defaults.output_format {
        config_map.insert("output_format".to_string(), output_format.clone());
    }

    if let Some(phase_timeout) = config.defaults.phase_timeout {
        config_map.insert("phase_timeout".to_string(), phase_timeout.to_string());
    }

    if let Some(stdout_cap_bytes) = config.defaults.stdout_cap_bytes {
        config_map.insert("stdout_cap_bytes".to_string(), stdout_cap_bytes.to_string());
    }

    if let Some(stderr_cap_bytes) = config.defaults.stderr_cap_bytes {
        config_map.insert("stderr_cap_bytes".to_string(), stderr_cap_bytes.to_string());
    }

    if let Some(lock_ttl_seconds) = config.defaults.lock_ttl_seconds {
        config_map.insert("lock_ttl_seconds".to_string(), lock_ttl_seconds.to_string());
    }

    if let Some(debug_packet) = config.defaults.debug_packet
        && debug_packet
    {
        config_map.insert("debug_packet".to_string(), "true".to_string());
    }

    if let Some(allow_links) = config.defaults.allow_links
        && allow_links
    {
        config_map.insert("allow_links".to_string(), "true".to_string());
    }

    if let Some(runner_mode) = &config.runner.mode {
        config_map.insert("runner_mode".to_string(), runner_mode.clone());
    }

    if let Some(runner_distro) = &config.runner.distro {
        config_map.insert("runner_distro".to_string(), runner_distro.clone());
    }

    if let Some(claude_path) = &config.runner.claude_path {
        config_map.insert("claude_path".to_string(), claude_path.clone());
    }

    if let Some(provider) = &config.llm.provider {
        config_map.insert("llm_provider".to_string(), provider.clone());
    }

    if let Some(fallback_provider) = &config.llm.fallback_provider {
        config_map.insert(
            "llm_fallback_provider".to_string(),
            fallback_provider.clone(),
        );
    }

    if let Some(execution_strategy) = &config.llm.execution_strategy {
        config_map.insert("execution_strategy".to_string(), execution_strategy.clone());
    }

    if let Some(prompt_template) = &config.llm.prompt_template {
        config_map.insert("prompt_template".to_string(), prompt_template.clone());
    }

    if let Some(claude_config) = &config.llm.claude
        && let Some(binary) = &claude_config.binary
    {
        config_map.insert("llm_claude_binary".to_string(), binary.clone());
    }

    if let Some(gemini_config) = &config.llm.gemini {
        if let Some(binary) = &gemini_config.binary {
            config_map.insert("llm_gemini_binary".to_string(), binary.clone());
        }
        if let Some(default_model) = &gemini_config.default_model {
            config_map.insert(
                "llm_gemini_default_model".to_string(),
                default_model.clone(),
            );
        }
    }

    // Add new CLI arguments (R7.2, R7.4, R9.2)
    if !cli_args.allow.is_empty() {
        config_map.insert("allowed_tools".to_string(), cli_args.allow.join(","));
    }

    if !cli_args.deny.is_empty() {
        config_map.insert("disallowed_tools".to_string(), cli_args.deny.join(","));
    }

    if cli_args.dangerously_skip_permissions {
        config_map.insert(
            "dangerously_skip_permissions".to_string(),
            "true".to_string(),
        );
    }

    if !cli_args.ignore_secret_pattern.is_empty() {
        config_map.insert(
            "ignore_secret_patterns".to_string(),
            cli_args.ignore_secret_pattern.join("|"),
        );
    }

    if !cli_args.extra_secret_pattern.is_empty() {
        config_map.insert(
            "extra_secret_patterns".to_string(),
            cli_args.extra_secret_pattern.join("|"),
        );
    }

    // Add debug_packet flag (FR-PKT-006, FR-PKT-007) for CLI-only overrides
    if cli_args.debug_packet {
        config_map.insert("debug_packet".to_string(), "true".to_string());
    }

    config_map
}

/// Build an OrchestratorConfig from CLI parameters.
///
/// This helper reduces duplication between execute_spec_command and execute_resume_command
/// by combining create_default_config with the common additional parameters.
///
/// # Arguments
/// * `dry_run` - Whether to run in simulation mode
/// * `verbose` - Enable verbose logging
/// * `apply_fixups` - Whether to apply fixups (true) or preview (false)
/// * `config` - The loaded xchecker configuration
/// * `cli_args` - CLI arguments passed by the user
/// * `problem_statement` - Optional problem statement to include in phase prompts
fn build_orchestrator_config(
    dry_run: bool,
    verbose: bool,
    apply_fixups: bool,
    config: &Config,
    cli_args: &CliArgs,
    problem_statement: Option<&str>,
    redactor: Arc<SecretRedactor>,
) -> OrchestratorConfig {
    let mut config_map = create_default_config(verbose, config, cli_args);
    config_map.insert("logger_enabled".to_string(), verbose.to_string());
    config_map.insert("apply_fixups".to_string(), apply_fixups.to_string());

    // Include problem statement in config for prompt construction (FR-PKT)
    if let Some(ps) = problem_statement {
        config_map.insert("problem_statement".to_string(), ps.to_string());
    }

    OrchestratorConfig {
        dry_run,
        config: config_map,
        full_config: Some(config.clone()),
        selectors: Some(config.selectors.clone()),
        strict_validation: config.strict_validation(),
        redactor,
        hooks: Some(config.hooks.clone()),
    }
}

/// Enhance error reporting for common failure scenarios
fn enhance_error_context(error: &anyhow::Error) -> Option<Vec<String>> {
    let error_str = error.to_string();

    if error_str.contains("Failed to create orchestrator") {
        Some(vec![
            "Check that the current directory is writable".to_string(),
            "Ensure sufficient disk space is available".to_string(),
            "Verify directory permissions".to_string(),
            "Try running from a different directory".to_string(),
        ])
    } else if error_str.contains("Failed to execute") {
        Some(vec![
            "Check the spec ID is valid and doesn't contain special characters".to_string(),
            "Verify Claude CLI is installed and accessible".to_string(),
            "Try running with --dry-run to test configuration".to_string(),
            "Check your internet connection if using Claude API".to_string(),
        ])
    } else if error_str.contains("Permission denied") {
        Some(vec![
            "Check file and directory permissions".to_string(),
            "Ensure you have write access to the current directory".to_string(),
            "Try running from your home directory or a writable location".to_string(),
        ])
    } else if error_str.contains("No such file or directory") {
        Some(vec![
            "Verify the specified paths exist".to_string(),
            "Check that you're running from the correct directory".to_string(),
            "Ensure all required files are present".to_string(),
        ])
    } else {
        None
    }
}

/// Execute the test command for integration validation
fn execute_test_command(components: bool, smoke: bool, verbose: bool) -> Result<()> {
    use crate::integration_tests;

    if verbose {
        println!("Running integration tests...");
    }

    // If no specific test type is specified, run both
    let run_components = components || !smoke;
    let run_smoke = smoke || !components;

    if run_components {
        integration_tests::validate_component_integration()
            .with_context(|| "Component integration validation failed")?;
    }

    if run_smoke {
        integration_tests::run_smoke_tests().with_context(|| "Smoke tests failed")?;
    }

    println!("✓ All integration tests passed successfully");
    Ok(())
}

/// Execute the benchmark command (NFR1 validation)
#[allow(clippy::too_many_arguments)]
fn execute_benchmark_command(
    file_count: usize,
    file_size: usize,
    iterations: usize,
    json: bool,
    max_empty_run_secs: Option<f64>,
    max_packetization_ms: Option<f64>,
    max_rss_mb: Option<f64>,
    max_commit_mb: Option<f64>,
    verbose: bool,
) -> Result<()> {
    use crate::benchmark::{BenchmarkConfig, BenchmarkRunner, BenchmarkThresholds};

    // Build custom thresholds if any overrides provided
    let mut thresholds = BenchmarkThresholds::default();
    if let Some(max_secs) = max_empty_run_secs {
        thresholds.empty_run_max_secs = max_secs;
    }
    if let Some(max_ms) = max_packetization_ms {
        thresholds.packetization_max_ms_per_100_files = max_ms;
    }
    if let Some(max_rss) = max_rss_mb {
        thresholds.max_rss_mb = Some(max_rss);
    }
    if let Some(max_commit) = max_commit_mb {
        thresholds.max_commit_mb = Some(max_commit);
    }

    // Only print header if not in JSON mode
    if !json {
        println!("=== xchecker Performance Benchmark ===");
        println!("Validating NFR1 performance targets:");
        println!("  - Empty run: ≤ {:.3}s", thresholds.empty_run_max_secs);
        println!(
            "  - Packetization: ≤ {:.1}ms per 100 files",
            thresholds.packetization_max_ms_per_100_files
        );
        if let Some(max_rss) = thresholds.max_rss_mb {
            println!("  - RSS memory: ≤ {max_rss:.1}MB");
        }
        if let Some(max_commit) = thresholds.max_commit_mb {
            println!("  - Commit memory: ≤ {max_commit:.1}MB");
        }
        println!();
    }

    // Create benchmark configuration
    let config = BenchmarkConfig {
        file_count,
        file_size_bytes: file_size,
        iterations,
        verbose: verbose && !json, // Suppress verbose output in JSON mode
        thresholds,
    };

    if verbose && !json {
        println!("Benchmark configuration:");
        println!("  File count: {}", config.file_count);
        println!("  File size: {} bytes", config.file_size_bytes);
        println!("  Iterations: {}", config.iterations);
        println!();
    }

    // Create and run benchmark
    let runner = BenchmarkRunner::new(config);
    let results = runner
        .run_all_benchmarks()
        .context("Failed to run benchmarks")?;

    // Output results
    if json {
        // Emit structured JSON output (FR-BENCH-004)
        // Use JCS canonicalization for consistent JSON output (FR-CLI-6)
        use serde_json::json;

        let json_output = json!({
            "ok": results.ok,
            "timings_ms": results.timings_ms,
            "rss_mb": results.rss_mb,
            "commit_mb": results.commit_mb,
            "violations": results.violations,
            "config": {
                "file_count": file_count,
                "file_size_bytes": file_size,
                "iterations": iterations,
            },
            "thresholds": {
                "empty_run_max_secs": runner.config.thresholds.empty_run_max_secs,
                "packetization_max_ms_per_100_files": runner.config.thresholds.packetization_max_ms_per_100_files,
                "max_rss_mb": runner.config.thresholds.max_rss_mb,
                "max_commit_mb": runner.config.thresholds.max_commit_mb,
            }
        });

        let canonical_json = emit_jcs(&json_output).context("Failed to emit benchmark JSON")?;
        println!("{canonical_json}");
    } else {
        // Print human-readable results
        runner.print_summary(&results);
    }

    // Exit with appropriate code based on results
    if results.ok {
        if !json {
            println!("\n✓ All performance targets met!");
        }
        Ok(())
    } else {
        if !json {
            println!("\n✗ Some performance targets not met.");
        }
        std::process::exit(1);
    }
}

/// Execute the doctor command for environment health checks
fn execute_doctor_command(json: bool, strict_exit: bool, config: &Config) -> Result<()> {
    use crate::doctor::DoctorCommand;

    // Create and run doctor command (wired through Doctor::run)
    let mut doctor = DoctorCommand::new(config.clone());

    // Show spinner if interactive TTY and not JSON mode (RAII ensures cleanup on panic)
    let spinner_guard = if !json && std::io::stdout().is_terminal() {
        Some(SpinnerGuard::new())
    } else {
        None
    };

    let result = doctor.run_with_options_strict(strict_exit);

    // Explicitly drop spinner to clear the line before printing results
    drop(spinner_guard);

    let output = result.context("Failed to run doctor checks")?;

    if json {
        // Emit as canonical JSON (JCS) for stable diffs (FR-CLI-6)
        // Use emit_jcs for consistent canonicalization with receipts/status
        let json_output = emit_jcs(&output).context("Failed to emit doctor JSON")?;
        println!("{json_output}");
    } else {
        // Use log_doctor_report for human-readable output (wired into logging)
        crate::logging::log_doctor_report(&output);

        if !output.ok {
            println!();
            if strict_exit {
                println!(
                    "Some checks failed or warned (strict mode). Please address the issues above."
                );
            } else {
                println!(
                    "Some checks failed. Please address the issues above before using xchecker."
                );
            }
        }
    }

    // Exit with non-zero code if any check failed (R5.6)
    // In strict mode, warnings also cause non-zero exit
    if !output.ok {
        std::process::exit(1);
    }

    Ok(())
}

/// Execute the gate command for policy-based spec validation
/// Per FR-GATE (Requirements 4.5.1, 4.5.2, 4.5.3, 4.5.4)
fn execute_gate_command(
    spec_id: &str,
    policy_path: Option<&std::path::Path>,
    min_phase: Option<&str>,
    fail_on_pending_fixups: bool,
    max_phase_age: Option<&str>,
    json: bool,
) -> Result<()> {
    use xchecker_gate::{
        GateCommand, GatePolicy, emit_gate_json, load_policy_from_path, parse_duration,
        parse_phase, resolve_policy_path,
    };

    let policy_path = resolve_policy_path(policy_path).map_err(|e| {
        XCheckerError::Config(ConfigError::InvalidValue {
            key: "policy".to_string(),
            value: e.to_string(),
        })
    })?;

    let mut policy = if let Some(path) = policy_path {
        load_policy_from_path(&path).map_err(|e| {
            XCheckerError::Config(ConfigError::InvalidValue {
                key: "policy".to_string(),
                value: e.to_string(),
            })
        })?
    } else {
        GatePolicy::default()
    };

    if let Some(min_phase) = min_phase {
        policy.min_phase = Some(parse_phase(min_phase).map_err(|e| {
            XCheckerError::Config(ConfigError::InvalidValue {
                key: "min_phase".to_string(),
                value: e.to_string(),
            })
        })?);
    }

    if fail_on_pending_fixups {
        policy.fail_on_pending_fixups = true;
    }

    if let Some(age_str) = max_phase_age {
        policy.max_phase_age = Some(parse_duration(age_str).map_err(|e| {
            XCheckerError::Config(ConfigError::InvalidValue {
                key: "max_phase_age".to_string(),
                value: e.to_string(),
            })
        })?);
    }

    // Execute gate evaluation
    let gate = GateCommand::new(spec_id.to_string(), policy);
    let result = gate
        .execute()
        .with_context(|| format!("Failed to evaluate gate for spec: {spec_id}"))?;

    // Output results
    if json {
        let json_output =
            emit_gate_json(&result, spec_id).with_context(|| "Failed to emit gate JSON")?;
        println!("{json_output}");
    } else {
        // Human-friendly output
        if result.passed {
            println!("{}", result.summary);
        } else {
            println!("{}", result.summary);
        }

        println!();
        println!("Conditions evaluated:");
        for condition in &result.conditions {
            let status = if condition.passed { "" } else { "" };
            println!("  {} {}: {}", status, condition.name, condition.description);
            if let Some(actual) = &condition.actual {
                println!("      Actual: {}", actual);
            }
            if let Some(expected) = &condition.expected {
                println!("      Expected: {}", expected);
            }
        }

        if !result.failure_reasons.is_empty() {
            println!();
            println!("Failure reasons:");
            for reason in &result.failure_reasons {
                println!("  - {}", reason);
            }
        }
    }

    // Exit with appropriate code
    if result.passed {
        Ok(())
    } else {
        std::process::exit(crate::gate::exit_codes::POLICY_VIOLATION);
    }
}

/// Execute the init command to initialize a spec with optional lockfile
fn execute_init_command(spec_id: &str, create_lock: bool, config: &Config) -> Result<()> {
    use crate::lock::XCheckerLock;

    println!("{}", styled_info(&format!("Initializing spec: {spec_id}")));

    // Create spec directory structure
    let spec_dir = PathBuf::from(".xchecker").join("specs").join(spec_id);
    let artifacts_dir = spec_dir.join("artifacts");
    let receipts_dir = spec_dir.join("receipts");
    let context_dir = spec_dir.join("context");

    // Check if spec already exists
    if spec_dir.exists() {
        println!("  Spec directory already exists: {}", spec_dir.display());

        // Check if lockfile exists
        let lock_path = spec_dir.join("lock.json");
        if lock_path.exists() {
            println!("  Lockfile already exists: {}", lock_path.display());

            if create_lock {
                println!(
                    "  {} Warning: --create-lock specified but lockfile already exists",
                    styled_warning()
                );
                println!("  To update the lockfile, delete it first and run init again");
            }

            return Ok(());
        }
    } else {
        // Create directory structure (ignore benign races)
        crate::paths::ensure_dir_all(&artifacts_dir).with_context(|| {
            format!(
                "Failed to create artifacts directory: {}",
                artifacts_dir.display()
            )
        })?;
        crate::paths::ensure_dir_all(&receipts_dir).with_context(|| {
            format!(
                "Failed to create receipts directory: {}",
                receipts_dir.display()
            )
        })?;
        crate::paths::ensure_dir_all(&context_dir).with_context(|| {
            format!(
                "Failed to create context directory: {}",
                context_dir.display()
            )
        })?;

        println!(
            "  {} Created spec directory: {}",
            styled_check(),
            spec_dir.display()
        );
        println!("  {} Created artifacts directory", styled_check());
        println!("  {} Created receipts directory", styled_check());
        println!("  {} Created context directory", styled_check());
    }

    // Create lockfile if requested
    if create_lock {
        // Get model from config or use default
        let model = config.defaults.model.as_deref().unwrap_or("haiku");

        // Get Claude CLI version (we'll need to detect this - for now use a placeholder)
        // In a real implementation, this would call `claude --version` and parse the output
        let claude_cli_version =
            detect_claude_cli_version().unwrap_or_else(|_| "unknown".to_string());

        let lock = XCheckerLock::new(model.to_string(), claude_cli_version.clone());

        lock.save(spec_id)
            .with_context(|| "Failed to save lockfile")?;

        println!("  {} Created lockfile: lock.json", styled_check());
        println!("    Model: {model}");
        println!("    Claude CLI version: {claude_cli_version}");
        println!("    Schema version: 1");

        println!("\n  Lockfile will track drift for:");
        println!("    - Model changes (current: {model})");
        println!("    - Claude CLI version changes (current: {claude_cli_version})");
        println!("    - Schema version changes (current: 1)");
        println!("\n  Use --strict-lock flag to hard fail on drift detection");
    } else {
        println!("\n  No lockfile created (use --create-lock to pin model and CLI version)");
    }

    println!(
        "\n{}",
        styled_success(&format!("Spec '{spec_id}' initialized successfully"))
    );
    println!("  Directory: {}", spec_dir.display());

    println!("\nNext steps:");
    println!("  1. Create your problem statement:");
    println!("     echo \"Your problem description\" | xchecker spec {spec_id}");
    println!("  2. Or resume from existing source:");
    println!("     xchecker resume {spec_id} --phase requirements");

    Ok(())
}

/// Detect Claude CLI version by running `claude --version`
fn detect_claude_cli_version() -> Result<String> {
    use crate::runner::CommandSpec;

    let output = CommandSpec::new("claude")
        .arg("--version")
        .to_command()
        .output()
        .context("Failed to execute 'claude --version'")?;

    if !output.status.success() {
        return Err(anyhow::anyhow!(
            "claude --version exited with non-zero status"
        ));
    }

    let version_str = String::from_utf8(output.stdout)
        .context("Failed to parse claude --version output as UTF-8")?;

    // Parse version from output (format: "claude 0.8.1" or similar)
    let version = version_str
        .split_whitespace()
        .last()
        .ok_or_else(|| anyhow::anyhow!("Failed to parse version from output"))?
        .to_string();

    Ok(version)
}

/// Check for lockfile drift and warn or fail based on `strict_lock` flag
fn check_lockfile_drift(
    spec_id: &str,
    strict_lock: bool,
    model_full_name: &str,
    claude_cli_version: &str,
) -> Result<Option<crate::types::LockDrift>> {
    use crate::lock::{RunContext, XCheckerLock};

    // Try to load lockfile
    let lock = match XCheckerLock::load(spec_id) {
        Ok(Some(lock)) => lock,
        Ok(None) => return Ok(None), // No lockfile, no drift
        Err(e) => {
            eprintln!("⚠ Warning: Failed to load lockfile: {e}");
            return Ok(None);
        }
    };

    // Create current run context
    let context = RunContext {
        model_full_name: model_full_name.to_string(),
        claude_cli_version: claude_cli_version.to_string(),
        schema_version: "1".to_string(),
    };

    // Detect drift
    if let Some(drift) = lock.detect_drift(&context) {
        // Print drift warning
        eprintln!("\n⚠ Lockfile drift detected for spec '{spec_id}':");

        if let Some(ref model_drift) = drift.model_full_name {
            eprintln!("  Model: {}{}", model_drift.locked, model_drift.current);
        }

        if let Some(ref cli_drift) = drift.claude_cli_version {
            eprintln!("  Claude CLI: {}{}", cli_drift.locked, cli_drift.current);
        }

        if let Some(ref schema_drift) = drift.schema_version {
            eprintln!(
                "  Schema: {}{}",
                schema_drift.locked, schema_drift.current
            );
        }

        if strict_lock {
            eprintln!("\n✗ Strict lock mode enabled: failing due to drift");
            eprintln!("  To proceed, either:");
            eprintln!(
                "    - Update the lockfile: rm .xchecker/specs/{spec_id}/lock.json && xchecker init {spec_id} --create-lock"
            );
            eprintln!("    - Remove --strict-lock flag to allow drift with warning");

            return Err(anyhow::anyhow!("Lockfile drift detected in strict mode"));
        }
        eprintln!("\n  Continuing with drift (use --strict-lock to fail on drift)");

        Ok(Some(drift))
    } else {
        Ok(None)
    }
}

struct SpinnerGuard {
    running: Arc<AtomicBool>,
    handle: Option<thread::JoinHandle<()>>,
}

impl SpinnerGuard {
    fn new() -> Self {
        let running = Arc::new(AtomicBool::new(true));
        let running_clone = running.clone();

        // Hide cursor to prevent flickering
        let _ = crossterm::execute!(std::io::stdout(), crossterm::cursor::Hide);

        let handle = thread::spawn(move || {
            let frames = ["", "", "", "", "", "", "", "", "", ""];
            let mut i = 0;
            while running_clone.load(Ordering::Relaxed) {
                print!("\r{} Running health checks...", frames[i]);
                let _ = std::io::stdout().flush();
                i = (i + 1) % frames.len();
                thread::sleep(Duration::from_millis(80));
            }
            // Clear the line when done (use crossterm for portability)
            let _ = crossterm::execute!(
                std::io::stdout(),
                crossterm::terminal::Clear(crossterm::terminal::ClearType::CurrentLine)
            );
            print!("\r");
            let _ = std::io::stdout().flush();
        });

        Self {
            running,
            handle: Some(handle),
        }
    }
}

impl Drop for SpinnerGuard {
    fn drop(&mut self) {
        self.running.store(false, Ordering::Relaxed);
        if let Some(handle) = self.handle.take() {
            let _ = handle.join();
        }
        // Restore cursor
        let _ = crossterm::execute!(std::io::stdout(), crossterm::cursor::Show);
    }
}

#[cfg(test)]
#[allow(clippy::items_after_test_module)] // Test helper functions defined after tests is intentional
#[allow(clippy::await_holding_lock)] // Test synchronization using mutex guards across awaits is intentional
mod tests {
    use super::*;
    use serial_test::serial;
    use std::env;
    use std::sync::{Mutex, MutexGuard, OnceLock};
    use tempfile::TempDir;
    use xchecker_utils::test_support::EnvVarGuard;

    // Global lock for tests that mutate process-global CLI state (env vars, cwd).
    // Any test that uses `TestEnvGuard` or `cli_env_guard()` will be serialized.
    static CLI_ENV_LOCK: OnceLock<Mutex<()>> = OnceLock::new();

    fn cli_env_guard() -> MutexGuard<'static, ()> {
        CLI_ENV_LOCK.get_or_init(|| Mutex::new(())).lock().unwrap()
    }

    struct TestEnvGuard {
        // Hold the lock for the entire lifetime of the guard
        _lock: MutexGuard<'static, ()>,
        _temp_dir: TempDir,
        original_dir: PathBuf,
        // EnvVarGuard handles save/restore of XCHECKER_HOME automatically on drop
        _env_guard: EnvVarGuard,
    }

    impl Drop for TestEnvGuard {
        fn drop(&mut self) {
            // Restore cwd while still holding the lock
            // _env_guard drops after this, restoring XCHECKER_HOME
            let _ = env::set_current_dir(&self.original_dir);
            // _lock field drops last, releasing the mutex
        }
    }

    fn setup_test_environment() -> TestEnvGuard {
        // Take the global CLI lock first
        let lock = cli_env_guard();

        let temp_dir = TempDir::new().unwrap();
        let original_dir = env::current_dir().unwrap();

        // EnvVarGuard captures original value and will restore on drop
        let env_guard = EnvVarGuard::cleared("XCHECKER_HOME");

        // From here onwards we're serialized against other CLI tests
        env::set_current_dir(temp_dir.path()).unwrap();

        TestEnvGuard {
            _lock: lock,
            _temp_dir: temp_dir,
            original_dir,
            _env_guard: env_guard,
        }
    }

    #[test]
    fn test_create_default_config() {
        let cli_args = CliArgs::default();
        let config = Config::discover(&cli_args).unwrap();
        let config_map = create_default_config(true, &config, &cli_args);

        assert_eq!(config_map.get("verbose"), Some(&"true".to_string()));
        assert_eq!(
            config_map.get("packet_max_bytes"),
            Some(&"65536".to_string())
        );
        assert_eq!(
            config_map.get("packet_max_lines"),
            Some(&"1200".to_string())
        );
    }

    #[test]
    fn test_create_default_config_no_verbose() {
        let cli_args = CliArgs::default();
        let config = Config::discover(&cli_args).unwrap();
        let config_map = create_default_config(false, &config, &cli_args);

        assert!(!config_map.contains_key("verbose"));
        assert_eq!(
            config_map.get("packet_max_bytes"),
            Some(&"65536".to_string())
        );
        assert_eq!(
            config_map.get("packet_max_lines"),
            Some(&"1200".to_string())
        );
    }

    #[tokio::test]
    #[serial]
    async fn test_spec_command_execution() -> anyhow::Result<()> {
        use tempfile::TempDir;

        // Take the global CLI lock for env/cwd mutations
        let _lock = cli_env_guard();

        // Setup isolated test root
        let temp = TempDir::new()?;
        let root = temp.path();

        // Make it look like a repo root
        std::fs::create_dir_all(root.join(".git"))?;

        // Use guards that restore env vars on drop (including on panic)
        let _home_guard = EnvVarGuard::set("XCHECKER_HOME", root.to_str().unwrap());
        let _skip_guard = EnvVarGuard::set("XCHECKER_SKIP_LLM_TESTS", "1");

        // Save and change CWD
        let original_dir = std::env::current_dir()?;
        std::env::set_current_dir(root)?;

        // Create minimal config
        std::fs::write(
            root.join("xchecker.toml"),
            r#"
[runner]
runner_mode = "native"

[packet]
packet_max_bytes = 1048576
packet_max_lines = 5000
"#,
        )?;

        // Create minimal CLI args for dry-run
        let cli_args = CliArgs::default();

        let config = Config::discover(&cli_args)?;
        let redactor = Arc::new(SecretRedactor::from_config(&config)?);

        // Create a minimal input file for the spec
        std::fs::write(root.join("input.txt"), "Test requirement")?;

        // Test dry-run execution (fast, no real LLMs)
        // This should complete quickly and not hang
        let result = execute_spec_command(
            "test-spec",
            "fs",
            Some("input.txt"),
            Some(root.to_str().unwrap()), // repo path
            true,                         // dry_run = true
            false,
            false,
            false,
            false,
            &config,
            &cli_args,
            &redactor,
        )
        .await;

        // Restore CWD before asserting (env vars restored by guards on drop)
        let _ = std::env::set_current_dir(&original_dir);

        // In dry-run mode with a valid source, this should succeed
        // The important thing is it doesn't hang and completes quickly
        assert!(
            result.is_ok(),
            "Dry-run spec execution should succeed: {:?}",
            result.err()
        );

        Ok(())
    }

    #[test]
    fn test_status_command_no_spec() {
        let _temp_dir = setup_test_environment();

        let cli_args = CliArgs::default();
        let config = Config::discover(&cli_args).unwrap();

        // Test status for non-existent spec
        let result = execute_status_command("nonexistent-spec", false, &config);
        assert!(result.is_ok());
    }

    #[test]
    fn test_status_command_with_spec() {
        let _temp_dir = setup_test_environment();

        let cli_args = CliArgs::default();
        let config = Config::discover(&cli_args).unwrap();

        // Note: We can't easily test spec creation with stdin in unit tests
        // This test just verifies status command works with non-existent spec
        let result = execute_status_command("test-status-spec", false, &config);
        assert!(result.is_ok());
    }

    // ===== Spec JSON Output Tests (Task 21.1) =====
    // **Property: JSON output includes schema version**
    // **Validates: Requirements 4.1.1**

    #[test]
    fn test_spec_json_output_schema_version() {
        // Test that spec JSON output includes schema_version field
        use crate::types::{PhaseInfo, SpecConfigSummary, SpecOutput};

        let output = SpecOutput {
            schema_version: "spec-json.v1".to_string(),
            spec_id: "test-spec".to_string(),
            phases: vec![PhaseInfo {
                phase_id: "requirements".to_string(),
                status: "completed".to_string(),
                last_run: Some(chrono::Utc::now()),
            }],
            config_summary: SpecConfigSummary {
                execution_strategy: "controlled".to_string(),
                provider: Some("claude-cli".to_string()),
                spec_path: ".xchecker/specs/test-spec".to_string(),
            },
        };

        // Emit as JSON
        let json_result = emit_spec_json(&output);
        assert!(json_result.is_ok(), "Failed to emit spec JSON");

        let json_str = json_result.unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&json_str).unwrap();

        // Verify schema_version is present and correct
        assert_eq!(parsed["schema_version"], "spec-json.v1");
        assert_eq!(parsed["spec_id"], "test-spec");
    }

    #[test]
    fn test_spec_json_output_excludes_packet_contents() {
        // Test that spec JSON output excludes full packet contents
        // per Requirements 4.1.4
        use crate::types::{PhaseInfo, SpecConfigSummary, SpecOutput};

        let output = SpecOutput {
            schema_version: "spec-json.v1".to_string(),
            spec_id: "test-spec".to_string(),
            phases: vec![
                PhaseInfo {
                    phase_id: "requirements".to_string(),
                    status: "completed".to_string(),
                    last_run: None,
                },
                PhaseInfo {
                    phase_id: "design".to_string(),
                    status: "not_started".to_string(),
                    last_run: None,
                },
            ],
            config_summary: SpecConfigSummary {
                execution_strategy: "controlled".to_string(),
                provider: None,
                spec_path: ".xchecker/specs/test-spec".to_string(),
            },
        };

        let json_result = emit_spec_json(&output);
        assert!(json_result.is_ok());

        let json_str = json_result.unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&json_str).unwrap();

        // Verify no packet contents are present
        assert!(
            parsed.get("packet").is_none(),
            "JSON should not contain packet field"
        );
        assert!(
            parsed.get("artifacts").is_none(),
            "JSON should not contain artifacts field"
        );
        assert!(
            parsed.get("raw_response").is_none(),
            "JSON should not contain raw_response field"
        );

        // Verify only expected fields are present
        assert!(parsed.get("schema_version").is_some());
        assert!(parsed.get("spec_id").is_some());
        assert!(parsed.get("phases").is_some());
        assert!(parsed.get("config_summary").is_some());
    }

    #[test]
    fn test_spec_json_command_no_spec() {
        let _temp_dir = setup_test_environment();

        let cli_args = CliArgs::default();
        let config = Config::discover(&cli_args).unwrap();

        // Test spec --json for non-existent spec
        let result = execute_spec_json_command("nonexistent-spec-json", &config);
        assert!(result.is_ok());
    }

    #[test]
    fn test_spec_json_canonical_format() {
        // Test that spec JSON output is in canonical JCS format (no extra whitespace)
        use crate::types::{PhaseInfo, SpecConfigSummary, SpecOutput};

        let output = SpecOutput {
            schema_version: "spec-json.v1".to_string(),
            spec_id: "test-spec".to_string(),
            phases: vec![PhaseInfo {
                phase_id: "requirements".to_string(),
                status: "completed".to_string(),
                last_run: None,
            }],
            config_summary: SpecConfigSummary {
                execution_strategy: "controlled".to_string(),
                provider: None,
                spec_path: ".xchecker/specs/test-spec".to_string(),
            },
        };

        let json_result = emit_spec_json(&output);
        assert!(json_result.is_ok());

        let json_str = json_result.unwrap();

        // Verify canonical JSON properties (no extra whitespace, no newlines)
        assert!(
            !json_str.contains("  "),
            "Canonical JSON should not have indentation"
        );
        assert!(
            !json_str.contains('\n'),
            "Canonical JSON should not have newlines"
        );
    }

    #[test]
    fn test_spec_json_all_phases_present() {
        // Test that all phases are represented in the output
        use crate::types::{PhaseInfo, SpecConfigSummary, SpecOutput};

        let phases = vec![
            PhaseInfo {
                phase_id: "requirements".to_string(),
                status: "completed".to_string(),
                last_run: None,
            },
            PhaseInfo {
                phase_id: "design".to_string(),
                status: "pending".to_string(),
                last_run: None,
            },
            PhaseInfo {
                phase_id: "tasks".to_string(),
                status: "not_started".to_string(),
                last_run: None,
            },
            PhaseInfo {
                phase_id: "review".to_string(),
                status: "not_started".to_string(),
                last_run: None,
            },
            PhaseInfo {
                phase_id: "fixup".to_string(),
                status: "not_started".to_string(),
                last_run: None,
            },
            PhaseInfo {
                phase_id: "final".to_string(),
                status: "not_started".to_string(),
                last_run: None,
            },
        ];

        let output = SpecOutput {
            schema_version: "spec-json.v1".to_string(),
            spec_id: "test-spec".to_string(),
            phases,
            config_summary: SpecConfigSummary {
                execution_strategy: "controlled".to_string(),
                provider: Some("openrouter".to_string()),
                spec_path: ".xchecker/specs/test-spec".to_string(),
            },
        };

        let json_result = emit_spec_json(&output);
        assert!(json_result.is_ok());

        let json_str = json_result.unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&json_str).unwrap();

        // Verify all 6 phases are present
        let phases_array = parsed["phases"].as_array().unwrap();
        assert_eq!(phases_array.len(), 6);

        // Verify phase IDs
        let phase_ids: Vec<&str> = phases_array
            .iter()
            .map(|p| p["phase_id"].as_str().unwrap())
            .collect();
        assert!(phase_ids.contains(&"requirements"));
        assert!(phase_ids.contains(&"design"));
        assert!(phase_ids.contains(&"tasks"));
        assert!(phase_ids.contains(&"review"));
        assert!(phase_ids.contains(&"fixup"));
        assert!(phase_ids.contains(&"final"));
    }

    #[test]
    fn test_benchmark_command_basic() {
        // Test basic benchmark execution with realistic thresholds for test environments
        // Use more generous thresholds since test environments can be slower
        let result = execute_benchmark_command(
            5,            // file_count
            100,          // file_size
            2,            // iterations
            false,        // json
            Some(10.0),   // max_empty_run_secs - generous for test env
            Some(2000.0), // max_packetization_ms - generous for test env (100ms for 5 files)
            None,         // max_rss_mb
            None,         // max_commit_mb
            false,        // verbose
        );

        // Should succeed with realistic test environment thresholds
        assert!(result.is_ok());
    }

    #[test]
    fn test_benchmark_command_with_threshold_overrides() {
        // Test benchmark with custom thresholds (very generous to ensure pass)
        let result = execute_benchmark_command(
            5,             // file_count
            100,           // file_size
            2,             // iterations
            false,         // json
            Some(100.0),   // max_empty_run_secs - very generous
            Some(10000.0), // max_packetization_ms - very generous
            Some(1000.0),  // max_rss_mb - very generous
            Some(2000.0),  // max_commit_mb - very generous
            false,         // verbose
        );

        // Should succeed with generous thresholds
        assert!(result.is_ok());
    }

    #[test]
    fn test_benchmark_command_json_output() {
        // Test that JSON mode runs successfully
        // (We can't easily capture stdout in unit tests, but integration tests verify JSON structure)
        let result = execute_benchmark_command(
            5,             // file_count
            100,           // file_size
            2,             // iterations
            true,          // json - this is what we're testing
            Some(100.0),   // max_empty_run_secs
            Some(10000.0), // max_packetization_ms
            None,          // max_rss_mb
            None,          // max_commit_mb
            false,         // verbose (should be suppressed in JSON mode)
        );

        // Should succeed
        assert!(result.is_ok());
    }

    #[test]
    fn test_benchmark_thresholds_applied() {
        // Test that custom thresholds are properly applied
        use crate::benchmark::{BenchmarkConfig, BenchmarkThresholds};

        let thresholds = BenchmarkThresholds {
            empty_run_max_secs: 3.0,
            packetization_max_ms_per_100_files: 150.0,
            max_rss_mb: Some(500.0),
            max_commit_mb: Some(1000.0),
        };

        let config = BenchmarkConfig {
            file_count: 10,
            file_size_bytes: 100,
            iterations: 2,
            verbose: false,
            thresholds,
        };

        // Verify thresholds are set correctly
        assert_eq!(config.thresholds.empty_run_max_secs, 3.0);
        assert_eq!(config.thresholds.packetization_max_ms_per_100_files, 150.0);
        assert_eq!(config.thresholds.max_rss_mb, Some(500.0));
        assert_eq!(config.thresholds.max_commit_mb, Some(1000.0));
    }

    #[test]
    fn test_benchmark_cli_parsing() {
        // Test that CLI arguments are properly parsed
        use clap::Parser;

        // Test basic benchmark command
        let args = vec![
            "xchecker",
            "benchmark",
            "--file-count",
            "50",
            "--iterations",
            "3",
        ];
        let cli = Cli::try_parse_from(args);
        assert!(cli.is_ok());

        if let Ok(cli) = cli {
            match cli.command {
                Commands::Benchmark {
                    file_count,
                    iterations,
                    ..
                } => {
                    assert_eq!(file_count, 50);
                    assert_eq!(iterations, 3);
                }
                _ => panic!("Expected Benchmark command"),
            }
        }

        // Test benchmark with threshold overrides
        let args_with_thresholds = vec![
            "xchecker",
            "benchmark",
            "--max-empty-run-secs",
            "3.5",
            "--max-packetization-ms",
            "180.0",
            "--json",
        ];
        let cli_thresholds = Cli::try_parse_from(args_with_thresholds);
        assert!(cli_thresholds.is_ok());

        if let Ok(cli) = cli_thresholds {
            match cli.command {
                Commands::Benchmark {
                    max_empty_run_secs,
                    max_packetization_ms,
                    json,
                    ..
                } => {
                    assert_eq!(max_empty_run_secs, Some(3.5));
                    assert_eq!(max_packetization_ms, Some(180.0));
                    assert!(json);
                }
                _ => panic!("Expected Benchmark command"),
            }
        }
    }

    #[test]
    fn test_benchmark_default_values() {
        // Test that default values are applied correctly
        use clap::Parser;

        let args = vec!["xchecker", "benchmark"];
        let cli = Cli::try_parse_from(args);
        assert!(cli.is_ok());

        if let Ok(cli) = cli {
            match cli.command {
                Commands::Benchmark {
                    file_count,
                    file_size,
                    iterations,
                    json,
                    max_empty_run_secs,
                    max_packetization_ms,
                    ..
                } => {
                    assert_eq!(file_count, 100); // default
                    assert_eq!(file_size, 1024); // default
                    assert_eq!(iterations, 5); // default
                    assert!(!json); // default false
                    assert_eq!(max_empty_run_secs, None); // default None
                    assert_eq!(max_packetization_ms, None); // default None
                }
                _ => panic!("Expected Benchmark command"),
            }
        }
    }

    // ===== Status JSON Output Tests (Task 22) =====
    // **Property: JSON output includes schema version**
    // **Validates: Requirements 4.1.2**

    #[test]
    fn test_status_json_output_schema_version() {
        // Test that status JSON output includes schema_version field
        use crate::types::{PhaseStatusInfo, StatusJsonOutput};

        let output = StatusJsonOutput {
            schema_version: "status-json.v2".to_string(),
            spec_id: "test-spec".to_string(),
            phase_statuses: vec![PhaseStatusInfo {
                phase_id: "requirements".to_string(),
                status: "success".to_string(),
                receipt_id: Some("requirements-20241201_100000".to_string()),
            }],
            pending_fixups: 0,
            has_errors: false,
            strict_validation: false,
            artifacts: Vec::new(),
            effective_config: std::collections::BTreeMap::new(),
            lock_drift: None,
        };

        // Emit as JSON
        let json_result = emit_status_json(&output);
        assert!(json_result.is_ok(), "Failed to emit status JSON");

        let json_str = json_result.unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&json_str).unwrap();

        // Verify schema_version is present and correct
        assert_eq!(parsed["schema_version"], "status-json.v2");
        assert_eq!(parsed["spec_id"], "test-spec");
    }

    #[test]
    fn test_status_json_output_has_required_fields() {
        // Test that status JSON output has all required fields per Requirements 4.1.2
        use crate::types::{PhaseStatusInfo, StatusJsonOutput};

        let output = StatusJsonOutput {
            schema_version: "status-json.v2".to_string(),
            spec_id: "test-spec".to_string(),
            phase_statuses: vec![
                PhaseStatusInfo {
                    phase_id: "requirements".to_string(),
                    status: "success".to_string(),
                    receipt_id: Some("requirements-20241201_100000".to_string()),
                },
                PhaseStatusInfo {
                    phase_id: "design".to_string(),
                    status: "failed".to_string(),
                    receipt_id: Some("design-20241201_110000".to_string()),
                },
                PhaseStatusInfo {
                    phase_id: "tasks".to_string(),
                    status: "not_started".to_string(),
                    receipt_id: None,
                },
            ],
            pending_fixups: 3,
            has_errors: true,
            strict_validation: false,
            artifacts: Vec::new(),
            effective_config: std::collections::BTreeMap::new(),
            lock_drift: None,
        };

        let json_result = emit_status_json(&output);
        assert!(json_result.is_ok());

        let json_str = json_result.unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&json_str).unwrap();

        // Verify all required fields are present
        assert!(parsed.get("schema_version").is_some());
        assert!(parsed.get("spec_id").is_some());
        assert!(parsed.get("phase_statuses").is_some());
        assert!(parsed.get("pending_fixups").is_some());
        assert!(parsed.get("has_errors").is_some());
        assert!(
            parsed.get("strict_validation").is_some(),
            "strict_validation field should be present"
        );

        // Verify values
        assert_eq!(parsed["pending_fixups"], 3);
        assert_eq!(parsed["has_errors"], true);
        assert_eq!(parsed["strict_validation"], false);
    }

    #[test]
    fn test_status_json_canonical_format() {
        // Test that status JSON output is in canonical JCS format (no extra whitespace)
        use crate::types::{PhaseStatusInfo, StatusJsonOutput};

        let output = StatusJsonOutput {
            schema_version: "status-json.v2".to_string(),
            spec_id: "test-spec".to_string(),
            phase_statuses: vec![PhaseStatusInfo {
                phase_id: "requirements".to_string(),
                status: "success".to_string(),
                receipt_id: None,
            }],
            pending_fixups: 0,
            has_errors: false,
            strict_validation: false,
            artifacts: Vec::new(),
            effective_config: std::collections::BTreeMap::new(),
            lock_drift: None,
        };

        let json_result = emit_status_json(&output);
        assert!(json_result.is_ok());

        let json_str = json_result.unwrap();

        // Verify canonical JSON properties (no extra whitespace, no newlines)
        assert!(
            !json_str.contains("  "),
            "Canonical JSON should not have indentation"
        );
        assert!(
            !json_str.contains('\n'),
            "Canonical JSON should not have newlines"
        );
    }

    #[test]
    fn test_status_json_excludes_raw_packet_contents() {
        // Test that status JSON output excludes raw packet contents (like raw_response)
        // but does include summarized artifacts and effective_config per v2 schema
        use crate::types::{
            ArtifactInfo, ConfigSource, ConfigValue, PhaseStatusInfo, StatusJsonOutput,
        };

        let mut effective_config = std::collections::BTreeMap::new();
        effective_config.insert(
            "model".to_string(),
            ConfigValue {
                value: serde_json::Value::String("haiku".to_string()),
                source: ConfigSource::Config,
            },
        );

        let output = StatusJsonOutput {
            schema_version: "status-json.v2".to_string(),
            spec_id: "test-spec".to_string(),
            phase_statuses: vec![PhaseStatusInfo {
                phase_id: "requirements".to_string(),
                status: "success".to_string(),
                receipt_id: Some("requirements-20241201_100000".to_string()),
            }],
            pending_fixups: 0,
            has_errors: false,
            strict_validation: false,
            artifacts: vec![ArtifactInfo {
                path: "artifacts/requirements.yaml".to_string(),
                blake3_first8: "abc12345".to_string(),
            }],
            effective_config,
            lock_drift: None,
        };

        let json_result = emit_status_json(&output);
        assert!(json_result.is_ok());

        let json_str = json_result.unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&json_str).unwrap();

        // Verify no raw packet/response contents are present
        assert!(
            parsed.get("packet").is_none(),
            "JSON should not contain packet field"
        );
        assert!(
            parsed.get("raw_response").is_none(),
            "JSON should not contain raw_response field"
        );

        // Verify artifacts and effective_config ARE present in v2
        assert!(
            parsed.get("artifacts").is_some(),
            "JSON should contain artifacts field in v2"
        );
        assert!(
            parsed.get("effective_config").is_some(),
            "JSON should contain effective_config field in v2"
        );

        // Verify artifacts have only summary data (blake3_first8), not full content
        let artifacts = parsed["artifacts"].as_array().unwrap();
        assert_eq!(artifacts.len(), 1);
        assert_eq!(artifacts[0]["blake3_first8"], "abc12345");
        assert!(
            artifacts[0].get("content").is_none(),
            "Artifacts should not include full content"
        );
    }

    #[test]
    fn test_status_json_command_no_spec() {
        let _temp_dir = setup_test_environment();

        let cli_args = CliArgs::default();
        let config = Config::discover(&cli_args).unwrap();

        // Test status --json for non-existent spec
        let result = execute_status_command("nonexistent-spec-json", true, &config);
        assert!(result.is_ok());
    }

    #[test]
    fn test_status_json_all_phases_present() {
        // Test that all phases can be represented in the output
        use crate::types::{PhaseStatusInfo, StatusJsonOutput};

        let phase_statuses = vec![
            PhaseStatusInfo {
                phase_id: "requirements".to_string(),
                status: "success".to_string(),
                receipt_id: Some("requirements-20241201_100000".to_string()),
            },
            PhaseStatusInfo {
                phase_id: "design".to_string(),
                status: "success".to_string(),
                receipt_id: Some("design-20241201_110000".to_string()),
            },
            PhaseStatusInfo {
                phase_id: "tasks".to_string(),
                status: "failed".to_string(),
                receipt_id: Some("tasks-20241201_120000".to_string()),
            },
            PhaseStatusInfo {
                phase_id: "review".to_string(),
                status: "not_started".to_string(),
                receipt_id: None,
            },
            PhaseStatusInfo {
                phase_id: "fixup".to_string(),
                status: "not_started".to_string(),
                receipt_id: None,
            },
            PhaseStatusInfo {
                phase_id: "final".to_string(),
                status: "not_started".to_string(),
                receipt_id: None,
            },
        ];

        let output = StatusJsonOutput {
            schema_version: "status-json.v2".to_string(),
            spec_id: "test-spec".to_string(),
            phase_statuses,
            pending_fixups: 0,
            has_errors: true, // tasks failed
            strict_validation: false,
            artifacts: Vec::new(),
            effective_config: std::collections::BTreeMap::new(),
            lock_drift: None,
        };

        let json_result = emit_status_json(&output);
        assert!(json_result.is_ok());

        let json_str = json_result.unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&json_str).unwrap();

        // Verify all 6 phases are present
        let phases_array = parsed["phase_statuses"].as_array().unwrap();
        assert_eq!(phases_array.len(), 6);

        // Verify phase IDs
        let phase_ids: Vec<&str> = phases_array
            .iter()
            .map(|p| p["phase_id"].as_str().unwrap())
            .collect();
        assert!(phase_ids.contains(&"requirements"));
        assert!(phase_ids.contains(&"design"));
        assert!(phase_ids.contains(&"tasks"));
        assert!(phase_ids.contains(&"review"));
        assert!(phase_ids.contains(&"fixup"));
        assert!(phase_ids.contains(&"final"));
    }

    // ===== Resume JSON Output Tests (Task 23) =====
    // **Property: JSON output includes schema version**
    // **Validates: Requirements 4.1.3**

    #[test]
    fn test_resume_json_output_schema_version() {
        // Test that resume JSON output includes schema_version field
        use crate::types::{CurrentInputs, ResumeJsonOutput};

        let output = ResumeJsonOutput {
            schema_version: "resume-json.v1".to_string(),
            spec_id: "test-spec".to_string(),
            phase: "design".to_string(),
            current_inputs: CurrentInputs {
                available_artifacts: vec!["00-requirements.md".to_string()],
                spec_exists: true,
                latest_completed_phase: Some("requirements".to_string()),
            },
            next_steps: "Run design phase to generate architecture and design from requirements."
                .to_string(),
        };

        // Emit as JSON
        let json_result = emit_resume_json(&output);
        assert!(json_result.is_ok(), "Failed to emit resume JSON");

        let json_str = json_result.unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&json_str).unwrap();

        // Verify schema_version is present and correct
        assert_eq!(parsed["schema_version"], "resume-json.v1");
        assert_eq!(parsed["spec_id"], "test-spec");
        assert_eq!(parsed["phase"], "design");
    }

    #[test]
    fn test_resume_json_output_has_required_fields() {
        // Test that resume JSON output has all required fields per Requirements 4.1.3
        use crate::types::{CurrentInputs, ResumeJsonOutput};

        let output = ResumeJsonOutput {
            schema_version: "resume-json.v1".to_string(),
            spec_id: "test-spec".to_string(),
            phase: "tasks".to_string(),
            current_inputs: CurrentInputs {
                available_artifacts: vec![
                    "00-requirements.md".to_string(),
                    "10-design.md".to_string(),
                ],
                spec_exists: true,
                latest_completed_phase: Some("design".to_string()),
            },
            next_steps: "Run tasks phase to generate implementation tasks from design.".to_string(),
        };

        let json_result = emit_resume_json(&output);
        assert!(json_result.is_ok());

        let json_str = json_result.unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&json_str).unwrap();

        // Verify all required fields are present
        assert!(parsed.get("schema_version").is_some());
        assert!(parsed.get("spec_id").is_some());
        assert!(parsed.get("phase").is_some());
        assert!(parsed.get("current_inputs").is_some());
        assert!(parsed.get("next_steps").is_some());

        // Verify current_inputs structure
        let current_inputs = &parsed["current_inputs"];
        assert!(current_inputs.get("available_artifacts").is_some());
        assert!(current_inputs.get("spec_exists").is_some());
        assert!(current_inputs.get("latest_completed_phase").is_some());
    }

    #[test]
    fn test_resume_json_canonical_format() {
        // Test that resume JSON output is in canonical JCS format (no extra whitespace)
        use crate::types::{CurrentInputs, ResumeJsonOutput};

        let output = ResumeJsonOutput {
            schema_version: "resume-json.v1".to_string(),
            spec_id: "test-spec".to_string(),
            phase: "requirements".to_string(),
            current_inputs: CurrentInputs {
                available_artifacts: vec![],
                spec_exists: true,
                latest_completed_phase: None,
            },
            next_steps: "Run requirements phase.".to_string(),
        };

        let json_result = emit_resume_json(&output);
        assert!(json_result.is_ok());

        let json_str = json_result.unwrap();

        // Verify canonical JSON properties (no extra whitespace, no newlines)
        assert!(
            !json_str.contains("  "),
            "Canonical JSON should not have indentation"
        );
        assert!(
            !json_str.contains('\n'),
            "Canonical JSON should not have newlines"
        );
    }

    #[test]
    fn test_resume_json_excludes_raw_artifacts() {
        // Test that resume JSON output excludes full packet and raw artifacts
        // per Requirements 4.1.4
        use crate::types::{CurrentInputs, ResumeJsonOutput};

        let output = ResumeJsonOutput {
            schema_version: "resume-json.v1".to_string(),
            spec_id: "test-spec".to_string(),
            phase: "design".to_string(),
            current_inputs: CurrentInputs {
                available_artifacts: vec!["00-requirements.md".to_string()],
                spec_exists: true,
                latest_completed_phase: Some("requirements".to_string()),
            },
            next_steps: "Run design phase.".to_string(),
        };

        let json_result = emit_resume_json(&output);
        assert!(json_result.is_ok());

        let json_str = json_result.unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&json_str).unwrap();

        // Verify no packet contents or raw artifacts are present
        assert!(
            parsed.get("packet").is_none(),
            "JSON should not contain packet field"
        );
        assert!(
            parsed.get("artifacts").is_none(),
            "JSON should not contain artifacts field"
        );
        assert!(
            parsed.get("raw_response").is_none(),
            "JSON should not contain raw_response field"
        );
        assert!(
            parsed.get("artifact_contents").is_none(),
            "JSON should not contain artifact_contents field"
        );

        // Verify only artifact names are present, not contents
        let artifacts = parsed["current_inputs"]["available_artifacts"]
            .as_array()
            .unwrap();
        for artifact in artifacts {
            // Each artifact should be a simple string (name), not an object with contents
            assert!(
                artifact.is_string(),
                "Artifacts should be names only, not objects with contents"
            );
        }
    }

    #[test]
    fn test_resume_json_command_no_spec() {
        let _temp_dir = setup_test_environment();

        let cli_args = CliArgs::default();
        let config = Config::discover(&cli_args).unwrap();

        // Test resume --json for non-existent spec
        let result = execute_resume_json_command("nonexistent-spec-json", "design", &config);
        assert!(result.is_ok());
    }

    #[test]
    fn test_resume_json_all_phases_valid() {
        // Test that all valid phases can be used in resume JSON output
        use crate::types::{CurrentInputs, ResumeJsonOutput};

        let phases = [
            "requirements",
            "design",
            "tasks",
            "review",
            "fixup",
            "final",
        ];

        for phase in &phases {
            let output = ResumeJsonOutput {
                schema_version: "resume-json.v1".to_string(),
                spec_id: "test-spec".to_string(),
                phase: phase.to_string(),
                current_inputs: CurrentInputs {
                    available_artifacts: vec![],
                    spec_exists: true,
                    latest_completed_phase: None,
                },
                next_steps: format!("Run {} phase.", phase),
            };

            let json_result = emit_resume_json(&output);
            assert!(
                json_result.is_ok(),
                "Failed to emit resume JSON for phase: {}",
                phase
            );

            let json_str = json_result.unwrap();
            let parsed: serde_json::Value = serde_json::from_str(&json_str).unwrap();

            assert_eq!(parsed["phase"], *phase);
        }
    }

    #[test]
    fn test_resume_json_spec_not_exists() {
        // Test resume JSON output when spec doesn't exist
        use crate::types::{CurrentInputs, ResumeJsonOutput};

        let output = ResumeJsonOutput {
            schema_version: "resume-json.v1".to_string(),
            spec_id: "nonexistent-spec".to_string(),
            phase: "requirements".to_string(),
            current_inputs: CurrentInputs {
                available_artifacts: vec![],
                spec_exists: false,
                latest_completed_phase: None,
            },
            next_steps: "Spec 'nonexistent-spec' does not exist. Run 'xchecker spec nonexistent-spec' to create it first.".to_string(),
        };

        let json_result = emit_resume_json(&output);
        assert!(json_result.is_ok());

        let json_str = json_result.unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&json_str).unwrap();

        // Verify spec_exists is false
        assert_eq!(parsed["current_inputs"]["spec_exists"], false);
        // Verify available_artifacts is either empty or not present (due to skip_serializing_if)
        let artifacts = parsed["current_inputs"].get("available_artifacts");
        match artifacts {
            Some(arr) => {
                let arr = arr.as_array().unwrap();
                assert!(arr.is_empty());
            }
            None => {
                // Field is skipped when empty, which is valid
            }
        }
    }

    // ===== Project List Tests (Task 28) =====
    // Tests for derive_spec_status function
    // **Validates: Requirements 4.3.3**

    #[test]
    fn test_derive_spec_status_not_started() {
        // Use isolated home to avoid conflicts with other tests
        let _temp_dir = crate::paths::with_isolated_home();

        // Test status for non-existent spec
        let status = derive_spec_status("nonexistent-spec-status-test");
        assert_eq!(status, "not_started");
    }

    #[test]
    fn test_derive_spec_status_with_receipt() {
        // Use isolated home to avoid conflicts with other tests
        let _temp_dir = crate::paths::with_isolated_home();

        use crate::receipt::ReceiptManager;
        use crate::types::{PacketEvidence, PhaseId};
        use std::collections::HashMap;

        // Create a spec with a receipt
        let spec_id = "test-spec-with-receipt";
        let base_path = crate::paths::spec_root(spec_id);
        crate::paths::ensure_dir_all(&base_path).unwrap();

        let receipt_manager = ReceiptManager::new(&base_path);

        let packet = PacketEvidence {
            files: vec![],
            max_bytes: 65536,
            max_lines: 1200,
        };

        // Create a successful receipt
        let receipt = receipt_manager.create_receipt(
            spec_id,
            PhaseId::Requirements,
            0, // exit_code 0 = success
            vec![],
            "0.1.0",
            "0.8.1",
            "haiku",
            None,
            HashMap::new(),
            packet,
            None,
            None,
            vec![],
            None,
            "native",
            None,
            None,
            None,
            None,
            None,
        );

        receipt_manager.write_receipt(&receipt).unwrap();

        // Test status derivation
        let status = derive_spec_status(spec_id);
        assert!(
            status.contains("success"),
            "Expected 'success' in status, got: {}",
            status
        );
        assert!(
            status.contains("requirements"),
            "Expected 'requirements' in status, got: {}",
            status
        );
    }

    #[test]
    fn test_derive_spec_status_with_failed_receipt() {
        // Use isolated home to avoid conflicts with other tests
        let _temp_dir = crate::paths::with_isolated_home();

        use crate::receipt::ReceiptManager;
        use crate::types::{PacketEvidence, PhaseId};
        use std::collections::HashMap;

        // Create a spec with a failed receipt
        let spec_id = "test-spec-with-failed-receipt";
        let base_path = crate::paths::spec_root(spec_id);
        crate::paths::ensure_dir_all(&base_path).unwrap();

        let receipt_manager = ReceiptManager::new(&base_path);

        let packet = PacketEvidence {
            files: vec![],
            max_bytes: 65536,
            max_lines: 1200,
        };

        // Create a failed receipt
        let receipt = receipt_manager.create_receipt(
            spec_id,
            PhaseId::Design,
            1, // exit_code 1 = failure
            vec![],
            "0.1.0",
            "0.8.1",
            "haiku",
            None,
            HashMap::new(),
            packet,
            None,
            None,
            vec![],
            None,
            "native",
            None,
            None,
            None,
            None,
            None,
        );

        receipt_manager.write_receipt(&receipt).unwrap();

        // Test status derivation
        let status = derive_spec_status(spec_id);
        assert!(
            status.contains("failed"),
            "Expected 'failed' in status, got: {}",
            status
        );
        assert!(
            status.contains("design"),
            "Expected 'design' in status, got: {}",
            status
        );
    }

    #[test]
    fn test_derive_spec_status_uses_latest_receipt() {
        // Use isolated home to avoid conflicts with other tests
        let _temp_dir = crate::paths::with_isolated_home();

        use crate::receipt::ReceiptManager;
        use crate::types::{PacketEvidence, PhaseId};
        use std::collections::HashMap;

        // Create a spec with multiple receipts
        let spec_id = "test-spec-multiple-receipts";
        let base_path = crate::paths::spec_root(spec_id);
        crate::paths::ensure_dir_all(&base_path).unwrap();

        let receipt_manager = ReceiptManager::new(&base_path);

        let packet = PacketEvidence {
            files: vec![],
            max_bytes: 65536,
            max_lines: 1200,
        };

        // Create first receipt (requirements - success)
        let receipt1 = receipt_manager.create_receipt(
            spec_id,
            PhaseId::Requirements,
            0,
            vec![],
            "0.1.0",
            "0.8.1",
            "haiku",
            None,
            HashMap::new(),
            packet.clone(),
            None,
            None,
            vec![],
            None,
            "native",
            None,
            None,
            None,
            None,
            None,
        );
        receipt_manager.write_receipt(&receipt1).unwrap();

        // Small delay to ensure different timestamps
        std::thread::sleep(std::time::Duration::from_millis(1100));

        // Create second receipt (design - success)
        let receipt2 = receipt_manager.create_receipt(
            spec_id,
            PhaseId::Design,
            0,
            vec![],
            "0.1.0",
            "0.8.1",
            "haiku",
            None,
            HashMap::new(),
            packet,
            None,
            None,
            vec![],
            None,
            "native",
            None,
            None,
            None,
            None,
            None,
        );
        receipt_manager.write_receipt(&receipt2).unwrap();

        // Test status derivation - should show design (latest)
        let status = derive_spec_status(spec_id);
        assert!(
            status.contains("design"),
            "Expected 'design' (latest) in status, got: {}",
            status
        );
        assert!(
            status.contains("success"),
            "Expected 'success' in status, got: {}",
            status
        );
    }

    // ===== Workspace Status JSON Output Tests (Task 29) =====
    // **Property: JSON output includes schema version**
    // **Validates: Requirements 4.3.4**

    #[test]
    fn test_workspace_status_json_output_schema_version() {
        // Test that workspace status JSON output includes schema_version field
        use crate::types::{
            WorkspaceSpecStatus, WorkspaceStatusJsonOutput, WorkspaceStatusSummary,
        };

        let output = WorkspaceStatusJsonOutput {
            schema_version: "workspace-status-json.v1".to_string(),
            workspace_name: "test-workspace".to_string(),
            workspace_path: "/path/to/workspace.yaml".to_string(),
            specs: vec![WorkspaceSpecStatus {
                spec_id: "spec-1".to_string(),
                tags: vec!["backend".to_string()],
                status: "success".to_string(),
                latest_phase: Some("tasks".to_string()),
                last_activity: Some(chrono::Utc::now()),
                pending_fixups: 0,
                has_errors: false,
            }],
            summary: WorkspaceStatusSummary {
                total_specs: 1,
                successful_specs: 1,
                failed_specs: 0,
                pending_specs: 0,
                not_started_specs: 0,
                stale_specs: 0,
            },
        };

        // Emit as JSON
        let json_result = emit_workspace_status_json(&output);
        assert!(json_result.is_ok(), "Failed to emit workspace status JSON");

        let json_str = json_result.unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&json_str).unwrap();

        // Verify schema_version is present and correct
        assert_eq!(parsed["schema_version"], "workspace-status-json.v1");
        assert_eq!(parsed["workspace_name"], "test-workspace");
    }

    #[test]
    fn test_workspace_status_json_output_has_required_fields() {
        // Test that workspace status JSON output has all required fields per Requirements 4.3.4
        use crate::types::{
            WorkspaceSpecStatus, WorkspaceStatusJsonOutput, WorkspaceStatusSummary,
        };

        let output = WorkspaceStatusJsonOutput {
            schema_version: "workspace-status-json.v1".to_string(),
            workspace_name: "test-workspace".to_string(),
            workspace_path: "/path/to/workspace.yaml".to_string(),
            specs: vec![
                WorkspaceSpecStatus {
                    spec_id: "spec-1".to_string(),
                    tags: vec![],
                    status: "success".to_string(),
                    latest_phase: Some("design".to_string()),
                    last_activity: None,
                    pending_fixups: 0,
                    has_errors: false,
                },
                WorkspaceSpecStatus {
                    spec_id: "spec-2".to_string(),
                    tags: vec!["frontend".to_string()],
                    status: "failed".to_string(),
                    latest_phase: Some("requirements".to_string()),
                    last_activity: None,
                    pending_fixups: 2,
                    has_errors: true,
                },
            ],
            summary: WorkspaceStatusSummary {
                total_specs: 2,
                successful_specs: 1,
                failed_specs: 1,
                pending_specs: 0,
                not_started_specs: 0,
                stale_specs: 0,
            },
        };

        let json_result = emit_workspace_status_json(&output);
        assert!(json_result.is_ok());

        let json_str = json_result.unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&json_str).unwrap();

        // Verify all required fields are present
        assert!(parsed.get("schema_version").is_some());
        assert!(parsed.get("workspace_name").is_some());
        assert!(parsed.get("workspace_path").is_some());
        assert!(parsed.get("specs").is_some());
        assert!(parsed.get("summary").is_some());

        // Verify summary fields
        let summary = &parsed["summary"];
        assert!(summary.get("total_specs").is_some());
        assert!(summary.get("successful_specs").is_some());
        assert!(summary.get("failed_specs").is_some());
        assert!(summary.get("pending_specs").is_some());
        assert!(summary.get("not_started_specs").is_some());
        assert!(summary.get("stale_specs").is_some());

        // Verify values
        assert_eq!(summary["total_specs"], 2);
        assert_eq!(summary["failed_specs"], 1);
    }

    #[test]
    fn test_workspace_status_json_canonical_format() {
        // Test that workspace status JSON output is in canonical JCS format (no extra whitespace)
        use crate::types::{WorkspaceStatusJsonOutput, WorkspaceStatusSummary};

        let output = WorkspaceStatusJsonOutput {
            schema_version: "workspace-status-json.v1".to_string(),
            workspace_name: "test-workspace".to_string(),
            workspace_path: "/path/to/workspace.yaml".to_string(),
            specs: vec![],
            summary: WorkspaceStatusSummary {
                total_specs: 0,
                successful_specs: 0,
                failed_specs: 0,
                pending_specs: 0,
                not_started_specs: 0,
                stale_specs: 0,
            },
        };

        let json_result = emit_workspace_status_json(&output);
        assert!(json_result.is_ok());

        let json_str = json_result.unwrap();

        // Verify canonical JSON properties (no extra whitespace, no newlines)
        assert!(
            !json_str.contains("  "),
            "Canonical JSON should not have indentation"
        );
        assert!(
            !json_str.contains('\n'),
            "Canonical JSON should not have newlines"
        );
    }

    #[test]
    fn test_workspace_status_json_spec_statuses() {
        // Test that spec statuses are correctly represented
        use crate::types::{
            WorkspaceSpecStatus, WorkspaceStatusJsonOutput, WorkspaceStatusSummary,
        };

        let output = WorkspaceStatusJsonOutput {
            schema_version: "workspace-status-json.v1".to_string(),
            workspace_name: "test-workspace".to_string(),
            workspace_path: "/path/to/workspace.yaml".to_string(),
            specs: vec![
                WorkspaceSpecStatus {
                    spec_id: "spec-success".to_string(),
                    tags: vec!["tag1".to_string(), "tag2".to_string()],
                    status: "success".to_string(),
                    latest_phase: Some("final".to_string()),
                    last_activity: Some(chrono::Utc::now()),
                    pending_fixups: 0,
                    has_errors: false,
                },
                WorkspaceSpecStatus {
                    spec_id: "spec-failed".to_string(),
                    tags: vec![],
                    status: "failed".to_string(),
                    latest_phase: Some("design".to_string()),
                    last_activity: None,
                    pending_fixups: 3,
                    has_errors: true,
                },
                WorkspaceSpecStatus {
                    spec_id: "spec-not-started".to_string(),
                    tags: vec![],
                    status: "not_started".to_string(),
                    latest_phase: None,
                    last_activity: None,
                    pending_fixups: 0,
                    has_errors: false,
                },
            ],
            summary: WorkspaceStatusSummary {
                total_specs: 3,
                successful_specs: 1,
                failed_specs: 1,
                pending_specs: 0,
                not_started_specs: 1,
                stale_specs: 0,
            },
        };

        let json_result = emit_workspace_status_json(&output);
        assert!(json_result.is_ok());

        let json_str = json_result.unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&json_str).unwrap();

        // Verify specs array
        let specs = parsed["specs"].as_array().unwrap();
        assert_eq!(specs.len(), 3);

        // Verify spec IDs
        let spec_ids: Vec<&str> = specs
            .iter()
            .map(|s| s["spec_id"].as_str().unwrap())
            .collect();
        assert!(spec_ids.contains(&"spec-success"));
        assert!(spec_ids.contains(&"spec-failed"));
        assert!(spec_ids.contains(&"spec-not-started"));

        // Verify statuses
        let statuses: Vec<&str> = specs
            .iter()
            .map(|s| s["status"].as_str().unwrap())
            .collect();
        assert!(statuses.contains(&"success"));
        assert!(statuses.contains(&"failed"));
        assert!(statuses.contains(&"not_started"));
    }

    #[test]
    fn test_workspace_status_cli_parsing() {
        // Test that CLI arguments are properly parsed for project status command
        use clap::Parser;

        // Test basic project status command
        let args = vec!["xchecker", "project", "status"];
        let cli = Cli::try_parse_from(args);
        assert!(cli.is_ok());

        if let Ok(cli) = cli {
            match cli.command {
                Commands::Project(ProjectCommands::Status { workspace, json }) => {
                    assert!(workspace.is_none());
                    assert!(!json);
                }
                _ => panic!("Expected Project Status command"),
            }
        }

        // Test project status with --json flag
        let args_json = vec!["xchecker", "project", "status", "--json"];
        let cli_json = Cli::try_parse_from(args_json);
        assert!(cli_json.is_ok());

        if let Ok(cli) = cli_json {
            match cli.command {
                Commands::Project(ProjectCommands::Status { workspace, json }) => {
                    assert!(workspace.is_none());
                    assert!(json);
                }
                _ => panic!("Expected Project Status command"),
            }
        }

        // Test project status with --workspace flag
        let args_workspace = vec![
            "xchecker",
            "project",
            "status",
            "--workspace",
            "/path/to/workspace.yaml",
        ];
        let cli_workspace = Cli::try_parse_from(args_workspace);
        assert!(cli_workspace.is_ok());

        if let Ok(cli) = cli_workspace {
            match cli.command {
                Commands::Project(ProjectCommands::Status { workspace, json }) => {
                    assert!(workspace.is_some());
                    assert_eq!(
                        workspace.unwrap().to_str().unwrap(),
                        "/path/to/workspace.yaml"
                    );
                    assert!(!json);
                }
                _ => panic!("Expected Project Status command"),
            }
        }
    }

    // ===== Project History Tests (Task 30) =====
    // **Validates: Requirements 4.3.5**

    #[test]
    fn test_workspace_history_cli_parsing() {
        // Test that CLI arguments are properly parsed for project history command
        use clap::Parser;

        // Test basic project history command
        let args = vec!["xchecker", "project", "history", "my-spec"];
        let cli = Cli::try_parse_from(args);
        assert!(cli.is_ok());

        if let Ok(cli) = cli {
            match cli.command {
                Commands::Project(ProjectCommands::History { spec_id, json }) => {
                    assert_eq!(spec_id, "my-spec");
                    assert!(!json);
                }
                _ => panic!("Expected Project History command"),
            }
        }

        // Test project history with --json flag
        let args_json = vec!["xchecker", "project", "history", "my-spec", "--json"];
        let cli_json = Cli::try_parse_from(args_json);
        assert!(cli_json.is_ok());

        if let Ok(cli) = cli_json {
            match cli.command {
                Commands::Project(ProjectCommands::History { spec_id, json }) => {
                    assert_eq!(spec_id, "my-spec");
                    assert!(json);
                }
                _ => panic!("Expected Project History command"),
            }
        }
    }

    #[test]
    fn test_history_json_output_schema_version() {
        // Test that history JSON output includes schema_version field
        use crate::types::{HistoryEntry, HistoryMetrics, WorkspaceHistoryJsonOutput};

        let output = WorkspaceHistoryJsonOutput {
            schema_version: "workspace-history-json.v1".to_string(),
            spec_id: "test-spec".to_string(),
            timeline: vec![HistoryEntry {
                phase: "requirements".to_string(),
                timestamp: chrono::Utc::now(),
                exit_code: 0,
                success: true,
                tokens_input: Some(1000),
                tokens_output: Some(500),
                fixup_count: None,
                model: Some("haiku".to_string()),
                provider: Some("claude-cli".to_string()),
            }],
            metrics: HistoryMetrics {
                total_executions: 1,
                successful_executions: 1,
                failed_executions: 0,
                total_tokens_input: 1000,
                total_tokens_output: 500,
                total_fixups: 0,
                first_execution: Some(chrono::Utc::now()),
                last_execution: Some(chrono::Utc::now()),
            },
        };

        // Emit as JSON
        let json_result = emit_workspace_history_json(&output);
        assert!(json_result.is_ok(), "Failed to emit history JSON");

        let json_str = json_result.unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&json_str).unwrap();

        // Verify schema_version is present and correct
        assert_eq!(parsed["schema_version"], "workspace-history-json.v1");
        assert_eq!(parsed["spec_id"], "test-spec");
    }

    #[test]
    fn test_history_json_output_has_required_fields() {
        // Test that history JSON output has all required fields per Requirements 4.3.5
        use crate::types::{HistoryEntry, HistoryMetrics, WorkspaceHistoryJsonOutput};

        let output = WorkspaceHistoryJsonOutput {
            schema_version: "workspace-history-json.v1".to_string(),
            spec_id: "test-spec".to_string(),
            timeline: vec![
                HistoryEntry {
                    phase: "requirements".to_string(),
                    timestamp: chrono::Utc::now(),
                    exit_code: 0,
                    success: true,
                    tokens_input: Some(1000),
                    tokens_output: Some(500),
                    fixup_count: None,
                    model: Some("haiku".to_string()),
                    provider: None,
                },
                HistoryEntry {
                    phase: "design".to_string(),
                    timestamp: chrono::Utc::now(),
                    exit_code: 1,
                    success: false,
                    tokens_input: Some(2000),
                    tokens_output: Some(100),
                    fixup_count: None,
                    model: Some("haiku".to_string()),
                    provider: None,
                },
            ],
            metrics: HistoryMetrics {
                total_executions: 2,
                successful_executions: 1,
                failed_executions: 1,
                total_tokens_input: 3000,
                total_tokens_output: 600,
                total_fixups: 0,
                first_execution: Some(chrono::Utc::now()),
                last_execution: Some(chrono::Utc::now()),
            },
        };

        let json_result = emit_workspace_history_json(&output);
        assert!(json_result.is_ok());

        let json_str = json_result.unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&json_str).unwrap();

        // Verify all required fields are present
        assert!(parsed.get("schema_version").is_some());
        assert!(parsed.get("spec_id").is_some());
        assert!(parsed.get("timeline").is_some());
        assert!(parsed.get("metrics").is_some());

        // Verify metrics structure
        let metrics = &parsed["metrics"];
        assert!(metrics.get("total_executions").is_some());
        assert!(metrics.get("successful_executions").is_some());
        assert!(metrics.get("failed_executions").is_some());
        assert!(metrics.get("total_tokens_input").is_some());
        assert!(metrics.get("total_tokens_output").is_some());
        assert!(metrics.get("total_fixups").is_some());

        // Verify values
        assert_eq!(metrics["total_executions"], 2);
        assert_eq!(metrics["successful_executions"], 1);
        assert_eq!(metrics["failed_executions"], 1);
        assert_eq!(metrics["total_tokens_input"], 3000);
        assert_eq!(metrics["total_tokens_output"], 600);
    }

    #[test]
    fn test_history_json_canonical_format() {
        // Test that history JSON output is in canonical JCS format (no extra whitespace)
        use crate::types::{HistoryMetrics, WorkspaceHistoryJsonOutput};

        let output = WorkspaceHistoryJsonOutput {
            schema_version: "workspace-history-json.v1".to_string(),
            spec_id: "test-spec".to_string(),
            timeline: vec![],
            metrics: HistoryMetrics {
                total_executions: 0,
                successful_executions: 0,
                failed_executions: 0,
                total_tokens_input: 0,
                total_tokens_output: 0,
                total_fixups: 0,
                first_execution: None,
                last_execution: None,
            },
        };

        let json_result = emit_workspace_history_json(&output);
        assert!(json_result.is_ok());

        let json_str = json_result.unwrap();

        // Verify canonical JSON properties (no extra whitespace, no newlines)
        assert!(
            !json_str.contains("  "),
            "Canonical JSON should not have indentation"
        );
        assert!(
            !json_str.contains('\n'),
            "Canonical JSON should not have newlines"
        );
    }

    #[test]
    fn test_history_command_no_spec() {
        let _temp_dir = setup_test_environment();

        // Test history for non-existent spec
        let result = execute_project_history_command("nonexistent-spec-history", false);
        assert!(result.is_ok());
    }

    #[test]
    fn test_history_command_json_no_spec() {
        let _temp_dir = setup_test_environment();

        // Test history --json for non-existent spec
        let result = execute_project_history_command("nonexistent-spec-history-json", true);
        assert!(result.is_ok());
    }

    #[test]
    fn test_history_timeline_entry_structure() {
        // Test that timeline entries have correct structure
        use crate::types::HistoryEntry;

        let entry = HistoryEntry {
            phase: "requirements".to_string(),
            timestamp: chrono::Utc::now(),
            exit_code: 0,
            success: true,
            tokens_input: Some(1000),
            tokens_output: Some(500),
            fixup_count: Some(3),
            model: Some("haiku".to_string()),
            provider: Some("openrouter".to_string()),
        };

        // Serialize and verify
        let json_value = serde_json::to_value(&entry).unwrap();

        assert_eq!(json_value["phase"], "requirements");
        assert_eq!(json_value["exit_code"], 0);
        assert_eq!(json_value["success"], true);
        assert_eq!(json_value["tokens_input"], 1000);
        assert_eq!(json_value["tokens_output"], 500);
        assert_eq!(json_value["fixup_count"], 3);
        assert_eq!(json_value["model"], "haiku");
        assert_eq!(json_value["provider"], "openrouter");
    }

    #[test]
    fn test_history_metrics_aggregation() {
        // Test that metrics are correctly aggregated
        use crate::types::HistoryMetrics;

        let metrics = HistoryMetrics {
            total_executions: 5,
            successful_executions: 3,
            failed_executions: 2,
            total_tokens_input: 10000,
            total_tokens_output: 5000,
            total_fixups: 7,
            first_execution: Some(chrono::Utc::now()),
            last_execution: Some(chrono::Utc::now()),
        };

        // Serialize and verify
        let json_value = serde_json::to_value(&metrics).unwrap();

        assert_eq!(json_value["total_executions"], 5);
        assert_eq!(json_value["successful_executions"], 3);
        assert_eq!(json_value["failed_executions"], 2);
        assert_eq!(json_value["total_tokens_input"], 10000);
        assert_eq!(json_value["total_tokens_output"], 5000);
        assert_eq!(json_value["total_fixups"], 7);
    }
}

/// Derive spec status from the latest receipt
///
/// Returns a human-readable status string based on the latest receipt:
/// - "success" if the latest receipt has exit_code 0
/// - "failed" if the latest receipt has non-zero exit_code
/// - "not_started" if no receipts exist
/// - "unknown" if receipts cannot be read
fn derive_spec_status(spec_id: &str) -> String {
    use crate::receipt::ReceiptManager;

    let base_path = crate::paths::spec_root(spec_id);
    let receipt_manager = ReceiptManager::new(&base_path);

    // Try to list all receipts for this spec
    match receipt_manager.list_receipts() {
        Ok(receipts) => {
            if receipts.is_empty() {
                "not_started".to_string()
            } else {
                // Get the latest receipt (list_receipts returns sorted by emitted_at)
                let latest = receipts.last().unwrap();
                if latest.exit_code == 0 {
                    // Include the phase name for more context
                    format!("{}: success", latest.phase)
                } else {
                    format!("{}: failed", latest.phase)
                }
            }
        }
        Err(_) => {
            // Check if the spec directory exists at all
            if base_path.exists() {
                "unknown".to_string()
            } else {
                "not_started".to_string()
            }
        }
    }
}

/// Execute project/workspace management commands
fn execute_project_command(cmd: ProjectCommands) -> Result<()> {
    use crate::workspace::{self, Workspace};

    match cmd {
        ProjectCommands::Init { name } => {
            let cwd = std::env::current_dir().context("Failed to get current directory")?;

            let workspace_path = workspace::init_workspace(&cwd, &name)?;

            println!("✓ Initialized workspace: {}", name);
            println!("  Created: {}", workspace_path.display());
            println!("\nNext steps:");
            println!("  - Add specs with: xchecker project add-spec <spec-id>");
            println!("  - List specs with: xchecker project list");

            Ok(())
        }
        ProjectCommands::AddSpec {
            spec_id,
            tag,
            force,
        } => {
            // Sanitize spec ID
            let sanitized_id = sanitize_spec_id(&spec_id).map_err(|e| {
                XCheckerError::Config(ConfigError::InvalidValue {
                    key: "spec_id".to_string(),
                    value: format!("{e}"),
                })
            })?;

            // Discover workspace
            let workspace_path = workspace::discover_workspace_from_cwd()?.ok_or_else(|| {
                anyhow::anyhow!("No workspace found. Run 'xchecker project init <name>' first.")
            })?;

            // Load workspace
            let mut ws = Workspace::load(&workspace_path)?;

            // Add spec
            ws.add_spec(&sanitized_id, tag.clone(), force)?;

            // Save workspace
            ws.save(&workspace_path)?;

            println!("✓ Added spec '{}' to workspace", sanitized_id);
            if !tag.is_empty() {
                println!("  Tags: {}", tag.join(", "));
            }

            Ok(())
        }
        ProjectCommands::List { workspace } => {
            // Resolve workspace path
            let workspace_path =
                workspace::resolve_workspace(workspace.as_deref())?.ok_or_else(|| {
                    anyhow::anyhow!("No workspace found. Run 'xchecker project init <name>' first.")
                })?;

            // Load workspace
            let ws = Workspace::load(&workspace_path)?;

            println!("Workspace: {}", ws.name);
            println!("Location: {}", workspace_path.display());
            println!();

            if ws.specs.is_empty() {
                println!("No specs registered.");
                println!("\nAdd specs with: xchecker project add-spec <spec-id>");
            } else {
                println!("Specs ({}):", ws.specs.len());
                for spec in ws.list_specs() {
                    // Derive status from latest receipt
                    let status = derive_spec_status(&spec.id);

                    let tags_str = if spec.tags.is_empty() {
                        String::new()
                    } else {
                        format!(" [{}]", spec.tags.join(", "))
                    };

                    // Format: spec-id (status) [tags]
                    println!("  - {} ({}){}", spec.id, status, tags_str);
                }
            }

            Ok(())
        }
        ProjectCommands::Status { workspace, json } => {
            execute_project_status_command(workspace.as_deref(), json)
        }
        ProjectCommands::History { spec_id, json } => {
            // Sanitize spec ID
            let sanitized_id = sanitize_spec_id(&spec_id).map_err(|e| {
                XCheckerError::Config(ConfigError::InvalidValue {
                    key: "spec_id".to_string(),
                    value: format!("{e}"),
                })
            })?;
            execute_project_history_command(&sanitized_id, json)
        }
        ProjectCommands::Tui { workspace } => execute_project_tui_command(workspace.as_deref()),
    }
}

/// Execute the project status command
/// Per FR-WORKSPACE (Requirements 4.3.4): Emits aggregated status for all specs
fn execute_project_status_command(
    workspace_override: Option<&std::path::Path>,
    json: bool,
) -> Result<()> {
    use crate::receipt::ReceiptManager;
    use crate::types::{WorkspaceSpecStatus, WorkspaceStatusJsonOutput, WorkspaceStatusSummary};
    use crate::workspace::{self, Workspace};

    // Resolve workspace path
    let workspace_path = workspace::resolve_workspace(workspace_override)?.ok_or_else(|| {
        anyhow::anyhow!("No workspace found. Run 'xchecker project init <name>' first.")
    })?;

    // Load workspace
    let ws = Workspace::load(&workspace_path)?;

    // Collect status for each spec
    let mut spec_statuses = Vec::new();
    let mut summary = WorkspaceStatusSummary {
        total_specs: ws.specs.len() as u32,
        successful_specs: 0,
        failed_specs: 0,
        pending_specs: 0,
        not_started_specs: 0,
        stale_specs: 0,
    };

    // Define stale threshold (7 days)
    let stale_threshold = chrono::Duration::days(7);
    let now = chrono::Utc::now();

    for spec in ws.list_specs() {
        let base_path = crate::paths::spec_root(&spec.id);
        let receipt_manager = ReceiptManager::new(&base_path);

        // Get receipts for this spec
        let receipts = receipt_manager.list_receipts().unwrap_or_default();

        // Determine spec status
        let (status, latest_phase, last_activity, has_errors) = if receipts.is_empty() {
            summary.not_started_specs += 1;
            ("not_started".to_string(), None, None, false)
        } else {
            let latest = receipts.last().unwrap();
            let last_activity_time = latest.emitted_at;
            let is_stale = now.signed_duration_since(last_activity_time) > stale_threshold;

            if is_stale {
                summary.stale_specs += 1;
            }

            if latest.exit_code == 0 {
                // Check if all phases are complete
                let all_phases_complete = receipts
                    .iter()
                    .any(|r| r.phase == "final" && r.exit_code == 0);
                if all_phases_complete {
                    summary.successful_specs += 1;
                    (
                        if is_stale { "stale" } else { "success" }.to_string(),
                        Some(latest.phase.clone()),
                        Some(last_activity_time),
                        false,
                    )
                } else {
                    summary.pending_specs += 1;
                    (
                        if is_stale { "stale" } else { "pending" }.to_string(),
                        Some(latest.phase.clone()),
                        Some(last_activity_time),
                        false,
                    )
                }
            } else {
                summary.failed_specs += 1;
                (
                    "failed".to_string(),
                    Some(latest.phase.clone()),
                    Some(last_activity_time),
                    true,
                )
            }
        };

        // Count pending fixups for this spec
        let pending_fixups = count_pending_fixups_for_spec(&spec.id);

        spec_statuses.push(WorkspaceSpecStatus {
            spec_id: spec.id.clone(),
            tags: spec.tags.clone(),
            status,
            latest_phase,
            last_activity,
            pending_fixups,
            has_errors,
        });
    }

    if json {
        // Emit JSON output
        let output = WorkspaceStatusJsonOutput {
            schema_version: "workspace-status-json.v1".to_string(),
            workspace_name: ws.name.clone(),
            workspace_path: workspace_path.display().to_string(),
            specs: spec_statuses,
            summary,
        };

        let json_output = emit_workspace_status_json(&output)?;
        println!("{json_output}");
    } else {
        // Human-readable output
        println!("Workspace: {}", ws.name);
        println!("Location: {}", workspace_path.display());
        println!();

        // Summary
        println!("Summary:");
        println!("  Total specs: {}", summary.total_specs);
        println!("  Successful: {}", summary.successful_specs);
        println!("  Failed: {}", summary.failed_specs);
        println!("  Pending: {}", summary.pending_specs);
        println!("  Not started: {}", summary.not_started_specs);
        if summary.stale_specs > 0 {
            println!("  Stale (>7 days): {}", summary.stale_specs);
        }
        println!();

        if spec_statuses.is_empty() {
            println!("No specs registered.");
            println!("\nAdd specs with: xchecker project add-spec <spec-id>");
        } else {
            println!("Specs:");
            for spec in &spec_statuses {
                let tags_str = if spec.tags.is_empty() {
                    String::new()
                } else {
                    format!(" [{}]", spec.tags.join(", "))
                };

                let phase_str = spec.latest_phase.as_deref().unwrap_or("-");
                let fixups_str = if spec.pending_fixups > 0 {
                    format!(" ({} fixups)", spec.pending_fixups)
                } else {
                    String::new()
                };

                // Format: spec-id (status, phase) [tags] (fixups)
                println!(
                    "  - {} ({}, {}){}{}",
                    spec.spec_id, spec.status, phase_str, tags_str, fixups_str
                );
            }
        }
    }

    Ok(())
}

/// Count pending fixups for a spec
fn count_pending_fixups_for_spec(spec_id: &str) -> u32 {
    crate::fixup::pending_fixups_for_spec(spec_id).targets
}

/// Emit workspace status output as canonical JSON using JCS (RFC 8785)
fn emit_workspace_status_json(output: &crate::types::WorkspaceStatusJsonOutput) -> Result<String> {
    // Use emit_jcs from crate root for JCS canonicalization
    emit_jcs(output).context("Failed to emit workspace status JSON")
}

/// Execute the project history command
/// Per FR-WORKSPACE (Requirements 4.3.5): Emits timeline of phase progression
fn execute_project_history_command(spec_id: &str, json: bool) -> Result<()> {
    use crate::receipt::ReceiptManager;
    use crate::types::{HistoryEntry, HistoryMetrics, WorkspaceHistoryJsonOutput};

    // Get spec base path
    let base_path = crate::paths::spec_root(spec_id);

    // Check if spec exists
    if !base_path.exists() {
        if json {
            // Return empty history for non-existent spec
            let output = WorkspaceHistoryJsonOutput {
                schema_version: "workspace-history-json.v1".to_string(),
                spec_id: spec_id.to_string(),
                timeline: vec![],
                metrics: HistoryMetrics {
                    total_executions: 0,
                    successful_executions: 0,
                    failed_executions: 0,
                    total_tokens_input: 0,
                    total_tokens_output: 0,
                    total_fixups: 0,
                    first_execution: None,
                    last_execution: None,
                },
            };
            let json_output = emit_workspace_history_json(&output)?;
            println!("{json_output}");
        } else {
            println!("History for spec: {spec_id}");
            println!("  Status: Spec not found");
            println!("  Directory: {} (does not exist)", base_path);
        }
        return Ok(());
    }

    // Load receipts
    let receipt_manager = ReceiptManager::new(&base_path);
    let receipts = receipt_manager.list_receipts().unwrap_or_default();

    // Build timeline from receipts
    let mut timeline: Vec<HistoryEntry> = Vec::new();
    let mut metrics = HistoryMetrics {
        total_executions: 0,
        successful_executions: 0,
        failed_executions: 0,
        total_tokens_input: 0,
        total_tokens_output: 0,
        total_fixups: 0,
        first_execution: None,
        last_execution: None,
    };

    for receipt in &receipts {
        let success = receipt.exit_code == 0;

        // Extract LLM metadata if available
        let (tokens_input, tokens_output, provider, model) = if let Some(ref llm) = receipt.llm {
            (
                llm.tokens_input,
                llm.tokens_output,
                llm.provider.clone(),
                llm.model_used.clone(),
            )
        } else {
            (None, None, None, Some(receipt.model_full_name.clone()))
        };

        // Count fixups for fixup phase
        let fixup_count = if receipt.phase == "fixup" && success {
            Some(receipt.outputs.len() as u32)
        } else {
            None
        };

        let entry = HistoryEntry {
            phase: receipt.phase.clone(),
            timestamp: receipt.emitted_at,
            exit_code: receipt.exit_code,
            success,
            tokens_input,
            tokens_output,
            fixup_count,
            model,
            provider,
        };

        // Update metrics
        metrics.total_executions += 1;
        if success {
            metrics.successful_executions += 1;
        } else {
            metrics.failed_executions += 1;
        }
        if let Some(ti) = tokens_input {
            metrics.total_tokens_input += ti;
        }
        if let Some(to) = tokens_output {
            metrics.total_tokens_output += to;
        }
        if let Some(fc) = fixup_count {
            metrics.total_fixups += fc;
        }

        // Track first and last execution
        if metrics.first_execution.is_none()
            || receipt.emitted_at < metrics.first_execution.unwrap()
        {
            metrics.first_execution = Some(receipt.emitted_at);
        }
        if metrics.last_execution.is_none() || receipt.emitted_at > metrics.last_execution.unwrap()
        {
            metrics.last_execution = Some(receipt.emitted_at);
        }

        timeline.push(entry);
    }

    // Sort timeline by timestamp (oldest first)
    timeline.sort_by_key(|e| e.timestamp);

    if json {
        let output = WorkspaceHistoryJsonOutput {
            schema_version: "workspace-history-json.v1".to_string(),
            spec_id: spec_id.to_string(),
            timeline,
            metrics,
        };
        let json_output = emit_workspace_history_json(&output)?;
        println!("{json_output}");
    } else {
        // Human-readable output
        println!("History for spec: {spec_id}");
        println!("Location: {}", base_path);
        println!();

        // Summary metrics
        println!("Summary:");
        println!("  Total executions: {}", metrics.total_executions);
        println!("  Successful: {}", metrics.successful_executions);
        println!("  Failed: {}", metrics.failed_executions);
        if metrics.total_tokens_input > 0 || metrics.total_tokens_output > 0 {
            println!(
                "  Total tokens: {} input, {} output",
                metrics.total_tokens_input, metrics.total_tokens_output
            );
        }
        if metrics.total_fixups > 0 {
            println!("  Total fixups applied: {}", metrics.total_fixups);
        }
        if let Some(first) = metrics.first_execution {
            println!(
                "  First execution: {}",
                first.format("%Y-%m-%d %H:%M:%S UTC")
            );
        }
        if let Some(last) = metrics.last_execution {
            println!("  Last execution: {}", last.format("%Y-%m-%d %H:%M:%S UTC"));
        }
        println!();

        if timeline.is_empty() {
            println!("No executions recorded.");
        } else {
            println!("Timeline ({} entries):", timeline.len());
            for entry in &timeline {
                let status_icon = if entry.success { "" } else { "" };
                let tokens_str = match (entry.tokens_input, entry.tokens_output) {
                    (Some(ti), Some(to)) => format!(" [{} in, {} out]", ti, to),
                    (Some(ti), None) => format!(" [{} in]", ti),
                    (None, Some(to)) => format!(" [{} out]", to),
                    (None, None) => String::new(),
                };
                let fixup_str = entry
                    .fixup_count
                    .map(|c| format!(" ({} fixups)", c))
                    .unwrap_or_default();

                println!(
                    "  {} {} {} (exit {}){}{}",
                    entry.timestamp.format("%Y-%m-%d %H:%M:%S"),
                    status_icon,
                    entry.phase,
                    entry.exit_code,
                    tokens_str,
                    fixup_str
                );
            }
        }
    }

    Ok(())
}

/// Emit workspace history output as canonical JSON using JCS (RFC 8785)
fn emit_workspace_history_json(
    output: &crate::types::WorkspaceHistoryJsonOutput,
) -> Result<String> {
    // Use emit_jcs from crate root for JCS canonicalization
    emit_jcs(output).context("Failed to emit workspace history JSON")
}

/// Execute the project TUI command
/// Per FR-WORKSPACE-TUI (Requirements 4.4.1, 4.4.2, 4.4.3): Interactive terminal UI
fn execute_project_tui_command(workspace_override: Option<&std::path::Path>) -> Result<()> {
    use crate::workspace;

    // Resolve workspace path
    let workspace_path = workspace::resolve_workspace(workspace_override)?.ok_or_else(|| {
        anyhow::anyhow!("No workspace found. Run 'xchecker project init <name>' first.")
    })?;

    // Run the TUI
    crate::tui::run_tui(&workspace_path)
}

/// Execute template management commands
/// Per FR-TEMPLATES (Requirements 4.7.1, 4.7.2, 4.7.3)
fn execute_template_command(cmd: TemplateCommands) -> Result<()> {
    match cmd {
        TemplateCommands::List => {
            println!("Available templates:\n");

            for t in xchecker_engine::templates::list_templates() {
                println!("  {}", t.id);
                println!("    Name: {}", t.name);
                println!("    Description: {}", t.description);
                println!("    Use case: {}", t.use_case);
                if !t.prerequisites.is_empty() {
                    println!("    Prerequisites: {}", t.prerequisites.join(", "));
                }
                println!();
            }

            println!("To initialize a spec from a template:");
            println!("  xchecker template init <template> <spec-id>");

            Ok(())
        }
        TemplateCommands::Init { template, spec_id } => {
            // Sanitize spec ID
            let sanitized_id = sanitize_spec_id(&spec_id).map_err(|e| {
                XCheckerError::Config(ConfigError::InvalidValue {
                    key: "spec_id".to_string(),
                    value: format!("{e}"),
                })
            })?;

            // Validate template
            if !xchecker_engine::templates::is_valid_template(&template) {
                let valid_templates = xchecker_engine::templates::BUILT_IN_TEMPLATES.join(", ");
                return Err(XCheckerError::Config(ConfigError::InvalidValue {
                    key: "template".to_string(),
                    value: format!(
                        "Unknown template '{}'. Valid templates: {}",
                        template, valid_templates
                    ),
                })
                .into());
            }

            // Initialize from template
            xchecker_engine::templates::init_from_template(&template, &sanitized_id)?;

            // Get template info for display
            let template_info = xchecker_engine::templates::get_template(&template).unwrap();

            println!(
                "✓ Initialized spec '{}' from template '{}'",
                sanitized_id, template
            );
            println!();
            println!("Template: {}", template_info.name);
            println!("Description: {}", template_info.description);
            println!();
            println!("Created files:");
            println!(
                "  - .xchecker/specs/{}/context/problem-statement.md",
                sanitized_id
            );
            println!("  - .xchecker/specs/{}/README.md", sanitized_id);
            println!();
            println!("Next steps:");
            println!("  1. Review the problem statement:");
            println!(
                "     cat .xchecker/specs/{}/context/problem-statement.md",
                sanitized_id
            );
            println!("  2. Customize the problem statement for your needs");
            println!("  3. Run the requirements phase:");
            println!("     xchecker resume {} --phase requirements", sanitized_id);

            Ok(())
        }
    }
}