heddle-cli 0.3.1

An AI-native version control system
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
// SPDX-License-Identifier: Apache-2.0
//! `heddle schemas <verb>` — runtime introspection for CLI JSON output shapes.
//!
//! This module owns the JSON schema mirrors for `--output json`-emitting
//! verbs. Schema registration metadata comes from the active command
//! catalog; the schemas themselves are schemars-derived mirror structs
//! rather than threading
//! `JsonSchema` through every output struct in the workspace
//! (`repo`, `objects`, etc.). The cost: when a real output struct
//! changes, the mirror here must change too. The benefit:
//! `heddle doctor schemas` validates the documented samples against
//! these schemas, catching the mirror drift the same way it catches
//! doc drift.
//!
//! See [`super::doctor_schemas`] for the drift checker.

use std::{collections::BTreeMap, sync::OnceLock};

use anyhow::{Result, anyhow};
use schemars::{JsonSchema, schema_for};
use serde::Serialize;
use serde_json::Value;

use super::{RecoveryAdvice, command_catalog};
use crate::cli::{Cli, should_output_json};

static SCHEMA_VERBS: OnceLock<Vec<&'static str>> = OnceLock::new();
static DOCUMENTED_SCHEMA_VERBS: OnceLock<Vec<&'static str>> = OnceLock::new();
static OPAQUE_SCHEMA_VERBS: OnceLock<Vec<&'static str>> = OnceLock::new();

macro_rules! schema_registry {
    ($(($verbs:expr, $schema:ty)),+ $(,)?) => {
        fn schema_for_registered_verb(verb: &str) -> Option<Value> {
            $(
                if $verbs.contains(&verb) {
                    let root = schema_for!($schema);
                    return serde_json::to_value(&root).ok();
                }
            )+
            None
        }

        #[cfg(test)]
        fn schema_implementation_verbs() -> Vec<&'static str> {
            let mut verbs = Vec::new();
            $(
                for verb in $verbs {
                    if !verbs.contains(verb) {
                        verbs.push(*verb);
                    }
                }
            )+
            verbs
        }
    };
}

schema_registry! {
    (&["init"], InitSchema),
    (&["status"], StatusSchema),
    (&["verify"], VerifySchema),
    (&["adopt"], AdoptSchema),
    (&["capture"], CaptureSchema),
    (&["commit"], CommitSchema),
    (&["checkpoint"], CheckpointSchema),
    (&["undo", "undo --redo"], UndoSchema),
    (&["undo --list"], UndoListSchema),
    (&["clean"], CleanSchema),
    (&["diff"], DiffSchema),
    (&["switch"], SwitchCheckoutSchema),
    (&["merge --preview"], MergePreviewSchema),
    (&["ready"], ReadySchema),
    (&["land"], LandSchema),
    (&["sync"], SyncSchema),
    (&["continue", "abort"], OperatorCommandSchema),
    (&["start"], ThreadStartSchema),
    (&["thread create", "thread switch", "thread rename"], ThreadStartSchema),
    (&["thread current"], ThreadCurrentSchema),
    (&["thread captures"], ThreadCapturesSchema),
    (&["thread refresh", "thread drop"], ThreadCommandSchema),
    (&["thread promote"], ThreadCommandSchema),
    (&["thread move"], ThreadMoveSchema),
    (&["thread absorb"], ThreadAbsorbSchema),
    (&["thread resolve"], ThreadResolveSchema),
    (&["thread approve"], ThreadApprovalSchema),
    (&["thread approvals"], ThreadApprovalListSchema),
    (&["thread revoke-approval"], ThreadRevokeApprovalSchema),
    (&["thread check-merge"], ThreadMergeEligibilitySchema),
    (&["thread cleanup"], ThreadCleanupSchema),
    (&["thread marker list"], ThreadMarkerListSchema),
    (&["thread marker create", "thread marker delete", "thread marker show"], ThreadMarkerOpSchema),
    (&["thread show"], ThreadShowSchema),
    (&["clone"], CloneSchema),
    (&["remote list"], RemoteListSchema),
    (&["remote show"], RemoteInfoSchema),
    (&["remote add", "remote remove", "remote set-default"], RemoteMutationSchema),
    (&["fetch"], FetchSchema),
    (&["pull"], PullSchema),
    (&["push"], PushSchema),
    (&["bridge git status"], BridgeGitStatusSchema),
    (&["expand"], ExpandSchema),
    (&["log"], LogSchema),
    (&["log --reflog"], LogReflogSchema),
    (&["log --timeline"], TimelineLogSchema),
    (&["timeline fork", "timeline reset", "timeline recover"], TimelineActionSchema),
    (&["show"], ShowSchema),
    (&["thread list"], ThreadListSchema),
    (&["schemas"], SchemasListSchema),
    (&["review show"], ReviewShowSchema),
    (&["review sign"], ReviewSignSchema),
    (&["review next"], ReviewNextSchema),
    (&["review health"], ReviewHealthSchema),
    (&["retro"], RetroSchema),
    (&["discuss open", "discuss append", "discuss resolve", "discuss show"], DiscussionEnvelopeSchema),
    (&["discuss list"], DiscussionListSchema),
    (&["query"], QuerySchema),
    (&["query --attribution"], BlameSchema),
    (&["transaction commit"], TransactionCommitSchema),
    (&["bridge git init"], BridgeInitSchema),
    (&["bridge git export"], BridgeExportSchema),
    (&["bridge git import"], BridgeImportSchema),
    (&["bridge git sync"], BridgeSyncSchema),
    (&["bridge git reconcile"], BridgeGitReconcileSchema),
    (&["bridge git push"], BridgePushSchema),
    (&["bridge git pull"], BridgePullSchema),
    (&["stash push", "stash pop", "stash apply", "stash drop", "stash clear"], StashMutationSchema),
    (&["stash list"], StashListSchema),
    (&["stash show"], StashShowSchema),
    (&["revert"], RevertSchema),
    (&["doctor"], DiagnoseSchema),
    (&["doctor docs"], DoctorDocsSchema),
    (&["doctor schemas"], DoctorSchemasSchema),
    (&["actor spawn", "actor show"], ActorSingleSchema),
    (&["actor list"], ActorListSchema),
    (&["actor done"], ActorDoneSchema),
    (&["actor explain"], ActorExplainSchema),
    (&["agent serve"], AgentServeSchema),
    (&["agent status"], AgentDaemonStatusSchema),
    (&["agent stop"], AgentStopSchema),
    (&["agent reserve", "agent heartbeat", "agent release"], AgentReservationEnvelopeSchema),
    (&["agent capture"], CaptureSchema),
    (&["agent ready"], ReadySchema),
    (&["agent list"], AgentReservationListSchema),
    (&["session start", "session end", "session show"], SessionEnvelopeSchema),
    (&["session segment"], SessionSegmentEnvelopeSchema),
    (&["session list"], SessionListSchema),
    (&["git-overlay"], GitOverlayGuideSchema),
    (&["watch"], WatchLineSchema),
    (&["integration list", "integration doctor"], IntegrationStatusListSchema),
    (&["try"], TrySchema),
    (&["fsck"], FsckSchema),
    (&["resolve"], ResolveSchema),
    (&["maintenance index"], IndexSchema),
    (&["error"], ErrorEnvelopeSchema),
}

/// All verbs whose `--output json` output has a schema mirror, derived from
/// the active command catalog.
pub fn schema_verbs() -> &'static [&'static str] {
    SCHEMA_VERBS
        .get_or_init(command_catalog::schema_verbs)
        .as_slice()
}

/// Schema verbs that `heddle doctor schemas` must check against
/// `docs/json-schemas.md`, derived from the active command catalog.
pub fn documented_schema_verbs() -> &'static [&'static str] {
    DOCUMENTED_SCHEMA_VERBS
        .get_or_init(command_catalog::documented_schema_verbs)
        .as_slice()
}

/// Runtime schema verbs that intentionally expose only an opaque JSON
/// object shape. Coverage reports count these separately from
/// concrete schema mirrors.
pub(crate) fn opaque_schema_verbs() -> &'static [&'static str] {
    OPAQUE_SCHEMA_VERBS
        .get_or_init(command_catalog::opaque_schema_verbs)
        .as_slice()
}

/// Generate the schema for `verb`. Returns `None` if no schema is registered.
pub fn schema_for_verb(verb: &str) -> Option<Value> {
    let verb = resolve_schema_verb(verb)?;
    if !schema_verbs().contains(&verb) {
        return None;
    }
    let mut schema = schema_for_registered_verb(verb).or_else(|| {
        opaque_schema_verbs()
            .contains(&verb)
            .then(|| serde_json::to_value(schema_for!(GenericJsonObjectSchema)).ok())
            .flatten()
    })?;
    add_op_id_replay_fields_if_supported(verb, &mut schema);
    add_json_discriminator_if_advertised(verb, &mut schema);
    Some(schema)
}

fn resolve_schema_verb(verb: &str) -> Option<&'static str> {
    let verb = verb.trim();
    if let Some(registered) = schema_verbs()
        .iter()
        .copied()
        .find(|registered| *registered == verb)
    {
        return Some(registered);
    }

    let matches = matching_schema_verbs(verb, schema_verbs());
    if matches.len() == 1 {
        matches.first().copied()
    } else {
        None
    }
}

#[cfg(test)]
const OP_ID_REPLAY_FIELD_NAMES: &[&str] = &[
    "op_id",
    "operation_record",
    "idempotency_status",
    "replayed",
];

fn add_op_id_replay_fields_if_supported(verb: &str, schema: &mut Value) {
    if !schema_verb_supports_op_id(verb) {
        return;
    }

    let Some(object) = schema.as_object_mut() else {
        return;
    };
    let properties = object
        .entry("properties".to_string())
        .or_insert_with(|| serde_json::json!({}));
    let Some(properties) = properties.as_object_mut() else {
        return;
    };

    properties
        .entry("op_id".to_string())
        .or_insert_with(|| serde_json::json!({ "type": ["string", "null"] }));
    properties
        .entry("idempotency_status".to_string())
        .or_insert_with(|| serde_json::json!({ "type": ["string", "null"] }));
    properties
        .entry("replayed".to_string())
        .or_insert_with(|| serde_json::json!({ "type": ["boolean", "null"] }));
    properties
        .entry("operation_record".to_string())
        .or_insert_with(|| {
            serde_json::json!({
                "anyOf": [
                    {
                        "type": "object",
                        "properties": {
                            "op_id": { "type": "string" },
                            "command": { "type": "string" },
                            "idempotency_status": { "type": "string" },
                            "replayed": { "type": "boolean" }
                        },
                        "required": [
                            "command",
                            "idempotency_status",
                            "op_id",
                            "replayed"
                        ]
                    },
                    { "type": "null" }
                ]
            })
        });
}

fn add_json_discriminator_if_advertised(verb: &str, schema: &mut Value) {
    let mut discriminators = command_catalog::command_json_discriminators_for_schema_verb(verb);
    if schema.get("anyOf").is_some() {
        for discriminator in command_catalog::command_json_discriminators()
            .into_iter()
            .filter(|discriminator| {
                discriminator.display == verb && discriminator.schema_verb.as_deref() != Some(verb)
            })
        {
            discriminators.push(discriminator);
        }
    }
    discriminators.sort_by(|left, right| {
        (&left.field, &left.value, &left.display).cmp(&(&right.field, &right.value, &right.display))
    });
    discriminators.dedup_by(|left, right| left.field == right.field && left.value == right.value);

    if discriminators.is_empty() {
        return;
    };

    if add_json_discriminators_to_union_branches(verb, schema, &discriminators) {
        return;
    }

    let field = discriminators[0].field.as_str();
    let values = discriminators
        .iter()
        .filter(|discriminator| discriminator.field == field)
        .map(|discriminator| discriminator.value.as_str())
        .collect::<Vec<_>>();
    add_json_discriminator_to_schema_object(schema, field, &values);
}

fn add_json_discriminators_to_union_branches(
    verb: &str,
    schema: &mut Value,
    discriminators: &[command_catalog::CommandJsonDiscriminator],
) -> bool {
    let Some(branches) = schema
        .get_mut("anyOf")
        .and_then(|value| value.as_array_mut())
    else {
        return false;
    };

    let mut injected = 0usize;
    for branch in branches {
        let Some(branch_ref) = branch
            .get("$ref")
            .and_then(|value| value.as_str())
            .map(str::to_string)
        else {
            continue;
        };
        let Some(discriminator) = discriminator_for_union_branch(verb, &branch_ref, discriminators)
        else {
            continue;
        };
        let original_branch = branch.clone();
        let mut discriminator_schema = serde_json::json!({ "type": "object" });
        add_json_discriminator_to_schema_object(
            &mut discriminator_schema,
            &discriminator.field,
            &[&discriminator.value],
        );
        *branch = serde_json::json!({
            "allOf": [original_branch, discriminator_schema],
        });
        injected += 1;
    }

    injected > 0
}

fn discriminator_for_union_branch<'a>(
    verb: &str,
    branch_ref: &str,
    discriminators: &'a [command_catalog::CommandJsonDiscriminator],
) -> Option<&'a command_catalog::CommandJsonDiscriminator> {
    if discriminators.len() == 1 {
        return discriminators.first();
    }

    let def_name = schema_ref_name(branch_ref)?;
    if verb == "inspect" {
        let value = match def_name {
            "ShowSchema" => "inspect_state",
            "ThreadShowSchema" => "thread_show",
            _ => return None,
        };
        return discriminators
            .iter()
            .find(|discriminator| discriminator.value == value);
    }

    None
}

fn schema_ref_name(reference: &str) -> Option<&str> {
    reference
        .strip_prefix("#/$defs/")
        .or_else(|| reference.strip_prefix("#/definitions/"))
}

fn add_json_discriminator_to_schema_object(schema: &mut Value, field: &str, values: &[&str]) {
    let enum_values = values
        .iter()
        .map(|value| Value::String((*value).to_string()))
        .collect::<Vec<_>>();

    let Some(object) = schema.as_object_mut() else {
        return;
    };
    let properties = object
        .entry("properties".to_string())
        .or_insert_with(|| serde_json::json!({}));
    let Some(properties) = properties.as_object_mut() else {
        return;
    };
    properties.insert(
        field.to_string(),
        serde_json::json!({
            "type": "string",
            "enum": enum_values,
        }),
    );

    let required = object
        .entry("required".to_string())
        .or_insert_with(|| serde_json::json!([]));
    let Some(required) = required.as_array_mut() else {
        return;
    };
    if !required
        .iter()
        .any(|required_field| required_field.as_str() == Some(field))
    {
        required.push(Value::String(field.to_string()));
    }
}

fn schema_verb_supports_op_id(verb: &str) -> bool {
    command_catalog::command_runtime_contract_for_schema_verb(verb)
        .is_some_and(|contract| contract.supports_op_id)
}

/// Public entrypoint for `heddle schemas [<verb>]`.
///
/// `verb_parts` are the raw trailing tokens after `schemas`.
/// Lookup is a flat string match after filtering global flags that
/// clap cannot see because the schema command intentionally accepts
/// literal command flags like `--preview` and `--reflog`.
pub fn cmd_schemas(cli: &Cli, verb_parts: &[String]) -> Result<()> {
    let verb_parts = normalize_schema_verb_parts(verb_parts)?;
    if verb_parts.is_empty() {
        let out = serde_json::json!({
            "output_kind": "schemas",
            "status": "completed",
            "schema_verbs": schema_verbs(),
            "documented_schema_verbs": documented_schema_verbs(),
        });
        return render_schema_json(&out);
    }

    let verb = verb_parts.join(" ");
    let schema = schema_for_verb(&verb)
        .ok_or_else(|| anyhow!(schema_not_registered_advice(&verb, schema_verbs())))?;

    // `heddle schemas` always emits machine-readable JSON.
    let _json = should_output_json(cli, None);
    render_schema_json(&schema)
}

fn render_schema_json(value: &serde_json::Value) -> Result<()> {
    println!("{}", serde_json::to_string_pretty(value)?);
    Ok(())
}

fn schema_not_registered_advice(verb: &str, known_verbs: &[&str]) -> RecoveryAdvice {
    let matches = suggested_schema_verbs(verb, known_verbs);
    let primary_command = matches
        .first()
        .map(|matched| format!("heddle schemas {matched}"))
        .unwrap_or_else(|| "heddle schemas".to_string());
    let hint = if matches.is_empty() {
        "Run `heddle schemas` to list schema-backed verbs, or inspect the command catalog with `heddle help --output json`.".to_string()
    } else {
        format!(
            "`{verb}` is not exact; available schema verb{}: {}.",
            if matches.len() == 1 { "" } else { "s" },
            matches
                .iter()
                .map(|matched| format!("`{matched}`"))
                .collect::<Vec<_>>()
                .join(", ")
        )
    };
    let mut recovery_commands = Vec::new();
    push_unique_command(&mut recovery_commands, primary_command.clone());
    push_unique_command(&mut recovery_commands, "heddle schemas".to_string());
    push_unique_command(
        &mut recovery_commands,
        "heddle help --output json".to_string(),
    );
    for matched in matches.iter().skip(1) {
        push_unique_command(&mut recovery_commands, format!("heddle schemas {matched}"));
    }

    RecoveryAdvice::safety_refusal(
        "schema_not_registered",
        format!("No JSON schema is registered for `{verb}`"),
        hint,
        format!("`{verb}` is not in the runtime schema registry"),
        "schema lookup does not change repository state; retrying the same unknown verb will fail until a schema is registered",
        "no repository objects, refs, metadata, or worktree files were changed",
        primary_command,
        recovery_commands,
    )
}

fn suggested_schema_verbs<'a>(verb: &str, known_verbs: &'a [&'a str]) -> Vec<&'a str> {
    let exactish = matching_schema_verbs(verb, known_verbs);
    if !exactish.is_empty() {
        return exactish;
    }

    let normalized = verb.trim();
    if normalized.is_empty() {
        return Vec::new();
    }
    let bare = command_catalog::schema_verb_without_flags(normalized);
    if bare.is_empty() {
        return Vec::new();
    }

    known_verbs
        .iter()
        .copied()
        .filter(|known| {
            known.starts_with(normalized)
                || command_catalog::schema_verb_without_flags(known).starts_with(&bare)
        })
        .take(5)
        .collect()
}

fn push_unique_command(commands: &mut Vec<String>, command: String) {
    if !commands.iter().any(|existing| existing == &command) {
        commands.push(command);
    }
}

fn matching_schema_verbs<'a>(verb: &str, known_verbs: &'a [&'a str]) -> Vec<&'a str> {
    let normalized = verb.trim();
    if normalized.is_empty() {
        return Vec::new();
    }
    let bare = command_catalog::schema_verb_without_flags(normalized);
    let prefix = format!("{bare} ");
    known_verbs
        .iter()
        .copied()
        .filter(|known| {
            *known != normalized
                && (*known == bare
                    || known.starts_with(&prefix)
                    || command_catalog::schema_verb_without_flags(known) == bare)
        })
        .collect()
}

fn normalize_schema_verb_parts(parts: &[String]) -> Result<Vec<String>> {
    let mut normalized = Vec::new();
    let mut iter = parts.iter();
    while let Some(part) = iter.next() {
        match part.as_str() {
            "--no-color" | "-q" | "--quiet" | "-v" | "--verbose" => {}
            "--output" | "--repo" => {
                iter.next()
                    .ok_or_else(|| anyhow!("missing value for `{part}`"))?;
            }
            _ if part.starts_with("--output=") || part.starts_with("--repo=") => {}
            _ => normalized.push(part.clone()),
        }
    }
    Ok(normalized)
}

// ---------------------------------------------------------------------------
// Mirror types
// ---------------------------------------------------------------------------
//
// Each mirror struct mirrors the JSON wire shape of a single
// `--output json`-emitting verb. The struct's `serde` attributes match the
// real serializer; the `schemars` derive produces a JSON Schema we
// emit verbatim.
//
// When you add or rename a field on a real output struct, update the
// matching mirror here and the entry in `docs/json-schemas.md`. CI
// runs `heddle doctor schemas` which validates the doc samples
// against these schemas.

// ---- shared sub-types ------------------------------------------------------
//
// Variants here are referenced only through the schemars derive,
// which the dead-code lint can't see. The annotation keeps the
// surface honest without polluting downstream warnings.
#[allow(dead_code)]
#[derive(Debug, Serialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum ThreadModeSchema {
    Materialized,
    Virtualized,
    Solid,
}

#[allow(dead_code)]
#[derive(Debug, Serialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum ThreadStateSchema {
    Draft,
    Active,
    Ready,
    Blocked,
    Merged,
    Abandoned,
    Promoted,
}

#[allow(dead_code)]
#[derive(Debug, Serialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum ThreadFreshnessSchema {
    Current,
    Stale,
    Unknown,
}

#[allow(dead_code)]
#[derive(Debug, Serialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum ThreadImpactCategorySchema {
    DependencyGraph,
    BuildRuntimeConfig,
    GeneratedOutputs,
    RepoWideRefactor,
    PublicApiSurface,
}

#[allow(dead_code)]
#[derive(Debug, Serialize, JsonSchema)]
#[serde(rename_all = "kebab-case")]
pub enum CoordinationStatusSchema {
    Clean,
    Ahead,
    Diverged,
    Blocked,
    MergeReady,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct ActorInfoSchema {
    pub provider: Option<String>,
    pub model: Option<String>,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct StateInfoSchema {
    pub change_id: String,
    pub content_hash: String,
    pub intent: Option<String>,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct GitCheckpointInfoSchema {
    pub git_commit: String,
    pub committed_at: String,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct ChangesInfoSchema {
    pub modified: Vec<String>,
    pub added: Vec<String>,
    pub deleted: Vec<String>,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct GitIndexInfoSchema {
    pub commit_mode: String,
    pub has_staged_changes: bool,
    pub staged_paths: Vec<String>,
    pub unstaged_paths: Vec<String>,
    pub untracked_paths: Vec<String>,
    pub will_commit: Vec<String>,
    pub preserved_after_commit: Vec<String>,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct GenericJsonObjectSchema {
    #[serde(flatten)]
    pub fields: BTreeMap<String, Value>,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct IntegrationStatusListSchema(pub Vec<IntegrationStatusSchema>);

#[derive(Debug, Serialize, JsonSchema)]
pub struct IntegrationStatusSchema {
    pub harness: String,
    pub scope: String,
    pub method: String,
    pub status: String,
    pub healthy: bool,
    pub paths: Vec<String>,
    pub capabilities: Vec<String>,
    pub capability_paths: Vec<String>,
    pub path_mode: String,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct IndexSchema {
    pub output_kind: String,
    pub present: bool,
    pub path: String,
    pub file_entries: usize,
    pub directory_entries: usize,
    pub untracked_directory_entries: usize,
    pub snapshot_bytes: u64,
    pub journal_bytes: u64,
    pub journal_ops: usize,
    pub journal_replay_ms: u128,
    pub dump: Option<String>,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct BlameSchema {
    pub output_kind: Option<String>,
    pub status: Option<String>,
    pub file: String,
    pub context: Vec<BlameContextSnippetSchema>,
    pub lines: Vec<BlameLineSchema>,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct BlameLineSchema {
    pub line_number: usize,
    pub content: String,
    pub change_id: String,
    pub principal: BlamePrincipalSchema,
    pub agent: Option<BlameAgentSchema>,
    pub timestamp: String,
    pub origins: Option<Vec<BlameOriginSchema>>,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct BlameOriginSchema {
    pub change_id: String,
    pub principal: BlamePrincipalSchema,
    pub agent: Option<BlameAgentSchema>,
    pub timestamp: String,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct BlamePrincipalSchema {
    pub name: String,
    pub email: String,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct BlameAgentSchema {
    pub provider: String,
    pub model: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub session_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub policy_id: Option<String>,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct BlameContextSnippetSchema {
    pub annotation_id: String,
    pub kind: String,
    pub content: String,
    pub revision_count: usize,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct FsckSchema {
    pub valid: bool,
    pub errors: Vec<FsckErrorSchema>,
    pub warnings: Vec<String>,
    pub objects_checked: usize,
    pub bridge_checked: bool,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct FsckErrorSchema {
    pub kind: String,
    pub message: String,
    pub object: Option<String>,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct ResolveSchema {
    pub output_kind: String,
    pub message: Option<String>,
    pub resolved: Option<Vec<String>>,
    pub remaining: Option<Vec<String>>,
    pub conflicts: Option<Vec<String>>,
    pub continued: Option<bool>,
    pub continuation_status: Option<String>,
    pub continuation_message: Option<String>,
    pub next_action: Option<String>,
    pub recommended_action: Option<String>,
}

#[allow(dead_code, clippy::large_enum_variant)]
#[derive(Debug, Serialize, JsonSchema)]
#[serde(untagged)]
pub enum InspectSchema {
    #[allow(dead_code)]
    State(ShowSchema),
    #[allow(dead_code)]
    Thread(ThreadShowSchema),
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct RetroSchema {
    pub since: Option<String>,
    pub until: Option<String>,
    pub duration_secs: Option<i64>,
    pub states_captured: Vec<RetroStateEntrySchema>,
    pub agents_active: Vec<RetroAgentEntrySchema>,
    pub markers_created: Vec<RetroMarkerEntrySchema>,
    pub context_annotations: Vec<RetroContextAnnotationEntrySchema>,
    pub verify_signals: Vec<RetroVerifySignalSchema>,
    pub merges: Vec<RetroOperationEntrySchema>,
    pub undos: Vec<RetroOperationEntrySchema>,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct RetroStateEntrySchema {
    pub change_id: String,
    pub intent: Option<String>,
    pub confidence: Option<f32>,
    pub agent: Option<String>,
    pub principal: String,
    pub timestamp: String,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct RetroAgentEntrySchema {
    pub session_id: String,
    pub provider: Option<String>,
    pub model: Option<String>,
    pub status: String,
    pub started_at: String,
    pub completed_at: Option<String>,
    pub tokens: RetroAgentTokensSchema,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct RetroAgentTokensSchema {
    pub input: Option<u64>,
    pub output: Option<u64>,
    pub reasoning: Option<u64>,
    pub tool_calls: Option<u32>,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct RetroMarkerEntrySchema {
    pub name: String,
    pub state: String,
    pub timestamp: String,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct RetroContextAnnotationEntrySchema {
    pub path: String,
    pub scope: String,
    pub kind: String,
    pub content_excerpt: String,
    pub attribution: String,
    pub created_at: String,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct RetroVerifySignalSchema {
    pub kind: String,
    pub label: String,
    pub timestamp: String,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct RetroOperationEntrySchema {
    pub description: String,
    pub timestamp: String,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct DiscussionSchema {
    pub id: String,
    pub file: String,
    pub symbol: String,
    pub opened_against_state: String,
    pub opened_at_secs: i64,
    pub visibility: String,
    pub body_changed_since_open: bool,
    pub orphaned: bool,
    pub resolution: DiscussionResolutionSchema,
    pub turns: Vec<DiscussionTurnSchema>,
    pub resolved_annotation_id: Option<String>,
}

/// Per-discussion verbs (`open`/`append`/`resolve`/`show`) emit the
/// discussion payload flattened beneath an `output_kind` discriminator,
/// mirroring `DiscussionEnvelope` in `discuss.rs`. `discuss list` reuses
/// the bare [`DiscussionSchema`] for its inner items — those carry no
/// per-item discriminator (the list envelope owns it), so the
/// discriminator lives on this wrapper rather than on the shared inner
/// struct.
#[derive(Debug, Serialize, JsonSchema)]
pub struct DiscussionEnvelopeSchema {
    pub output_kind: String,
    #[serde(flatten)]
    pub discussion: DiscussionSchema,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct DiscussionResolutionSchema {
    pub kind: String,
    pub annotation_id: Option<String>,
    pub state_id: Option<String>,
    pub reason: Option<String>,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct DiscussionTurnSchema {
    pub author_name: String,
    pub author_email: String,
    pub body: String,
    pub posted_at_secs: i64,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct DiscussionListSchema {
    pub output_kind: String,
    pub discussions: Vec<DiscussionSchema>,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct QuerySchema {
    pub output_kind: String,
    pub hits: Vec<QueryHitSchema>,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct QueryHitSchema {
    pub seq: u64,
    pub timestamp_secs: i64,
    pub verb: String,
    pub actor_email: String,
    pub operation_id: Option<String>,
    pub thread: Option<String>,
    pub symbols: Vec<String>,
    pub signal_kinds: Vec<String>,
    pub change_id: Option<String>,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct OperationRecordSchema {
    pub op_id: String,
    pub command: String,
    pub idempotency_status: String,
    pub replayed: bool,
}

// ---- core loop write/read helpers -----------------------------------------

#[derive(Debug, Serialize, JsonSchema)]
pub struct InitSchema {
    pub output_kind: String,
    pub status: String,
    pub action: String,
    pub path: String,
    pub repository_mode: String,
    pub git_detected: bool,
    pub heddle_initialized: bool,
    pub installed_heddleignore: bool,
    pub principal_configured: bool,
    pub principal_status: String,
    pub principal_source: Option<String>,
    pub principal: Option<InitPrincipalSchema>,
    pub principal_recommended_action: Option<String>,
    pub side_effects: Vec<String>,
    pub message: String,
    pub next_action: Option<String>,
    pub recommended_action: Option<String>,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct InitPrincipalSchema {
    pub name: String,
    pub email: String,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct CaptureSchema {
    pub output_kind: Option<String>,
    pub status: String,
    pub action: String,
    pub change_id: String,
    pub content_hash: String,
    pub intent: Option<String>,
    pub confidence: Option<f32>,
    pub principal: CommitPrincipalSchema,
    pub agent: Option<CommitAgentSchema>,
    pub promotion_suggested: bool,
    pub heavy_impact_paths: Vec<String>,
    pub signed: bool,
    pub message: String,
    pub next_action: Option<String>,
    pub next_action_template: Option<ActionTemplateSchema>,
    pub recommended_action: Option<String>,
    pub recommended_action_template: Option<ActionTemplateSchema>,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct CommitSchema {
    pub output_kind: Option<String>,
    pub status: String,
    pub action: String,
    pub change_id: String,
    pub git_commit: Option<String>,
    pub git_previous_commit: Option<String>,
    pub summary: String,
    pub confidence: Option<f32>,
    pub git_index: Option<GitIndexInfoSchema>,
    pub included_pending_capture: Option<String>,
    pub principal: CommitPrincipalSchema,
    pub agent: Option<CommitAgentSchema>,
    pub next_action: Option<String>,
    pub next_action_template: Option<ActionTemplateSchema>,
    pub recommended_action: Option<String>,
    pub recommended_action_template: Option<ActionTemplateSchema>,
    pub op_id: Option<String>,
    pub operation_record: Option<OperationRecordSchema>,
    pub idempotency_status: Option<String>,
    pub replayed: Option<bool>,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct CommitPrincipalSchema {
    pub name: String,
    pub email: String,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct CommitAgentSchema {
    pub provider: String,
    pub model: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub session_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub segment_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub policy_id: Option<String>,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct CheckpointSchema {
    pub output_kind: Option<String>,
    pub status: String,
    pub action: String,
    pub change_id: String,
    pub git_commit: String,
    pub summary: String,
    pub capability: String,
    pub storage_model: String,
    pub committed_at: String,
    pub next_action: Option<String>,
    pub next_action_template: Option<ActionTemplateSchema>,
    pub recommended_action: Option<String>,
    pub recommended_action_template: Option<ActionTemplateSchema>,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct OperatorCommandSchema {
    pub output_kind: Option<String>,
    pub status: String,
    pub action: String,
    pub message: String,
    pub blockers: Vec<String>,
    pub warnings: Vec<String>,
    pub next_action: Option<String>,
    pub next_action_template: Option<ActionTemplateSchema>,
    pub recommended_action: Option<String>,
    pub recommended_action_template: Option<ActionTemplateSchema>,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct UndoSchema {
    pub output_kind: Option<String>,
    pub status: Option<String>,
    pub action: String,
    pub message: String,
    pub batches: Vec<Value>,
    pub next_action: Option<String>,
    pub next_action_template: Option<ActionTemplateSchema>,
    pub recommended_action: Option<String>,
    pub recommended_action_template: Option<ActionTemplateSchema>,
    /// heddle#305: the pre-undo state preserved for recovery, and the marker
    /// pointing at it. Present only on a completed `undo`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub recovery_state: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub recovery_marker: Option<String>,
}

/// `heddle undo --list --output json` history view. Distinct from
/// [`UndoSchema`] (the rewind/redo payload): the list view carries only the
/// discriminator and the oplog batches, with none of the action/status/
/// recovery fields a real undo emits. Mirrors `OpListOutput` in `undo.rs`.
#[derive(Debug, Serialize, JsonSchema)]
pub struct UndoListSchema {
    pub output_kind: Option<String>,
    pub batches: Vec<Value>,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct CleanSchema {
    pub output_kind: String,
    pub removed: Vec<String>,
    pub dry_run: bool,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct DiffSchema {
    pub output_kind: Option<String>,
    pub status: Option<String>,
    pub from_state: Option<String>,
    pub to_state: Option<String>,
    pub changed_path_count: usize,
    pub stats: DiffStatsSchema,
    /// Worktree-mode diff (`heddle diff` with no revision args) groups the
    /// per-file changes into `{modified, added, deleted}` category arrays,
    /// mirroring the `status` command's `changes` shape so a UI can derive
    /// add/modify/delete badges from `diff` alone. A state-to-state diff
    /// (`heddle diff <a> <b>`) instead emits a flat `array<object>` here.
    pub changes: DiffChangesSchema,
    pub semantic_changes: Option<Vec<Value>>,
    pub context: Option<Vec<Value>>,
    pub broader_guidance: Option<Vec<Value>>,
    /// Rendered unified-diff text, suitable for `patch(1)` / `git apply`.
    /// Present whenever line-level hunks exist, regardless of the
    /// `--patch` CLI flag — JSON consumers always get a parseable diff.
    pub patch: Option<String>,
}

/// `changes` admits the two documented shapes the `diff` command emits:
/// worktree mode (`heddle diff` with no revision args) groups entries into
/// `{modified, added, deleted}` category arrays; a state-to-state diff
/// (`heddle diff <a> <b>`) emits a flat `array<object>`. The schema is a
/// union of both so either documented output validates.
#[derive(Debug, Serialize, JsonSchema)]
#[serde(untagged)]
#[allow(dead_code)]
pub enum DiffChangesSchema {
    /// Worktree-mode: per-file diff entries bucketed by category, mirroring
    /// the `status` command's `{modified, added, deleted}` field names. Each
    /// entry carries its path plus the per-file diff fields (`kind`,
    /// `old_path`, `lines`, …). A `renamed` entry buckets under `modified`
    /// (its `kind`/`old_path` identify the rename).
    Grouped(DiffChangesGroupedSchema),
    /// State-to-state: a flat array of per-file diff entries.
    Flat(Vec<Value>),
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct DiffChangesGroupedSchema {
    pub modified: Vec<Value>,
    pub added: Vec<Value>,
    pub deleted: Vec<Value>,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct DiffStatsSchema {
    pub files_changed: usize,
    pub additions: usize,
    pub modifications: usize,
    pub deletions: usize,
    pub renames: usize,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct SwitchCheckoutSchema {
    pub output_kind: Option<String>,
    pub status: Option<String>,
    pub action: Option<String>,
    pub name: Option<String>,
    pub message: String,
    pub thread: Option<ThreadSummarySchema>,
    pub path: Option<String>,
    pub execution_path: Option<String>,
    pub target: Option<String>,
    pub intent: Option<String>,
    pub next_action: Option<String>,
    pub next_action_template: Option<ActionTemplateSchema>,
    pub recommended_action: Option<String>,
    pub recommended_action_template: Option<ActionTemplateSchema>,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct MergePreviewSchema {
    pub output_kind: Option<String>,
    pub status: Option<String>,
    pub action: Option<String>,
    pub message: Option<String>,
    pub would_merge: bool,
    pub applied: bool,
    pub blockers: Option<Vec<String>>,
    pub warnings: Option<Vec<String>>,
    pub next_action: Option<String>,
    pub next_action_template: Option<ActionTemplateSchema>,
    pub recommended_action: Option<String>,
    pub recommended_action_template: Option<ActionTemplateSchema>,
    pub fast_forward: Option<bool>,
    pub preview_only: Option<bool>,
    pub merge_state: Option<String>,
    pub conflicts: Option<Vec<String>>,
    pub preview_summary: Option<Vec<String>>,
    pub thread_state: Option<String>,
    pub freshness: Option<String>,
    pub changed_paths: Option<Vec<String>>,
    pub changed_path_count: Option<usize>,
    pub impact_categories: Option<Vec<String>>,
    pub promotion_suggested: Option<bool>,
    pub heavy_impact_paths: Option<Vec<String>>,
    pub merge_relation: Option<String>,
    pub conflict_count: Option<usize>,
    pub thread_health: Option<String>,
    pub diff: Option<Value>,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct ReadySchema {
    pub output_kind: Option<String>,
    pub status: String,
    pub action: String,
    pub message: String,
    pub blockers: Vec<String>,
    pub warnings: Vec<String>,
    pub next_action: Option<String>,
    pub next_action_template: Option<ActionTemplateSchema>,
    pub recommended_action: Option<String>,
    pub recommended_action_template: Option<ActionTemplateSchema>,
    pub captured: bool,
    pub captured_state: Option<String>,
    pub thread_state: Option<String>,
    pub readiness: ReadyReadinessSchema,
    pub report: Value,
    #[serde(rename = "verification")]
    pub verification: RepositoryVerificationStateSchema,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct ReadyReadinessSchema {
    pub status: String,
    pub captured: bool,
    pub captured_state: Option<String>,
    pub checks: ReadyChecksSchema,
    pub integration: String,
    pub freshness: String,
    pub merge_type: String,
    pub changed_path_count: usize,
    pub changed_paths: Vec<String>,
    pub conflict_count: usize,
    pub conflicts: Vec<String>,
    pub impact: String,
    pub impact_categories: Vec<String>,
    pub blockers: Vec<String>,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct ReadyChecksSchema {
    pub status: String,
    pub reason: String,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct SyncSchema {
    #[serde(flatten)]
    pub operator: OperatorCommandSchema,
    pub thread: Option<String>,
    pub current_state: Option<String>,
    pub chosen_path: Option<String>,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct LandSchema {
    pub output_kind: Option<String>,
    pub status: String,
    pub action: String,
    pub message: String,
    pub blockers: Option<Vec<String>>,
    pub warnings: Option<Vec<String>>,
    pub next_action: Option<String>,
    pub next_action_template: Option<ActionTemplateSchema>,
    pub recommended_action: Option<String>,
    pub recommended_action_template: Option<ActionTemplateSchema>,
    pub thread: String,
    pub captured: bool,
    pub checkpointed: bool,
    pub git_commit: Option<String>,
    pub synced: bool,
    pub integrated: bool,
    pub pushed: bool,
    pub pushed_remote: Option<String>,
    pub performed_steps: Vec<String>,
    pub skipped_steps: Vec<String>,
    pub merge_state: Option<String>,
    pub chosen_path: String,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct ThreadStartSchema {
    pub output_kind: Option<String>,
    pub status: Option<String>,
    pub action: Option<String>,
    pub name: String,
    pub message: String,
    pub next_action: Option<String>,
    pub next_action_template: Option<ActionTemplateSchema>,
    pub recommended_action: Option<String>,
    pub recommended_action_template: Option<ActionTemplateSchema>,
    pub thread: Option<ThreadSummarySchema>,
    pub path: Option<String>,
    pub execution_path: Option<String>,
    pub fskit_readiness: Option<FsKitReadinessSchema>,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct FsKitReadinessSchema {
    pub state: String,
    pub backend: String,
    pub action: String,
    pub settings_url: Option<String>,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct ThreadCurrentSchema {
    pub thread: String,
}

#[derive(Debug, Serialize, JsonSchema)]
#[serde(transparent)]
pub struct ThreadCapturesSchema(pub Vec<ThreadCaptureEntrySchema>);

#[derive(Debug, Serialize, JsonSchema)]
pub struct ThreadCaptureEntrySchema {
    pub change_id: String,
    pub created_at: String,
    pub intent: Option<String>,
    pub confidence: Option<f32>,
    pub agent: Option<String>,
    pub message: String,
    pub summary: Option<ThreadCaptureSummarySchema>,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct ThreadCaptureSummarySchema {
    pub added: usize,
    pub modified: usize,
    pub deleted: usize,
    pub total: usize,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct ThreadCommandSchema {
    pub output_kind: String,
    pub status: String,
    pub action: String,
    pub name: String,
    pub message: String,
    pub next_action: Option<String>,
    pub next_action_template: Option<ActionTemplateSchema>,
    pub recommended_action: Option<String>,
    pub recommended_action_template: Option<ActionTemplateSchema>,
    pub thread: Option<ThreadSummarySchema>,
    pub path: Option<String>,
    pub execution_path: Option<String>,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct ThreadMoveSchema {
    pub from_thread: String,
    pub to_thread: String,
    pub moved_paths: Vec<String>,
    pub source_change_id: Option<String>,
    pub target_change_id: String,
    pub message: String,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct ThreadAbsorbSchema {
    pub thread: String,
    pub into: String,
    pub preview_only: bool,
    pub conflicts: Vec<String>,
    pub merge_state: Option<String>,
    pub message: String,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct ThreadResolveSchema {
    #[serde(flatten)]
    pub operator: OperatorCommandSchema,
    pub thread: String,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct ThreadApprovalSchema {
    pub id: String,
    pub repo_path: String,
    pub source_thread: String,
    pub target_thread: String,
    pub source_state: String,
    pub approver_user_id: String,
    pub note: String,
    pub approved_at: u64,
    pub expires_at: u64,
}

#[derive(Debug, Serialize, JsonSchema)]
#[serde(transparent)]
pub struct ThreadApprovalListSchema(pub Vec<ThreadApprovalSchema>);

#[derive(Debug, Serialize, JsonSchema)]
pub struct ThreadRevokeApprovalSchema {
    pub output_kind: String,
    pub deleted: bool,
    pub id: String,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct ThreadMergeEligibilitySchema {
    pub allowed: bool,
    pub unmet: Vec<ThreadMergeRequirementSchema>,
    pub valid_approvals: Vec<ThreadApprovalSchema>,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct ThreadMergeRequirementSchema {
    pub policy_id: String,
    pub kind: String,
    pub group_id: String,
    pub reason: String,
    pub needed: u32,
    pub have: u32,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct ThreadCleanupSchema {
    #[serde(flatten)]
    pub operator: OperatorCommandSchema,
    pub dry_run: bool,
    pub merged: Vec<ThreadDroppedSchema>,
    pub auto: Vec<ThreadDroppedSchema>,
    pub reclaimed_bytes: u64,
    pub would_reclaim_bytes: u64,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub skipped: Vec<ThreadCleanupSkippedSchema>,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct ThreadDroppedSchema {
    pub thread: String,
    pub id: String,
    pub reason: String,
    pub age_seconds: i64,
    pub bytes: u64,
    pub execution_path: Option<String>,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct ThreadCleanupSkippedSchema {
    pub thread: String,
    pub id: String,
    pub reason: String,
    pub note: String,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct ThreadMarkerListSchema {
    pub output_kind: String,
    pub markers: Vec<ThreadMarkerEntrySchema>,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct ThreadMarkerEntrySchema {
    pub name: String,
    pub change_id: String,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct ThreadMarkerOpSchema {
    pub output_kind: String,
    pub name: Option<String>,
    pub change_id: Option<String>,
    pub deleted: Option<Vec<ThreadMarkerEntrySchema>>,
    pub count: Option<usize>,
    pub message: String,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct ThreadShowSchema {
    pub output_kind: Option<String>,
    pub repository_label: String,
    pub repository_context: Option<RepositoryContextInfoSchema>,
    #[serde(flatten)]
    pub summary: ThreadSummarySchema,
    pub next_action: Option<String>,
    pub next_action_template: Option<ActionTemplateSchema>,
    pub recommended_action: Option<String>,
    pub recommended_action_template: Option<ActionTemplateSchema>,
    #[serde(rename = "verification")]
    pub trust: RepositoryVerificationStateSchema,
    pub recovery_commands: Vec<String>,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct ThreadSummarySchema {
    pub name: String,
    pub operation: OpaqueObject,
    pub remote_tracking: OpaqueObject,
    pub base_state: Option<String>,
    pub base_root: Option<String>,
    pub current_state: Option<String>,
    pub path: Option<String>,
    pub execution_path: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub session_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub heddle_session_id: Option<String>,
    pub actor: Option<ActorInfoSchema>,
    pub harness: Option<String>,
    pub thinking_level: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub native_actor_key: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub native_parent_actor_key: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub probe_source: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub probe_confidence: Option<f32>,
    pub usage_summary: OpaqueObject,
    pub last_progress_at: Option<String>,
    pub last_activity_at: Option<String>,
    pub report_flush_state: Option<String>,
    pub attach_reason: Option<String>,
    pub thread_mode: Option<ThreadModeSchema>,
    pub thread_state: Option<ThreadStateSchema>,
    pub freshness: Option<ThreadFreshnessSchema>,
    pub visibility: String,
    pub target_thread: Option<String>,
    pub parent_thread: Option<String>,
    pub child_threads: Vec<String>,
    pub sibling_threads: Vec<String>,
    pub stack_depth: usize,
    pub stale_from_parent: bool,
    pub task: Option<String>,
    pub changed_paths: Vec<String>,
    pub promotion_suggested: bool,
    pub impact_categories: Vec<ThreadImpactCategorySchema>,
    pub heavy_impact_paths: Vec<String>,
    pub verification_summary: Value,
    pub confidence_summary: Value,
    pub integration_policy_result: Value,
    pub coordination_status: CoordinationStatusSchema,
    pub is_current: bool,
    pub is_isolated: bool,
    pub thread_health: String,
    pub blockers: Vec<String>,
    // Runtime `ThreadSummary.recommended_action` is a `String` serialized
    // through `serialize_empty_action_as_null`, so the wire value is
    // `string | null` (HeddleCo/heddle#645 presence contract).
    pub recommended_action: Option<String>,
    pub recommended_action_template: Option<ActionTemplateSchema>,
    pub git_branch_tip: Option<String>,
    pub history_imported: bool,
    pub auto: bool,
    pub shared_target_dir: Option<String>,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct CloneSchema {
    pub output_kind: Option<String>,
    pub action: Option<String>,
    pub status: Option<String>,
    pub success: Option<bool>,
    pub cloned: Option<bool>,
    pub transport: Option<String>,
    pub remote: Option<String>,
    pub local: Option<String>,
    pub branch: Option<String>,
    pub repository_capability: Option<String>,
    pub commits_imported: Option<u64>,
    pub states_created: Option<u64>,
    pub objects: Option<usize>,
    pub state: Option<String>,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct AdoptSchema {
    pub output_kind: Option<String>,
    pub status: Option<String>,
    pub action: Option<String>,
    pub adopted: bool,
    pub initialized: bool,
    pub path: String,
    pub refs: Vec<String>,
    pub commits_imported: usize,
    pub states_created: usize,
    pub branches_synced: usize,
    pub tags_synced: usize,
    pub skipped_non_commit_refs: usize,
    pub already_in_sync: bool,
    pub recommended_action: Option<String>,
    pub recommended_action_template: Option<ActionTemplateSchema>,
    #[serde(rename = "verification")]
    pub trust: RepositoryVerificationStateSchema,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct RemoteListSchema {
    pub output_kind: Option<String>,
    pub remotes: Vec<RemoteInfoSchema>,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct RemoteInfoSchema {
    pub output_kind: Option<String>,
    pub name: String,
    pub url: String,
    pub source: String,
    pub is_default: bool,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct RemoteMutationSchema {
    pub output_kind: Option<String>,
    pub status: String,
    pub action: String,
    pub name: String,
    pub url: Option<String>,
    pub default: Option<String>,
    pub message: String,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct ActorSingleSchema {
    pub output_kind: String,
    pub actor: ActorEntrySchema,
    #[serde(rename = "verification")]
    pub trust: RepositoryVerificationStateSchema,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct ActorListSchema {
    pub output_kind: String,
    pub actors: Vec<ActorEntrySchema>,
    pub active_only: bool,
    #[serde(rename = "verification")]
    pub trust: RepositoryVerificationStateSchema,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct ActorDoneSchema {
    pub output_kind: String,
    pub session_id: String,
    pub status: String,
    pub thread: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub coordination_status: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub recommended_action: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub recommended_action_template: Option<ActionTemplateSchema>,
    #[serde(rename = "verification")]
    pub trust: RepositoryVerificationStateSchema,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct ActorExplainSchema {
    pub output_kind: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub attached: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub active_actor: Option<Value>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub repository: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub detected: Option<Value>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub environment: Option<Value>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub recommended_action: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub recommended_action_template: Option<ActionTemplateSchema>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub session_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub thread: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub heddle_session_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub client_instance_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub native_actor_key: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub native_parent_actor_key: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub native_instance_key: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub probe_source: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub probe_confidence: Option<f32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub attach_reason: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub attach_precedence: Option<Vec<String>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub winning_rule: Option<String>,
    #[serde(rename = "verification")]
    pub trust: RepositoryVerificationStateSchema,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct ActorEntrySchema {
    pub session_id: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub client_instance_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub native_actor_key: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub native_parent_actor_key: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub native_instance_key: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub heddle_session_id: Option<String>,
    pub thread: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub thread_id: Option<String>,
    pub base_state: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub path: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub provider: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub model: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub harness: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub thinking_level: Option<String>,
    pub usage_summary: Value,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub last_progress_at: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub report_flush_state: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub attach_reason: Option<String>,
    pub attach_precedence: Vec<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub winning_attach_rule: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub probe_source: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub probe_confidence: Option<f32>,
    pub status: String,
    pub started_at: String,
    pub actor_chain: Vec<ActorChainEntrySchema>,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct ActorChainEntrySchema {
    pub session_id: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub native_actor_key: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub native_parent_actor_key: Option<String>,
    pub thread: String,
    pub status: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub provider: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub model: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub harness: Option<String>,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct AgentServeSchema {
    pub output_kind: String,
    pub status: String,
    pub socket_path: String,
    pub pid_path: String,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct AgentDaemonStatusSchema {
    pub output_kind: String,
    pub running: bool,
    pub pid: Option<u32>,
    pub socket_path: String,
    pub pid_path: String,
    #[serde(rename = "verification")]
    pub trust: RepositoryVerificationStateSchema,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct AgentStopSchema {
    pub output_kind: String,
    pub stopped: bool,
    pub swept_stale: bool,
    pub pid: Option<i32>,
    pub reason: Option<String>,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct AgentReservationEnvelopeSchema {
    pub reservation: AgentReservationSchema,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct AgentReservationListSchema {
    pub reservations: Vec<AgentReservationSchema>,
    pub alive_only: bool,
    pub thread: Option<String>,
    #[serde(rename = "verification")]
    pub trust: RepositoryVerificationStateSchema,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct AgentReservationSchema {
    pub session_id: String,
    pub reservation_token: Option<String>,
    pub thread: String,
    pub anchor_state: Option<String>,
    pub anchor_root: Option<String>,
    pub status: String,
    pub path: Option<String>,
    pub task: Option<String>,
    pub provider: Option<String>,
    pub model: Option<String>,
    pub harness: Option<String>,
    pub thinking_level: Option<String>,
    pub probe_source: Option<String>,
    pub probe_confidence: Option<f32>,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct SessionEnvelopeSchema {
    pub session: SessionEntrySchema,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct SessionSegmentEnvelopeSchema {
    pub segment: SessionSegmentSchema,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct SessionListSchema {
    pub sessions: Vec<SessionEntrySchema>,
    pub active_only: bool,
    #[serde(rename = "verification")]
    pub trust: RepositoryVerificationStateSchema,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct SessionEntrySchema {
    pub id: String,
    pub principal: String,
    pub created_at: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ended_at: Option<String>,
    pub active: bool,
    pub segments: Vec<SessionSegmentSchema>,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct SessionSegmentSchema {
    pub id: String,
    pub provider: String,
    pub model: String,
    pub started_at: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub policy_id: Option<String>,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct FetchSchema {
    pub output_kind: Option<String>,
    pub remote: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ref_scope: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tags_included: Option<bool>,
    pub refs_fetched: usize,
    pub objects_fetched: usize,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct PullSchema {
    pub output_kind: Option<String>,
    pub action: Option<String>,
    pub status: Option<String>,
    pub pulled: Option<bool>,
    pub changed: Option<bool>,
    pub success: Option<bool>,
    pub transport: Option<String>,
    pub remote: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub branch: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub old_git_head: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub new_git_head: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub old_state: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub new_state: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ref_scope: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub thread: Option<String>,
    pub state: Option<String>,
    pub objects: Option<usize>,
    pub states_created: Option<usize>,
    pub commits_seen: Option<usize>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub commits_seen_scope: Option<String>,
    pub materialized_checkout: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub changed_path_count: Option<usize>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub changed_paths: Option<Vec<String>>,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct PushSchema {
    pub output_kind: String,
    pub action: String,
    pub status: String,
    pub pushed: bool,
    pub changed: bool,
    pub success: bool,
    pub transport: String,
    pub remote: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub push_scope: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ref_scope: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub git_notes_ref: Option<String>,
    /// Full ref names this push wrote at the destination (sorted; empty
    /// for a no-op push). Present on the Git-overlay refs path; omitted
    /// on the native Heddle transport. Verify with `git ls-remote`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub refs_written: Option<Vec<String>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub git_notes_visibility_warning: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub git_tracking_remote: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub git_remote_configured: Option<GitRemoteConfiguredSchema>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub git_upstream_configured: Option<GitUpstreamConfiguredSchema>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tags_included: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub force: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub force_discard_warning: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub thread: Option<String>,
    pub state: Option<String>,
    pub objects: Option<usize>,
    // Required AND nullable (the `#[schemars(required)]` shorthand strips
    // the null variant from `Option<T>`, mis-declaring the wire contract —
    // HeddleCo/heddle#645 conformance): push always emits these fields,
    // serializing null for the no-action case.
    pub next_action: NullableStringSchema,
    pub next_action_template: NullableActionTemplateSchema,
    pub recommended_action: NullableStringSchema,
    pub recommended_action_template: NullableActionTemplateSchema,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct GitRemoteConfiguredSchema {
    pub name: String,
    pub url: String,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct GitUpstreamConfiguredSchema {
    pub branch: String,
    pub remote: String,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct ParallelThreadInfoSchema {
    pub name: String,
    pub coordination_status: CoordinationStatusSchema,
    pub current_state: Option<String>,
}

/// Operation banner — kept opaque because the underlying
/// [`repo::RepositoryOperationStatus`] is a workspace type and its
/// shape is internal. `Value` here means "any JSON object or null".
type OpaqueObject = Option<Value>;

#[derive(Debug, Serialize, JsonSchema)]
pub struct RepositoryContextInfoSchema {
    pub kind: String,
    pub parent_repository: Option<String>,
    pub target_thread: Option<String>,
    pub parent_thread: Option<String>,
}

// ---- status ---------------------------------------------------------------

#[derive(Debug, Serialize, JsonSchema)]
pub struct StatusSchema {
    pub output_kind: Option<String>,
    pub repository_capability: String,
    pub repository_label: String,
    pub repository_context: Option<RepositoryContextInfoSchema>,
    pub storage_model: String,
    pub hosted_enabled: bool,
    pub operation: OpaqueObject,
    pub remote_tracking: OpaqueObject,
    pub git_overlay_health: GitOverlayHealthSchema,
    #[serde(rename = "verification")]
    pub trust: RepositoryVerificationStateSchema,
    pub thread: Option<String>,
    pub base_state: Option<String>,
    pub base_root: Option<String>,
    pub current_state: Option<String>,
    pub path: Option<String>,
    pub execution_path: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub session_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub heddle_session_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub actor: Option<ActorInfoSchema>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub harness: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub thinking_level: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub usage_summary: OpaqueObject,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub last_progress_at: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub report_flush_state: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub attach_reason: Option<String>,
    pub thread_mode: Option<ThreadModeSchema>,
    pub thread_state: Option<ThreadStateSchema>,
    pub freshness: Option<ThreadFreshnessSchema>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub target_thread: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub parent_thread: Option<String>,
    pub child_threads: Vec<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub task: Option<String>,
    pub promotion_suggested: bool,
    pub impact_categories: Vec<ThreadImpactCategorySchema>,
    pub heavy_impact_paths: Vec<String>,
    pub changed_path_count: usize,
    pub worktree_changed_path_count: usize,
    pub thread_changed_path_count: usize,
    pub blockers: Vec<String>,
    pub recommended_action: NullableStringSchema,
    pub recommended_action_template: Option<ActionTemplateSchema>,
    pub recovery_commands: Vec<String>,
    pub recovery_action_templates: Vec<ActionTemplateSchema>,
    pub thread_health: String,
    pub coordination_status: CoordinationStatusSchema,
    pub is_isolated: bool,
    pub parallel_threads: Vec<ParallelThreadInfoSchema>,
    pub state: Option<StateInfoSchema>,
    pub git_checkpoint: Option<GitCheckpointInfoSchema>,
    pub changes: ChangesInfoSchema,
    pub git_index: Option<GitIndexInfoSchema>,
}

// ---- verify ---------------------------------------------------------------

#[derive(Debug, Serialize, JsonSchema)]
pub struct VerifySchema {
    pub output_kind: String,
    pub clean: bool,
    pub repository_label: String,
    pub repository_context: Option<RepositoryContextInfoSchema>,
    #[serde(flatten)]
    pub verification: RepositoryVerificationStateSchema,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct RepositoryVerificationStateSchema {
    #[serde(rename = "verified")]
    pub verified: bool,
    pub status: String,
    pub repository_mode: String,
    pub heddle_initialized: bool,
    pub git_branch: Option<String>,
    pub heddle_thread: Option<String>,
    pub worktree_dirty: bool,
    pub worktree_state: String,
    pub import_state: String,
    pub mapping_state: String,
    pub remote_drift: String,
    pub active_operation: Option<String>,
    pub default_remote: Option<String>,
    pub clone_verification: String,
    pub machine_contract: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub machine_contract_coverage: Option<MachineContractCoverageSchema>,
    pub workflow_status: String,
    pub workflow_summary: String,
    pub summary: String,
    pub recommended_action: Option<String>,
    pub recommended_action_template: Option<ActionTemplateSchema>,
    pub recovery_commands: Vec<String>,
    pub recovery_action_templates: Vec<ActionTemplateSchema>,
    pub checks: Vec<VerificationCheckSchema>,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct MachineContractCoverageSchema {
    pub status: String,
    #[serde(rename = "verified_scope")]
    pub verified_scope: String,
    pub advanced_scope: String,
    pub summary: String,
    pub catalog_commands_total: usize,
    pub catalog_mutating_commands_total: usize,
    pub json_commands_total: usize,
    pub json_mutating_commands_total: usize,
    pub json_commands_with_schema: usize,
    pub json_commands_with_accepted_opaque_schema: usize,
    pub json_commands_without_schema: usize,
    #[serde(rename = "verified_scope_json_commands_total")]
    pub verified_scope_json_commands_total: usize,
    #[serde(rename = "verified_scope_json_commands_with_schema")]
    pub verified_scope_json_commands_with_schema: usize,
    #[serde(rename = "verified_scope_json_commands_with_accepted_opaque_schema")]
    pub verified_scope_json_commands_with_accepted_opaque_schema: usize,
    #[serde(rename = "verified_scope_json_commands_without_schema")]
    pub verified_scope_json_commands_without_schema: usize,
    pub advanced_scope_json_commands_total: usize,
    pub advanced_scope_json_commands_with_accepted_opaque_schema: usize,
    pub mutating_commands_total: usize,
    pub mutating_commands_with_schema: usize,
    pub mutating_commands_with_accepted_opaque_schema: usize,
    pub mutating_commands_without_schema: usize,
    #[serde(rename = "verified_scope_mutating_commands_total")]
    pub verified_scope_mutating_commands_total: usize,
    #[serde(rename = "verified_scope_mutating_commands_with_schema")]
    pub verified_scope_mutating_commands_with_schema: usize,
    #[serde(rename = "verified_scope_mutating_commands_with_accepted_opaque_schema")]
    pub verified_scope_mutating_commands_with_accepted_opaque_schema: usize,
    #[serde(rename = "verified_scope_mutating_commands_without_schema")]
    pub verified_scope_mutating_commands_without_schema: usize,
    pub advanced_scope_mutating_commands_total: usize,
    pub advanced_scope_mutating_commands_with_accepted_opaque_schema: usize,
    pub schema_verbs_total: usize,
    pub documented_schema_verbs_total: usize,
    pub undocumented_schema_verbs_total: usize,
    pub opaque_schema_verbs_total: usize,
    pub accepted_opaque_schema_verbs_total: usize,
    pub unaccepted_opaque_schema_verbs_total: usize,
    pub supports_op_id_total: usize,
    pub jsonl_commands_total: usize,
    pub missing_schema_examples: Vec<String>,
    pub missing_mutating_schema_examples: Vec<String>,
    #[serde(rename = "verified_scope_missing_schema_examples")]
    pub verified_scope_missing_schema_examples: Vec<String>,
    #[serde(rename = "verified_scope_accepted_opaque_schema_examples")]
    pub verified_scope_accepted_opaque_schema_examples: Vec<String>,
    pub advanced_scope_accepted_opaque_schema_examples: Vec<String>,
    pub accepted_opaque_schema_examples: Vec<String>,
    pub unaccepted_opaque_schema_examples: Vec<String>,
    pub undocumented_schema_examples: Vec<String>,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct VerificationCheckSchema {
    pub name: String,
    pub status: String,
    pub clean: bool,
    pub summary: String,
    pub recommended_action: Option<String>,
    pub recommended_action_template: Option<ActionTemplateSchema>,
    pub recovery_commands: Vec<String>,
    pub recovery_action_templates: Vec<ActionTemplateSchema>,
    pub details: std::collections::BTreeMap<String, String>,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct ActionTemplateSchema {
    pub action: String,
    pub argv_template: Vec<String>,
    pub required_inputs: Vec<String>,
    /// Whether an agent may replace placeholders in `argv_template`.
    ///
    /// When `agent_may_fill` is false, treat `action` and `argv_template` as
    /// display-only: do not substitute `<name>`/`<url>` placeholders. Surface
    /// the template to a human or discard it. Substituting and running it will
    /// pass literal `<name>` to Heddle and fail.
    pub agent_may_fill: bool,
}

// ---- bridge git status ----------------------------------------------------

#[derive(Debug, Serialize, JsonSchema)]
pub struct BridgeGitStatusSchema {
    pub output_kind: Option<String>,
    pub repository_capability: String,
    pub storage_model: String,
    pub mirror_path: Option<String>,
    pub mirror_initialized: bool,
    pub git_overlay_import_hint: Option<GitOverlayImportHintSchema>,
    pub git_overlay_health: GitOverlayHealthSchema,
    pub recommended_action: Option<String>,
    pub recommended_action_template: Option<ActionTemplateSchema>,
    pub recovery_commands: Vec<String>,
    #[serde(rename = "verification")]
    pub trust: RepositoryVerificationStateSchema,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct GitOverlayImportHintSchema {
    pub current_branch: String,
    pub missing_branch_count: usize,
    pub missing_branches: Vec<String>,
    pub recommended_command: String,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct GitOverlayHealthSchema {
    pub status: String,
    pub clean: bool,
    pub summary: String,
    pub recovery_commands: Vec<String>,
    pub checks: Vec<GitOverlayHealthCheckSchema>,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct GitOverlayHealthCheckSchema {
    pub name: String,
    pub status: String,
    pub summary: String,
}

// ---- log ------------------------------------------------------------------

#[derive(Debug, Serialize, JsonSchema)]
pub struct LogSchema {
    pub output_kind: Option<String>,
    pub status: Option<String>,
    pub repository_capability: String,
    pub storage_model: String,
    pub states: Vec<StateEntrySchema>,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct StateEntrySchema {
    pub change_id: String,
    pub content_hash: String,
    pub intent: Option<String>,
    pub principal: String,
    pub agent: Option<String>,
    pub confidence: Option<f32>,
    pub created_at: String,
    pub parents: Vec<String>,
    pub git_checkpoint: Option<String>,
    pub collapsed: Option<CollapsedEntrySchema>,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct CollapsedEntrySchema {
    pub expandable: bool,
    pub source_count: usize,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct TimelineLogSchema {
    pub output_kind: String,
    pub status: String,
    pub repository_capability: String,
    pub storage_model: String,
    pub thread: String,
    pub cursor: TimelineCursorSchema,
    pub branches: Vec<TimelineBranchSchema>,
    pub steps: Vec<TimelineStepSchema>,
    pub active_branch_path: Vec<String>,
    pub actions: TimelineActionsSchema,
    pub recovery: Option<TimelineRecoverySchema>,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct TimelineCursorSchema {
    pub branch_id: Option<String>,
    pub step_id: Option<String>,
    pub state: Option<String>,
    pub state_full: Option<String>,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct TimelineBranchSchema {
    pub branch_id: String,
    pub parent_branch_id: Option<String>,
    pub forked_from_step_id: Option<String>,
    pub forked_from_state: Option<String>,
    pub reason: Option<String>,
    pub created_at_ms: Option<i64>,
    pub step_ids: Vec<String>,
    pub is_active: bool,
    pub is_on_active_path: bool,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct TimelineStepSchema {
    pub step_id: String,
    pub branch_id: String,
    pub parent_step_id: Option<String>,
    pub native: Option<TimelineNativeSchema>,
    pub tool_name: Option<String>,
    pub status: Option<String>,
    pub changed: Option<bool>,
    pub touched_paths: Vec<String>,
    pub labels: Vec<String>,
    pub before_state: Option<String>,
    pub after_state: Option<String>,
    pub capture_state: Option<String>,
    pub cursor_state: Option<String>,
    pub cursor_state_full: Option<String>,
    pub payload_summary: Option<String>,
    pub payload_hash: Option<String>,
    pub capture_oplog_batch_id: Option<u64>,
    pub started_at_ms: Option<i64>,
    pub finished_at_ms: Option<i64>,
    pub operation_ids: Vec<String>,
    pub is_current: bool,
    pub is_on_active_branch_path: bool,
    pub can_seek: bool,
    pub can_fork: bool,
    pub can_reset: bool,
    pub can_materialize: bool,
    pub has_boundary_warning: bool,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct TimelineNativeSchema {
    pub harness: String,
    pub session_id: Option<String>,
    pub message_id: Option<String>,
    pub tool_call_id: String,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct TimelineActionsSchema {
    pub can_undo: bool,
    pub can_redo: bool,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct TimelineRecoverySchema {
    pub status: String,
    pub branch_id: String,
    pub from_step_id: Option<String>,
    pub to_step_id: Option<String>,
    pub from_state: String,
    pub to_state: String,
    pub reason: String,
    pub moved_at_ms: i64,
    pub checkout_state: Option<String>,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct TimelineActionSchema {
    pub output_kind: String,
    pub status: String,
    pub action: String,
    pub thread: String,
    pub branch_id: Option<String>,
    pub parent_branch_id: Option<String>,
    pub from_step_id: Option<String>,
    pub cursor_branch_id: Option<String>,
    pub cursor_step_id: Option<String>,
    pub operation_id: Option<String>,
    pub recovered_operation_id: Option<String>,
    pub materialized: Option<bool>,
    pub materialization_status: Option<String>,
    pub recovery_status: Option<String>,
    pub blocker_count: usize,
    pub branch_count: usize,
    pub step_count: usize,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct ExpandSchema {
    pub output_kind: String,
    pub status: String,
    pub requested: String,
    pub collapsed: ExpandedCollapseSchema,
    pub captures: Vec<ExpandedCaptureSchema>,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct ExpandedCollapseSchema {
    pub change_id: String,
    pub change_id_full: String,
    pub git_commit: Option<String>,
    pub thread: Option<String>,
    pub source_count: usize,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct ExpandedCaptureSchema {
    pub change_id: String,
    pub change_id_full: String,
    pub content_hash: String,
    pub intent: Option<String>,
    pub principal: String,
    pub agent: Option<String>,
    pub confidence: Option<f32>,
    pub created_at: String,
    pub parents: Vec<String>,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct LogReflogSchema {
    pub output_kind: Option<String>,
    pub status: Option<String>,
    pub repository_capability: String,
    pub storage_model: String,
    pub entries: Vec<ReflogEntrySchema>,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct ReflogEntrySchema {
    pub source: String,
    pub reference: String,
    pub old_oid: String,
    pub new_oid: String,
    pub actor: String,
    pub timestamp: Option<String>,
    pub message: String,
}

// ---- show -----------------------------------------------------------------

#[derive(Debug, Serialize, JsonSchema)]
pub struct ShowSchema {
    pub output_kind: String,
    pub repository_capability: String,
    pub storage_model: String,
    pub change_id: String,
    pub change_id_full: String,
    pub content_hash: String,
    pub tree: String,
    pub parents: Vec<String>,
    pub intent: Option<String>,
    pub confidence: Option<f32>,
    pub principal: ShowPrincipalSchema,
    pub agent: Option<ShowAgentSchema>,
    pub created_at: String,
    pub status: String,
    pub verification: OpaqueObject,
    pub git_checkpoint: Option<String>,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct ShowPrincipalSchema {
    pub name: String,
    pub email: String,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct ShowAgentSchema {
    pub provider: Option<String>,
    pub model: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub session_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub policy_id: Option<String>,
}

// ---- thread list ----------------------------------------------------------

#[derive(Debug, Serialize, JsonSchema)]
pub struct ThreadListSchema {
    pub output_kind: Option<String>,
    pub repository_capability: String,
    pub repository_label: String,
    pub repository_context: Option<RepositoryContextInfoSchema>,
    pub storage_model: String,
    pub hosted_enabled: bool,
    pub threads: Vec<ThreadSummarySchema>,
    pub available_git_refs: Vec<AvailableGitRefSchema>,
    pub current: Option<String>,
    #[serde(rename = "verification")]
    pub trust: RepositoryVerificationStateSchema,
    pub recommended_action: Option<String>,
    pub recommended_action_template: Option<ActionTemplateSchema>,
    pub recovery_commands: Vec<String>,
    pub recovery_action_templates: Vec<ActionTemplateSchema>,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct AvailableGitRefSchema {
    pub name: String,
    pub git_commit: String,
    pub recommended_action: Option<String>,
    pub recommended_action_template: Option<ActionTemplateSchema>,
}

// ---- review ---------------------------------------------------------------

#[derive(Debug, Serialize, JsonSchema)]
pub struct ReviewShowSchema {
    pub output_kind: String,
    pub change_id: String,
    pub headline: String,
    pub agent_narrative: Option<String>,
    pub files_changed: usize,
    pub in_budget_signals: Vec<Value>,
    pub all_signals: Vec<Value>,
    pub discussions: Vec<Value>,
    pub signing_kinds: Vec<String>,
    pub signatures: Vec<Value>,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct ReviewSignSchema {
    pub output_kind: String,
    pub signature_id: String,
    pub change_id: String,
}

/// `heddle review next --output json` emits a stable envelope keyed by
/// `output_kind: "review_next"`. When the scan window holds a pending
/// review, the pending state's view is flattened alongside `output_kind`
/// (`change_id`, `headline`, `existing_signatures`) and the same view is
/// echoed under `next`. When no pending review is found, only
/// `output_kind` and `next: null` are emitted — there is no top-level
/// `null`. Mirrors the envelope built in `review::run_next`.
#[derive(Debug, Serialize, JsonSchema)]
pub struct ReviewNextSchema {
    pub output_kind: String,
    pub change_id: Option<String>,
    pub headline: Option<String>,
    pub existing_signatures: Option<u32>,
    pub next: RequiredNullableNextState,
}

/// `next` is ALWAYS present in the runtime envelope — either the pending
/// review state or an explicit JSON `null`. Modeling it as
/// `Option<ReviewNextStateSchema>` directly would let schemars drop the
/// field from the schema's `required` set, advertising a shape the command
/// never emits. This wrapper keeps the value nullable (its schema delegates
/// to `Option`'s nullable form) while reporting `_schemars_private_is_option
/// == false`, so the derive marks `next` required (heddle#272 Codex r7).
#[derive(Debug, Serialize)]
#[serde(transparent)]
pub struct RequiredNullableNextState(pub Option<ReviewNextStateSchema>);

impl JsonSchema for RequiredNullableNextState {
    fn schema_name() -> std::borrow::Cow<'static, str> {
        std::borrow::Cow::Borrowed("RequiredNullableNextState")
    }

    fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
        <Option<ReviewNextStateSchema> as JsonSchema>::json_schema(generator)
    }
}

/// The pending review state echoed under `review next`'s `next` field.
#[derive(Debug, Serialize, JsonSchema)]
pub struct ReviewNextStateSchema {
    pub change_id: String,
    pub headline: String,
    pub existing_signatures: u32,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct ReviewHealthSchema {
    pub output_kind: String,
    pub entries: Vec<ReviewHealthEntrySchema>,
    pub window_states: usize,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct ReviewHealthEntrySchema {
    pub module_id: String,
    pub fire_rate: f64,
    pub warn: bool,
}

// ---- transaction commit ---------------------------------------------------

#[derive(Debug, Serialize, JsonSchema)]
pub struct TransactionCommitSchema {
    pub change_id: String,
    pub op_count: u32,
}

// ---- command/schema introspection ----------------------------------------

#[derive(Debug, Serialize, JsonSchema)]
pub struct SchemasListSchema {
    pub output_kind: Option<String>,
    pub status: Option<String>,
    pub schema_verbs: Vec<String>,
    pub documented_schema_verbs: Vec<String>,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct DoctorDocsSchema {
    pub output_kind: String,
    pub status: String,
    #[serde(rename = "verified")]
    pub verified: bool,
    pub recommended_action: Option<String>,
    pub files_scanned: usize,
    pub issues: Vec<DoctorDocsIssueSchema>,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct DoctorDocsIssueSchema {
    pub file: String,
    pub line: usize,
    pub invocation: String,
    pub kind: String,
    pub detail: String,
    pub suggestion: Option<String>,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct DoctorSchemasSchema {
    pub output_kind: String,
    pub status: String,
    #[serde(rename = "verified")]
    pub verified: bool,
    pub summary: String,
    pub recommended_action: Option<String>,
    pub recovery_commands: Vec<String>,
    pub registered_verbs: Vec<String>,
    pub documented_verbs: Vec<String>,
    pub undocumented_verbs: Vec<String>,
    pub unmatched_verbs: Vec<String>,
    pub passing_verbs: Vec<String>,
    pub issues: Vec<DoctorSchemaIssueSchema>,
    pub command_contract_schema_coverage: CommandContractSchemaCoverageSchema,
    pub doc_path: String,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct DoctorSchemaIssueSchema {
    pub verb: String,
    pub line: usize,
    pub unknown_key: String,
    pub detail: String,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct CommandContractSchemaCoverageSchema {
    pub status: String,
    #[serde(rename = "verified_scope")]
    pub verified_scope: String,
    pub advanced_scope: String,
    pub summary: String,
    pub catalog_commands_total: usize,
    pub catalog_mutating_commands_total: usize,
    pub json_commands_total: usize,
    pub json_mutating_commands_total: usize,
    pub json_commands_with_schema: usize,
    pub json_commands_with_accepted_opaque_schema: usize,
    pub json_commands_without_schema: usize,
    #[serde(rename = "verified_scope_json_commands_total")]
    pub verified_scope_json_commands_total: usize,
    #[serde(rename = "verified_scope_json_commands_with_schema")]
    pub verified_scope_json_commands_with_schema: usize,
    #[serde(rename = "verified_scope_json_commands_with_accepted_opaque_schema")]
    pub verified_scope_json_commands_with_accepted_opaque_schema: usize,
    #[serde(rename = "verified_scope_json_commands_without_schema")]
    pub verified_scope_json_commands_without_schema: usize,
    pub advanced_scope_json_commands_total: usize,
    pub advanced_scope_json_commands_with_accepted_opaque_schema: usize,
    pub mutating_commands_total: usize,
    pub mutating_commands_with_schema: usize,
    pub mutating_commands_with_accepted_opaque_schema: usize,
    pub mutating_commands_without_schema: usize,
    #[serde(rename = "verified_scope_mutating_commands_total")]
    pub verified_scope_mutating_commands_total: usize,
    #[serde(rename = "verified_scope_mutating_commands_with_schema")]
    pub verified_scope_mutating_commands_with_schema: usize,
    #[serde(rename = "verified_scope_mutating_commands_with_accepted_opaque_schema")]
    pub verified_scope_mutating_commands_with_accepted_opaque_schema: usize,
    #[serde(rename = "verified_scope_mutating_commands_without_schema")]
    pub verified_scope_mutating_commands_without_schema: usize,
    pub advanced_scope_mutating_commands_total: usize,
    pub advanced_scope_mutating_commands_with_accepted_opaque_schema: usize,
    pub undocumented_schema_verbs_total: usize,
    pub opaque_schema_verbs_total: usize,
    pub accepted_opaque_schema_verbs_total: usize,
    pub unaccepted_opaque_schema_verbs_total: usize,
    pub missing_schema_examples: Vec<String>,
    pub missing_mutating_schema_examples: Vec<String>,
    #[serde(rename = "verified_scope_missing_schema_examples")]
    pub verified_scope_missing_schema_examples: Vec<String>,
    #[serde(rename = "verified_scope_accepted_opaque_schema_examples")]
    pub verified_scope_accepted_opaque_schema_examples: Vec<String>,
    pub advanced_scope_accepted_opaque_schema_examples: Vec<String>,
    pub accepted_opaque_schema_examples: Vec<String>,
    pub unaccepted_opaque_schema_examples: Vec<String>,
    pub undocumented_schema_examples: Vec<String>,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct GitOverlayGuideSchema {
    pub topic: String,
    pub summary: String,
    pub steps: Vec<String>,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct WatchLineSchema {
    pub ts: String,
    pub thread: Option<String>,
    pub kind: String,
    pub change_id: Option<String>,
    pub intent: Option<String>,
    pub confidence: Option<f32>,
    pub actor: Option<ActorInfoSchema>,
    pub id: u64,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct TrySchema {
    pub status: String,
    pub action: String,
    pub message: String,
    pub thread: String,
    pub thread_dropped: bool,
    pub cleanup_error: Option<String>,
    pub exit_code: Option<i32>,
    pub duration_ms: u128,
    pub captured_state: Option<String>,
    pub merge_state: Option<String>,
    pub next_action: Option<String>,
    pub next_action_template: Option<ActionTemplateSchema>,
    pub recommended_action: Option<String>,
    pub recommended_action_template: Option<ActionTemplateSchema>,
    pub recovery_commands: Vec<String>,
    pub recovery_action_templates: Vec<ActionTemplateSchema>,
}

// ---- bridge ops -----------------------------------------------------------

#[derive(Debug, Serialize, JsonSchema)]
pub struct BridgeInitSchema {
    pub initialized: bool,
    pub path: String,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct ExportedRefSchema {
    pub name: String,
    pub tip: String,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct BridgeExportSchema {
    pub states_exported: u64,
    pub commits_total: u64,
    pub threads_synced: u64,
    pub markers_synced: u64,
    pub branches: Vec<ExportedRefSchema>,
    pub tags: Vec<ExportedRefSchema>,
    pub destination: String,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct BridgeImportSchema {
    pub output_kind: Option<String>,
    pub status: String,
    pub action: Option<String>,
    pub summary: String,
    pub commits_imported: u64,
    pub states_created: u64,
    pub branches_synced: u64,
    pub tags_synced: u64,
    pub skipped_non_commit_refs: u64,
    pub lossy_entries: Vec<LossyImportEntrySchema>,
    pub already_in_sync: bool,
    pub recommended_action: Option<String>,
    pub recommended_action_template: Option<ActionTemplateSchema>,
    pub recovery_commands: Vec<String>,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct LossyImportEntrySchema {
    pub path: String,
    pub action: String,
    pub reason: String,
    pub git_object: Option<String>,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct BridgeSyncSchema {
    pub output_kind: Option<String>,
    pub status: String,
    pub action: Option<String>,
    pub summary: String,
    pub states_exported: u64,
    pub commits_exported_total: u64,
    pub commits_imported: u64,
    pub threads_synced: u64,
    pub markers_synced: u64,
    pub recommended_action: Option<String>,
    pub recommended_action_template: Option<ActionTemplateSchema>,
    pub recovery_commands: Vec<String>,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct BridgeGitReconcileSchema {
    pub output_kind: Option<String>,
    pub status: String,
    pub action: Option<String>,
    pub prefer: Option<String>,
    pub ref_name: String,
    pub preview: bool,
    pub summary: String,
    pub recommended_action: Option<String>,
    pub recommended_action_template: Option<ActionTemplateSchema>,
    pub recovery_commands: Vec<String>,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct BridgePushSchema {
    pub output_kind: Option<String>,
    pub action: Option<String>,
    pub status: Option<String>,
    pub success: Option<bool>,
    pub pushed: bool,
    pub changed: Option<bool>,
    pub transport: Option<String>,
    pub remote: String,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct BridgePullSchema {
    pub output_kind: Option<String>,
    pub action: Option<String>,
    pub status: Option<String>,
    pub success: Option<bool>,
    pub pulled: bool,
    pub changed: Option<bool>,
    pub transport: Option<String>,
    pub remote: String,
}

// ---- stash / revert -------------------------------------------------------

#[derive(Debug, Serialize, JsonSchema)]
pub struct StashMutationSchema {
    pub message: String,
    pub stash_index: Option<usize>,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct StashListSchema {
    pub output_kind: String,
    pub stashes: Vec<StashListEntrySchema>,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct StashListEntrySchema {
    pub index: usize,
    pub message: Option<String>,
    pub created_at: String,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct StashShowSchema {
    pub output_kind: String,
    pub modified: Vec<String>,
    pub added: Vec<String>,
    pub deleted: Vec<String>,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct RevertSchema {
    pub output_kind: String,
    pub change_id: Option<String>,
    pub reverted_state: String,
    pub files_affected: Vec<String>,
    pub message: String,
}

// ---- diagnose -------------------------------------------------------------

#[derive(Debug, Serialize, JsonSchema)]
pub struct DiagnoseSchema {
    pub output_kind: Option<String>,
    pub repository: String,
    pub repository_capability: String,
    pub storage_model: String,
    pub hosted_enabled: bool,
    pub git_overlay_import_hint: Option<GitOverlayImportHintSchema>,
    pub git_overlay_health: GitOverlayHealthSchema,
    #[serde(rename = "verification")]
    pub trust: RepositoryVerificationStateSchema,
    pub operation: OpaqueObject,
    pub remote_tracking: OpaqueObject,
    pub thread: Option<Value>,
    pub state: Option<Value>,
    pub changes: Value,
    pub workspace: Value,
    pub health: Value,
    pub recommended_action: Option<String>,
    pub recommended_action_template: Option<ActionTemplateSchema>,
    pub recovery_commands: Vec<String>,
    pub profile: Option<Value>,
}

// ---- error envelope (cross-cutting) ---------------------------------------
//
// Emitted to **stderr** (not stdout) by any state-changing verb that fails
// when JSON output is selected. The 21 verb schemas above describe the
// stdout success shape; this schema describes the stderr failure shape so
// scripts and agents can parse failures without scraping freeform text.
//
// Field contract:
//
// - `code` — stable machine code; currently mirrors `kind`.
// - `error` — human-readable message (the anyhow chain rendered via `{:#}`).
//   Always present, never empty.
// - `exit_code` — process exit code emitted for the failure.
// - `hint` — single-line next-step recommendation. Empty string when no
//   actionable hint applies. JSON-mode runtime errors use a non-empty
//   fallback hint when no specific recovery class applies.
// - `kind` — stable predicate name keying the hint family. JSON-mode
//   runtime errors use `runtime_error` when the error didn't match a
//   known class. Current values include:
//   `repository_not_found`, `repository_exists`, `state_not_found`,
//   `thread_not_found`, `out_of_space`, `permission_denied`,
//   `read_only_filesystem`, and `runtime_error`. New kinds may be added
//   (additive); existing ones are stable.
// - `unsafe_condition`, `would_change`, `preserved` — typed safety facts.
// - `primary_command`, `primary_command_template` — the main recovery
//   action as a human-readable command string plus a fillable template
//   (always present for a valid action). The `_argv` sidecar was dropped
//   (HeddleCo/heddle#254): it was null for every placeholder action and
//   silently read as "no action" to agents — use the template instead.
// - `recovery_commands`, `recovery_action_templates` — all recovery
//   actions the runtime can represent, as command strings or fillable
//   templates.

#[derive(Debug, Serialize, JsonSchema)]
pub struct ErrorEnvelopeSchema {
    pub error: String,
    pub exit_code: u8,
    pub hint: String,
    pub kind: String,
    pub op_id: Option<String>,
    pub idempotency_status: Option<String>,
    pub replayed: Option<bool>,
    pub unsafe_condition: String,
    pub would_change: String,
    pub preserved: String,
    pub primary_command: String,
    pub primary_command_template: NullableActionTemplateSchema,
    pub recovery_commands: Vec<String>,
    pub recovery_action_templates: Vec<ActionTemplateSchema>,
}

#[derive(Debug, Serialize, JsonSchema)]
#[serde(untagged)]
#[allow(dead_code)]
pub enum NullableActionTemplateSchema {
    Template(ActionTemplateSchema),
    Null(()),
}

#[derive(Debug, Serialize, JsonSchema)]
#[serde(untagged)]
#[allow(dead_code)]
pub enum NullableStringSchema {
    Value(String),
    Null(()),
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    fn required_fields(schema: &Value) -> Vec<&str> {
        schema
            .get("required")
            .and_then(|value| value.as_array())
            .expect("schema has required fields")
            .iter()
            .map(|value| value.as_str().expect("required field is a string"))
            .collect()
    }

    fn property_schema<'a>(schema: &'a Value, property: &str) -> &'a Value {
        schema
            .get("properties")
            .and_then(|p| p.as_object())
            .and_then(|properties| properties.get(property))
            .unwrap_or_else(|| panic!("schema has `{property}` property"))
    }

    fn resolve_schema_ref<'a>(root: &'a Value, reference: &str) -> &'a Value {
        reference
            .strip_prefix("#/$defs/")
            .or_else(|| reference.strip_prefix("#/definitions/"))
            .and_then(|name| {
                root.get("$defs")
                    .or_else(|| root.get("definitions"))
                    .and_then(|defs| defs.get(name))
            })
            .unwrap_or_else(|| panic!("schema reference `{reference}` resolves"))
    }

    fn schema_declares_property(root: &Value, schema: &Value, property: &str) -> bool {
        if let Some(reference) = schema.get("$ref").and_then(|value| value.as_str()) {
            return schema_declares_property(root, resolve_schema_ref(root, reference), property);
        }

        if schema
            .get("properties")
            .and_then(|properties| properties.get(property))
            .is_some()
        {
            return true;
        }

        for combinator in ["anyOf", "oneOf"] {
            if let Some(schemas) = schema.get(combinator).and_then(|value| value.as_array()) {
                return !schemas.is_empty()
                    && schemas
                        .iter()
                        .all(|schema| schema_declares_property(root, schema, property));
            }
        }

        schema
            .get("allOf")
            .and_then(|value| value.as_array())
            .is_some_and(|schemas| {
                schemas
                    .iter()
                    .any(|schema| schema_declares_property(root, schema, property))
            })
    }

    fn schema_allows_null(root: &Value, schema: &Value) -> bool {
        if let Some(reference) = schema.get("$ref").and_then(|value| value.as_str()) {
            return schema_allows_null(root, resolve_schema_ref(root, reference));
        }

        if schema.get("type") == Some(&Value::String("null".to_string())) {
            return true;
        }
        if schema
            .get("type")
            .and_then(|value| value.as_array())
            .is_some_and(|types| types.contains(&Value::String("null".to_string())))
        {
            return true;
        }

        ["anyOf", "oneOf", "allOf"].iter().any(|combinator| {
            schema
                .get(*combinator)
                .and_then(|value| value.as_array())
                .is_some_and(|schemas| {
                    schemas
                        .iter()
                        .any(|schema| schema_allows_null(root, schema))
                })
        })
    }

    fn collect_string_enums<'a>(root: &'a Value, schema: &'a Value, values: &mut Vec<&'a str>) {
        if let Some(reference) = schema.get("$ref").and_then(|value| value.as_str()) {
            collect_string_enums(root, resolve_schema_ref(root, reference), values);
        }

        if let Some(enum_values) = schema.get("enum").and_then(|value| value.as_array()) {
            for value in enum_values {
                if let Some(value) = value.as_str() {
                    values.push(value);
                }
            }
        }

        for combinator in ["anyOf", "oneOf", "allOf"] {
            if let Some(schemas) = schema.get(combinator).and_then(|value| value.as_array()) {
                for schema in schemas {
                    collect_string_enums(root, schema, values);
                }
            }
        }
    }

    fn collect_discriminator_values<'a>(
        root: &'a Value,
        schema: &'a Value,
        field: &str,
        values: &mut Vec<&'a str>,
    ) {
        if let Some(reference) = schema.get("$ref").and_then(|value| value.as_str()) {
            collect_discriminator_values(root, resolve_schema_ref(root, reference), field, values);
            return;
        }

        if let Some(property) = schema
            .get("properties")
            .and_then(|properties| properties.get(field))
        {
            collect_string_enums(root, property, values);
        }

        for combinator in ["anyOf", "oneOf", "allOf"] {
            if let Some(schemas) = schema.get(combinator).and_then(|value| value.as_array()) {
                for schema in schemas {
                    collect_discriminator_values(root, schema, field, values);
                }
            }
        }
    }

    fn schema_requires_discriminator(root: &Value, schema: &Value, field: &str) -> bool {
        if let Some(reference) = schema.get("$ref").and_then(|value| value.as_str()) {
            return schema_requires_discriminator(root, resolve_schema_ref(root, reference), field);
        }

        if schema
            .get("properties")
            .and_then(|properties| properties.get(field))
            .is_some()
        {
            return schema
                .get("required")
                .and_then(|value| value.as_array())
                .is_some_and(|required| {
                    required
                        .iter()
                        .any(|required_field| required_field.as_str() == Some(field))
                });
        }

        for combinator in ["anyOf", "oneOf"] {
            if let Some(schemas) = schema.get(combinator).and_then(|value| value.as_array()) {
                return !schemas.is_empty()
                    && schemas
                        .iter()
                        .all(|schema| schema_requires_discriminator(root, schema, field));
            }
        }

        schema
            .get("allOf")
            .and_then(|value| value.as_array())
            .is_some_and(|schemas| {
                schemas
                    .iter()
                    .any(|schema| schema_requires_discriminator(root, schema, field))
            })
    }

    /// Every schema verb advertised by the command contract table must
    /// produce a schema.
    /// Otherwise `heddle doctor schemas` would silently miss drift on
    /// that verb.
    #[test]
    fn registry_covers_every_listed_verb() {
        for verb in schema_verbs() {
            assert!(
                schema_for_verb(verb).is_some(),
                "verb '{verb}' is advertised by command contracts but schema_for_verb returned None"
            );
        }
    }

    #[test]
    fn documented_registry_is_subset_of_runtime_registry() {
        let all = schema_verbs();
        for verb in documented_schema_verbs() {
            assert!(
                all.contains(verb),
                "documented schema verb '{verb}' is not advertised as a runtime schema"
            );
        }
    }

    /// Every documented (non-opaque) verb whose catalog advertises an
    /// `output_kind` discriminator must declare the `output_kind`
    /// property on its *registered schema struct*, not merely rely on the
    /// runtime injection in [`schema_for_verb`].
    ///
    /// heddle#272 r6 (Codex P2): `schema_for_verb` injects the
    /// discriminator from the catalog after deriving the struct schema,
    /// so `heddle schemas <verb>` already surfaces `output_kind`. That
    /// injection masks the fact that the Rust mirror struct (e.g.
    /// `CleanSchema`, `DiffSchema`) never declares the field. The mirror
    /// is the source of truth a reader greps; it must be honest about the
    /// discriminator the runtime always emits. This check reads the
    /// *pre-injection* struct schema so a missing field fails CI rather
    /// than being papered over by the catalog.
    #[test]
    fn documented_swept_schema_structs_declare_output_kind() {
        let mut missing = Vec::new();
        for verb in documented_schema_verbs() {
            // Opaque verbs expose a generic object schema; their
            // discriminator is genuinely catalog-only (there is no
            // Serialize mirror struct to declare it on).
            if opaque_schema_verbs().contains(verb) {
                continue;
            }
            let Some(discriminator) =
                command_catalog::command_json_discriminator_for_schema_verb(verb)
            else {
                continue;
            };
            if discriminator.field != "output_kind" {
                continue;
            }
            let bare = schema_for_registered_verb(verb)
                .unwrap_or_else(|| panic!("documented verb `{verb}` has no registered schema"));
            let declares = schema_declares_property(&bare, &bare, "output_kind");
            if !declares {
                missing.push(format!(
                    "{verb}: catalog advertises output_kind=`{}` but the schema struct declares no `output_kind` property",
                    discriminator.value
                ));
            }
        }
        assert!(
            missing.is_empty(),
            "Documented swept schema structs missing the `output_kind` property. Add \
             `pub output_kind: String` to each mirror struct so it matches the runtime \
             emission (the catalog injection masks this at the `heddle schemas` layer, \
             but the struct must be honest):\n  - {}",
            missing.join("\n  - ")
        );
    }

    #[test]
    fn implementation_registry_matches_command_contract_registry() {
        let advertised = schema_verbs();
        let mut implemented = schema_implementation_verbs();
        for verb in opaque_schema_verbs() {
            if !implemented.contains(verb) {
                implemented.push(*verb);
            }
            assert!(
                advertised.contains(verb),
                "opaque schema verb '{verb}' must also be advertised by active command contracts"
            );
        }
        for verb in advertised {
            assert!(
                implemented.contains(verb),
                "verb '{verb}' is advertised by command contracts but the schema implementation registry does not handle it"
            );
        }
        for verb in &implemented {
            if cfg!(all(feature = "git-overlay", feature = "semantic")) {
                assert!(
                    advertised.contains(verb),
                    "verb '{verb}' has a schema implementation but is not advertised by active command contracts"
                );
            } else if !advertised.contains(verb) {
                assert!(
                    schema_for_verb(verb).is_none(),
                    "inactive schema implementation '{verb}' must not be publicly resolvable"
                );
            }
        }
    }

    #[test]
    fn command_catalog_schema_verbs_match_schema_list_except_error_envelope() {
        let catalog = command_catalog::build_command_catalog();
        let mut catalog_verbs = catalog
            .commands
            .iter()
            .flat_map(|command| command.schema_verbs.iter().map(String::as_str))
            .collect::<Vec<_>>();
        catalog_verbs.sort_unstable();
        catalog_verbs.dedup();

        let mut listed_verbs = schema_verbs().to_vec();
        listed_verbs.sort_unstable();
        listed_verbs.retain(|verb| *verb != "error");

        assert_eq!(
            catalog_verbs, listed_verbs,
            "`heddle help --output json` command schema verbs must match `heddle schemas` except for the cross-cutting JSON error envelope"
        );
    }

    #[cfg(not(feature = "git-overlay"))]
    #[test]
    fn native_only_schema_registry_excludes_git_overlay_verbs() {
        let catalog = command_catalog::build_command_catalog();
        for verb in [
            "bridge git status",
            "bridge git init",
            "bridge git import",
            "bridge git export",
            "bridge git sync",
            "bridge git reconcile",
            "bridge git push",
            "bridge git pull",
            "bridge git reason",
            "git-overlay",
        ] {
            assert!(
                !schema_verbs().contains(&verb),
                "native-only schema listing must not advertise git-overlay verb `{verb}`"
            );
            assert!(
                !documented_schema_verbs().contains(&verb),
                "native-only documented schema listing must not advertise git-overlay verb `{verb}`"
            );
            assert!(
                schema_for_verb(verb).is_none(),
                "native-only schema lookup must reject git-overlay verb `{verb}`"
            );
            assert!(
                catalog.commands.iter().all(|command| {
                    !command
                        .schema_verbs
                        .iter()
                        .any(|schema_verb| schema_verb == verb)
                        && !command
                            .documented_schema_verbs
                            .iter()
                            .any(|schema_verb| schema_verb == verb)
                }),
                "native-only command catalog must not advertise git-overlay schema verb `{verb}`"
            );
        }
    }

    #[test]
    fn unknown_verb_returns_none() {
        assert!(schema_for_verb("nope").is_none());
    }

    #[test]
    fn status_schema_has_expected_top_level_properties() {
        let schema = schema_for_verb("status").expect("status schema");
        let properties = schema
            .get("properties")
            .and_then(|p| p.as_object())
            .expect("status schema has properties");
        for required in &[
            "repository_capability",
            "storage_model",
            "hosted_enabled",
            "thread",
            "current_state",
            "actor",
            "blockers",
            "changes",
        ] {
            assert!(
                properties.contains_key(*required),
                "status schema missing property '{required}'"
            );
        }
    }

    #[test]
    fn action_template_agent_may_fill_schema_describes_false_semantics() {
        let schema = schema_for_verb("verify").expect("verify schema");
        let action_template = schema
            .get("$defs")
            .or_else(|| schema.get("definitions"))
            .and_then(|defs| defs.get("ActionTemplateSchema"))
            .expect("verify schema includes ActionTemplateSchema definition");
        let description = property_schema(action_template, "agent_may_fill")
            .get("description")
            .and_then(Value::as_str)
            .expect("agent_may_fill schema description is present");

        assert!(
            description.contains("When `agent_may_fill` is false"),
            "agent_may_fill schema description must document false semantics: {description}"
        );
        assert!(
            description.contains("display-only"),
            "agent_may_fill schema description must warn agents not to execute display-only templates: {description}"
        );
        assert!(
            description.contains("do not substitute `<name>`/`<url>` placeholders"),
            "agent_may_fill schema description must prohibit placeholder substitution when false: {description}"
        );
    }

    /// HeddleCo/heddle#645 conformance: the action-field presence contract.
    ///
    /// `next_action` / `recommended_action` encode "no action needed" as
    /// `null` and "not applicable to this output shape" as an absent
    /// field — never as `""` (the runtime maps empty selections to `None`
    /// via `next_action::normalized_action` /
    /// `serialize_empty_action_as_null`, and the serialization walker in
    /// `validate_next_actions_at_path` rejects any empty string that
    /// slips past). At the schema level that means: wherever one of these
    /// properties is *required*, its schema must allow `null` — a
    /// non-nullable required action field would force emitters to leak
    /// `""` for the no-action case.
    #[test]
    fn action_fields_follow_presence_contract_in_every_schema() {
        fn walk(root: &Value, schema: &Value, verb: &str, path: &str) {
            match schema {
                Value::Object(object) => {
                    if let Some(properties) = object.get("properties").and_then(|p| p.as_object()) {
                        let required: Vec<&str> = object
                            .get("required")
                            .and_then(|value| value.as_array())
                            .map(|fields| {
                                fields.iter().filter_map(|field| field.as_str()).collect()
                            })
                            .unwrap_or_default();
                        for (name, child) in properties {
                            if matches!(name.as_str(), "next_action" | "recommended_action")
                                && required.contains(&name.as_str())
                            {
                                assert!(
                                    schema_allows_null(root, child),
                                    "`{verb}` schema requires `{path}.{name}` without allowing \
                                     null; the action contract is null = no action, absent = \
                                     not applicable, never \"\": {child}"
                                );
                            }
                        }
                    }
                    for (key, child) in object {
                        walk(root, child, verb, &format!("{path}.{key}"));
                    }
                }
                Value::Array(items) => {
                    for (index, child) in items.iter().enumerate() {
                        walk(root, child, verb, &format!("{path}[{index}]"));
                    }
                }
                _ => {}
            }
        }

        for verb in schema_verbs() {
            let schema =
                schema_for_verb(verb).unwrap_or_else(|| panic!("schema registered for `{verb}`"));
            walk(&schema, &schema, verb, "$");
        }
    }

    #[test]
    fn status_schema_allows_null_recommended_action() {
        let schema = schema_for_verb("status").expect("status schema");
        let recommended_action = property_schema(&schema, "recommended_action");
        assert!(
            schema_allows_null(&schema, recommended_action),
            "status recommended_action must allow null because empty actions serialize as null: {recommended_action}"
        );

        let required = required_fields(&schema);
        assert!(
            required.contains(&"recommended_action"),
            "status recommended_action should remain a stable emitted field: {schema}"
        );
    }

    #[test]
    fn status_agent_context_fields_are_omittable() {
        let schema = schema_for_verb("status").expect("status schema");
        let required = required_fields(&schema);
        for field in [
            "path",
            "execution_path",
            "session_id",
            "heddle_session_id",
            "actor",
            "harness",
            "thinking_level",
            "usage_summary",
            "last_progress_at",
            "report_flush_state",
            "attach_reason",
            "target_thread",
            "parent_thread",
            "task",
        ] {
            assert!(
                !required.contains(&field),
                "status `{field}` is omitted when no agent/materialized context is recorded: {schema}"
            );
        }
    }

    #[test]
    fn status_thread_mode_schema_matches_observed_modes() {
        let schema = schema_for_verb("status").expect("status schema");
        let mut values = Vec::new();
        collect_string_enums(
            &schema,
            property_schema(&schema, "thread_mode"),
            &mut values,
        );

        for expected in ["materialized", "virtualized", "solid"] {
            assert!(
                values.contains(&expected),
                "status thread_mode schema missing observed mode `{expected}`: {values:?}"
            );
        }
        assert!(
            !values.contains(&"lightweight"),
            "status thread_mode schema must not advertise removed mode `lightweight`: {values:?}"
        );
    }

    #[test]
    fn ready_schema_requires_stable_operator_and_readiness_fields() {
        let schema = schema_for_verb("ready").expect("ready schema");
        let properties = schema
            .get("properties")
            .and_then(|p| p.as_object())
            .expect("ready schema has properties");
        assert!(
            properties.contains_key("blockers"),
            "ready schema should still document blockers when emitted"
        );
        assert!(
            properties.contains_key("warnings"),
            "ready schema should still document warnings when emitted"
        );
        assert!(
            properties.contains_key("readiness"),
            "ready schema should document the stable readiness summary"
        );
        assert!(
            properties.contains_key("verification"),
            "ready schema should document the repository verification proof"
        );

        let required = required_fields(&schema);
        for stable_field in ["blockers", "warnings", "readiness", "verification"] {
            assert!(
                required.contains(&stable_field),
                "ready schema must require `{stable_field}` because ready JSON always emits the stable field set: {schema}"
            );
        }
        assert!(
            properties.contains_key("captured_state"),
            "ready schema should document captured_state even though schemars models nullable Option fields as optional"
        );
    }

    #[test]
    fn push_schema_requires_stable_runtime_fields() {
        let schema = schema_for_verb("push").expect("push schema");
        let required = required_fields(&schema);
        for stable_field in [
            "output_kind",
            "action",
            "status",
            "pushed",
            "changed",
            "success",
            "transport",
            "next_action",
            "next_action_template",
            "recommended_action",
            "recommended_action_template",
        ] {
            assert!(
                required.contains(&stable_field),
                "push schema must require stable emitted field `{stable_field}`: {schema}"
            );
        }

        for skipped_when_none in [
            "remote",
            "push_scope",
            "ref_scope",
            "git_notes_ref",
            "git_notes_visibility_warning",
            "git_tracking_remote",
            "git_remote_configured",
            "git_upstream_configured",
            "tags_included",
            "force",
            "force_discard_warning",
            "thread",
            "state",
            "objects",
        ] {
            assert!(
                !required.contains(&skipped_when_none),
                "push schema must not require conditionally omitted field `{skipped_when_none}`: {schema}"
            );
        }
    }

    #[test]
    fn advertised_json_discriminators_are_reflected_in_schemas() {
        use std::collections::{BTreeMap, BTreeSet};

        for schema_verb in schema_verbs() {
            let mut discriminators =
                command_catalog::command_json_discriminators_for_schema_verb(schema_verb);
            if discriminators.is_empty() {
                continue;
            };
            let schema =
                schema_for_verb(schema_verb).unwrap_or_else(|| panic!("{schema_verb} schema"));
            if schema.get("anyOf").is_some() {
                // A union schema published under this verb covers every schema
                // verb its catalog entry documents — the expected discriminator
                // set must include the siblings (e.g. inspect's union carries
                // the `thread show` branch's thread_show).
                for sibling in command_catalog::sibling_documented_schema_verbs(schema_verb) {
                    discriminators.extend(
                        command_catalog::command_json_discriminators_for_schema_verb(sibling),
                    );
                }
                for discriminator in command_catalog::command_json_discriminators()
                    .into_iter()
                    .filter(|discriminator| {
                        discriminator.display == *schema_verb
                            && discriminator.schema_verb.as_deref() != Some(schema_verb)
                    })
                {
                    discriminators.push(discriminator);
                }
            }

            let mut expected_by_field = BTreeMap::<String, BTreeSet<String>>::new();
            for discriminator in discriminators {
                expected_by_field
                    .entry(discriminator.field)
                    .or_default()
                    .insert(discriminator.value);
            }

            for (field, expected) in expected_by_field {
                let mut actual = Vec::new();
                collect_discriminator_values(&schema, &schema, &field, &mut actual);
                let actual = actual
                    .into_iter()
                    .map(str::to_string)
                    .collect::<BTreeSet<_>>();
                assert_eq!(
                    actual, expected,
                    "{schema_verb} schema must narrow `{field}` to every catalog-advertised value"
                );
                assert!(
                    schema_requires_discriminator(&schema, &schema, &field),
                    "{schema_verb} schema must require discriminator field `{field}`"
                );
            }
        }
    }

    #[test]
    fn oss_recovery_surfaces_do_not_use_opaque_generic_schema() {
        for verb in [
            "fsck",
            "resolve",
            "retro",
            "discuss open",
            "discuss append",
            "discuss resolve",
            "discuss list",
            "discuss show",
            "query",
            "query --attribution",
        ] {
            assert!(
                !opaque_schema_verbs().contains(&verb),
                "`{verb}` should have a concrete machine-contract schema, not the opaque generic object"
            );
            let schema = schema_for_verb(verb).unwrap_or_else(|| panic!("{verb} schema exists"));
            assert_ne!(
                schema.get("additionalProperties"),
                Some(&Value::Bool(true)),
                "`{verb}` schema should not accept arbitrary top-level fields"
            );
        }
    }

    #[test]
    fn commit_schema_declares_op_id_replay_fields() {
        let schema = schema_for_verb("commit").expect("commit schema");
        let properties = schema
            .get("properties")
            .and_then(|p| p.as_object())
            .expect("commit schema has properties");
        for required in OP_ID_REPLAY_FIELD_NAMES {
            assert!(
                properties.contains_key(*required),
                "commit schema missing op-id replay property '{required}'"
            );
        }
    }

    #[test]
    fn op_id_supported_schema_verbs_declare_replay_fields() {
        let mut checked = 0;
        for verb in schema_verbs() {
            if !schema_verb_supports_op_id(verb) {
                continue;
            }
            checked += 1;
            let schema =
                schema_for_verb(verb).unwrap_or_else(|| panic!("schema for `{verb}` exists"));
            let properties = schema
                .get("properties")
                .and_then(|p| p.as_object())
                .unwrap_or_else(|| panic!("schema for `{verb}` should expose properties"));
            for required in OP_ID_REPLAY_FIELD_NAMES {
                assert!(
                    properties.contains_key(*required),
                    "schema for op-id-supported verb `{verb}` missing replay property `{required}`"
                );
            }
        }
        assert!(
            checked > 1,
            "op-id schema coverage test should exercise more than commit"
        );
    }

    #[test]
    fn log_schema_has_states_array() {
        let schema = schema_for_verb("log").expect("log schema");
        let properties = schema
            .get("properties")
            .and_then(|p| p.as_object())
            .unwrap();
        assert!(properties.contains_key("states"));
        assert!(properties.contains_key("repository_capability"));
    }
}