mif-rh-cli 0.6.1

Command-line interface for the mif-rh research-harness ontology engine
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
//! Command-line interface for [`mif_rh`], the compiled ontology
//! resolution/review engine for research-harness-template (rht) corpora.
//!
//! `resolve`/`review` are drop-in replacements for rht's own
//! `scripts/resolve-ontology.sh`/`scripts/ontology-review.sh`: same flag
//! shapes, same `ontology-map.json`/`--followup` backlog output. A CLI
//! naturally writes to stdout/stderr; this binary exempts itself from the
//! workspace's `print_stdout`/`print_stderr` lints for that reason (see
//! `mif-cli`'s own `CLAUDE.md` note).
#![allow(clippy::print_stdout, clippy::print_stderr)]

use std::io::IsTerminal;
use std::path::{Path, PathBuf};
use std::process::ExitCode;

use clap::{Parser, Subcommand};
use mif_problem::{OutputFormat, ToProblem};

const DEFAULT_CATALOG: &str = ".claude/enabled-packs.json";
const DEFAULT_CONFIG: &str = "harness.config.json";
const DEFAULT_REPORTS_DIR: &str = "reports";
const ONTOLOGY_SOURCE_ENV: &str = "MIF_ONTOLOGY_SOURCE";

#[derive(Parser)]
#[command(
    name = "mif-rh-cli",
    version,
    about = "CLI for the mif-rh research-harness ontology engine"
)]
struct Cli {
    /// Error rendering format. Defaults to `pretty` on a terminal and `json`
    /// otherwise.
    #[arg(long, global = true, value_parser = ["pretty", "json"])]
    format: Option<String>,
    #[command(subcommand)]
    command: Command,
}

#[derive(Subcommand)]
enum Command {
    /// Resolve one finding against its topic's bound ontologies.
    Resolve {
        /// Path to the finding JSON file.
        finding: PathBuf,
        /// The finding's topic. If omitted, derived from `finding`'s path
        /// (`reports/<topic>/...`).
        #[arg(long)]
        topic: Option<String>,
        /// Path to the ontology catalog. Defaults to
        /// `.claude/enabled-packs.json`.
        #[arg(long)]
        catalog: Option<PathBuf>,
        /// Path to the harness config. Defaults to `harness.config.json`.
        #[arg(long)]
        config: Option<PathBuf>,
        /// Path to write the updated `ontology-map.json` record to. If
        /// omitted and the topic's `reports/<topic>/` directory exists,
        /// defaults to `reports/<topic>/ontology-map.json`; otherwise no
        /// map is written.
        #[arg(long)]
        map: Option<PathBuf>,
        /// Base directory ontology catalog `source` paths resolve against.
        /// Defaults to the current directory.
        #[arg(long)]
        root: Option<PathBuf>,
    },
    /// Rebuild `ontology-map.json` for one or more topics and aggregate
    /// coverage.
    Review {
        /// Topic to review. Repeatable. Defaults to every configured topic.
        #[arg(long)]
        topic: Vec<String>,
        /// Fail (`--strict`) only on invalid/unresolved mappings, never on
        /// discovery-only/untyped findings alone.
        #[arg(long)]
        strict: bool,
        /// Root `reports/` directory. Defaults to `reports`.
        #[arg(long)]
        reports_dir: Option<PathBuf>,
        /// Path to the harness config. Defaults to `harness.config.json`.
        #[arg(long)]
        config: Option<PathBuf>,
        /// Path to the ontology catalog. Defaults to
        /// `.claude/enabled-packs.json`.
        #[arg(long)]
        catalog: Option<PathBuf>,
        /// Path to write a `--followup` backlog of findings that still
        /// need attention.
        #[arg(long)]
        followup: Option<PathBuf>,
        /// Base directory ontology catalog `source` paths resolve against.
        /// Defaults to the current directory.
        #[arg(long)]
        root: Option<PathBuf>,
        /// Path to rht's `check-relationship-targets.sh`, run once,
        /// corpus-wide, after classification. Defaults to
        /// `<root>/scripts/check-relationship-targets.sh` if that file
        /// exists; otherwise the check is skipped. Unix-only: the script is
        /// spawned directly and relies on its `#!` shebang, which Windows
        /// does not honor.
        #[arg(long)]
        relationship_script: Option<PathBuf>,
        /// Rebuild the corpus-wide search index (every topic in `config`,
        /// not just `--topic`) after classification, for `mif-rh-mcp`'s
        /// `search`/`find_similar` tools. Off by default: index building
        /// re-embeds every finding and is far more expensive than
        /// classification alone.
        #[arg(long)]
        build_index: bool,
        /// Path to the search index database. Defaults to
        /// `<reports-dir>/_meta/search-index.sqlite`.
        #[arg(long)]
        index: Option<PathBuf>,
        /// After classification, write tier-annotated entity-type
        /// suggestions for this review's not-durably-stamped findings to
        /// `<reports-dir>/_meta/suggestions/<topic>.json` (preserving any
        /// confirmed/rejected verdicts), and record tier-3 misses in the
        /// index for `expansion-candidates`. Off by default: suggesting
        /// re-embeds findings, which the fail-closed classification path
        /// must never pay for.
        #[arg(long)]
        suggest: bool,
        /// Path to the confidence-calibration artifact used by
        /// `--suggest`. Defaults to
        /// `<reports-dir>/_meta/confidence-calibration.json`.
        #[arg(long, requires = "suggest")]
        calibration: Option<PathBuf>,
    },
    /// Suggest candidate entity types for a text or a finding, ranked by
    /// embedding similarity with confidence tiers (MIF ADR-020). Prints a
    /// JSON array of hypotheses; never writes to `reports/`.
    SuggestType {
        /// The text to classify. Omit when using `--finding`. Accepts a
        /// value starting with `-` (free-authored prose, e.g. a Markdown
        /// bullet); the accepted trade-off is that an unrecognized
        /// flag-like token (e.g. a typo'd `-x`) is silently accepted as
        /// this positional instead of producing an "unknown argument"
        /// error.
        #[arg(
            required_unless_present = "finding",
            conflicts_with = "finding",
            allow_hyphen_values = true
        )]
        text: Option<String>,
        /// Path to a finding JSON file whose indexed text (discovery text,
        /// else its entity's name) is the query.
        #[arg(long)]
        finding: Option<PathBuf>,
        /// The topic whose bound ontologies supply candidate entity types.
        /// Required with TEXT; with `--finding` it may instead derive from
        /// the finding's `reports/<topic>/...` path.
        #[arg(long, required_unless_present = "finding")]
        topic: Option<String>,
        /// Path to the ontology catalog. Defaults to
        /// `.claude/enabled-packs.json`.
        #[arg(long)]
        catalog: Option<PathBuf>,
        /// Path to the harness config. Defaults to `harness.config.json`.
        #[arg(long)]
        config: Option<PathBuf>,
        /// Base directory ontology catalog `source` paths resolve against.
        /// Defaults to the current directory.
        #[arg(long)]
        root: Option<PathBuf>,
        /// Maximum number of ranked candidates to return.
        #[arg(long, default_value_t = 10)]
        limit: usize,
        /// Path to the confidence-calibration artifact. Defaults to
        /// `reports/_meta/confidence-calibration.json`; when absent,
        /// conservative built-in thresholds apply and candidates carry
        /// `calibrated: false`.
        #[arg(long)]
        calibration: Option<PathBuf>,
        /// Record the query as a tier-3 miss in the search index when its
        /// best candidate is `trigger_expansion` (or no candidate exists),
        /// feeding `expansion-candidates`. Requires `--finding` (a miss is
        /// a property of a finding, not of ad-hoc text).
        #[arg(long, requires = "finding")]
        record: bool,
        /// Path to the search index database `--record` writes to.
        /// Defaults to `reports/_meta/search-index.sqlite`.
        #[arg(long)]
        index: Option<PathBuf>,
    },
    /// Derive the corpus's confidence-calibration artifact from its
    /// stamped findings (`stamped-quantile-v1`, MIF ADR-020 PDD-2).
    Calibrate {
        /// Root `reports/` directory. Defaults to `reports`.
        #[arg(long)]
        reports_dir: Option<PathBuf>,
        /// Path to the harness config. Defaults to `harness.config.json`.
        #[arg(long)]
        config: Option<PathBuf>,
        /// Path to the ontology catalog. Defaults to
        /// `.claude/enabled-packs.json`.
        #[arg(long)]
        catalog: Option<PathBuf>,
        /// Base directory ontology catalog `source` paths resolve against.
        /// Defaults to the current directory.
        #[arg(long)]
        root: Option<PathBuf>,
        /// Minimum empirical top-1 precision the tier-1 gate must achieve.
        #[arg(long, default_value_t = 0.95)]
        target_precision: f32,
        /// Minimum gold-in-candidates rate above the tier-2 floor.
        #[arg(long, default_value_t = 0.5)]
        tier2_target: f32,
        /// Cap the number of stamped samples used (deterministic,
        /// seed-keyed). Defaults to every stamped finding.
        #[arg(long)]
        sample: Option<usize>,
        /// Seed for the deterministic sample selection.
        #[arg(long, default_value_t = 0)]
        seed: u64,
        /// Where to write the calibration artifact. Defaults to
        /// `<reports-dir>/_meta/confidence-calibration.json`.
        #[arg(long)]
        out: Option<PathBuf>,
        /// Also write the ranked confusable type pairs from the stamped
        /// samples here (`confusions-v1` JSON: per pair the gold type, the
        /// type that took top-1, the count, and representative finding
        /// ids), grounding the `negative_examples` curation MIF ADR-020
        /// mandates. Written before the threshold sweep, so an
        /// uncalibratable corpus still gets its confusion export. Derived
        /// data — regenerate, never commit.
        #[arg(long)]
        confusions: Option<PathBuf>,
    },
    /// Cluster recorded tier-3 misses into ontology-expansion candidates
    /// (recurring, mutually-similar misses across runs — never a single
    /// miss). Prints JSON, or writes it with `--out` for
    /// `author-ontology.sh --from-clusters`.
    ExpansionCandidates {
        /// Path to the search index database holding recorded misses.
        /// Defaults to `reports/_meta/search-index.sqlite`.
        #[arg(long)]
        index: Option<PathBuf>,
        /// Path to the confidence-calibration artifact carrying the
        /// clustering knobs. Defaults to
        /// `reports/_meta/confidence-calibration.json`.
        #[arg(long)]
        calibration: Option<PathBuf>,
        /// Write the clusters JSON here instead of stdout.
        #[arg(long)]
        out: Option<PathBuf>,
    },
    /// On-demand ontology vendoring (rht ADR-0012): fetch, catalog, and
    /// verify domain ontology packs from the canonical registry — a
    /// compiled replacement for `fetch-ontology.sh`, the ontology-catalog
    /// section of `sync-packs.sh`, `check-ontology-lock.sh`, and
    /// `sync-registry-ontologies.sh`.
    Ontology {
        #[command(subcommand)]
        action: OntologyCommand,
    },
    /// Harness-native release/versioning tooling (rht Category B, Story
    /// #298): the compiled replacement for `goal-version.sh`,
    /// `bump-version.sh`, and `check-version-bump.sh` (ADR-0010).
    Harness {
        #[command(subcommand)]
        action: HarnessCommand,
    },
}

#[derive(Subcommand)]
enum OntologyCommand {
    /// Vendor one or more ontologies (and their `extends` closure) from the
    /// registry, sha256-verified and pinned in `ontologies.lock.json`.
    Fetch {
        /// Ontology ids to fetch. Mutually exclusive with `--all-enabled`.
        ids: Vec<String>,
        /// Fetch every ontology enabled in `harness.config.json`, instead
        /// of the ids given positionally.
        #[arg(long, conflicts_with = "ids")]
        all_enabled: bool,
        /// Repo root `packs/ontologies/`/`schemas/ontologies/`/
        /// `ontologies.lock.json` resolve against. Defaults to the current
        /// directory.
        #[arg(long)]
        root: Option<PathBuf>,
        /// Path to the harness config (read for `--all-enabled`). Defaults
        /// to `harness.config.json`.
        #[arg(long)]
        config: Option<PathBuf>,
        /// Override the registry source (a local directory or an http(s)
        /// base URL). Defaults to the `MIF_ONTOLOGY_SOURCE` env var, then
        /// `<root>/.ontologies.source`, then the canonical registry.
        #[arg(long)]
        source: Option<String>,
        /// Advance an id already pinned in `ontologies.lock.json` to the
        /// registry's current version. Without this, an id already pinned
        /// is left untouched (with a warning) whenever the registry's
        /// current version differs from it — the lock IS the version pin
        /// (rht#270): a corpus
        /// must not have an ontology's schema silently advance underneath
        /// its already-stamped findings. Has no effect on an id with no
        /// existing lock entry (a first-time fetch always vendors current).
        #[arg(long)]
        refresh: bool,
    },
    /// Rebuild the ontology-catalog section of the catalog sidecar
    /// (`.claude/enabled-packs.json`'s `.ontologies` key) from committed
    /// base layers plus every vendored, enabled ontology.
    Sync {
        /// Repo root ontology directories resolve against. Defaults to the
        /// current directory.
        #[arg(long)]
        root: Option<PathBuf>,
        /// Path to the harness config. Defaults to `harness.config.json`.
        #[arg(long)]
        config: Option<PathBuf>,
        /// Path to the catalog sidecar to update. Defaults to
        /// `.claude/enabled-packs.json`.
        #[arg(long)]
        catalog: Option<PathBuf>,
    },
    /// Prove every vendored domain ontology matches
    /// `ontologies.lock.json`'s pin (coverage + integrity), fail-closed.
    LockCheck {
        /// Repo root ontology directories and the lock file resolve
        /// against. Defaults to the current directory.
        #[arg(long)]
        root: Option<PathBuf>,
        /// Path to the harness config. Defaults to `harness.config.json`.
        #[arg(long)]
        config: Option<PathBuf>,
    },
    /// Discover domain ontologies newly published to the registry, add
    /// each (enabled by default) to `harness.config.json`, then vendor and
    /// catalog everything currently enabled.
    SyncRegistry {
        /// Repo root ontology directories resolve against. Defaults to the
        /// current directory.
        #[arg(long)]
        root: Option<PathBuf>,
        /// Path to the harness config. Defaults to `harness.config.json`.
        #[arg(long)]
        config: Option<PathBuf>,
        /// Path to the catalog sidecar to update. Defaults to
        /// `.claude/enabled-packs.json`.
        #[arg(long)]
        catalog: Option<PathBuf>,
        /// Override the registry source. See `ontology fetch --source`.
        #[arg(long)]
        source: Option<String>,
    },
    /// Draft a new domain ontology YAML from research: entity types a
    /// topic's findings actually used, or clusters of recurring tier-3
    /// misses. Contributing it upstream (`--open-pr`) stays rht's own
    /// script's job — it orchestrates `git`/`gh`, not `jq`.
    Author {
        /// The new ontology's id.
        new_id: String,
        /// Topic dir under `reports/` to mine observed types from.
        /// Required unless `--from-clusters` is given.
        #[arg(
            required_unless_present = "from_clusters",
            conflicts_with = "from_clusters"
        )]
        topic: Option<String>,
        /// Alternate input: a `mif-rh-cli ontology expansion-candidates
        /// --out` file. One candidate type is drafted per cluster.
        #[arg(long)]
        from_clusters: Option<PathBuf>,
        /// Write the draft here. Defaults to a temp file (path printed).
        #[arg(long)]
        out: Option<PathBuf>,
        /// Root `reports/` directory (read for topic mode). Defaults to
        /// `reports`.
        #[arg(long)]
        reports_dir: Option<PathBuf>,
    },
    /// For each pinned id the registry has advanced past, diff the vendored
    /// and registry schemas' required fields and warn only when a stamped
    /// finding is actually missing a newly required one — narrower than
    /// `fetch`'s plain version-drift warning. Read-only: never vendors,
    /// never advances a pin.
    CheckPinSafety {
        /// Ontology ids to check.
        ids: Vec<String>,
        /// Repo root `packs/ontologies/`/`ontologies.lock.json` resolve
        /// against. Defaults to the current directory.
        #[arg(long)]
        root: Option<PathBuf>,
        /// Path to the harness config (read for the topic list to scan).
        /// Defaults to `harness.config.json`.
        #[arg(long)]
        config: Option<PathBuf>,
        /// Override the registry source. See `ontology fetch --source`.
        #[arg(long)]
        source: Option<String>,
        /// Root `reports/` directory whose topics' stamped findings are
        /// checked. Defaults to `reports`.
        #[arg(long)]
        reports_dir: Option<PathBuf>,
    },
}

#[derive(Subcommand)]
enum HarnessCommand {
    /// Print a goal's content-hash identity (`gv-<sha256(...)[:12]>`).
    GoalVersion {
        /// Path to `goal.json`.
        goal: PathBuf,
    },
    /// Change-driven version bump (ADR-0010): the release pointer, the
    /// marketplace catalog, a dated CHANGELOG section, and (with `--pack`)
    /// a component's own plugin/skill/doc stamps.
    BumpVersion {
        /// `patch`, `minor`, `major`, or an explicit `X.Y.Z`.
        spec: String,
        /// Also bump this pack component (repeatable).
        #[arg(long = "pack")]
        packs: Vec<String>,
        /// CHANGELOG date for the new section (`YYYY-MM-DD`). Defaults to
        /// today (UTC).
        #[arg(long)]
        date: Option<String>,
        /// Dry run: report what would change, write nothing.
        #[arg(long)]
        check: bool,
        /// Repo root. Defaults to the current directory.
        #[arg(long)]
        root: Option<PathBuf>,
    },
    /// Enforce ADR-0010's change-driven versioning invariants (the PR-only
    /// CI gate): a changed pack/core-skill must move its own version, and
    /// the release pointer must stay ahead of the last release tag.
    CheckVersionBump {
        /// The base ref to diff against. Defaults to `origin/main`.
        base: Option<String>,
        /// Repo root. Defaults to the current directory.
        #[arg(long)]
        root: Option<PathBuf>,
    },
    /// Project a MIF-L3 report's frontmatter + body into JSON and validate
    /// it against a schema (with `$ref` dependencies). Does not run
    /// citation-integrity — that stays a separate check until it is
    /// migrated in its own story.
    ProjectReport {
        /// Path to the report markdown file.
        report: PathBuf,
        /// Path to the schema to validate against.
        #[arg(long)]
        schema: PathBuf,
        /// A `$ref` dependency schema (repeatable). Each must declare its
        /// own `$id`.
        #[arg(long = "ref")]
        refs: Vec<PathBuf>,
        /// Write the projected JSON here.
        #[arg(long = "json-out")]
        json_out: Option<PathBuf>,
    },
    /// Set `.site.primarySurface` in the harness manifest.
    SiteTogglePrimary {
        /// `reports`, `docs`, or `auto`.
        value: String,
        /// Manifest path. Defaults to `harness.config.json`.
        #[arg(long)]
        config: Option<PathBuf>,
    },
    /// Set `.site.plugins.<name>` in the harness manifest.
    SiteTogglePlugin {
        /// `llmsTxt`, `mermaid`, `imageZoom`, or `linksValidator`.
        name: String,
        /// `on` or `off`.
        state: String,
        /// Manifest path. Defaults to `harness.config.json`.
        #[arg(long)]
        config: Option<PathBuf>,
    },
    /// Set `.packs[].enabled` for an already-declared pack.
    PackToggle {
        /// The pack's declared name.
        pack: String,
        /// `on` or `off`.
        state: String,
        /// Manifest path. Defaults to `harness.config.json`.
        #[arg(long)]
        config: Option<PathBuf>,
    },
    /// Compose and validate a MIF source-envelope from a raw ingested
    /// source.
    WrapSource {
        /// The source URL.
        #[arg(long)]
        url: String,
        /// The source's MIME content type.
        #[arg(long = "content-type")]
        content_type: String,
        /// The namespace the source belongs to.
        #[arg(long)]
        namespace: String,
        /// The source's slug.
        #[arg(long)]
        slug: String,
        /// Write the envelope here.
        #[arg(long)]
        out: PathBuf,
        /// The source's title. Defaults to `slug`. Accepts a value
        /// starting with `-`; the accepted trade-off is that an omitted
        /// value lets the next token be consumed as this one instead of
        /// erroring.
        #[arg(long, allow_hyphen_values = true)]
        title: Option<String>,
        /// Read content from this file.
        #[arg(long = "content-file")]
        content_file: Option<PathBuf>,
        /// Content given directly on the command line. Accepts a value
        /// starting with `-`; the accepted trade-off is that an omitted
        /// value lets the next token be consumed as this one instead of
        /// erroring.
        #[arg(long, allow_hyphen_values = true)]
        content: Option<String>,
        /// The provenance `sourceType`. Defaults to `agent_inferred`.
        #[arg(long = "source-type")]
        source_type: Option<String>,
        /// Path to `schemas/mif/source-envelope.schema.json`.
        #[arg(long)]
        schema: PathBuf,
        /// A `$ref` dependency schema (repeatable). Each must declare its
        /// own `$id`.
        #[arg(long = "ref")]
        refs: Vec<PathBuf>,
    },
    /// Build the MIF-native knowledge graph from a findings directory.
    BuildGraph {
        /// Directory of finding JSON files.
        findings_dir: PathBuf,
        /// Write the graph here. Defaults to `<findings-dir>/../knowledge-graph.json`.
        out: Option<PathBuf>,
    },
    /// Build the flat research index from a findings directory, folding in
    /// the goal-version membership mirror.
    BuildIndex {
        /// Directory of finding JSON files.
        findings_dir: PathBuf,
        /// Write the index here. Defaults to `<findings-dir>/../research-index.json`.
        out: Option<PathBuf>,
    },
    /// Resolve a goal version's deterministic scope over a topic's
    /// findings, writing the authoritative members file.
    ResolveMembership {
        /// The topic name (`reports/<topic>/`).
        topic: String,
        /// The goal version. Defaults to the content hash of
        /// `reports/<topic>/goal.json`.
        version: Option<String>,
        /// Repo root. Defaults to the current directory.
        #[arg(long)]
        root: Option<PathBuf>,
    },
    /// Print a knowledge-graph JSON file's node/edge counts as `NODES
    /// EDGES` (for build-graph-viz.sh's HTML header).
    GraphStats {
        /// Path to a `knowledge-graph.json` file.
        graph: PathBuf,
    },
    /// Render one typed Artifact to an output channel (`report`, `blog`,
    /// or `book`). Composition only — write-then-validate (`report`'s L3
    /// conformance check) stays the bash wrapper's job, via
    /// `mif-project.sh`.
    RenderArtifact {
        /// Path to the `artifact.json` file.
        artifact: PathBuf,
        /// `report`, `blog`, or `book`.
        channel: String,
        /// Write the rendered markdown here.
        out: PathBuf,
        /// The output file's slug (its basename, minus `.md`).
        #[arg(long)]
        slug: String,
        /// The output file's repo-root-relative path.
        #[arg(long)]
        slugpath: String,
        /// The RFC 3339 `created` timestamp.
        #[arg(long)]
        created: String,
        /// This revision's version number.
        #[arg(long)]
        version: u64,
        /// A `verification.json` falsification verdict to fold into the
        /// `report` channel's frontmatter.
        #[arg(long)]
        verification: Option<PathBuf>,
    },
    /// Synthesize an Artifact from a findings directory's surviving
    /// (non-falsified) findings.
    SynthesizeArtifact {
        /// Directory of finding JSON files.
        findings_dir: PathBuf,
        /// The artifact's genre. Defaults to `general`.
        genre: Option<String>,
        /// Write the artifact here. Defaults to `<findings-dir>/../artifact.json`.
        out: Option<PathBuf>,
    },
    /// Validate and import a corpus's findings into a topic, refusing
    /// anything that fails schema validation or lacks a provenance block.
    ImportCorpus {
        /// Directory of source finding JSON files to import.
        src_findings_dir: PathBuf,
        /// Destination findings directory.
        dest_dir: PathBuf,
        /// The topic id to register the corpus under.
        topic: String,
        /// Path to `schemas/findings.schema.json`.
        #[arg(long)]
        schema: PathBuf,
        /// A `$ref` dependency schema (repeatable). Each must declare its
        /// own `$id`.
        #[arg(long = "ref")]
        refs: Vec<PathBuf>,
        /// `harness.config.json`, to register the topic in.
        #[arg(long)]
        config: Option<PathBuf>,
    },
    /// Build the cross-topic concordance (the ontological spine) from
    /// every topic's findings.
    BuildConcordance {
        /// The reports root directory (each subdirectory with a
        /// `findings/` is a topic).
        reports_dir: PathBuf,
        /// Write the concordance here. Defaults to `<reports-dir>/concordance.json`.
        out: Option<PathBuf>,
    },
    /// Derive a durable session checkpoint (`state.json`) purely from
    /// disk and print the remaining-work plan.
    ReconcileSession {
        /// The topic's reports directory (`reports/<topic>`).
        topic_reports_dir: PathBuf,
        /// Path to `schemas/findings.schema.json`.
        #[arg(long)]
        schema: PathBuf,
        /// A `$ref` dependency schema (repeatable). Each must declare its
        /// own `$id`.
        #[arg(long = "ref")]
        refs: Vec<PathBuf>,
        /// A known-good sample finding, validated first as an
        /// environment sanity check.
        #[arg(long)]
        sample: PathBuf,
    },
    /// Compute a topic README's metadata rollup, emitted as
    /// `source`-able shell variable assignments.
    TopicMetadata {
        /// The registered topic id.
        topic: String,
        /// Path to `harness.config.json`.
        #[arg(long)]
        config: PathBuf,
        /// The topic's findings directory.
        #[arg(long)]
        findings: PathBuf,
        /// The topic's `goal.json` (treated as empty if missing/unreadable).
        #[arg(long)]
        goal: PathBuf,
    },
    /// Build the cross-topic corpus atlas (`corpus-map.json` +
    /// `corpus-synthesis.md`) from the concordance.
    SynthesizeCorpus {
        /// Path to `reports/concordance.json`.
        concordance: PathBuf,
        /// Write the corpus map here.
        map_out: PathBuf,
        /// Write the corpus synthesis markdown here.
        markdown_out: PathBuf,
        /// Previously authored "Cross-Corpus Insights" prose to preserve
        /// across rebuilds (omit to seed the draft marker). Accepts a
        /// value starting with `-` (e.g. an authored Markdown bullet); the
        /// accepted trade-off is that passing this flag with no value lets
        /// the next token be silently consumed as this one instead of
        /// erroring, so always pair `--preserved-insights` with a value.
        #[arg(long, allow_hyphen_values = true)]
        preserved_insights: Option<String>,
    },
    /// Prove a knowledge graph is MIF-derived (urn:mif: ids, typed
    /// relationships, referential integrity) rather than tag co-occurrence.
    AssertGraphMif {
        /// Path to the `knowledge-graph.json` to check.
        graph: PathBuf,
    },
    /// Citation-integrity gate: every finding has >=1 traceable citation
    /// with a role, no falsified finding ships, and no citation URL is
    /// listed dead.
    CheckCitationIntegrity {
        /// One or more findings files (a single finding object or an array).
        #[arg(required = true)]
        findings: Vec<PathBuf>,
        /// `harness.config.json`, read for the `features.internalCitations`
        /// opt-in (defaults to strict http(s)-only when omitted/unreadable).
        #[arg(long)]
        config: Option<PathBuf>,
    },
    /// Fail-closed pre-synthesis typing gate (ADR-0011): every shippable
    /// (survived/weakened) finding must resolve to a valid ontology type.
    CheckShippableTyping {
        /// The topic's reports directory (e.g. `reports/<topic>`).
        reports_dir: PathBuf,
    },
    /// Falsification gate substrate (SPEC §6b): assigns an ordinal verdict
    /// to a finding from an offline evidence fixture and writes it back,
    /// enforcing the one-round rule. Prints the updated finding JSON.
    Falsify {
        /// The finding file to grade.
        finding: PathBuf,
        /// The evidence fixture (JSON object keyed by finding `@id`); omit
        /// for a placeholder `inconclusive` verdict.
        fixture: Option<PathBuf>,
    },
    /// Corpus-wide relationship-target integrity gate: every
    /// `relationships[].target` in the active corpus must resolve to a
    /// real, active finding `@id`.
    CheckRelationshipTargets {
        /// The corpus-wide reports directory (spans every topic).
        #[arg(long)]
        reports_dir: PathBuf,
    },
    /// Fail-closed ontology conformance for the concordance (SPEC §8d):
    /// every node `entityType` and relationship edge type must be declared
    /// by an ontology bound to the node's topic(s), and every relationship
    /// edge's endpoints must satisfy its declared `from`/`to` domains.
    ValidateConcordance {
        /// Path to `concordance.json`.
        concordance: PathBuf,
        /// Path to `harness.config.json`.
        #[arg(long)]
        config: PathBuf,
        /// Path to the enabled-ontologies catalog (`.claude/enabled-packs.json`).
        #[arg(long)]
        catalog: PathBuf,
        /// The repo root each cataloged ontology's `source` path is
        /// relative to.
        #[arg(long)]
        root: PathBuf,
    },
    /// Whole-registry ontology reference integrity: every relationship
    /// `from`/`to` endpoint and every `subtype_of` parent, across every
    /// ontology in the registry, must name a declared entity type.
    CheckOntologyRegistry {
        /// The repo root (`schemas/ontologies/*/*.yaml` and
        /// `packs/ontologies/*/*.ontology.yaml` are scanned beneath it).
        #[arg(long)]
        root: PathBuf,
    },
}

/// This binary has no failure modes of its own beyond what [`mif_rh`]
/// already reports — every fallible operation below delegates straight to
/// `mif_rh::MifRhError`, so there is no separate CLI-local error enum to
/// keep in sync with it.
type CliError = mif_rh::MifRhError;

/// A subcommand's successful outcome: the message to print, and the exit
/// code to report — distinct from `Err`, since e.g. an invalid/unresolved
/// classification is still a successfully *produced* record, but must
/// still exit non-zero, matching rht's own bash exit-code contract.
#[derive(Debug)]
struct Outcome {
    message: String,
    exit_code: u8,
}

/// The stack size the real work runs on (see [`main`]'s doc comment for why).
const MAIN_STACK_SIZE: usize = 16 * 1024 * 1024;

fn main() -> ExitCode {
    // `HarnessCommand`'s clap-derive expansion has grown large enough (18+
    // subcommand variants) that building/parsing it overflows Windows'
    // small default main-thread stack (1 MiB, vs. 8 MiB on Linux/macOS) —
    // even for a trivial invocation like an unrecognized subcommand, which
    // never reaches any of this binary's own logic. Run the real work on a
    // thread with an explicit larger stack instead, matching the standard
    // Rust idiom for this exact class of Windows crash (e.g. rustc/cargo
    // do the same).
    let handle = match std::thread::Builder::new()
        .stack_size(MAIN_STACK_SIZE)
        .spawn(run_main)
    {
        Ok(handle) => handle,
        Err(source) => {
            eprintln!("mif-rh-cli: failed to spawn the main worker thread: {source}");
            return ExitCode::FAILURE;
        },
    };
    handle.join().unwrap_or_else(|_| {
        eprintln!("mif-rh-cli: main worker thread panicked");
        ExitCode::FAILURE
    })
}

fn run_main() -> ExitCode {
    let cli = Cli::parse();
    let format = OutputFormat::select(cli.format.as_deref(), std::io::stderr().is_terminal());
    match run(&cli.command) {
        Ok(outcome) => {
            println!("{}", outcome.message);
            ExitCode::from(outcome.exit_code)
        },
        Err(error) => {
            eprintln!("{}", error.render(format));
            ExitCode::from(error.to_problem().exit_code.unwrap_or(1))
        },
    }
}

fn run(command: &Command) -> Result<Outcome, CliError> {
    match command {
        Command::Resolve {
            finding,
            topic,
            catalog,
            config,
            map,
            root,
        } => resolve(
            finding,
            topic.as_deref(),
            catalog.as_deref(),
            config.as_deref(),
            map.as_deref(),
            root.as_deref(),
        ),
        Command::Review {
            topic,
            strict,
            reports_dir,
            config,
            catalog,
            followup,
            root,
            relationship_script,
            build_index,
            index,
            suggest,
            calibration,
        } => review(&ReviewArgs {
            topics: topic,
            strict: *strict,
            reports_dir: reports_dir.as_deref(),
            config: config.as_deref(),
            catalog: catalog.as_deref(),
            followup: followup.as_deref(),
            root: root.as_deref(),
            relationship_script: relationship_script.as_deref(),
            build_index: *build_index,
            index: index.as_deref(),
            suggest: *suggest,
            calibration: calibration.as_deref(),
        }),
        Command::SuggestType {
            text,
            finding,
            topic,
            catalog,
            config,
            root,
            limit,
            calibration,
            record,
            index,
        } => suggest_type_cmd(&SuggestTypeArgs {
            text: text.as_deref(),
            finding: finding.as_deref(),
            topic: topic.as_deref(),
            catalog: catalog.as_deref(),
            config: config.as_deref(),
            root: root.as_deref(),
            limit: *limit,
            calibration: calibration.as_deref(),
            record: *record,
            index: index.as_deref(),
        }),
        Command::Calibrate {
            reports_dir,
            config,
            catalog,
            root,
            target_precision,
            tier2_target,
            sample,
            seed,
            out,
            confusions,
        } => calibrate_cmd(&CalibrateArgs {
            reports_dir: reports_dir.as_deref(),
            config: config.as_deref(),
            catalog: catalog.as_deref(),
            root: root.as_deref(),
            target_precision: *target_precision,
            tier2_target: *tier2_target,
            sample: *sample,
            seed: *seed,
            out: out.as_deref(),
            confusions: confusions.as_deref(),
        }),
        Command::ExpansionCandidates {
            index,
            calibration,
            out,
        } => expansion_candidates_cmd(index.as_deref(), calibration.as_deref(), out.as_deref()),
        Command::Ontology { action } => ontology_cmd(action),
        Command::Harness { action } => harness_cmd(action),
    }
}

/// Resolves an ontology-registry source override: an explicit `--source`
/// flag first, then the `MIF_ONTOLOGY_SOURCE` env var — `mif_rh::vendor`'s
/// own precedence (a `.ontologies.source` marker file, then the canonical
/// default) applies underneath when both are absent.
fn ontology_source_override(explicit: Option<&str>) -> Option<String> {
    explicit
        .map(str::to_string)
        .or_else(|| std::env::var(ONTOLOGY_SOURCE_ENV).ok())
}

fn ontology_cmd(action: &OntologyCommand) -> Result<Outcome, CliError> {
    match action {
        OntologyCommand::Fetch {
            ids,
            all_enabled,
            root,
            config,
            source,
            refresh,
        } => ontology_fetch_cmd(
            ids,
            *all_enabled,
            root.as_deref(),
            config.as_deref(),
            source.as_deref(),
            *refresh,
        ),
        OntologyCommand::Sync {
            root,
            config,
            catalog,
        } => ontology_sync_cmd(root.as_deref(), config.as_deref(), catalog.as_deref()),
        OntologyCommand::LockCheck { root, config } => {
            ontology_lock_check_cmd(root.as_deref(), config.as_deref())
        },
        OntologyCommand::SyncRegistry {
            root,
            config,
            catalog,
            source,
        } => ontology_sync_registry_cmd(
            root.as_deref(),
            config.as_deref(),
            catalog.as_deref(),
            source.as_deref(),
        ),
        OntologyCommand::Author {
            new_id,
            topic,
            from_clusters,
            out,
            reports_dir,
        } => ontology_author_cmd(
            new_id,
            topic.as_deref(),
            from_clusters.as_deref(),
            out.as_deref(),
            reports_dir.as_deref(),
        ),
        OntologyCommand::CheckPinSafety {
            ids,
            root,
            config,
            source,
            reports_dir,
        } => ontology_check_pin_safety_cmd(
            ids,
            root.as_deref(),
            config.as_deref(),
            source.as_deref(),
            reports_dir.as_deref(),
        ),
    }
}

fn ontology_fetch_cmd(
    ids: &[String],
    all_enabled: bool,
    root: Option<&Path>,
    config: Option<&Path>,
    source: Option<&str>,
    refresh: bool,
) -> Result<Outcome, CliError> {
    let root = effective_path(root, ".");
    let resolved_source =
        mif_rh::vendor::resolve_source(&root, ontology_source_override(source).as_deref());
    let fetch_ids = if all_enabled {
        let config_path = effective_path(config, DEFAULT_CONFIG);
        enabled_ontology_ids_from_file(&config_path)?
    } else {
        ids.to_vec()
    };
    if fetch_ids.is_empty() {
        return Ok(Outcome {
            message: "ontology fetch: nothing to fetch (no ids given and no enabled ontologies \
                      configured)"
                .to_string(),
            exit_code: 0,
        });
    }
    let report = mif_rh::vendor::fetch(&root, &resolved_source, &fetch_ids, refresh)?;
    let mut message = if report.vendored.is_empty() {
        if report.pinned_skipped.is_empty() {
            "ontology fetch: nothing to fetch (all requested layers are committed base layers \
             or already vendored)"
                .to_string()
        } else {
            "ontology fetch: nothing newly vendored (every requested layer is either already \
             vendored or held at its pinned version)"
                .to_string()
        }
    } else {
        let names: Vec<String> = report
            .vendored
            .iter()
            .map(|v| format!("{}@{}", v.id, v.version))
            .collect();
        format!(
            "ontology fetch: vendored {} ({}); lock updated at {}",
            report.vendored.len(),
            names.join(", "),
            root.join("ontologies.lock.json").display()
        )
    };
    // rht#270: never let a version-pin skip pass silently — every id left
    // at its pinned version because the registry has moved past it is
    // named here, so a `copier update` run surfaces the drift instead of
    // burying it in an otherwise-quiet success message.
    if !report.pinned_skipped.is_empty() {
        use std::fmt::Write as _;

        let drift: Vec<String> = report
            .pinned_skipped
            .iter()
            .map(|p| {
                format!(
                    "{} (pinned {}, registry has {})",
                    p.id, p.locked_version, p.registry_version
                )
            })
            .collect();
        let _ = write!(
            message,
            "\nWARNING: {} ontology pack{} left at the pinned version, not the registry's \
             current one: {}. Pass --refresh to advance deliberately.",
            report.pinned_skipped.len(),
            if report.pinned_skipped.len() == 1 {
                ""
            } else {
                "s"
            },
            drift.join(", ")
        );
    }
    Ok(Outcome {
        message,
        exit_code: 0,
    })
}

fn ontology_check_pin_safety_cmd(
    ids: &[String],
    root: Option<&Path>,
    config: Option<&Path>,
    source: Option<&str>,
    reports_dir: Option<&Path>,
) -> Result<Outcome, CliError> {
    if ids.is_empty() {
        return Ok(Outcome {
            message: "ontology check-pin-safety: no ids given".to_string(),
            exit_code: 0,
        });
    }
    let root = effective_path(root, ".");
    let reports_dir = effective_path(reports_dir, DEFAULT_REPORTS_DIR);
    let resolved_source =
        mif_rh::vendor::resolve_source(&root, ontology_source_override(source).as_deref());
    let config_path = effective_path(config, DEFAULT_CONFIG);
    let harness_config = mif_rh::HarnessConfig::load(&config_path)?;
    let topics: Vec<String> = harness_config.topics.iter().map(|t| t.id.clone()).collect();

    let reports = mif_rh::check_pin_safety(&root, &resolved_source, &reports_dir, &topics, ids)?;

    if reports.is_empty() {
        return Ok(Outcome {
            message: "ontology check-pin-safety: no drifted pinned ontologies among the \
                      requested ids"
                .to_string(),
            exit_code: 0,
        });
    }

    let mut lines = Vec::new();
    for report in &reports {
        if !report.analyzed {
            lines.push(format!(
                "{}: pinned {} -> registry {} (analysis skipped: the vendored pack is not on \
                 disk to diff against)",
                report.id, report.locked_version, report.registry_version
            ));
        } else if report.newly_required.is_empty() {
            lines.push(format!(
                "{}: pinned {} -> registry {} (nothing newly required)",
                report.id, report.locked_version, report.registry_version
            ));
        } else if report.gaps.is_empty() {
            let fields: Vec<String> = report
                .newly_required
                .iter()
                .map(|nrf| format!("{}.{}", nrf.entity_type, nrf.field))
                .collect();
            lines.push(format!(
                "{}: pinned {} -> registry {}, newly requires {} (no stamped finding affected)",
                report.id,
                report.locked_version,
                report.registry_version,
                fields.join(", ")
            ));
        } else {
            let gap_details: Vec<String> = report
                .gaps
                .iter()
                .map(|gap| {
                    format!(
                        "{}/{} ({} missing {})",
                        gap.topic, gap.finding_id, gap.entity_type, gap.field
                    )
                })
                .collect();
            // Distinct findings, not gap count: a single finding missing
            // multiple newly required fields produces multiple gaps, and
            // counting gaps would overstate how many findings are affected.
            // Keyed by (topic, finding_id), not finding_id alone: finding
            // ids are only scoped within their own topic, so the same id
            // in two different topics is two distinct findings, not one.
            let distinct_findings: std::collections::HashSet<(&str, &str)> = report
                .gaps
                .iter()
                .map(|gap| (gap.topic.as_str(), gap.finding_id.as_str()))
                .collect();
            lines.push(format!(
                "WARNING: {}: pinned {} -> registry {}, {} stamped finding{} missing a newly \
                 required field: {}",
                report.id,
                report.locked_version,
                report.registry_version,
                distinct_findings.len(),
                if distinct_findings.len() == 1 {
                    ""
                } else {
                    "s"
                },
                gap_details.join(", ")
            ));
        }
    }

    // Always exit 0, even on a WARNING line: this is an informational
    // report, matching `ontology fetch`'s own pinned-skipped warning
    // (`ontology_fetch_cmd`, above) — a CI job that wants a hard gate on a
    // breaking-change gap should check the message text (the "WARNING:"
    // prefix) rather than the exit code, since this command deliberately
    // never fails closed.
    Ok(Outcome {
        message: format!("ontology check-pin-safety:\n{}", lines.join("\n")),
        exit_code: 0,
    })
}

fn ontology_sync_cmd(
    root: Option<&Path>,
    config: Option<&Path>,
    catalog: Option<&Path>,
) -> Result<Outcome, CliError> {
    let root = effective_path(root, ".");
    let config_path = effective_path(config, DEFAULT_CONFIG);
    let catalog_path = effective_path(catalog, DEFAULT_CATALOG);
    let report = mif_rh::vendor::sync_catalog(&root, &config_path, &catalog_path)?;
    Ok(Outcome {
        message: format!(
            "ontology sync: cataloged {} ontolog{} -> {}",
            report.cataloged,
            if report.cataloged == 1 { "y" } else { "ies" },
            catalog_path.display()
        ),
        exit_code: 0,
    })
}

fn ontology_lock_check_cmd(
    root: Option<&Path>,
    config: Option<&Path>,
) -> Result<Outcome, CliError> {
    let root = effective_path(root, ".");
    let config_path = effective_path(config, DEFAULT_CONFIG);
    let report = mif_rh::vendor::lock_check(&root, &config_path)?;
    Ok(format_lock_check_outcome(&report))
}

fn ontology_sync_registry_cmd(
    root: Option<&Path>,
    config: Option<&Path>,
    catalog: Option<&Path>,
    source: Option<&str>,
) -> Result<Outcome, CliError> {
    let root = effective_path(root, ".");
    let config_path = effective_path(config, DEFAULT_CONFIG);
    let catalog_path = effective_path(catalog, DEFAULT_CATALOG);
    let resolved_source =
        mif_rh::vendor::resolve_source(&root, ontology_source_override(source).as_deref());
    let report =
        mif_rh::vendor::sync_registry(&root, &config_path, &catalog_path, &resolved_source)?;
    let message = if report.discovered.is_empty() {
        "ontology sync-registry: no new ontologies in the registry".to_string()
    } else {
        format!(
            "ontology sync-registry: discovered and enabled {} new ontology(ies): {}",
            report.discovered.len(),
            report.discovered.join(", ")
        )
    };
    Ok(Outcome {
        message,
        exit_code: 0,
    })
}

/// The subset of `mif-rh-cli ontology expansion-candidates --out` output
/// `ontology author --from-clusters` reads (ignores `misses_considered`/
/// `expansion`, which are diagnostic, not drafting input).
#[derive(serde::Deserialize)]
struct ExpansionCandidatesFile {
    clusters: Vec<mif_rh::ExpansionCandidate>,
}

fn ontology_author_cmd(
    new_id: &str,
    topic: Option<&str>,
    from_clusters: Option<&Path>,
    out: Option<&Path>,
    reports_dir: Option<&Path>,
) -> Result<Outcome, CliError> {
    let report = if let Some(clusters_path) = from_clusters {
        let contents =
            std::fs::read_to_string(clusters_path).map_err(|source| mif_rh::MifRhError::Io {
                path: clusters_path.display().to_string(),
                source,
            })?;
        let file: ExpansionCandidatesFile =
            serde_json::from_str(&contents).map_err(|source| mif_rh::MifRhError::Json {
                path: clusters_path.display().to_string(),
                source,
            })?;
        let source_name = clusters_path.file_name().map_or_else(
            || clusters_path.display().to_string(),
            |name| name.to_string_lossy().to_string(),
        );
        mif_rh::draft_from_clusters(&file.clusters, new_id, &source_name)?
    } else {
        // clap's `required_unless_present` guarantees `topic` is present.
        let topic = topic.unwrap_or_default();
        let reports_dir = effective_path(reports_dir, DEFAULT_REPORTS_DIR);
        let map_path = reports_dir.join(topic).join("ontology-map.json");
        let contents =
            std::fs::read_to_string(&map_path).map_err(|source| mif_rh::MifRhError::Io {
                path: map_path.display().to_string(),
                source,
            })?;
        let records: Vec<mif_rh::MapRecord> =
            serde_json::from_str(&contents).map_err(|source| mif_rh::MifRhError::Json {
                path: map_path.display().to_string(),
                source,
            })?;
        mif_rh::draft_from_topic(&records, new_id, topic)?
    };

    let out_path = out.map_or_else(
        || std::env::temp_dir().join(format!("{new_id}.ontology.yaml")),
        Path::to_path_buf,
    );
    std::fs::write(&out_path, &report.yaml).map_err(|source| mif_rh::MifRhError::Io {
        path: out_path.display().to_string(),
        source,
    })?;

    Ok(Outcome {
        message: format!(
            "ontology author: drafted '{new_id}' with {} candidate type(s) -> {}",
            report.type_count,
            out_path.display()
        ),
        exit_code: 0,
    })
}

// One arm per subcommand variant, each a thin dispatch call — length is
// inherent to the variant count, not a complexity signal.
#[allow(clippy::too_many_lines)]
fn harness_cmd(action: &HarnessCommand) -> Result<Outcome, CliError> {
    match action {
        HarnessCommand::GoalVersion { goal } => harness_goal_version_cmd(goal),
        HarnessCommand::BumpVersion {
            spec,
            packs,
            date,
            check,
            root,
        } => harness_bump_version_cmd(spec, packs, date.as_deref(), *check, root.as_deref()),
        HarnessCommand::CheckVersionBump { base, root } => {
            harness_check_version_bump_cmd(base.as_deref(), root.as_deref())
        },
        HarnessCommand::ProjectReport {
            report,
            schema,
            refs,
            json_out,
        } => harness_project_report_cmd(report, schema, refs, json_out.as_deref()),
        HarnessCommand::SiteTogglePrimary { value, config } => {
            harness_site_toggle_primary_cmd(value, config.as_deref())
        },
        HarnessCommand::SiteTogglePlugin {
            name,
            state,
            config,
        } => harness_site_toggle_plugin_cmd(name, state, config.as_deref()),
        HarnessCommand::PackToggle {
            pack,
            state,
            config,
        } => harness_pack_toggle_cmd(pack, state, config.as_deref()),
        HarnessCommand::WrapSource {
            url,
            content_type,
            namespace,
            slug,
            out,
            title,
            content_file,
            content,
            source_type,
            schema,
            refs,
        } => harness_wrap_source_cmd(&WrapSourceArgs {
            url,
            content_type,
            namespace,
            slug,
            out,
            title: title.as_deref(),
            content_file: content_file.as_deref(),
            content: content.as_deref(),
            source_type: source_type.as_deref(),
            schema,
            refs,
        }),
        HarnessCommand::BuildGraph { findings_dir, out } => {
            harness_build_graph_cmd(findings_dir, out.as_deref())
        },
        HarnessCommand::BuildIndex { findings_dir, out } => {
            harness_build_index_cmd(findings_dir, out.as_deref())
        },
        HarnessCommand::ResolveMembership {
            topic,
            version,
            root,
        } => harness_resolve_membership_cmd(topic, version.as_deref(), root.as_deref()),
        HarnessCommand::GraphStats { graph } => harness_graph_stats_cmd(graph),
        HarnessCommand::RenderArtifact {
            artifact,
            channel,
            out,
            slug,
            slugpath,
            created,
            version,
            verification,
        } => harness_render_artifact_cmd(&RenderArtifactArgs {
            artifact,
            channel,
            out,
            slug,
            slugpath,
            created,
            version: *version,
            verification: verification.as_deref(),
        }),
        HarnessCommand::SynthesizeArtifact {
            findings_dir,
            genre,
            out,
        } => harness_synthesize_artifact_cmd(findings_dir, genre.as_deref(), out.as_deref()),
        HarnessCommand::ImportCorpus {
            src_findings_dir,
            dest_dir,
            topic,
            schema,
            refs,
            config,
        } => harness_import_corpus_cmd(&ImportCorpusArgs {
            src_findings_dir,
            dest_dir,
            topic,
            schema,
            refs,
            config: config.as_deref(),
        }),
        HarnessCommand::BuildConcordance { reports_dir, out } => {
            harness_build_concordance_cmd(reports_dir, out.as_deref())
        },
        HarnessCommand::ReconcileSession {
            topic_reports_dir,
            schema,
            refs,
            sample,
        } => harness_reconcile_session_cmd(topic_reports_dir, schema, refs, sample),
        HarnessCommand::TopicMetadata {
            topic,
            config,
            findings,
            goal,
        } => harness_topic_metadata_cmd(topic, config, findings, goal),
        HarnessCommand::SynthesizeCorpus {
            concordance,
            map_out,
            markdown_out,
            preserved_insights,
        } => harness_synthesize_corpus_cmd(
            concordance,
            map_out,
            markdown_out,
            preserved_insights.as_deref(),
        ),
        HarnessCommand::AssertGraphMif { graph } => harness_assert_graph_mif_cmd(graph),
        HarnessCommand::CheckCitationIntegrity { findings, config } => Ok(
            harness_check_citation_integrity_cmd(findings, config.as_deref()),
        ),
        HarnessCommand::CheckShippableTyping { reports_dir } => {
            harness_check_shippable_typing_cmd(reports_dir)
        },
        HarnessCommand::Falsify { finding, fixture } => {
            harness_falsify_cmd(finding, fixture.as_deref())
        },
        HarnessCommand::CheckRelationshipTargets { reports_dir } => {
            harness_check_relationship_targets_cmd(reports_dir)
        },
        HarnessCommand::ValidateConcordance {
            concordance,
            config,
            catalog,
            root,
        } => harness_validate_concordance_cmd(concordance, config, catalog, root),
        HarnessCommand::CheckOntologyRegistry { root } => {
            Ok(harness_check_ontology_registry_cmd(root))
        },
    }
}

fn harness_assert_graph_mif_cmd(graph_path: &Path) -> Result<Outcome, CliError> {
    let assertion = mif_rh::assert_graph_mif_file(graph_path)?;
    let mut lines: Vec<String> = assertion
        .checks
        .iter()
        .map(|c| {
            if c.passed {
                format!("  graph: ok — {}", c.message)
            } else {
                format!("  graph: FAIL — {}", c.message)
            }
        })
        .collect();
    lines.push(if assertion.passed {
        "assert-graph: PASS".to_string()
    } else {
        "assert-graph: FAIL".to_string()
    });
    Ok(Outcome {
        message: lines.join("\n"),
        exit_code: u8::from(!assertion.passed),
    })
}

fn harness_check_citation_integrity_cmd(findings: &[PathBuf], config: Option<&Path>) -> Outcome {
    let report = mif_rh::check_citation_integrity(findings, config);
    let mut lines = report.violations.clone();
    if report.ok() {
        lines.push(format!(
            "citation-integrity: PASS ({} file(s))",
            report.files_checked
        ));
    } else {
        lines.push(format!(
            "citation-integrity: FAIL ({} violation(s))",
            report.violations.len()
        ));
    }
    Outcome {
        message: lines.join("\n"),
        exit_code: u8::from(!report.ok()),
    }
}

fn harness_check_shippable_typing_cmd(reports_dir: &Path) -> Result<Outcome, CliError> {
    let report = mif_rh::check_shippable_typing(reports_dir)?;
    let topic = reports_dir
        .file_name()
        .and_then(|name| name.to_str())
        .unwrap_or_default();
    let message = if report.ok() {
        "check-shippable-typing: all shippable findings carry a valid ontology type — ok"
            .to_string()
    } else {
        let mut lines = vec![format!(
            "check-shippable-typing: {} shippable finding(s) lack a valid ontology type — \
             synthesis BLOCKED (fail closed):",
            report.blockers.len()
        )];
        lines.extend(report.blockers.iter().cloned());
        lines.push(format!(
            "check-shippable-typing: unblock with  /ontology-review --topic {topic} --enrich  \
             then  /resume --topic {topic}"
        ));
        lines.join("\n")
    };
    Ok(Outcome {
        message,
        exit_code: u8::from(!report.ok()),
    })
}

fn harness_falsify_cmd(
    finding_path: &Path,
    fixture_path: Option<&Path>,
) -> Result<Outcome, CliError> {
    let result = mif_rh::falsify(finding_path, fixture_path)?;
    // The log line is a direct stderr side effect, not part of the Outcome:
    // callers redirect stdout (the finding JSON) and stderr (this line) to
    // separate destinations and assert on each independently.
    eprintln!("{}", result.log_line);
    let json_text = serde_json::to_string_pretty(&result.finding).map_err(|source| {
        mif_rh::MifRhError::JsonSerialize {
            path: finding_path.display().to_string(),
            source,
        }
    })?;
    Ok(Outcome {
        message: json_text,
        exit_code: 0,
    })
}

fn harness_validate_concordance_cmd(
    concordance_path: &Path,
    config_path: &Path,
    catalog_path: &Path,
    root: &Path,
) -> Result<Outcome, CliError> {
    let contents =
        std::fs::read_to_string(concordance_path).map_err(|source| mif_rh::MifRhError::Io {
            path: concordance_path.display().to_string(),
            source,
        })?;
    let concordance: serde_json::Value =
        serde_json::from_str(&contents).map_err(|source| mif_rh::MifRhError::Json {
            path: concordance_path.display().to_string(),
            source,
        })?;
    let catalog = mif_rh::Catalog::load(catalog_path)?;
    let config = mif_rh::HarnessConfig::load(config_path)?;

    let result = mif_rh::validate_concordance(&concordance, &config, &catalog, root)?;
    let message = if result.ok() {
        format!(
            "validate-concordance: conformant ({} nodes, {} edges)",
            result.nodes, result.edges
        )
    } else {
        let mut lines = result.violations.clone();
        lines.push(format!(
            "validate-concordance: {} conformance violation(s) — fail",
            result.violations.len()
        ));
        if result
            .violations
            .iter()
            .any(|v| v.contains("/ontology-review"))
        {
            lines.push(
                "validate-concordance: bind/enrich the named topic(s) with /ontology-review \
                 --topic <id> --enrich, then rebuild."
                    .to_string(),
            );
        }
        lines.join("\n")
    };
    Ok(Outcome {
        message,
        exit_code: u8::from(!result.ok()),
    })
}

fn harness_check_ontology_registry_cmd(root: &Path) -> Outcome {
    let result = mif_rh::validate_ontology_registry(root);
    let render = |orphans: &[String]| {
        if orphans.is_empty() {
            "none".to_string()
        } else {
            orphans.join(" ")
        }
    };
    let message = format!(
        "ontology-registry: {} type(s) across the registry\n\
         ontology-registry: relationship-endpoint orphans: {}\n\
         ontology-registry: subtype_of-parent orphans: {}",
        result.registry_type_count,
        render(&result.relationship_endpoint_orphans),
        render(&result.subtype_of_orphans),
    );
    Outcome {
        message,
        exit_code: u8::from(!result.ok()),
    }
}

fn harness_check_relationship_targets_cmd(reports_dir: &Path) -> Result<Outcome, CliError> {
    let report = mif_rh::check_relationship_targets(reports_dir)?;
    let message = if report.ok() {
        format!(
            "check-relationship-targets: ok ({} relationship target(s) checked across {} \
             active finding(s), 0 orphans)",
            report.checked, report.active_findings
        )
    } else {
        let mut lines: Vec<String> = report
            .orphans
            .iter()
            .map(|o| format!("ORPHAN\t{}\t{}", o.source_file, o.target))
            .collect();
        lines.push(
            "check-relationship-targets: one or more relationships[].target values do not \
             resolve to any active finding @id (see ORPHAN lines above)"
                .to_string(),
        );
        lines.join("\n")
    };
    Ok(Outcome {
        message,
        exit_code: u8::from(!report.ok()),
    })
}

fn harness_goal_version_cmd(goal_path: &Path) -> Result<Outcome, CliError> {
    let contents = std::fs::read_to_string(goal_path).map_err(|source| mif_rh::MifRhError::Io {
        path: goal_path.display().to_string(),
        source,
    })?;
    let goal: serde_json::Value =
        serde_json::from_str(&contents).map_err(|source| mif_rh::MifRhError::Json {
            path: goal_path.display().to_string(),
            source,
        })?;
    Ok(Outcome {
        message: mif_rh::goal_version_id(&goal),
        exit_code: 0,
    })
}

fn harness_bump_version_cmd(
    spec: &str,
    packs: &[String],
    date: Option<&str>,
    check: bool,
    root: Option<&Path>,
) -> Result<Outcome, CliError> {
    let root = effective_path(root, ".");
    let report = mif_rh::bump_version(&mif_rh::BumpOptions {
        root: &root,
        spec,
        packs,
        date,
        check,
    })?;
    let message = if report.applied {
        format!(
            "bump-version: {} -> {} (date {}){}",
            report.old_version,
            report.new_version,
            report.date,
            if report.packs.is_empty() {
                String::new()
            } else {
                format!("; packs: {}", report.packs.join(", "))
            }
        )
    } else {
        format!(
            "bump-version: --check, {} -> {} (date {}) — no files written",
            report.old_version, report.new_version, report.date
        )
    };
    Ok(Outcome {
        message,
        exit_code: 0,
    })
}

fn harness_check_version_bump_cmd(
    base: Option<&str>,
    root: Option<&Path>,
) -> Result<Outcome, CliError> {
    let root = effective_path(root, ".");
    let base = base.unwrap_or("origin/main");
    let report = mif_rh::check_version_bump(&root, base)?;

    let mut lines: Vec<String> = report
        .failures
        .iter()
        .map(|failure| match failure {
            mif_rh::VersionGateFailure::PackNotBumped { pack, version } => format!(
                "FAIL: {pack} changed but its plugin.json .version stayed at {version} — bump it"
            ),
            mif_rh::VersionGateFailure::SkillNotBumped { skill, version } => format!(
                "FAIL: {skill} changed but its SKILL.md version stayed at {version} — bump it"
            ),
            mif_rh::VersionGateFailure::PointerNotAhead {
                current,
                last_release,
            } => format!(
                "FAIL: harness.config.json .version ({current}) is not ahead of the last \
                 release (v{last_release}) — someone needs to bump it before the next release"
            ),
            mif_rh::VersionGateFailure::PointerMissing => {
                "FAIL: harness.config.json has no .version".to_string()
            },
        })
        .collect();
    if lines.is_empty() {
        lines.push(format!(
            "check-version-bump: changed components moved their own version, and the release \
             pointer ({}) is ahead of the last release",
            report.pointer_at_head.as_deref().unwrap_or("-")
        ));
    }
    Ok(Outcome {
        message: lines.join("\n"),
        exit_code: u8::from(!report.failures.is_empty()),
    })
}

fn harness_project_report_cmd(
    report: &Path,
    schema: &Path,
    refs: &[PathBuf],
    json_out: Option<&Path>,
) -> Result<Outcome, CliError> {
    let projected = mif_rh::project_report(report, schema, refs)?;
    if let Some(out_path) = json_out {
        let text = serde_json::to_string_pretty(&projected).map_err(|source| {
            mif_rh::MifRhError::JsonSerialize {
                path: out_path.display().to_string(),
                source,
            }
        })?;
        std::fs::write(out_path, format!("{text}\n")).map_err(|source| mif_rh::MifRhError::Io {
            path: out_path.display().to_string(),
            source,
        })?;
    }
    Ok(Outcome {
        message: format!(
            "mif-project: {} projects to a valid MIF L3 finding",
            report.display()
        ),
        exit_code: 0,
    })
}

fn harness_site_toggle_primary_cmd(
    value: &str,
    config: Option<&Path>,
) -> Result<Outcome, CliError> {
    let config_path = effective_path(config, DEFAULT_CONFIG);
    mif_rh::site_toggle_primary(&config_path, value)?;
    Ok(Outcome {
        message: format!(
            "site-toggle: primarySurface -> {value} in {}",
            config_path.display()
        ),
        exit_code: 0,
    })
}

fn harness_site_toggle_plugin_cmd(
    name: &str,
    state: &str,
    config: Option<&Path>,
) -> Result<Outcome, CliError> {
    let enabled = parse_on_off("site-toggle", state)?;
    let config_path = effective_path(config, DEFAULT_CONFIG);
    mif_rh::site_toggle_plugin(&config_path, name, enabled)?;
    Ok(Outcome {
        message: format!(
            "site-toggle: plugin {name} -> enabled={enabled} in {}",
            config_path.display()
        ),
        exit_code: 0,
    })
}

fn harness_pack_toggle_cmd(
    pack: &str,
    state: &str,
    config: Option<&Path>,
) -> Result<Outcome, CliError> {
    let enabled = parse_on_off("pack-toggle", state)?;
    let config_path = effective_path(config, DEFAULT_CONFIG);
    mif_rh::pack_toggle(&config_path, pack, enabled)?;
    Ok(Outcome {
        message: format!(
            "pack-toggle: {pack} -> enabled={enabled} in {}",
            config_path.display()
        ),
        exit_code: 0,
    })
}

/// Parses a bash-style `on|off` toggle state, reporting `caller` in the
/// error message so `site-toggle`/`pack-toggle` each name themselves.
fn parse_on_off(caller: &str, state: &str) -> Result<bool, CliError> {
    match state {
        "on" => Ok(true),
        "off" => Ok(false),
        other => Err(mif_rh::MifRhError::InvalidToggleValue {
            field: format!("{caller} state"),
            value: other.to_string(),
            allowed: "on|off".to_string(),
        }),
    }
}

/// Bundles [`HarnessCommand::WrapSource`]'s fields for
/// [`harness_wrap_source_cmd`] to stay under this workspace's
/// too-many-arguments threshold.
struct WrapSourceArgs<'a> {
    url: &'a str,
    content_type: &'a str,
    namespace: &'a str,
    slug: &'a str,
    out: &'a Path,
    title: Option<&'a str>,
    content_file: Option<&'a Path>,
    content: Option<&'a str>,
    source_type: Option<&'a str>,
    schema: &'a Path,
    refs: &'a [PathBuf],
}

fn harness_wrap_source_cmd(args: &WrapSourceArgs<'_>) -> Result<Outcome, CliError> {
    let content_text =
        mif_rh::read_source_content(args.content_file, args.content.unwrap_or_default())?;
    let created = chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string();
    let envelope = mif_rh::wrap_source(
        &mif_rh::WrapSourceInputs {
            url: args.url,
            content_type: args.content_type,
            namespace: args.namespace,
            slug: args.slug,
            title: args.title.unwrap_or_default(),
            content: &content_text,
            source_type: args.source_type.unwrap_or_default(),
            created: &created,
        },
        args.schema,
        args.refs,
    )?;

    if let Some(parent) = args.out.parent() {
        std::fs::create_dir_all(parent).map_err(|source| mif_rh::MifRhError::Io {
            path: parent.display().to_string(),
            source,
        })?;
    }
    let text = serde_json::to_string_pretty(&envelope).map_err(|source| {
        mif_rh::MifRhError::JsonSerialize {
            path: args.out.display().to_string(),
            source,
        }
    })?;
    std::fs::write(args.out, format!("{text}\n")).map_err(|source| mif_rh::MifRhError::Io {
        path: args.out.display().to_string(),
        source,
    })?;

    Ok(Outcome {
        message: format!(
            "wrap-source: wrote {} (urn:mif:source:{}:{}, {})",
            args.out.display(),
            args.namespace,
            args.slug,
            args.content_type
        ),
        exit_code: 0,
    })
}

fn harness_build_graph_cmd(findings_dir: &Path, out: Option<&Path>) -> Result<Outcome, CliError> {
    let out_path = out.map_or_else(
        || findings_dir.join("../knowledge-graph.json"),
        Path::to_path_buf,
    );
    let graph = mif_rh::build_graph(findings_dir)?;
    let node_count = graph["nodes"].as_array().map_or(0, Vec::len);
    let edge_count = graph["edges"].as_array().map_or(0, Vec::len);
    let text = serde_json::to_string_pretty(&graph).map_err(|source| {
        mif_rh::MifRhError::JsonSerialize {
            path: out_path.display().to_string(),
            source,
        }
    })?;
    std::fs::write(&out_path, format!("{text}\n")).map_err(|source| mif_rh::MifRhError::Io {
        path: out_path.display().to_string(),
        source,
    })?;
    Ok(Outcome {
        message: format!(
            "build-graph: wrote {} ({node_count} nodes, {edge_count} edges)",
            out_path.display()
        ),
        exit_code: 0,
    })
}

fn harness_build_index_cmd(findings_dir: &Path, out: Option<&Path>) -> Result<Outcome, CliError> {
    let out_path = out.map_or_else(
        || findings_dir.join("../research-index.json"),
        Path::to_path_buf,
    );
    let index = mif_rh::build_index(findings_dir)?;
    let count = index["count"].as_u64().unwrap_or(0);
    let text = serde_json::to_string_pretty(&index).map_err(|source| {
        mif_rh::MifRhError::JsonSerialize {
            path: out_path.display().to_string(),
            source,
        }
    })?;
    std::fs::write(&out_path, format!("{text}\n")).map_err(|source| mif_rh::MifRhError::Io {
        path: out_path.display().to_string(),
        source,
    })?;
    Ok(Outcome {
        message: format!(
            "build-index: wrote {} ({count} findings)",
            out_path.display()
        ),
        exit_code: 0,
    })
}

fn harness_resolve_membership_cmd(
    topic: &str,
    version: Option<&str>,
    root: Option<&Path>,
) -> Result<Outcome, CliError> {
    let root = effective_path(root, ".");
    let topic_dir = root.join("reports").join(topic);
    let config_path = root.join(DEFAULT_CONFIG);

    let version = if let Some(v) = version {
        v.to_string()
    } else {
        let goal_path = topic_dir.join("goal.json");
        let contents =
            std::fs::read_to_string(&goal_path).map_err(|source| mif_rh::MifRhError::Io {
                path: goal_path.display().to_string(),
                source,
            })?;
        let goal: serde_json::Value =
            serde_json::from_str(&contents).map_err(|source| mif_rh::MifRhError::Json {
                path: goal_path.display().to_string(),
                source,
            })?;
        mif_rh::goal_version_id(&goal)
    };
    let generated = chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string();
    let report = mif_rh::resolve_membership(
        &topic_dir,
        &config_path,
        &version,
        &generated,
        chrono::Utc::now(),
    )?;

    let members = report.members_file["members"]
        .as_array()
        .map_or(0, Vec::len);
    let stale = report.members_file["stale"].as_array().map_or(0, Vec::len);
    let excluded = report.members_file["excluded"]
        .as_array()
        .map_or(0, Vec::len);
    let gaps: Vec<&str> = report.members_file["gap_dimensions"]
        .as_array()
        .into_iter()
        .flatten()
        .filter_map(|v| v.as_str())
        .collect();
    let gaps_display = if gaps.is_empty() {
        "none".to_string()
    } else {
        gaps.join(", ")
    };

    Ok(Outcome {
        message: format!(
            "wrote {}\n  members: {members} | stale: {stale} | excluded: {excluded} | gap_dimensions: {gaps_display}",
            report.out_path.display()
        ),
        exit_code: 0,
    })
}

fn harness_graph_stats_cmd(graph: &Path) -> Result<Outcome, CliError> {
    let contents = std::fs::read_to_string(graph).map_err(|source| mif_rh::MifRhError::Io {
        path: graph.display().to_string(),
        source,
    })?;
    let value: serde_json::Value =
        serde_json::from_str(&contents).map_err(|source| mif_rh::MifRhError::Json {
            path: graph.display().to_string(),
            source,
        })?;
    let nodes = value["nodes"].as_array().map_or(0, Vec::len);
    let edges = value["edges"].as_array().map_or(0, Vec::len);
    Ok(Outcome {
        message: format!("{nodes} {edges}"),
        exit_code: 0,
    })
}

/// Bundles [`HarnessCommand::RenderArtifact`]'s fields for
/// [`harness_render_artifact_cmd`] to stay under this workspace's
/// too-many-arguments threshold.
struct RenderArtifactArgs<'a> {
    artifact: &'a Path,
    channel: &'a str,
    out: &'a Path,
    slug: &'a str,
    slugpath: &'a str,
    created: &'a str,
    version: u64,
    verification: Option<&'a Path>,
}

fn harness_render_artifact_cmd(args: &RenderArtifactArgs<'_>) -> Result<Outcome, CliError> {
    let contents =
        std::fs::read_to_string(args.artifact).map_err(|source| mif_rh::MifRhError::Io {
            path: args.artifact.display().to_string(),
            source,
        })?;
    let artifact: serde_json::Value =
        serde_json::from_str(&contents).map_err(|source| mif_rh::MifRhError::Json {
            path: args.artifact.display().to_string(),
            source,
        })?;

    let verification = args
        .verification
        .map(|path| {
            let text = std::fs::read_to_string(path).map_err(|source| mif_rh::MifRhError::Io {
                path: path.display().to_string(),
                source,
            })?;
            serde_json::from_str::<serde_json::Value>(&text).map_err(|source| {
                mif_rh::MifRhError::Json {
                    path: path.display().to_string(),
                    source,
                }
            })
        })
        .transpose()?;

    let rendered = mif_rh::render_artifact(
        &mif_rh::RenderInputs {
            artifact: &artifact,
            slug: args.slug,
            slugpath: args.slugpath,
            created: args.created,
            version: args.version,
            verification: verification.as_ref(),
        },
        args.channel,
    )?;

    if let Some(parent) = args.out.parent() {
        std::fs::create_dir_all(parent).map_err(|source| mif_rh::MifRhError::Io {
            path: parent.display().to_string(),
            source,
        })?;
    }
    std::fs::write(args.out, &rendered).map_err(|source| mif_rh::MifRhError::Io {
        path: args.out.display().to_string(),
        source,
    })?;

    let line_count = rendered.lines().count();
    Ok(Outcome {
        message: format!(
            "render: wrote {} ({}, {line_count} lines) from {}",
            args.out.display(),
            args.channel,
            args.artifact.display()
        ),
        exit_code: 0,
    })
}

fn harness_synthesize_artifact_cmd(
    findings_dir: &Path,
    genre: Option<&str>,
    out: Option<&Path>,
) -> Result<Outcome, CliError> {
    let genre = genre.unwrap_or("general");
    let out_path = out.map_or_else(|| findings_dir.join("../artifact.json"), Path::to_path_buf);
    let artifact = mif_rh::synthesize_artifact(findings_dir, genre)?;
    let section_count = artifact["sections"].as_array().map_or(0, Vec::len);
    let source_count = artifact["sources"].as_array().map_or(0, Vec::len);
    let text = serde_json::to_string_pretty(&artifact).map_err(|source| {
        mif_rh::MifRhError::JsonSerialize {
            path: out_path.display().to_string(),
            source,
        }
    })?;
    std::fs::write(&out_path, format!("{text}\n")).map_err(|source| mif_rh::MifRhError::Io {
        path: out_path.display().to_string(),
        source,
    })?;
    Ok(Outcome {
        message: format!(
            "synthesize: wrote {} (genre={genre}, {section_count} sections, {source_count} sources)",
            out_path.display()
        ),
        exit_code: 0,
    })
}

/// Bundles [`HarnessCommand::ImportCorpus`]'s fields for
/// [`harness_import_corpus_cmd`] to stay under this workspace's
/// too-many-arguments threshold.
struct ImportCorpusArgs<'a> {
    src_findings_dir: &'a Path,
    dest_dir: &'a Path,
    topic: &'a str,
    schema: &'a Path,
    refs: &'a [PathBuf],
    config: Option<&'a Path>,
}

fn harness_import_corpus_cmd(args: &ImportCorpusArgs<'_>) -> Result<Outcome, CliError> {
    let report = mif_rh::import_corpus(
        args.src_findings_dir,
        args.dest_dir,
        args.topic,
        args.config,
        args.schema,
        args.refs,
    )?;
    let mut message = format!(
        "import: imported {} finding(s) into {} (namespace {})",
        report.imported,
        args.dest_dir.display(),
        report.namespace
    );
    if report.topic_registered {
        use std::fmt::Write as _;
        let _ = write!(message, "; registered topic '{}'", args.topic);
    }
    Ok(Outcome {
        message,
        exit_code: 0,
    })
}

fn harness_build_concordance_cmd(
    reports_dir: &Path,
    out: Option<&Path>,
) -> Result<Outcome, CliError> {
    let out_path = out.map_or_else(|| reports_dir.join("concordance.json"), Path::to_path_buf);
    let concordance = mif_rh::build_concordance(reports_dir)?;
    let node_count = concordance["nodes"].as_array().map_or(0, Vec::len);
    let edge_count = concordance["edges"].as_array().map_or(0, Vec::len);
    let text = serde_json::to_string_pretty(&concordance).map_err(|source| {
        mif_rh::MifRhError::JsonSerialize {
            path: out_path.display().to_string(),
            source,
        }
    })?;
    std::fs::write(&out_path, format!("{text}\n")).map_err(|source| mif_rh::MifRhError::Io {
        path: out_path.display().to_string(),
        source,
    })?;
    Ok(Outcome {
        message: format!(
            "build-concordance: wrote {} ({node_count} nodes, {edge_count} edges) across topics",
            out_path.display()
        ),
        exit_code: 0,
    })
}

fn harness_reconcile_session_cmd(
    topic_reports_dir: &Path,
    schema: &Path,
    refs: &[PathBuf],
    sample: &Path,
) -> Result<Outcome, CliError> {
    let report = mif_rh::reconcile_session(topic_reports_dir, schema, refs, sample)?;
    let message = if report.plan.is_empty() {
        "nothing to do".to_string()
    } else {
        format!("REMAINING WORK PLAN\n{}", report.plan.join("\n"))
    };
    Ok(Outcome {
        message,
        exit_code: 0,
    })
}

fn harness_topic_metadata_cmd(
    topic: &str,
    config: &Path,
    findings: &Path,
    goal: &Path,
) -> Result<Outcome, CliError> {
    let metadata = mif_rh::topic_metadata(topic, config, findings, goal)?;
    Ok(Outcome {
        message: metadata.to_shell_script(),
        exit_code: 0,
    })
}

fn harness_synthesize_corpus_cmd(
    concordance: &Path,
    map_out: &Path,
    markdown_out: &Path,
    preserved_insights: Option<&str>,
) -> Result<Outcome, CliError> {
    let synthesis = mif_rh::synthesize_corpus(concordance, preserved_insights)?;
    let sorted_map = mif_rh::sort_object_keys(&synthesis.map);
    let map_text = serde_json::to_string_pretty(&sorted_map).map_err(|source| {
        mif_rh::MifRhError::JsonSerialize {
            path: map_out.display().to_string(),
            source,
        }
    })?;
    std::fs::write(map_out, format!("{map_text}\n")).map_err(|source| mif_rh::MifRhError::Io {
        path: map_out.display().to_string(),
        source,
    })?;
    std::fs::write(markdown_out, &synthesis.markdown).map_err(|source| mif_rh::MifRhError::Io {
        path: markdown_out.display().to_string(),
        source,
    })?;
    Ok(Outcome {
        message: format!(
            "synthesize-corpus: wrote {} and {} ({} topics, {} entities)",
            map_out.display(),
            markdown_out.display(),
            synthesis.topics,
            synthesis.entities
        ),
        exit_code: 0,
    })
}

/// Reads `harness.config.json`'s `.ontologies[]` directly (rather than
/// through [`mif_rh::HarnessConfig`], which deliberately only models
/// `topics[]`) to collect every enabled ontology id for `ontology fetch
/// --all-enabled`.
fn enabled_ontology_ids_from_file(config_path: &Path) -> Result<Vec<String>, CliError> {
    if !config_path.exists() {
        return Err(mif_rh::MifRhError::ConfigMissing {
            path: config_path.display().to_string(),
        });
    }
    let contents =
        std::fs::read_to_string(config_path).map_err(|source| mif_rh::MifRhError::Io {
            path: config_path.display().to_string(),
            source,
        })?;
    let config: serde_json::Value =
        serde_json::from_str(&contents).map_err(|source| mif_rh::MifRhError::Json {
            path: config_path.display().to_string(),
            source,
        })?;
    let ids = config
        .get("ontologies")
        .and_then(serde_json::Value::as_array)
        .map(|entries| {
            entries
                .iter()
                .filter(|entry| {
                    entry
                        .get("enabled")
                        .and_then(serde_json::Value::as_bool)
                        .unwrap_or(false)
                })
                .filter_map(|entry| entry.get("id").and_then(serde_json::Value::as_str))
                .map(str::to_string)
                .collect()
        })
        .unwrap_or_default();
    Ok(ids)
}

/// Formats `check-ontology-lock.sh`'s own per-issue lines plus a final
/// summary, matching its fail-closed exit-code contract (non-zero on any
/// missing pin, un-vendored ontology, or drift).
fn format_lock_check_outcome(report: &mif_rh::LockCheckReport) -> Outcome {
    let mut lines = Vec::new();
    for id in &report.missing_pins {
        lines.push(format!(
            "  MISSING PIN: '{id}' is enabled but absent from the lock — run `ontology fetch {id}`"
        ));
    }
    for id in &report.not_vendored {
        lines.push(format!(
            "  NOT VENDORED: enabled '{id}' is pinned but its file is absent — run `ontology \
             fetch {id}`"
        ));
    }
    for drift in &report.drift {
        lines.push(format!(
            "  DRIFT: '{}' sha256 {} != pinned {} — a vendored ontology was edited locally; \
             change it upstream and re-fetch",
            drift.id, drift.got, drift.pinned
        ));
    }
    if report.ok() {
        lines.push(format!(
            "check-ontology-lock: ok ({} vendored ontolog{} match the lock)",
            report.checked,
            if report.checked == 1 { "y" } else { "ies" }
        ));
    }
    Outcome {
        message: lines.join("\n"),
        exit_code: u8::from(!report.ok()),
    }
}

fn effective_path(given: Option<&Path>, default: &str) -> PathBuf {
    given.map_or_else(|| PathBuf::from(default), Path::to_path_buf)
}

/// Derives a finding's topic from its path (`reports/<topic>/...`), the
/// same convention `resolve-ontology.sh` uses when `--topic` is omitted.
fn topic_from_path(finding: &Path) -> Option<String> {
    let components: Vec<&str> = finding
        .components()
        .filter_map(|c| c.as_os_str().to_str())
        .collect();
    let index = components.iter().position(|c| *c == "reports")?;
    components.get(index + 1).map(|s| (*s).to_string())
}

fn resolve(
    finding_path: &Path,
    topic: Option<&str>,
    catalog: Option<&Path>,
    config: Option<&Path>,
    map: Option<&Path>,
    root: Option<&Path>,
) -> Result<Outcome, CliError> {
    let catalog_path = effective_path(catalog, DEFAULT_CATALOG);
    let config_path = effective_path(config, DEFAULT_CONFIG);
    let root = effective_path(root, ".");

    let topic = topic
        .map(str::to_string)
        .or_else(|| topic_from_path(finding_path))
        .unwrap_or_default();

    let finding = mif_rh::Finding::load(finding_path)?;
    let catalog = mif_rh::Catalog::load(&catalog_path)?;
    let config = mif_rh::HarnessConfig::load(&config_path)?;
    let ontology_packs = mif_rh::ontology_pack::load_packs_via_catalog(&catalog, &root)?;

    let ctx = mif_rh::ResolveContext {
        topic: &topic,
        catalog: &catalog,
        config: &config,
        ontology_packs: &ontology_packs,
    };
    let record = mif_rh::resolve_finding(&finding, &ctx)?;

    let map_path = map.map(Path::to_path_buf).or_else(|| {
        let topic_dir = PathBuf::from("reports").join(&topic);
        topic_dir
            .is_dir()
            .then(|| topic_dir.join("ontology-map.json"))
    });
    if let Some(map_path) = &map_path {
        upsert_map_record(map_path, &record)?;
    }

    // `record.valid` is already `true` for every `Discovery`/`Untyped`
    // record (see `discovery_classify`), so it alone captures "ok" — no
    // separate `Basis::Untyped` carve-out is needed.
    let message = format!(
        "{}: {} -> {} (valid={})",
        finding.id,
        record.basis.label(),
        record.resolved_ontology.as_deref().unwrap_or("-"),
        record.valid
    );
    Ok(Outcome {
        message,
        exit_code: u8::from(!record.valid),
    })
}

/// Upserts one record into a per-topic `ontology-map.json`, replacing any
/// existing record for the same `finding_id`, matching
/// `resolve-ontology.sh`'s own `record()` upsert semantics. A corrupt or
/// missing existing map resets to an empty one rather than blocking the
/// upsert.
fn upsert_map_record(
    map_path: &Path,
    record: &mif_rh::MapRecord,
) -> Result<(), mif_rh::MifRhError> {
    let mut records: Vec<mif_rh::MapRecord> = std::fs::read_to_string(map_path)
        .ok()
        .and_then(|contents| serde_json::from_str(&contents).ok())
        .unwrap_or_default();
    records.retain(|r| r.finding_id != record.finding_id);
    records.push(record.clone());
    records.sort_by(|a, b| a.finding_id.cmp(&b.finding_id));

    mif_rh::write_json_atomic(map_path, &records)
}

/// Arguments for the `suggest-type` subcommand, bundled to match the
/// `ReviewArgs` convention below.
struct SuggestTypeArgs<'a> {
    text: Option<&'a str>,
    finding: Option<&'a Path>,
    topic: Option<&'a str>,
    catalog: Option<&'a Path>,
    config: Option<&'a Path>,
    root: Option<&'a Path>,
    limit: usize,
    calibration: Option<&'a Path>,
    record: bool,
    index: Option<&'a Path>,
}

const DEFAULT_CALIBRATION: &str = "reports/_meta/confidence-calibration.json";
const DEFAULT_INDEX: &str = "reports/_meta/search-index.sqlite";

/// A run identifier for miss recording: wall-clock seconds plus pid —
/// distinct across real runs (what tier-3 recurrence counts), stable
/// within one invocation.
fn run_id() -> String {
    let epoch_secs = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map_or(0, |d| d.as_secs());
    format!("{epoch_secs}-{}", std::process::id())
}

/// Whether a suggestion outcome is a tier-3 miss worth recording: no
/// candidate at all, or a best candidate in the `trigger_expansion` band.
fn is_expansion_miss(suggestions: &[mif_rh::TypeSuggestion]) -> bool {
    suggestions
        .first()
        .is_none_or(|top| top.tier == mif_ontology::ConfidenceTier::TriggerExpansion)
}

/// Runs `suggest-type`: derives the query text (given directly, or a
/// finding's indexed text), loads the topic's ontology context and the
/// calibration artifact, and prints the tier-annotated candidate list as
/// pretty JSON. Exit code 0 — a hypothesis list, even an empty one, is a
/// successful outcome, and nothing is ever written to `reports/`.
fn suggest_type_cmd(args: &SuggestTypeArgs<'_>) -> Result<Outcome, CliError> {
    let catalog_path = effective_path(args.catalog, DEFAULT_CATALOG);
    let config_path = effective_path(args.config, DEFAULT_CONFIG);
    let root = effective_path(args.root, ".");
    let calibration_path = effective_path(args.calibration, DEFAULT_CALIBRATION);

    // clap guarantees exactly one of text/--finding, and --topic whenever
    // text is given; with --finding the topic may still derive from the
    // finding's reports/<topic>/... path, mirroring `resolve`.
    let (query, topic, finding_id) = if let Some(finding_path) = args.finding {
        let finding = mif_rh::Finding::load(finding_path)?;
        let topic = args
            .topic
            .map(str::to_string)
            .or_else(|| topic_from_path(finding_path))
            .unwrap_or_default();
        (mif_rh::index_text(&finding), topic, Some(finding.id))
    } else {
        (
            args.text.unwrap_or_default().to_string(),
            args.topic.unwrap_or_default().to_string(),
            None,
        )
    };

    let catalog = mif_rh::Catalog::load(&catalog_path)?;
    let config = mif_rh::HarnessConfig::load(&config_path)?;
    let ontology_packs = mif_rh::ontology_pack::load_packs_via_catalog(&catalog, &root)?;
    let ctx = mif_rh::ResolveContext {
        topic: &topic,
        catalog: &catalog,
        config: &config,
        ontology_packs: &ontology_packs,
    };
    let cal = mif_ontology::CalibrationConfig::load_or_default(&calibration_path)
        .map_err(mif_rh::MifRhError::from)?;
    let embedder = mif_embed::Embedder::load()?;
    // Embed the query once; the vector serves both the ranking and — on a
    // tier-3 miss — the recorded miss, with no second forward pass.
    let candidates = mif_rh::suggest::build_candidates(&ctx, &embedder, &cal)?;
    let query_vector = embedder.embed(&query)?;
    let suggestions =
        mif_rh::suggest::suggest_from_candidates(&query_vector, &candidates, &cal, args.limit);

    if args.record && is_expansion_miss(&suggestions) {
        // clap's `requires = "finding"` guarantees the id was captured above.
        if let Some(finding_id) = finding_id {
            let index_path = effective_path(args.index, DEFAULT_INDEX);
            if let Some(parent) = index_path.parent() {
                std::fs::create_dir_all(parent).map_err(|source| mif_rh::MifRhError::Io {
                    path: parent.display().to_string(),
                    source,
                })?;
            }
            let index = mif_rh::FindingIndex::open(&index_path)?;
            index.record_miss(&mif_rh::Miss {
                finding_id,
                topic: topic.clone(),
                content: query,
                vector: query_vector,
                run_id: run_id(),
                model: mif_embed::MODEL_ID.to_string(),
            })?;
        }
    }

    let message =
        serde_json::to_string_pretty(&suggestions).map_err(|source| CliError::JsonSerialize {
            path: "<stdout>".to_string(),
            source,
        })?;
    Ok(Outcome {
        message,
        exit_code: 0,
    })
}

/// Arguments for the `calibrate` subcommand.
struct CalibrateArgs<'a> {
    reports_dir: Option<&'a Path>,
    config: Option<&'a Path>,
    catalog: Option<&'a Path>,
    root: Option<&'a Path>,
    target_precision: f32,
    tier2_target: f32,
    sample: Option<usize>,
    seed: u64,
    out: Option<&'a Path>,
    confusions: Option<&'a Path>,
}

/// Runs `calibrate`: collects stamped-finding samples across every
/// configured topic, sweeps the threshold grid, and atomically writes the
/// calibration artifact.
fn calibrate_cmd(args: &CalibrateArgs<'_>) -> Result<Outcome, CliError> {
    let reports_dir = effective_path(args.reports_dir, DEFAULT_REPORTS_DIR);
    let config_path = effective_path(args.config, DEFAULT_CONFIG);
    let catalog_path = effective_path(args.catalog, DEFAULT_CATALOG);
    let root = effective_path(args.root, ".");
    let out = args.out.map_or_else(
        || reports_dir.join("_meta/confidence-calibration.json"),
        Path::to_path_buf,
    );

    let catalog = mif_rh::Catalog::load(&catalog_path)?;
    let config = mif_rh::HarnessConfig::load(&config_path)?;
    let ontology_packs = mif_rh::ontology_pack::load_packs_via_catalog(&catalog, &root)?;
    let embedder = mif_embed::Embedder::load()?;

    let opts = mif_rh::CalibrateOptions {
        target_precision: args.target_precision,
        tier2_target: args.tier2_target,
        sample: args.sample,
        seed: args.seed,
    };
    let mut samples = Vec::new();
    for topic in &config.topics {
        let ctx = mif_rh::ResolveContext {
            topic: &topic.id,
            catalog: &catalog,
            config: &config,
            ontology_packs: &ontology_packs,
        };
        samples.extend(mif_rh::collect_topic_samples(
            &reports_dir,
            &ctx,
            &embedder,
        )?);
    }
    let samples = mif_rh::subsample(samples, &opts);

    // The confusion export writes BEFORE the sweep: a corpus that cannot
    // reach the precision target is exactly the corpus whose confusions
    // curation needs to see, so a failing sweep must not take the export
    // down with it.
    let confusions_note = if let Some(confusions_path) = args.confusions {
        let report = mif_rh::confusions(&samples);
        if let Some(parent) = confusions_path.parent()
            && !parent.as_os_str().is_empty()
        {
            std::fs::create_dir_all(parent).map_err(|source| mif_rh::MifRhError::Io {
                path: parent.display().to_string(),
                source,
            })?;
        }
        mif_rh::write_json_atomic(confusions_path, &report)?;
        format!(
            ", {} confusion pair(s) written to {}",
            report.pairs.len(),
            confusions_path.display()
        )
    } else {
        String::new()
    };

    let mut cal = mif_rh::sweep(&samples, &opts, &out)?;
    // Record whether curated negatives were among the candidates that
    // scored the swept samples: only packs resolved for topics actually
    // represented in the final (post-subsample) sample set count — an
    // enabled-but-unbound negatives pack must not claim participation.
    let scored_topics: std::collections::BTreeSet<&str> =
        samples.iter().map(|s| s.topic.as_str()).collect();
    let mut negatives_active = false;
    for topic in &config.topics {
        if !scored_topics.contains(topic.id.as_str()) {
            continue;
        }
        let ctx = mif_rh::ResolveContext {
            topic: &topic.id,
            catalog: &catalog,
            config: &config,
            ontology_packs: &ontology_packs,
        };
        if mif_rh::packs_carry_negatives(mif_rh::build_allowed(&ctx)?) {
            negatives_active = true;
            break;
        }
    }
    cal.negatives_active = negatives_active;

    if let Some(parent) = out.parent() {
        std::fs::create_dir_all(parent).map_err(|source| mif_rh::MifRhError::Io {
            path: parent.display().to_string(),
            source,
        })?;
    }
    mif_rh::write_json_atomic(&out, &cal)?;

    let message = format!(
        "calibrate: {} sample(s) -> tier1_floor={:.2} tier1_margin={:.2} tier2_floor={:.2} \
         (method {}, written to {}{confusions_note})",
        samples.len(),
        cal.tier1_floor,
        cal.tier1_margin,
        cal.tier2_floor,
        cal.method.as_deref().unwrap_or("-"),
        out.display()
    );
    Ok(Outcome {
        message,
        exit_code: 0,
    })
}

/// Runs `expansion-candidates`: clusters recorded tier-3 misses under the
/// calibration artifact's expansion knobs and emits the candidates as
/// JSON (stdout, or `--out` for `author-ontology.sh --from-clusters`).
fn expansion_candidates_cmd(
    index: Option<&Path>,
    calibration: Option<&Path>,
    out: Option<&Path>,
) -> Result<Outcome, CliError> {
    let index_path = effective_path(index, DEFAULT_INDEX);
    let calibration_path = effective_path(calibration, DEFAULT_CALIBRATION);

    let cal = mif_ontology::CalibrationConfig::load_or_default(&calibration_path)
        .map_err(mif_rh::MifRhError::from)?;
    // A read-only query must not create the index as a side effect: a
    // missing index simply means no misses were ever recorded.
    let misses = if index_path.exists() {
        let idx = mif_rh::FindingIndex::open(&index_path)?;
        idx.misses()?
    } else {
        Vec::new()
    };
    // Vectors from different embedding models share no space; cluster
    // only what the model in use produced.
    let misses: Vec<mif_rh::Miss> = misses
        .into_iter()
        .filter(|m| m.model == mif_embed::MODEL_ID)
        .collect();
    let candidates = mif_rh::expansion_candidates(&misses, &cal.expansion);

    let payload = serde_json::json!({
        "clusters": candidates,
        "misses_considered": misses.len(),
        "expansion": cal.expansion,
    });
    if let Some(out_path) = out {
        mif_rh::write_json_atomic(out_path, &payload)?;
        return Ok(Outcome {
            message: format!(
                "expansion-candidates: {} cluster(s) from {} miss(es) written to {}",
                candidates.len(),
                misses.len(),
                out_path.display()
            ),
            exit_code: 0,
        });
    }
    let message =
        serde_json::to_string_pretty(&payload).map_err(|source| CliError::JsonSerialize {
            path: "<stdout>".to_string(),
            source,
        })?;
    Ok(Outcome {
        message,
        exit_code: 0,
    })
}

/// Arguments for the `review` subcommand, bundled (rather than passed as
/// ~10 positional parameters) to match `mif_rh::ReviewOptions`'s own
/// struct-of-options convention.
struct ReviewArgs<'a> {
    topics: &'a [String],
    strict: bool,
    reports_dir: Option<&'a Path>,
    config: Option<&'a Path>,
    catalog: Option<&'a Path>,
    followup: Option<&'a Path>,
    root: Option<&'a Path>,
    relationship_script: Option<&'a Path>,
    build_index: bool,
    index: Option<&'a Path>,
    suggest: bool,
    calibration: Option<&'a Path>,
}

/// Inputs for `review --suggest`'s post-classification suggestion pass.
struct SuggestPassInputs<'a> {
    backlog: &'a mif_rh::FollowupBacklog,
    catalog: &'a mif_rh::Catalog,
    config: &'a mif_rh::HarnessConfig,
    ontology_packs: &'a std::collections::HashMap<String, mif_rh::OntologyPack>,
    meta_dir: &'a Path,
    index: Option<&'a Path>,
    calibration: Option<&'a Path>,
}

/// Runs the opt-in `--suggest` pass over a review's followup findings:
/// writes tier-annotated suggestion queues under
/// `<meta_dir>/suggestions/<topic>.json` (preserving human verdicts) and
/// records tier-3 misses in the index. Returns the confirmation line.
fn run_suggest_pass(inputs: &SuggestPassInputs<'_>) -> Result<String, CliError> {
    let calibration_path = inputs.calibration.map_or_else(
        || inputs.meta_dir.join("confidence-calibration.json"),
        Path::to_path_buf,
    );
    let cal = mif_ontology::CalibrationConfig::load_or_default(&calibration_path)
        .map_err(mif_rh::MifRhError::from)?;
    let embedder = mif_embed::Embedder::load()?;
    let index_path = inputs.index.map_or_else(
        || inputs.meta_dir.join("search-index.sqlite"),
        Path::to_path_buf,
    );
    let index = mif_rh::FindingIndex::open(&index_path)?;
    let run = run_id();

    let mut topic_ids: Vec<&String> = inputs.backlog.topics.keys().collect();
    topic_ids.sort();

    let (mut total_entries, mut topics_written, mut misses_recorded) = (0_usize, 0_usize, 0_usize);
    for topic_id in topic_ids {
        let ctx = mif_rh::ResolveContext {
            topic: topic_id,
            catalog: inputs.catalog,
            config: inputs.config,
            ontology_packs: inputs.ontology_packs,
        };
        // One embedding pass over this topic's candidate documents,
        // reused for every followup finding below.
        let candidates = mif_rh::suggest::build_candidates(&ctx, &embedder, &cal)?;
        let mut fresh = Vec::new();
        for followup_entry in &inputs.backlog.topics[topic_id] {
            // A "gap" entry's file could not even be parsed by review;
            // skipping it here mirrors that — the followup backlog still
            // carries it for a human.
            let Some(file) = &followup_entry.file else {
                continue;
            };
            let Ok(finding) = mif_rh::Finding::load(Path::new(file)) else {
                continue;
            };
            let query = mif_rh::index_text(&finding);
            if query.is_empty() {
                continue;
            }
            let query_vector = embedder.embed(&query)?;
            let suggestions = mif_rh::suggest::suggest_from_candidates(
                &query_vector,
                &candidates,
                &cal,
                mif_rh::suggest::SUGGESTION_DEPTH,
            );
            if is_expansion_miss(&suggestions) {
                index.record_miss(&mif_rh::Miss {
                    finding_id: finding.id.clone(),
                    topic: topic_id.clone(),
                    vector: query_vector,
                    content: query,
                    run_id: run.clone(),
                    model: mif_embed::MODEL_ID.to_string(),
                })?;
                misses_recorded += 1;
            }
            fresh.push(mif_rh::SuggestionEntry {
                finding_id: finding.id,
                file: followup_entry.file.clone(),
                basis: followup_entry.basis.clone(),
                run_id: run.clone(),
                candidates: suggestions,
                status: mif_rh::queue::STATUS_PENDING.to_string(),
            });
        }
        if fresh.is_empty() {
            continue;
        }
        total_entries += fresh.len();
        topics_written += 1;
        let queue_path = inputs
            .meta_dir
            .join("suggestions")
            .join(format!("{topic_id}.json"));
        mif_rh::upsert_suggestions(&queue_path, topic_id, fresh)?;
    }

    if total_entries == 0 {
        return Ok(format!(
            "ontology-review: no findings needed suggestions; {misses_recorded} miss(es) recorded"
        ));
    }
    Ok(format!(
        "ontology-review: suggestions written to {} ({} finding(s) across {} topic(s); {} \
         miss(es) recorded)",
        inputs.meta_dir.join("suggestions").display(),
        total_entries,
        topics_written,
        misses_recorded,
    ))
}

/// Formats the `TOPIC BOUND FIND STAMPED DISCOVERY UNTYPED INVALID` table
/// `ontology-review.sh` prints once per reviewed topic, byte-for-byte
/// (`printf '%-28s %-22s %6s %8s %10s %8s %9s\n'`), plus its trailing
/// `---` separator before the final summary line.
fn format_topic_table(report: &mif_rh::ReviewReport) -> String {
    use std::fmt::Write as _;

    let mut out = format!(
        "{:<28} {:<22} {:>6} {:>8} {:>10} {:>8} {:>9}\n",
        "TOPIC", "BOUND", "FIND", "STAMPED", "DISCOVERY", "UNTYPED", "INVALID"
    );
    for topic in &report.topics {
        let bound = if topic.bound.is_empty() {
            "(core-only)".to_string()
        } else {
            topic.bound.join(",")
        };
        let bound: String = bound.chars().take(22).collect();
        let _ = writeln!(
            out,
            "{:<28} {:<22} {:>6} {:>8} {:>10} {:>8} {:>9}",
            topic.topic,
            bound,
            topic.total,
            topic.stamped,
            topic.discovery,
            topic.untyped,
            topic.bad
        );
    }
    out.push_str("---");
    out
}

/// Resolves rht's `check-relationship-targets.sh` path: the explicit
/// override if given, otherwise `<root>/scripts/check-relationship-targets.sh`
/// if that file exists, otherwise `None` (skip the check — matches
/// reviewing a corpus with no rht scripts available, e.g. isolated tests).
fn relationship_script_path(given: Option<&Path>, root: &Path) -> Option<PathBuf> {
    given.map(Path::to_path_buf).or_else(|| {
        let candidate = root.join("scripts/check-relationship-targets.sh");
        candidate.is_file().then_some(candidate)
    })
}

fn review(args: &ReviewArgs<'_>) -> Result<Outcome, CliError> {
    let reports_dir = effective_path(args.reports_dir, DEFAULT_REPORTS_DIR);
    let config_path = effective_path(args.config, DEFAULT_CONFIG);
    let catalog_path = effective_path(args.catalog, DEFAULT_CATALOG);
    let root = effective_path(args.root, ".");
    let meta_dir = reports_dir.join("_meta");
    std::fs::create_dir_all(&meta_dir).map_err(|source| mif_rh::MifRhError::Io {
        path: meta_dir.display().to_string(),
        source,
    })?;

    // Held for the rest of this function; released on drop. The direct fix
    // for two concurrent `review` runs corrupting `ontology-map.json`
    // mid-write (see `mif_rh::ReviewLock`'s own doc comment).
    let _lock = mif_rh::ReviewLock::acquire(&meta_dir.join(".review.lock"))?;

    let catalog = mif_rh::Catalog::load(&catalog_path)?;
    let config = mif_rh::HarnessConfig::load(&config_path)?;
    let ontology_packs = mif_rh::ontology_pack::load_packs_via_catalog(&catalog, &root)?;

    let relationship_script = relationship_script_path(args.relationship_script, &root);
    let topic_ids: Option<Vec<String>> = (!args.topics.is_empty()).then(|| args.topics.to_vec());
    let opts = mif_rh::ReviewOptions {
        topics: topic_ids.as_deref(),
        reports_dir: &reports_dir,
        ontology_packs: &ontology_packs,
        catalog: &catalog,
        config: &config,
        check_relationship_targets_script: relationship_script.as_deref(),
    };

    let (report, backlog) = mif_rh::review(&opts)?;

    let mut message = format_topic_table(&report);

    // Matches `ontology-review.sh`'s own output order exactly: the
    // `--followup` write confirmation prints before the final "---" +
    // summary line, so a caller capturing only the last stdout line (as
    // `verify.sh`'s gate_m12 does) always sees the aggregate summary, not
    // this confirmation.
    if let Some(followup_path) = args.followup {
        use std::fmt::Write as _;

        mif_rh::write_followup(followup_path, &backlog)?;
        message.push('\n');
        let _ = write!(
            message,
            "ontology-review: followup backlog written to {} ({} finding(s) across {} topic(s))",
            followup_path.display(),
            backlog.total_needs_followup,
            backlog.topics.len(),
        );
    }

    // Like the followup confirmation above: prints before the final
    // summary line, which callers treat as the last line of output.
    if args.suggest {
        message.push('\n');
        message.push_str(&run_suggest_pass(&SuggestPassInputs {
            backlog: &backlog,
            catalog: &catalog,
            config: &config,
            ontology_packs: &ontology_packs,
            meta_dir: &meta_dir,
            index: args.index,
            calibration: args.calibration,
        })?);
    }

    message.push('\n');
    message.push_str(&report.summary_line());

    if args.build_index {
        // Always the full corpus (every topic in `config`), never just the
        // topic(s) this run classified — a finding discovered while
        // researching one topic remains a searchable source for every
        // future topic, so a scoped `--topic` review must not narrow the
        // search index down to only what it just reviewed.
        let all_topic_ids: Vec<String> = config.topics.iter().map(|t| t.id.clone()).collect();
        let index_path = args
            .index
            .map_or_else(|| meta_dir.join("search-index.sqlite"), Path::to_path_buf);
        let mut index = mif_rh::FindingIndex::open(&index_path)?;
        mif_rh::build_search_index(&reports_dir, &all_topic_ids, &mut index)?;
    }

    let exit_ok = if args.strict {
        !report.strict_should_fail()
    } else {
        true
    };
    Ok(Outcome {
        message,
        exit_code: u8::from(!exit_ok),
    })
}

#[cfg(test)]
mod tests {
    use std::fs;

    use super::{
        CalibrateArgs, ImportCorpusArgs, RenderArtifactArgs, ReviewArgs, SuggestTypeArgs,
        WrapSourceArgs, calibrate_cmd, expansion_candidates_cmd, harness_assert_graph_mif_cmd,
        harness_build_concordance_cmd, harness_build_graph_cmd, harness_build_index_cmd,
        harness_bump_version_cmd, harness_check_citation_integrity_cmd,
        harness_check_ontology_registry_cmd, harness_check_relationship_targets_cmd,
        harness_check_shippable_typing_cmd, harness_check_version_bump_cmd, harness_falsify_cmd,
        harness_goal_version_cmd, harness_graph_stats_cmd, harness_import_corpus_cmd,
        harness_pack_toggle_cmd, harness_project_report_cmd, harness_reconcile_session_cmd,
        harness_render_artifact_cmd, harness_resolve_membership_cmd,
        harness_site_toggle_plugin_cmd, harness_site_toggle_primary_cmd,
        harness_synthesize_artifact_cmd, harness_synthesize_corpus_cmd, harness_topic_metadata_cmd,
        harness_validate_concordance_cmd, harness_wrap_source_cmd, ontology_author_cmd,
        ontology_check_pin_safety_cmd, ontology_fetch_cmd, ontology_lock_check_cmd,
        ontology_sync_cmd, ontology_sync_registry_cmd, resolve, review, suggest_type_cmd,
        topic_from_path,
    };

    fn write_fixture(dir: &std::path::Path) {
        fs::create_dir_all(dir.join(".claude")).unwrap();
        fs::create_dir_all(dir.join("packs")).unwrap();
        fs::create_dir_all(dir.join("reports/edu/findings")).unwrap();
        fs::write(
            dir.join("harness.config.json"),
            r#"{"topics":[{"id":"edu","ontologies":["edu-fixture"]}]}"#,
        )
        .unwrap();
        fs::write(
            dir.join(".claude/enabled-packs.json"),
            r#"{"ontologies":[{"id":"edu-fixture","version":"0.1.0","source":"packs/edu-fixture.yaml","core":false}]}"#,
        )
        .unwrap();
        fs::write(
            dir.join("packs/edu-fixture.yaml"),
            "ontology:\n  id: edu-fixture\n  version: \"0.1.0\"\nentity_types:\n  - name: title\n    schema:\n      required: [name]\n      properties: {name: {type: string}}\n",
        )
        .unwrap();
        fs::write(
            dir.join("reports/edu/findings/good.json"),
            r#"{"@id":"f-good","entity":{"name":"Algebra I","entity_type":"title"}}"#,
        )
        .unwrap();
        fs::write(
            dir.join("reports/edu/findings/invalid.json"),
            r#"{"@id":"f-invalid","entity":{"entity_type":"title"}}"#,
        )
        .unwrap();
    }

    #[test]
    fn resolve_a_valid_finding_exits_zero_and_writes_the_map() {
        let dir = tempfile::tempdir().unwrap();
        write_fixture(dir.path());
        let map_path = dir.path().join("map.json");

        let outcome = resolve(
            &dir.path().join("reports/edu/findings/good.json"),
            Some("edu"),
            Some(&dir.path().join(".claude/enabled-packs.json")),
            Some(&dir.path().join("harness.config.json")),
            Some(&map_path),
            Some(dir.path()),
        )
        .unwrap();

        assert_eq!(outcome.exit_code, 0);
        assert!(outcome.message.contains("resolved"));
        assert!(map_path.exists());
    }

    #[test]
    fn resolve_an_invalid_finding_exits_nonzero() {
        let dir = tempfile::tempdir().unwrap();
        write_fixture(dir.path());

        let outcome = resolve(
            &dir.path().join("reports/edu/findings/invalid.json"),
            Some("edu"),
            Some(&dir.path().join(".claude/enabled-packs.json")),
            Some(&dir.path().join("harness.config.json")),
            None,
            Some(dir.path()),
        )
        .unwrap();

        assert_eq!(outcome.exit_code, 1);
        assert!(outcome.message.contains("valid=false"));
    }

    #[test]
    fn suggest_type_prints_tier_annotated_json_and_exits_zero() {
        if mif_embed::Embedder::load().is_err() {
            eprintln!("skipping: embedding model unavailable in this environment");
            return;
        }
        let dir = tempfile::tempdir().unwrap();
        write_fixture(dir.path());

        let outcome = suggest_type_cmd(&SuggestTypeArgs {
            text: Some("A textbook titled Algebra I"),
            finding: None,
            topic: Some("edu"),
            catalog: Some(&dir.path().join(".claude/enabled-packs.json")),
            config: Some(&dir.path().join("harness.config.json")),
            root: Some(dir.path()),
            limit: 10,
            calibration: Some(&dir.path().join("absent-calibration.json")),
            record: false,
            index: None,
        })
        .unwrap();

        assert_eq!(outcome.exit_code, 0);
        let suggestions: serde_json::Value = serde_json::from_str(&outcome.message).unwrap();
        let list = suggestions.as_array().unwrap();
        // The fixture pack's only entity type carries no description/aliases/
        // exemplars — no positive embedding signal, so it is skipped and the
        // hypothesis list is empty, which is still a successful outcome.
        assert!(list.is_empty());
    }

    #[test]
    fn expansion_candidates_on_a_fresh_index_emit_an_empty_cluster_list() {
        let dir = tempfile::tempdir().unwrap();
        let index_path = dir.path().join("index.sqlite");

        let outcome = expansion_candidates_cmd(
            Some(&index_path),
            Some(&dir.path().join("absent-calibration.json")),
            None,
        )
        .unwrap();

        assert_eq!(outcome.exit_code, 0);
        let payload: serde_json::Value = serde_json::from_str(&outcome.message).unwrap();
        assert!(payload["clusters"].as_array().unwrap().is_empty());
        assert_eq!(payload["misses_considered"], 0);
    }

    /// Enriches the fixture pack with a described entity type so suggest/
    /// calibrate paths have a positive embedding signal to work with.
    fn enrich_fixture_pack(dir: &std::path::Path) {
        fs::write(
            dir.join("packs/edu-fixture.yaml"),
            "ontology:\n  id: edu-fixture\n  version: \"0.1.0\"\nentity_types:\n  - name: title\n    description: A published educational title\n    aliases: [textbook]\n    schema:\n      required: [name]\n      properties: {name: {type: string}}\n",
        )
        .unwrap();
    }

    #[test]
    fn calibrate_derives_a_wellformed_artifact_from_stamped_findings() {
        if mif_embed::Embedder::load().is_err() {
            eprintln!("skipping: embedding model unavailable in this environment");
            return;
        }
        let dir = tempfile::tempdir().unwrap();
        write_fixture(dir.path());
        enrich_fixture_pack(dir.path());

        // Stamp the valid finding into the topic map first — stamped
        // findings are calibrate's labeled sample.
        resolve(
            &dir.path().join("reports/edu/findings/good.json"),
            Some("edu"),
            Some(&dir.path().join(".claude/enabled-packs.json")),
            Some(&dir.path().join("harness.config.json")),
            Some(&dir.path().join("reports/edu/ontology-map.json")),
            Some(dir.path()),
        )
        .unwrap();

        let out = dir.path().join("reports/_meta/confidence-calibration.json");
        let confusions_path = dir.path().join("reports/_meta/confusions.json");
        let outcome = calibrate_cmd(&CalibrateArgs {
            reports_dir: Some(&dir.path().join("reports")),
            config: Some(&dir.path().join("harness.config.json")),
            catalog: Some(&dir.path().join(".claude/enabled-packs.json")),
            root: Some(dir.path()),
            target_precision: 1.0,
            tier2_target: 0.5,
            sample: None,
            seed: 0,
            out: Some(&out),
            confusions: Some(&confusions_path),
        })
        .unwrap();

        assert_eq!(outcome.exit_code, 0);
        let cal = mif_ontology::CalibrationConfig::load_or_default(&out).unwrap();
        assert!(cal.calibrated);
        assert_eq!(cal.method.as_deref(), Some("stamped-quantile-v1"));
        assert_eq!(cal.sample_size, Some(1));
        assert!(cal.tier2_floor <= cal.tier1_floor);
        // The fixture pack carries no negative_examples, so the artifact
        // records that the demotion gate did not participate.
        assert!(!cal.negatives_active);

        // The confusion export was written alongside the artifact: the
        // fixture's one sample is correct, so the report is versioned,
        // counts the sample, and carries no pairs.
        assert!(outcome.message.contains("confusion pair(s)"));
        let report: serde_json::Value =
            serde_json::from_str(&fs::read_to_string(&confusions_path).unwrap()).unwrap();
        assert_eq!(report["version"], "confusions-v1");
        assert_eq!(report["sample_count"], 1);
        assert!(report["pairs"].as_array().unwrap().is_empty());
    }

    #[test]
    fn calibrate_records_negatives_participation_in_the_artifact() {
        if mif_embed::Embedder::load().is_err() {
            eprintln!("skipping: embedding model unavailable in this environment");
            return;
        }
        let dir = tempfile::tempdir().unwrap();
        write_fixture(dir.path());
        // Enrich the pack WITH a curated negative: the artifact must record
        // that the demotion gate participated in the swept scores.
        fs::write(
            dir.path().join("packs/edu-fixture.yaml"),
            "ontology:\n  id: edu-fixture\n  version: \"0.1.0\"\nentity_types:\n  - name: title\n    description: A published educational title\n    aliases: [textbook]\n    negative_examples:\n      - A lesson plan for teachers\n    schema:\n      required: [name]\n      properties: {name: {type: string}}\n",
        )
        .unwrap();

        resolve(
            &dir.path().join("reports/edu/findings/good.json"),
            Some("edu"),
            Some(&dir.path().join(".claude/enabled-packs.json")),
            Some(&dir.path().join("harness.config.json")),
            Some(&dir.path().join("reports/edu/ontology-map.json")),
            Some(dir.path()),
        )
        .unwrap();

        let out = dir.path().join("reports/_meta/confidence-calibration.json");
        let outcome = calibrate_cmd(&CalibrateArgs {
            reports_dir: Some(&dir.path().join("reports")),
            config: Some(&dir.path().join("harness.config.json")),
            catalog: Some(&dir.path().join(".claude/enabled-packs.json")),
            root: Some(dir.path()),
            target_precision: 1.0,
            tier2_target: 0.5,
            sample: None,
            seed: 0,
            out: Some(&out),
            confusions: None,
        })
        .unwrap();

        assert_eq!(outcome.exit_code, 0);
        let cal = mif_ontology::CalibrationConfig::load_or_default(&out).unwrap();
        assert!(cal.negatives_active);
    }

    #[test]
    fn an_unbound_negatives_pack_never_claims_participation() {
        if mif_embed::Embedder::load().is_err() {
            eprintln!("skipping: embedding model unavailable in this environment");
            return;
        }
        let dir = tempfile::tempdir().unwrap();
        write_fixture(dir.path());
        enrich_fixture_pack(dir.path());
        // A SECOND pack carrying negatives is enabled in the catalog but
        // not core and not bound to the scored topic: it never scores a
        // sample, so the artifact must record negatives_active: false.
        fs::write(
            dir.path().join("packs/unbound-fixture.yaml"),
            "ontology:\n  id: unbound-fixture\n  version: \"0.1.0\"\nentity_types:\n  - name: lesson\n    description: A lesson plan\n    negative_examples:\n      - A published textbook\n",
        )
        .unwrap();
        fs::write(
            dir.path().join(".claude/enabled-packs.json"),
            r#"{"ontologies":[{"id":"edu-fixture","version":"0.1.0","source":"packs/edu-fixture.yaml","core":false},{"id":"unbound-fixture","version":"0.1.0","source":"packs/unbound-fixture.yaml","core":false}]}"#,
        )
        .unwrap();

        resolve(
            &dir.path().join("reports/edu/findings/good.json"),
            Some("edu"),
            Some(&dir.path().join(".claude/enabled-packs.json")),
            Some(&dir.path().join("harness.config.json")),
            Some(&dir.path().join("reports/edu/ontology-map.json")),
            Some(dir.path()),
        )
        .unwrap();

        let out = dir.path().join("reports/_meta/confidence-calibration.json");
        let outcome = calibrate_cmd(&CalibrateArgs {
            reports_dir: Some(&dir.path().join("reports")),
            config: Some(&dir.path().join("harness.config.json")),
            catalog: Some(&dir.path().join(".claude/enabled-packs.json")),
            root: Some(dir.path()),
            target_precision: 1.0,
            tier2_target: 0.5,
            sample: None,
            seed: 0,
            out: Some(&out),
            confusions: None,
        })
        .unwrap();

        assert_eq!(outcome.exit_code, 0);
        let cal = mif_ontology::CalibrationConfig::load_or_default(&out).unwrap();
        assert!(!cal.negatives_active);
    }

    #[test]
    fn calibrate_writes_the_confusion_export_even_when_the_sweep_fails() {
        if mif_embed::Embedder::load().is_err() {
            eprintln!("skipping: embedding model unavailable in this environment");
            return;
        }
        let dir = tempfile::tempdir().unwrap();
        write_fixture(dir.path());
        enrich_fixture_pack(dir.path());
        // Deliberately no resolve/stamping: zero labeled samples makes the
        // sweep fail loud, and an uncalibratable corpus is exactly the one
        // whose confusions curation needs — the export must survive.

        let confusions_path = dir.path().join("reports/_meta/confusions.json");
        let result = calibrate_cmd(&CalibrateArgs {
            reports_dir: Some(&dir.path().join("reports")),
            config: Some(&dir.path().join("harness.config.json")),
            catalog: Some(&dir.path().join(".claude/enabled-packs.json")),
            root: Some(dir.path()),
            target_precision: 1.0,
            tier2_target: 0.5,
            sample: None,
            seed: 0,
            out: Some(&dir.path().join("reports/_meta/confidence-calibration.json")),
            confusions: Some(&confusions_path),
        });

        // Outcome has no Debug impl; mapping the success side away lets
        // unwrap_err assert the failure directly.
        let error = result.map(|_| ()).unwrap_err();
        assert!(error.to_string().contains("no stamped"));
        let report: serde_json::Value =
            serde_json::from_str(&fs::read_to_string(&confusions_path).unwrap()).unwrap();
        assert_eq!(report["version"], "confusions-v1");
        assert_eq!(report["sample_count"], 0);
        assert!(report["pairs"].as_array().unwrap().is_empty());
    }

    #[test]
    fn review_suggest_writes_a_topic_queue_for_followup_findings() {
        if mif_embed::Embedder::load().is_err() {
            eprintln!("skipping: embedding model unavailable in this environment");
            return;
        }
        let dir = tempfile::tempdir().unwrap();
        write_fixture(dir.path());
        enrich_fixture_pack(dir.path());
        // An untyped finding WITH content: suggestable (the fixture's
        // invalid finding has no indexable text and is skipped).
        fs::write(
            dir.path().join("reports/edu/findings/untyped.json"),
            r#"{"@id":"f-untyped","content":"A fascinating textbook about geometry"}"#,
        )
        .unwrap();

        let outcome = review(&ReviewArgs {
            topics: &[],
            strict: false,
            reports_dir: Some(&dir.path().join("reports")),
            config: Some(&dir.path().join("harness.config.json")),
            catalog: Some(&dir.path().join(".claude/enabled-packs.json")),
            followup: None,
            root: Some(dir.path()),
            relationship_script: None,
            build_index: false,
            index: None,
            suggest: true,
            calibration: None,
        })
        .unwrap();

        // The suggestions confirmation prints before the final summary line.
        let lines: Vec<&str> = outcome.message.lines().collect();
        let confirmation = lines
            .iter()
            .position(|l| l.starts_with("ontology-review: suggestions written"))
            .expect("suggestions confirmation line present");
        assert!(confirmation < lines.len() - 1);

        // The untyped finding (not durably stamped) got queued.
        let queue_path = dir.path().join("reports/_meta/suggestions/edu.json");
        let queue: serde_json::Value =
            serde_json::from_str(&fs::read_to_string(&queue_path).unwrap()).unwrap();
        let entries = queue["entries"].as_array().unwrap();
        assert!(
            entries
                .iter()
                .any(|e| e["finding_id"] == "f-untyped" && e["status"] == "pending")
        );
    }

    #[test]
    fn suggest_type_ranks_a_described_type_from_a_finding_query() {
        if mif_embed::Embedder::load().is_err() {
            eprintln!("skipping: embedding model unavailable in this environment");
            return;
        }
        let dir = tempfile::tempdir().unwrap();
        write_fixture(dir.path());
        // Enrich the fixture pack with a described, aliased entity type so a
        // real candidate exists.
        fs::write(
            dir.path().join("packs/edu-fixture.yaml"),
            "ontology:\n  id: edu-fixture\n  version: \"0.1.0\"\nentity_types:\n  - name: title\n    description: A published educational title\n    aliases: [textbook]\n    schema:\n      required: [name]\n      properties: {name: {type: string}}\n",
        )
        .unwrap();

        let outcome = suggest_type_cmd(&SuggestTypeArgs {
            text: None,
            finding: Some(&dir.path().join("reports/edu/findings/good.json")),
            topic: None, // derived from the finding's reports/<topic>/ path
            catalog: Some(&dir.path().join(".claude/enabled-packs.json")),
            config: Some(&dir.path().join("harness.config.json")),
            root: Some(dir.path()),
            limit: 10,
            calibration: Some(&dir.path().join("absent-calibration.json")),
            record: false,
            index: None,
        })
        .unwrap();

        assert_eq!(outcome.exit_code, 0);
        let suggestions: serde_json::Value = serde_json::from_str(&outcome.message).unwrap();
        let list = suggestions.as_array().unwrap();
        assert_eq!(list.len(), 1);
        assert_eq!(list[0]["entity_type"], "title");
        assert!(list[0]["tier"].is_string());
        assert_eq!(list[0]["calibrated"], false);
    }

    #[test]
    fn review_strict_fails_closed_on_an_invalid_finding_but_succeeds_without_strict() {
        let dir = tempfile::tempdir().unwrap();
        write_fixture(dir.path());

        let strict_outcome = review(&ReviewArgs {
            topics: &[],
            strict: true,
            reports_dir: Some(&dir.path().join("reports")),
            config: Some(&dir.path().join("harness.config.json")),
            catalog: Some(&dir.path().join(".claude/enabled-packs.json")),
            followup: None,
            root: Some(dir.path()),
            relationship_script: None,
            build_index: false,
            index: None,
            suggest: false,
            calibration: None,
        })
        .unwrap();
        assert_eq!(strict_outcome.exit_code, 1);
        assert!(strict_outcome.message.contains("1 invalid/unresolved"));

        let lenient_outcome = review(&ReviewArgs {
            topics: &[],
            strict: false,
            reports_dir: Some(&dir.path().join("reports")),
            config: Some(&dir.path().join("harness.config.json")),
            catalog: Some(&dir.path().join(".claude/enabled-packs.json")),
            followup: None,
            root: Some(dir.path()),
            relationship_script: None,
            build_index: false,
            index: None,
            suggest: false,
            calibration: None,
        })
        .unwrap();
        assert_eq!(lenient_outcome.exit_code, 0);
    }

    #[test]
    fn review_acquires_and_releases_the_lock_and_prints_the_topic_table() {
        let dir = tempfile::tempdir().unwrap();
        write_fixture(dir.path());

        let outcome = review(&ReviewArgs {
            topics: &[],
            strict: false,
            reports_dir: Some(&dir.path().join("reports")),
            config: Some(&dir.path().join("harness.config.json")),
            catalog: Some(&dir.path().join(".claude/enabled-packs.json")),
            followup: None,
            root: Some(dir.path()),
            relationship_script: None,
            build_index: false,
            index: None,
            suggest: false,
            calibration: None,
        })
        .unwrap();

        assert!(outcome.message.contains("TOPIC"), "{}", outcome.message);
        assert!(outcome.message.contains("edu"), "{}", outcome.message);
        assert!(
            !dir.path().join("reports/_meta/.review.lock").exists(),
            "lock file must be released after review() returns"
        );
    }

    #[test]
    fn review_with_followup_prints_the_summary_line_last() {
        // `ontology-review.sh` always ends its stdout on the aggregate
        // summary line, even when `--followup` also prints a write
        // confirmation — callers that capture only the last line (like
        // `verify.sh`'s gate_m12) depend on this exact order.
        let dir = tempfile::tempdir().unwrap();
        write_fixture(dir.path());
        let followup_path = dir.path().join("followup.json");

        let outcome = review(&ReviewArgs {
            topics: &[],
            strict: false,
            reports_dir: Some(&dir.path().join("reports")),
            config: Some(&dir.path().join("harness.config.json")),
            catalog: Some(&dir.path().join(".claude/enabled-packs.json")),
            followup: Some(&followup_path),
            root: Some(dir.path()),
            relationship_script: None,
            build_index: false,
            index: None,
            suggest: false,
            calibration: None,
        })
        .unwrap();

        let last_line = outcome.message.lines().next_back().unwrap();
        assert!(
            last_line.starts_with("1 topic(s);"),
            "last line should be the summary, got: {last_line}"
        );
    }

    #[test]
    fn review_with_build_index_populates_the_default_index_path() {
        // `--build-index` loads the real embedding model (network access on
        // a cold cache) — skip gracefully rather than fail the suite if it
        // is unavailable, matching `mif-embed`'s own test convention.
        if mif_embed::Embedder::load().is_err() {
            eprintln!("skipping: could not load embedding model");
            return;
        }

        let dir = tempfile::tempdir().unwrap();
        write_fixture(dir.path());

        review(&ReviewArgs {
            topics: &[],
            strict: false,
            reports_dir: Some(&dir.path().join("reports")),
            config: Some(&dir.path().join("harness.config.json")),
            catalog: Some(&dir.path().join(".claude/enabled-packs.json")),
            followup: None,
            root: Some(dir.path()),
            relationship_script: None,
            build_index: true,
            index: None,
            suggest: false,
            calibration: None,
        })
        .unwrap();

        assert!(
            dir.path()
                .join("reports/_meta/search-index.sqlite")
                .exists()
        );
    }

    #[test]
    fn topic_from_path_derives_the_topic_from_a_reports_relative_finding_path() {
        assert_eq!(
            topic_from_path(std::path::Path::new("reports/edu/findings/f.json")),
            Some("edu".to_string())
        );
        assert_eq!(
            topic_from_path(std::path::Path::new("/some/other/path.json")),
            None
        );
    }

    #[test]
    fn assert_graph_mif_cmd_passes_a_well_formed_graph() {
        let dir = tempfile::tempdir().unwrap();
        let graph_path = dir.path().join("knowledge-graph.json");
        fs::write(
            &graph_path,
            r#"{"nodes":[{"id":"urn:mif:f1","kind":"concept"}],
                "edges":[{"source":"urn:mif:f1","target":"urn:mif:f1","via":"relationship"}]}"#,
        )
        .unwrap();

        let outcome = harness_assert_graph_mif_cmd(&graph_path).unwrap();
        assert_eq!(outcome.exit_code, 0);
        assert!(outcome.message.contains("assert-graph: PASS"));
    }

    #[test]
    fn assert_graph_mif_cmd_fails_on_a_tag_derived_id() {
        let dir = tempfile::tempdir().unwrap();
        let graph_path = dir.path().join("knowledge-graph.json");
        fs::write(
            &graph_path,
            r#"{"nodes":[{"id":"some-tag","kind":"concept"}],
                "edges":[{"source":"some-tag","target":"some-tag","via":"relationship"}]}"#,
        )
        .unwrap();

        let outcome = harness_assert_graph_mif_cmd(&graph_path).unwrap();
        assert_eq!(outcome.exit_code, 1);
        assert!(outcome.message.contains("assert-graph: FAIL"));
        assert!(
            outcome
                .message
                .contains("FAIL — every node id is a urn:mif:")
        );
    }

    #[test]
    fn check_citation_integrity_cmd_passes_a_well_formed_finding() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("f.json");
        fs::write(
            &path,
            r#"{"@id":"urn:mif:f1","citations":[{"url":"https://example.com","citationRole":"supports"}]}"#,
        )
        .unwrap();

        let outcome = harness_check_citation_integrity_cmd(&[path], None);
        assert_eq!(outcome.exit_code, 0);
        assert!(outcome.message.contains("citation-integrity: PASS"));
    }

    #[test]
    fn check_citation_integrity_cmd_fails_on_no_citations() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("f.json");
        fs::write(&path, r#"{"@id":"urn:mif:f1","citations":[]}"#).unwrap();

        let outcome = harness_check_citation_integrity_cmd(&[path], None);
        assert_eq!(outcome.exit_code, 1);
        assert!(outcome.message.contains("citation-integrity: FAIL"));
    }

    #[test]
    fn check_shippable_typing_cmd_passes_a_typed_shippable_finding() {
        let dir = tempfile::tempdir().unwrap();
        let reports_dir = dir.path().join("reports/edu");
        fs::create_dir_all(reports_dir.join("findings")).unwrap();
        fs::write(
            reports_dir.join("findings/f1.json"),
            r#"{"@id":"urn:mif:f1","extensions":{"harness":{"verification":{"verdict":"survived"}}}}"#,
        )
        .unwrap();
        fs::write(
            reports_dir.join("ontology-map.json"),
            r#"[{"finding_id":"urn:mif:f1","valid":true,"basis":"declared"}]"#,
        )
        .unwrap();

        let outcome = harness_check_shippable_typing_cmd(&reports_dir).unwrap();
        assert_eq!(outcome.exit_code, 0);
        assert!(
            outcome
                .message
                .contains("all shippable findings carry a valid ontology type")
        );
    }

    #[test]
    fn check_shippable_typing_cmd_blocks_an_untyped_shippable_finding() {
        let dir = tempfile::tempdir().unwrap();
        let reports_dir = dir.path().join("reports/edu");
        fs::create_dir_all(reports_dir.join("findings")).unwrap();
        fs::write(
            reports_dir.join("findings/f1.json"),
            r#"{"@id":"urn:mif:f1","extensions":{"harness":{"verification":{"verdict":"survived"}}}}"#,
        )
        .unwrap();
        fs::write(
            reports_dir.join("ontology-map.json"),
            r#"[{"finding_id":"urn:mif:f1","valid":true,"basis":"untyped"}]"#,
        )
        .unwrap();

        let outcome = harness_check_shippable_typing_cmd(&reports_dir).unwrap();
        assert_eq!(outcome.exit_code, 1);
        assert!(outcome.message.contains("synthesis BLOCKED"));
        assert!(outcome.message.contains("unblock with"));
    }

    #[test]
    fn check_shippable_typing_cmd_errors_on_a_missing_ontology_map() {
        let dir = tempfile::tempdir().unwrap();
        let reports_dir = dir.path().join("reports/edu");
        fs::create_dir_all(reports_dir.join("findings")).unwrap();

        assert!(harness_check_shippable_typing_cmd(&reports_dir).is_err());
    }

    #[test]
    fn falsify_cmd_writes_a_placeholder_inconclusive_verdict_and_logs_the_run_line() {
        let dir = tempfile::tempdir().unwrap();
        let finding = dir.path().join("f.json");
        fs::write(&finding, r#"{"@id":"urn:mif:f1"}"#).unwrap();

        let outcome = harness_falsify_cmd(&finding, None).unwrap();
        assert_eq!(outcome.exit_code, 0);
        assert!(outcome.message.contains("\"inconclusive\""));
    }

    #[test]
    fn falsify_cmd_errors_on_a_missing_finding_file() {
        let error =
            harness_falsify_cmd(std::path::Path::new("/no/such/file.json"), None).unwrap_err();
        assert!(matches!(error, mif_rh::MifRhError::Io { .. }));
    }

    fn write_concordance_fixture(
        dir: &std::path::Path,
    ) -> (std::path::PathBuf, std::path::PathBuf, std::path::PathBuf) {
        fs::write(
            dir.join("core.yaml"),
            "ontology:\n  id: mif-generic\n  version: \"1.0.0\"\n",
        )
        .unwrap();
        let catalog = dir.join("cat.json");
        fs::write(
            &catalog,
            r#"{"ontologies":[{"id":"mif-generic","version":"1.0.0","source":"core.yaml","core":true}]}"#,
        )
        .unwrap();
        let config = dir.join("cfg.json");
        fs::write(&config, r#"{"topics":[]}"#).unwrap();
        (catalog, config, dir.to_path_buf())
    }

    #[test]
    fn validate_concordance_cmd_passes_a_conformant_graph() {
        let dir = tempfile::tempdir().unwrap();
        let (catalog, config, root) = write_concordance_fixture(dir.path());
        let concordance = dir.path().join("concordance.json");
        fs::write(
            &concordance,
            r#"{"nodes":[{"id":"n1","entityType":"Concept","topics":[]}],"edges":[]}"#,
        )
        .unwrap();

        let outcome =
            harness_validate_concordance_cmd(&concordance, &config, &catalog, &root).unwrap();
        assert_eq!(outcome.exit_code, 0);
        assert!(outcome.message.contains("conformant"));
    }

    #[test]
    fn validate_concordance_cmd_flags_an_undeclared_type() {
        let dir = tempfile::tempdir().unwrap();
        let (catalog, config, root) = write_concordance_fixture(dir.path());
        let concordance = dir.path().join("concordance.json");
        fs::write(
            &concordance,
            r#"{"nodes":[{"id":"n1","entityType":"made-up-type","topics":[]}],"edges":[]}"#,
        )
        .unwrap();

        let outcome =
            harness_validate_concordance_cmd(&concordance, &config, &catalog, &root).unwrap();
        assert_eq!(outcome.exit_code, 1);
        assert!(outcome.message.contains("conformance violation"));
        assert!(outcome.message.contains("/ontology-review"));
    }

    #[test]
    fn validate_concordance_cmd_errors_on_a_missing_concordance_file() {
        let dir = tempfile::tempdir().unwrap();
        let (catalog, config, root) = write_concordance_fixture(dir.path());

        let error = harness_validate_concordance_cmd(
            &dir.path().join("missing.json"),
            &config,
            &catalog,
            &root,
        )
        .unwrap_err();
        assert!(matches!(error, mif_rh::MifRhError::Io { .. }));
    }

    #[test]
    fn check_ontology_registry_cmd_passes_an_empty_registry() {
        let dir = tempfile::tempdir().unwrap();

        let outcome = harness_check_ontology_registry_cmd(dir.path());
        assert_eq!(outcome.exit_code, 0);
        assert!(outcome.message.contains("0 type(s)"));
        assert!(
            outcome
                .message
                .contains("relationship-endpoint orphans: none")
        );
    }

    #[test]
    fn check_ontology_registry_cmd_flags_an_orphaned_relationship_endpoint() {
        let dir = tempfile::tempdir().unwrap();
        fs::create_dir_all(dir.path().join("packs/ontologies/x")).unwrap();
        fs::write(
            dir.path().join("packs/ontologies/x/x.ontology.yaml"),
            "ontology:\n  id: x\n  version: \"0.1.0\"\nentity_types:\n  - name: a\nrelationships:\n  rel:\n    from: [a]\n    to: [does-not-exist]\n",
        )
        .unwrap();

        let outcome = harness_check_ontology_registry_cmd(dir.path());
        assert_eq!(outcome.exit_code, 1);
        assert!(
            outcome
                .message
                .contains("relationship-endpoint orphans: does-not-exist")
        );
    }

    #[test]
    fn check_relationship_targets_cmd_passes_when_every_target_resolves() {
        let dir = tempfile::tempdir().unwrap();
        let reports_dir = dir.path().join("reports");
        fs::create_dir_all(reports_dir.join("t1/findings")).unwrap();
        fs::write(
            reports_dir.join("t1/findings/a.json"),
            r#"{"@id":"urn:mif:t1:a","relationships":[]}"#,
        )
        .unwrap();

        let outcome = harness_check_relationship_targets_cmd(&reports_dir).unwrap();
        assert_eq!(outcome.exit_code, 0);
        assert!(outcome.message.contains("check-relationship-targets: ok"));
    }

    #[test]
    fn check_relationship_targets_cmd_flags_a_dangling_target() {
        let dir = tempfile::tempdir().unwrap();
        let reports_dir = dir.path().join("reports");
        fs::create_dir_all(reports_dir.join("t1/findings")).unwrap();
        fs::write(
            reports_dir.join("t1/findings/a.json"),
            r#"{"@id":"urn:mif:t1:a","relationships":[{"type":"relates-to","target":"urn:mif:t1:missing"}]}"#,
        )
        .unwrap();

        let outcome = harness_check_relationship_targets_cmd(&reports_dir).unwrap();
        assert_eq!(outcome.exit_code, 1);
        assert!(outcome.message.contains("ORPHAN"));
    }

    #[test]
    fn check_relationship_targets_cmd_errors_on_a_malformed_finding() {
        let dir = tempfile::tempdir().unwrap();
        let reports_dir = dir.path().join("reports");
        fs::create_dir_all(reports_dir.join("t1/findings")).unwrap();
        fs::write(reports_dir.join("t1/findings/bad.json"), "{invalid json").unwrap();

        assert!(harness_check_relationship_targets_cmd(&reports_dir).is_err());
    }

    #[test]
    fn goal_version_cmd_returns_a_version_id_for_a_wellformed_goal() {
        let dir = tempfile::tempdir().unwrap();
        let goal_path = dir.path().join("goal.json");
        fs::write(
            &goal_path,
            r#"{"objective":"o","dimensions":["landscape"]}"#,
        )
        .unwrap();

        let outcome = harness_goal_version_cmd(&goal_path).unwrap();
        assert_eq!(outcome.exit_code, 0);
        assert!(!outcome.message.is_empty());
    }

    #[test]
    fn goal_version_cmd_errors_on_a_missing_goal_file() {
        let dir = tempfile::tempdir().unwrap();
        assert!(harness_goal_version_cmd(&dir.path().join("missing.json")).is_err());
    }

    fn write_release_fixture(root: &std::path::Path) {
        fs::write(
            root.join("harness.config.json"),
            r#"{"version": "0.4.0", "topics": []}"#,
        )
        .unwrap();
        fs::create_dir_all(root.join(".claude-plugin")).unwrap();
        fs::write(
            root.join(".claude-plugin/marketplace.json"),
            r#"{"name": "research-harness", "metadata": {"version": "0.4.0"}}"#,
        )
        .unwrap();
        fs::write(
            root.join("CHANGELOG.md"),
            "# Changelog\n\n## [Unreleased]\n\n## [0.4.0] - 2026-01-01\n\nInitial.\n",
        )
        .unwrap();
    }

    #[test]
    fn bump_version_cmd_bumps_the_release_pointer() {
        let dir = tempfile::tempdir().unwrap();
        write_release_fixture(dir.path());

        let outcome =
            harness_bump_version_cmd("patch", &[], Some("2026-02-01"), false, Some(dir.path()))
                .unwrap();
        assert_eq!(outcome.exit_code, 0);
        assert!(outcome.message.contains("0.4.0 -> 0.4.1"));
    }

    #[test]
    fn bump_version_cmd_check_mode_writes_nothing() {
        let dir = tempfile::tempdir().unwrap();
        write_release_fixture(dir.path());

        let outcome =
            harness_bump_version_cmd("patch", &[], Some("2026-02-01"), true, Some(dir.path()))
                .unwrap();
        assert_eq!(outcome.exit_code, 0);
        assert!(outcome.message.contains("no files written"));
    }

    // Isolated the same way `harness_release.rs`'s own `git_command` is:
    // `-C` alone does not override an inherited `GIT_DIR`/`GIT_WORK_TREE`,
    // which would silently redirect these calls onto whatever real repo the
    // test process happens to be running inside instead of `root`.
    fn git(root: &std::path::Path, args: &[&str]) {
        let status = std::process::Command::new("git")
            .current_dir(root)
            .env_remove("GIT_DIR")
            .env_remove("GIT_WORK_TREE")
            .env_remove("GIT_INDEX_FILE")
            .env_remove("GIT_CEILING_DIRECTORIES")
            .args(args)
            .status()
            .unwrap();
        assert!(status.success(), "git {args:?} failed");
    }

    #[test]
    fn check_version_bump_cmd_passes_with_no_changes_and_no_prior_release() {
        let dir = tempfile::tempdir().unwrap();
        git(dir.path(), &["init", "-q", "-b", "main"]);
        git(dir.path(), &["config", "user.email", "test@example.com"]);
        git(dir.path(), &["config", "user.name", "Test"]);
        write_release_fixture(dir.path());
        git(dir.path(), &["add", "-A"]);
        git(dir.path(), &["commit", "-q", "-m", "base"]);

        let outcome = harness_check_version_bump_cmd(Some("HEAD"), Some(dir.path())).unwrap();
        assert_eq!(outcome.exit_code, 0);
        assert!(outcome.message.contains("check-version-bump:"));
    }

    #[test]
    fn project_report_cmd_projects_a_wellformed_report() {
        let dir = tempfile::tempdir().unwrap();
        let schema = dir.path().join("schema.json");
        fs::write(&schema, r#"{"type":"object"}"#).unwrap();
        let report = dir.path().join("report.md");
        fs::write(&report, "---\nid: r1\n---\n\nBody text.\n").unwrap();

        let outcome = harness_project_report_cmd(&report, &schema, &[], None).unwrap();
        assert_eq!(outcome.exit_code, 0);
        assert!(
            outcome
                .message
                .contains("projects to a valid MIF L3 finding")
        );
    }

    #[test]
    fn site_toggle_primary_cmd_writes_the_primary_surface() {
        let dir = tempfile::tempdir().unwrap();
        let config = dir.path().join("harness.config.json");
        fs::write(&config, r#"{"version": "1.0.0"}"#).unwrap();

        let outcome = harness_site_toggle_primary_cmd("docs", Some(&config)).unwrap();
        assert_eq!(outcome.exit_code, 0);
        assert!(outcome.message.contains("primarySurface -> docs"));
    }

    #[test]
    fn site_toggle_plugin_cmd_flips_the_named_plugin() {
        let dir = tempfile::tempdir().unwrap();
        let config = dir.path().join("harness.config.json");
        fs::write(&config, r#"{"version": "1.0.0"}"#).unwrap();

        let outcome = harness_site_toggle_plugin_cmd("llmsTxt", "on", Some(&config)).unwrap();
        assert_eq!(outcome.exit_code, 0);
        assert!(outcome.message.contains("plugin llmsTxt -> enabled=true"));
    }

    #[test]
    fn site_toggle_plugin_cmd_rejects_a_non_on_off_state() {
        let dir = tempfile::tempdir().unwrap();
        let config = dir.path().join("harness.config.json");
        fs::write(&config, r#"{"version": "1.0.0"}"#).unwrap();

        assert!(harness_site_toggle_plugin_cmd("llmsTxt", "sideways", Some(&config)).is_err());
    }

    #[test]
    fn pack_toggle_cmd_flips_the_named_packs_flag() {
        let dir = tempfile::tempdir().unwrap();
        let config = dir.path().join("harness.config.json");
        fs::write(
            &config,
            r#"{"version": "1.0.0", "packs": [{"name": "pdf", "enabled": false}]}"#,
        )
        .unwrap();

        let outcome = harness_pack_toggle_cmd("pdf", "on", Some(&config)).unwrap();
        assert_eq!(outcome.exit_code, 0);
        assert!(outcome.message.contains("pdf -> enabled=true"));
    }

    #[test]
    fn wrap_source_cmd_writes_a_source_envelope() {
        let dir = tempfile::tempdir().unwrap();
        let schema = dir.path().join("schema.json");
        fs::write(&schema, r#"{"type":"object"}"#).unwrap();
        let out = dir.path().join("out/source.json");

        let outcome = harness_wrap_source_cmd(&WrapSourceArgs {
            url: "https://example.com/a",
            content_type: "article",
            namespace: "edu",
            slug: "a",
            out: &out,
            title: Some("Title"),
            content_file: None,
            content: Some("some content"),
            source_type: None,
            schema: &schema,
            refs: &[],
        })
        .unwrap();
        assert_eq!(outcome.exit_code, 0);
        assert!(out.exists());
        assert!(outcome.message.contains("wrap-source: wrote"));
    }

    #[test]
    fn build_graph_cmd_writes_a_graph_from_findings() {
        let dir = tempfile::tempdir().unwrap();
        let findings_dir = dir.path().join("reports/t1/findings");
        fs::create_dir_all(&findings_dir).unwrap();
        fs::write(
            findings_dir.join("f1.json"),
            r#"{"@id":"urn:mif:f1","entity":{"name":"E"}}"#,
        )
        .unwrap();
        let out = dir.path().join("graph.json");

        let outcome = harness_build_graph_cmd(&findings_dir, Some(&out)).unwrap();
        assert_eq!(outcome.exit_code, 0);
        assert!(out.exists());
        assert!(outcome.message.contains("build-graph: wrote"));
    }

    #[test]
    fn build_index_cmd_writes_an_index_from_findings() {
        let dir = tempfile::tempdir().unwrap();
        let findings_dir = dir.path().join("reports/t1/findings");
        fs::create_dir_all(&findings_dir).unwrap();
        fs::write(
            findings_dir.join("f1.json"),
            r#"{"@id":"urn:mif:f1","entity":{"name":"E"}}"#,
        )
        .unwrap();
        let out = dir.path().join("index.json");

        let outcome = harness_build_index_cmd(&findings_dir, Some(&out)).unwrap();
        assert_eq!(outcome.exit_code, 0);
        assert!(out.exists());
        assert!(outcome.message.contains("build-index: wrote"));
    }

    #[test]
    fn resolve_membership_cmd_reports_members_stale_and_excluded() {
        let dir = tempfile::tempdir().unwrap();
        let topic_dir = dir.path().join("reports/t1");
        fs::create_dir_all(topic_dir.join("findings")).unwrap();
        fs::write(
            topic_dir.join("goal.json"),
            r#"{"dimensions": ["landscape"]}"#,
        )
        .unwrap();
        fs::write(
            dir.path().join("harness.config.json"),
            r#"{"freshness": {"default_days": 30}}"#,
        )
        .unwrap();
        fs::write(
            topic_dir.join("findings/f1.json"),
            r#"{"@id": "urn:mif:f1", "extensions": {"harness": {"dimension": "landscape",
                "verification": {"verdict": "survived", "attempted_at": "2026-05-30"}}}}"#,
        )
        .unwrap();

        let outcome = harness_resolve_membership_cmd("t1", Some("gv-1"), Some(dir.path())).unwrap();
        assert_eq!(outcome.exit_code, 0);
        assert!(outcome.message.contains("members: 1"));
    }

    #[test]
    fn graph_stats_cmd_counts_nodes_and_edges() {
        let dir = tempfile::tempdir().unwrap();
        let graph_path = dir.path().join("knowledge-graph.json");
        fs::write(
            &graph_path,
            r#"{"nodes":[{"id":"a"},{"id":"b"}],"edges":[{"source":"a","target":"b"}]}"#,
        )
        .unwrap();

        let outcome = harness_graph_stats_cmd(&graph_path).unwrap();
        assert_eq!(outcome.exit_code, 0);
        assert_eq!(outcome.message, "2 1");
    }

    #[test]
    fn render_artifact_cmd_writes_a_rendered_channel_file() {
        let dir = tempfile::tempdir().unwrap();
        let artifact_path = dir.path().join("artifact.json");
        fs::write(
            &artifact_path,
            r#"{"title":"T","sections":[],"sources":[]}"#,
        )
        .unwrap();
        let out = dir.path().join("out.md");

        let outcome = harness_render_artifact_cmd(&RenderArtifactArgs {
            artifact: &artifact_path,
            channel: "blog",
            out: &out,
            slug: "t",
            slugpath: "reports/t1/t.md",
            created: "2026-06-01T00:00:00Z",
            version: 1,
            verification: None,
        })
        .unwrap();
        assert_eq!(outcome.exit_code, 0);
        assert!(out.exists());
        assert!(outcome.message.contains("render: wrote"));
    }

    #[test]
    fn synthesize_artifact_cmd_writes_an_artifact_from_findings() {
        let dir = tempfile::tempdir().unwrap();
        let findings_dir = dir.path().join("reports/t1/findings");
        fs::create_dir_all(&findings_dir).unwrap();
        fs::write(
            findings_dir.join("f1.json"),
            r#"{"@id":"urn:mif:f1","content":"insight text",
                "citations":[{"url":"https://example.com","title":"Example"}]}"#,
        )
        .unwrap();
        let out = dir.path().join("artifact.json");

        let outcome =
            harness_synthesize_artifact_cmd(&findings_dir, Some("general"), Some(&out)).unwrap();
        assert_eq!(outcome.exit_code, 0);
        assert!(out.exists());
        assert!(outcome.message.contains("synthesize: wrote"));
    }

    #[test]
    fn import_corpus_cmd_imports_findings_into_a_topic() {
        let dir = tempfile::tempdir().unwrap();
        let schema = dir.path().join("schema.json");
        fs::write(&schema, r#"{"type":"object"}"#).unwrap();
        let src = dir.path().join("src");
        fs::create_dir_all(&src).unwrap();
        fs::write(
            src.join("f1.json"),
            r#"{"@id":"urn:mif:f1","provenance":{"sourceType":"web"}}"#,
        )
        .unwrap();
        let dest = dir.path().join("reports/t1");

        let outcome = harness_import_corpus_cmd(&ImportCorpusArgs {
            src_findings_dir: &src,
            dest_dir: &dest,
            topic: "t1",
            schema: &schema,
            refs: &[],
            config: None,
        })
        .unwrap();
        assert_eq!(outcome.exit_code, 0);
        assert!(outcome.message.contains("import: imported"));
    }

    #[test]
    fn build_concordance_cmd_writes_a_concordance_across_topics() {
        let dir = tempfile::tempdir().unwrap();
        let reports_dir = dir.path().join("reports");
        fs::create_dir_all(reports_dir.join("t1/findings")).unwrap();
        fs::write(
            reports_dir.join("t1/findings/f1.json"),
            r#"{"@id":"urn:mif:f1","entity":{"name":"E","entity_type":"concept"}}"#,
        )
        .unwrap();
        let out = dir.path().join("concordance.json");

        let outcome = harness_build_concordance_cmd(&reports_dir, Some(&out)).unwrap();
        assert_eq!(outcome.exit_code, 0);
        assert!(out.exists());
        assert!(outcome.message.contains("build-concordance: wrote"));
    }

    #[test]
    fn reconcile_session_cmd_reports_nothing_to_do_on_a_complete_session() {
        let dir = tempfile::tempdir().unwrap();
        let schema = dir.path().join("schema.json");
        fs::write(&schema, r#"{"type":"object"}"#).unwrap();
        let topic_dir = dir.path().join("reports/t1");
        fs::create_dir_all(topic_dir.join("findings")).unwrap();
        let sample = dir.path().join("sample.json");
        fs::write(&sample, r#"{"@id":"urn:mif:sample"}"#).unwrap();

        let outcome = harness_reconcile_session_cmd(&topic_dir, &schema, &[], &sample).unwrap();
        assert_eq!(outcome.exit_code, 0);
    }

    #[test]
    fn topic_metadata_cmd_prints_a_shell_script_for_a_registered_topic() {
        let dir = tempfile::tempdir().unwrap();
        let config = dir.path().join("harness.config.json");
        fs::write(
            &config,
            r#"{"topics": [{"id": "t1", "title": "Topic One", "status": "active"}],
                "dimensions": [{"id": "landscape", "description": "Market landscape"}]}"#,
        )
        .unwrap();
        let findings_dir = dir.path().join("findings");
        fs::create_dir_all(&findings_dir).unwrap();
        let goal_path = dir.path().join("goal.json");

        let outcome = harness_topic_metadata_cmd("t1", &config, &findings_dir, &goal_path).unwrap();
        assert_eq!(outcome.exit_code, 0);
        assert!(!outcome.message.is_empty());
    }

    #[test]
    fn topic_metadata_cmd_errors_on_an_unregistered_topic() {
        let dir = tempfile::tempdir().unwrap();
        let config = dir.path().join("harness.config.json");
        fs::write(&config, r#"{"topics": []}"#).unwrap();
        let findings_dir = dir.path().join("findings");
        fs::create_dir_all(&findings_dir).unwrap();

        assert!(
            harness_topic_metadata_cmd(
                "nope",
                &config,
                &findings_dir,
                &dir.path().join("goal.json")
            )
            .is_err()
        );
    }

    #[test]
    fn synthesize_corpus_cmd_writes_a_map_and_markdown() {
        let dir = tempfile::tempdir().unwrap();
        let concordance = dir.path().join("concordance.json");
        fs::write(
            &concordance,
            r#"{"nodes":[{"id":"n1","entityType":"Concept","topics":["t1"],"name":"N1"}],"edges":[]}"#,
        )
        .unwrap();
        let map_out = dir.path().join("map.json");
        let markdown_out = dir.path().join("out.md");

        let outcome =
            harness_synthesize_corpus_cmd(&concordance, &map_out, &markdown_out, None).unwrap();
        assert_eq!(outcome.exit_code, 0);
        assert!(map_out.exists());
        assert!(markdown_out.exists());
        assert!(outcome.message.contains("synthesize-corpus: wrote"));
    }

    fn write_ontology_root(root: &std::path::Path) {
        fs::create_dir_all(root.join(".claude")).unwrap();
        fs::write(
            root.join("harness.config.json"),
            r#"{"topics":[{"id":"edu","ontologies":["edu-fixture"]}],"ontologies":[]}"#,
        )
        .unwrap();
        fs::write(
            root.join(".claude/enabled-packs.json"),
            r#"{"ontologies":[]}"#,
        )
        .unwrap();
    }

    #[test]
    fn ontology_fetch_cmd_reports_nothing_to_fetch_with_no_ids() {
        let dir = tempfile::tempdir().unwrap();
        write_ontology_root(dir.path());

        let outcome = ontology_fetch_cmd(&[], false, Some(dir.path()), None, None, false).unwrap();
        assert_eq!(outcome.exit_code, 0);
        assert!(outcome.message.contains("nothing to fetch"));
    }

    #[test]
    fn ontology_check_pin_safety_cmd_reports_nothing_given_no_ids() {
        let dir = tempfile::tempdir().unwrap();
        write_ontology_root(dir.path());

        let outcome =
            ontology_check_pin_safety_cmd(&[], Some(dir.path()), None, None, None).unwrap();
        assert_eq!(outcome.exit_code, 0);
        assert!(outcome.message.contains("no ids given"));
    }

    #[test]
    fn ontology_check_pin_safety_cmd_reports_nothing_for_an_unpinned_id() {
        let dir = tempfile::tempdir().unwrap();
        write_ontology_root(dir.path());
        let config_path = dir.path().join("harness.config.json");

        // A reachable registry with an index entry for edu-fixture, but no
        // ontologies.lock.json at all: check_pin_safety must always fetch
        // the index first (to resolve `--source`), then find nothing
        // pinned for the requested id and skip it.
        let registry = dir.path().join("registry");
        fs::create_dir_all(&registry).unwrap();
        fs::write(
            registry.join("index.json"),
            r#"{"ontologies":{"edu-fixture":{"version":"0.1.0","sha256":"irrelevant","file":"edu-fixture.ontology.yaml","extends":["mif-base"]}}}"#,
        )
        .unwrap();
        let source = registry.display().to_string();

        let outcome = ontology_check_pin_safety_cmd(
            &["edu-fixture".to_string()],
            Some(dir.path()),
            Some(config_path.as_path()),
            Some(&source),
            None,
        )
        .unwrap();
        assert_eq!(outcome.exit_code, 0);
        assert!(
            outcome
                .message
                .contains("no drifted pinned ontologies among the requested ids")
        );
    }

    #[test]
    fn ontology_check_pin_safety_cmd_warns_about_a_stamped_finding_missing_a_new_field() {
        let dir = tempfile::tempdir().unwrap();
        write_ontology_root(dir.path());

        // Vendored (old) pack: `title` requires only `name`.
        fs::create_dir_all(dir.path().join("packs/ontologies/edu-fixture")).unwrap();
        fs::write(
            dir.path()
                .join("packs/ontologies/edu-fixture/edu-fixture.ontology.yaml"),
            "ontology:\n  id: edu-fixture\n  version: \"0.1.0\"\n  extends: \
             [mif-base]\nentity_types:\n  - name: title\n    schema:\n      required: \
             [name]\n      properties:\n        name: {type: string}\n",
        )
        .unwrap();

        // Registry (new) pack: `title` now also requires `isbn`.
        // `check_pin_safety` verifies the fetched file's sha256 against the
        // index, the same integrity check `fetch` applies — the index
        // entry's `sha256` below must be real, not a placeholder. No
        // `index_sha256` is set in the lock, so the trust-on-first-use
        // check (only active when a prior pin exists) is not exercised
        // here.
        let registry = dir.path().join("registry");
        fs::create_dir_all(&registry).unwrap();
        let new_yaml = "ontology:\n  id: edu-fixture\n  version: \"0.2.0\"\n  extends: \
                         [mif-base]\nentity_types:\n  - name: title\n    schema:\n      \
                         required: [name, isbn]\n      properties:\n        name: {type: \
                         string}\n        isbn: {type: string}\n";
        let new_yaml_sha256 = {
            use std::fmt::Write as _;

            use sha2::{Digest, Sha256};
            let mut hasher = Sha256::new();
            hasher.update(new_yaml.as_bytes());
            hasher
                .finalize()
                .iter()
                .fold(String::new(), |mut hex, byte| {
                    let _ = write!(hex, "{byte:02x}");
                    hex
                })
        };
        let index = format!(
            r#"{{"ontologies":{{"edu-fixture":{{"version":"0.2.0","sha256":"{new_yaml_sha256}","file":"edu-fixture.ontology.yaml","extends":["mif-base"]}}}}}}"#
        );
        fs::write(registry.join("index.json"), &index).unwrap();
        fs::write(registry.join("edu-fixture.ontology.yaml"), new_yaml).unwrap();

        let source = registry.display().to_string();
        fs::write(
            dir.path().join("ontologies.lock.json"),
            serde_json::to_string(&serde_json::json!({
                "schema": "mif-ontology-lock/v1",
                "source": source,
                "ontologies": {"edu-fixture": {"version": "0.1.0", "sha256": "irrelevant"}}
            }))
            .unwrap(),
        )
        .unwrap();

        // A stamped finding, resolved against edu-fixture@0.1.0, missing isbn.
        let reports_dir = dir.path().join("reports");
        fs::create_dir_all(reports_dir.join("edu/findings")).unwrap();
        fs::write(
            reports_dir.join("edu/ontology-map.json"),
            r#"[{"finding_id":"f-1","entity_type":"title","resolved_ontology":"edu-fixture@0.1.0","basis":"resolved","valid":true}]"#,
        )
        .unwrap();
        fs::write(
            reports_dir.join("edu/findings/f-1.json"),
            r#"{"@id":"f-1","entity":{"name":"Algebra I"}}"#,
        )
        .unwrap();

        let config_path = dir.path().join("harness.config.json");
        let outcome = ontology_check_pin_safety_cmd(
            &["edu-fixture".to_string()],
            Some(dir.path()),
            Some(config_path.as_path()),
            Some(&source),
            Some(reports_dir.as_path()),
        )
        .unwrap();
        assert_eq!(outcome.exit_code, 0);
        assert!(outcome.message.contains("WARNING"));
        assert!(outcome.message.contains("f-1"));
        assert!(outcome.message.contains("isbn"));
    }

    #[test]
    fn ontology_check_pin_safety_cmd_reports_skipped_analysis_distinctly_from_safe() {
        let dir = tempfile::tempdir().unwrap();
        write_ontology_root(dir.path());

        // A registry ahead of the pinned lock, but no vendored pack on disk
        // to diff against: check_pin_safety cannot analyze this id, and the
        // CLI must not conflate that with "nothing newly required".
        let registry = dir.path().join("registry");
        fs::create_dir_all(&registry).unwrap();
        fs::write(
            registry.join("index.json"),
            r#"{"ontologies":{"edu-fixture":{"version":"0.2.0","sha256":"irrelevant","file":"edu-fixture.ontology.yaml","extends":["mif-base"]}}}"#,
        )
        .unwrap();
        fs::write(
            registry.join("edu-fixture.ontology.yaml"),
            "ontology:\n  id: edu-fixture\n  version: \"0.2.0\"\nentity_types: []\n",
        )
        .unwrap();
        let source = registry.display().to_string();
        fs::write(
            dir.path().join("ontologies.lock.json"),
            serde_json::to_string(&serde_json::json!({
                "schema": "mif-ontology-lock/v1",
                "source": source,
                "ontologies": {"edu-fixture": {"version": "0.1.0", "sha256": "irrelevant"}}
            }))
            .unwrap(),
        )
        .unwrap();

        let config_path = dir.path().join("harness.config.json");
        let outcome = ontology_check_pin_safety_cmd(
            &["edu-fixture".to_string()],
            Some(dir.path()),
            Some(config_path.as_path()),
            Some(&source),
            None,
        )
        .unwrap();
        assert_eq!(outcome.exit_code, 0);
        assert!(outcome.message.contains("analysis skipped"));
        assert!(!outcome.message.contains("nothing newly required"));
    }

    #[test]
    fn ontology_sync_cmd_catalogs_the_core_layers() {
        let dir = tempfile::tempdir().unwrap();
        write_ontology_root(dir.path());
        let config = dir.path().join("harness.config.json");
        let catalog = dir.path().join(".claude/enabled-packs.json");

        let outcome = ontology_sync_cmd(Some(dir.path()), Some(&config), Some(&catalog)).unwrap();
        assert_eq!(outcome.exit_code, 0);
        assert!(outcome.message.contains("ontology sync: cataloged"));
    }

    #[test]
    fn ontology_lock_check_cmd_passes_with_no_lock_file() {
        let dir = tempfile::tempdir().unwrap();
        write_ontology_root(dir.path());
        let config = dir.path().join("harness.config.json");

        let outcome = ontology_lock_check_cmd(Some(dir.path()), Some(&config)).unwrap();
        assert_eq!(outcome.exit_code, 0);
    }

    #[test]
    fn ontology_sync_registry_cmd_reports_no_new_ontologies_against_a_local_registry() {
        let dir = tempfile::tempdir().unwrap();
        write_ontology_root(dir.path());
        let config = dir.path().join("harness.config.json");
        let catalog = dir.path().join(".claude/enabled-packs.json");
        let registry = dir.path().join("registry");
        fs::create_dir_all(&registry).unwrap();
        fs::write(registry.join("index.json"), r#"{"ontologies":{}}"#).unwrap();

        let outcome = ontology_sync_registry_cmd(
            Some(dir.path()),
            Some(&config),
            Some(&catalog),
            Some(&registry.display().to_string()),
        )
        .unwrap();
        assert_eq!(outcome.exit_code, 0);
        assert!(outcome.message.contains("no new ontologies"));
    }

    #[test]
    fn ontology_author_cmd_drafts_from_a_topic_map() {
        let dir = tempfile::tempdir().unwrap();
        let reports_dir = dir.path().join("reports");
        fs::create_dir_all(reports_dir.join("t1")).unwrap();
        fs::write(
            reports_dir.join("t1/ontology-map.json"),
            r#"[{"finding_id":"urn:mif:f1","valid":false,"basis":"untyped",
                "entity_type":"widget","resolved_ontology":"mif-generic@1.0.0"}]"#,
        )
        .unwrap();
        let out = dir.path().join("new-id.ontology.yaml");

        let outcome =
            ontology_author_cmd("new-id", Some("t1"), None, Some(&out), Some(&reports_dir))
                .unwrap();
        assert_eq!(outcome.exit_code, 0);
        assert!(out.exists());
        assert!(outcome.message.contains("ontology author: drafted"));
    }
}