roteiro 1.4.0

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

use clap::{Parser, Subcommand};

mod config;
// The read-only `/v1/graph/*` JSON API. Its runtime callers are `run_explorer`
// (the llama-free standalone server) and `serve_v1_tail` (merged onto `/v1` in a
// full `serve` build), so under `explorer` the router is always live.
#[cfg(feature = "explorer")]
mod graph_api;
// The served workspace-explorer web app (HTML shell + hand-written ES app +
// vendored cytoscape.js), same-origin over the `explorer` server's data API.
#[cfg(feature = "explorer")]
mod explorer_app;
mod infer_links;
mod init;
mod overview;
mod pins;
mod review;

#[derive(Parser)]
#[command(
    name = "roteiro",
    version,
    about = "Provenance-tagged codebase knowledge graph",
    long_about = "Roteiro — the pilot book for your codebase.\n\n\
        One SQLite store holding structure, intent, and context as a single \
        provenance-tagged knowledge graph, queryable by humans and AI agents \
        alike. Subcommands are scaffolds while the graph core lands; see \
        ADR-0001 and docs/BUILD_PLAN.md for the roadmap.",
    arg_required_else_help = true,
    propagate_version = true
)]
struct Cli {
    #[command(subcommand)]
    command: Command,
}

#[derive(Subcommand)]
enum Command {
    /// Scaffold Roteiro in the current repository (store, hooks, agent skill).
    Init {
        /// Install freshness hooks that fetch the CI-published graph artifact
        /// (via `gh`) before rebuilding locally. Opt-in: the hooks only reach the
        /// network with this flag, and fall back to a local rebuild on any miss.
        #[arg(long)]
        fetch: bool,
        /// Also regenerate the local Obsidian vault (`vault/`, gitignored) from
        /// the graph on every checkout/merge/commit, so it stays current.
        #[arg(long)]
        vault: bool,
    },
    /// Incrementally update the graph for the current tree (content-addressed).
    ///
    /// By default this includes uncommitted edits to tracked files (a
    /// pre-commit preview); pass `--committed` to sync only the `HEAD` tree.
    Sync {
        /// Emit the sync report as JSON.
        #[arg(long)]
        json: bool,
        /// Sync only the committed `HEAD` tree, ignoring uncommitted edits.
        #[arg(long)]
        committed: bool,
    },
    /// Graph-grounded review of the current working-tree change: for each
    /// touched symbol, its callers/callees, the ADRs governing it, related docs,
    /// plus the intent-debt and authored drift the change introduces and the
    /// blast radius of dependents to check. Non-zero exit when the change
    /// introduces drift. The CLI-first review surface (MCP tools are a bonus).
    Review {
        /// Emit the review as JSON.
        #[arg(long)]
        json: bool,
        /// Review the commit range `<base>..HEAD` (any revspec — a branch,
        /// `HEAD~3`, a sha) against the committed graph, instead of the
        /// working-tree change. Use for a whole-branch review (e.g. `--base main`).
        #[arg(long)]
        base: Option<String>,
    },
    /// Verify authored links against code and ADR states; non-zero on drift.
    ///
    /// By default this validates the working tree — tracked files as they are on
    /// disk, unstaged edits included (not the git index). Pass `--staged` to
    /// validate exactly the git index (what a commit would record — the precise
    /// pre-commit gate), or `--committed` to validate only the `HEAD` tree (the
    /// CI merge gate).
    Check {
        /// Emit the check report as JSON.
        #[arg(long)]
        json: bool,
        /// Validate only the committed `HEAD` tree, ignoring uncommitted edits.
        #[arg(long, conflicts_with = "staged")]
        committed: bool,
        /// Validate the git index — exactly what a commit would record (staged
        /// changes only, not unstaged working-tree edits).
        #[arg(long)]
        staged: bool,
    },
    /// Query the graph: explain a node, or list all nodes of a kind.
    Query {
        /// Node key to explain (e.g. `sym:rust:…#Store`, `adr:0001`, `file:…`).
        key: Option<String>,
        /// List all nodes of this kind instead of explaining a key.
        #[arg(long, conflicts_with = "key")]
        kind: Option<String>,
        /// When listing `--kind config_key`, drop keys that come from build /
        /// tooling / CI config (`Cargo.toml`, `.github/` workflows, nextest, …),
        /// leaving only application config. Opt-in; the default lists everything.
        #[arg(long)]
        app_config_only: bool,
        /// Emit the result as JSON.
        #[arg(long)]
        json: bool,
    },
    /// Search the graph by text — ranked hits over names, keys, paths and
    /// captured content (doc/ADR/blueprint prose). The entry point for
    /// "what/why" questions; then `query` a returned key to explain it.
    Search {
        /// Free-text query (one or more words).
        query: String,
        /// Maximum number of hits to return.
        #[arg(long, default_value_t = 10)]
        limit: usize,
        /// Emit the results as JSON.
        #[arg(long)]
        json: bool,
    },
    /// Fetch a node's cached context bundle (its provenance-labelled
    /// neighbourhood), or refresh all cached contexts that have gone stale.
    Context {
        /// Node key to fetch context for. Omit together with `--refresh`.
        key: Option<String>,
        /// Rebuild every cached context whose node or a neighbour changed, prune
        /// entries for deleted nodes, and report the counts.
        #[arg(long, conflicts_with = "key")]
        refresh: bool,
        /// Emit the result as JSON.
        #[arg(long)]
        json: bool,
    },
    /// Show the effective, merged configuration. The default human-readable
    /// output labels each value's provenance (which layer set it); `--json`
    /// emits only the effective config, without provenance.
    Config {
        /// Emit the effective config as JSON (no provenance; use the default
        /// text output to see which layer set each value).
        #[arg(long)]
        json: bool,
    },
    /// List intent-debt markers (TODOs, stubs, deferred work) in the graph.
    Debt {
        /// Restrict to these categories (repeatable): todo | fixme | hack |
        /// stub | deferred. Omit to list all.
        #[arg(long, value_name = "CATEGORY")]
        kind: Vec<String>,
        /// Emit the report as JSON.
        #[arg(long)]
        json: bool,
    },
    /// Find a shortest path between two nodes (edges followed either direction).
    Path {
        /// Start node key.
        from: String,
        /// Goal node key.
        to: String,
        /// Emit the result as JSON.
        #[arg(long)]
        json: bool,
    },
    /// Verify cross-repo links across a workspace (ADR-0009): resolve each repo's
    /// authored `[[links]]` against the other repos' graphs, reporting the target
    /// each resolves to and flagging **drift** (targets that no longer exist).
    /// Exits non-zero when any link is unresolved, so it works as a CI gate.
    ///
    /// With `--infer`, instead auto-match each repo's **config keys** (TOML / JSON
    /// / `.env`) against a hub repo's — surfacing correspondences with no
    /// hand-authored links, and flagging orphan keys (drift candidates).
    ///
    /// With `--matrix`, render the cross-repo **config override matrix + drift**
    /// view (ADR-0009 "views") — every hub key against each spoke that overrides
    /// it — as a text table, `--json`, or a self-contained `--html` page.
    Links {
        /// Workspace root to include (repeatable); combined with `[workspace]`
        /// config and the current repo.
        #[arg(long, value_name = "ROOT")]
        workspace: Vec<String>,
        /// Select a **named** workspace from config (`[[workspaces]]`/`[standalone]`)
        /// to scope the report to. Default: the workspace containing the current
        /// repo, else today's flat `[workspace]` scope. Any `--workspace <ROOT>` is
        /// still unioned into the selected workspace.
        #[arg(long = "workspace-name", short = 'w', value_name = "NAME")]
        workspace_name: Option<String>,
        /// Infer links by matching config keys across repos, instead of verifying
        /// authored `[[links]]`. Mutually exclusive with `--matrix`.
        #[arg(long, conflicts_with = "matrix")]
        infer: bool,
        /// Render the cross-repo config override matrix + drift view instead of the
        /// authored-link report.
        #[arg(long)]
        matrix: bool,
        /// The source-of-truth project to match against (default: the repo with the
        /// most config keys). Applies to `--infer` and `--matrix`.
        #[arg(long, value_name = "PROJECT")]
        hub: Option<String>,
        /// Resolve against the hub at a **pinned version** (a commit sha / tag / any
        /// git rev — e.g. the sha a spoke's submodule points at) instead of its
        /// `HEAD`, so drift is measured against the version actually deployed
        /// (ADR-0009 step 8). Applies to `--infer` and `--matrix`.
        #[arg(long, value_name = "REV")]
        hub_rev: Option<String>,
        /// With `--infer`: resolve **each spoke against the hub version it itself
        /// pins** — read from the spoke's `submodule` / `image_ref` node — instead
        /// of one version for all (ADR-0009 step 8b). Spokes with no detectable pin
        /// fall back to the hub's `HEAD`.
        #[arg(long, requires = "infer", conflicts_with_all = ["matrix", "hub_rev"])]
        pinned: bool,
        /// With `--infer`: persist the inferred correspondences into each spoke's
        /// graph as durable cross-repo edges (an `inferred` import layer that
        /// survives sync), instead of only reporting them.
        #[arg(long, requires = "infer")]
        write: bool,
        /// With `--matrix`: write a self-contained HTML page (the `render web-graph`
        /// output) to `--out` (default `roteiro-overview.html`; `-` for stdout).
        #[arg(long, requires = "matrix")]
        html: bool,
        /// With `--matrix --html`: output file (default `roteiro-overview.html`).
        #[arg(long, value_name = "FILE", requires = "html")]
        out: Option<String>,
        /// Exclude build / tooling / CI config (`Cargo.toml`, `.github/` workflows,
        /// nextest, …) from cross-repo matching, so `--infer`/`--matrix` compare and
        /// drift-check only application config — sharpening drift. Opt-in; the
        /// default considers every config key. Applies to `--infer` and `--matrix`.
        #[arg(long)]
        app_config_only: bool,
        /// Emit the report as JSON.
        #[arg(long)]
        json: bool,
    },
    /// Export the assembled graph to a portable JSON artifact.
    Export {
        /// Output file (default: `roteiro-graph.json`); `-` writes to stdout.
        #[arg(long)]
        out: Option<String>,
    },
    /// Load a graph artifact into the local store, skipping extraction.
    Load {
        /// Artifact file to load (`-` reads from stdin).
        file: String,
        /// Load even if the artifact's tree does not match the working `HEAD`.
        /// By default a mismatch is refused, so a fetched CI artifact for a
        /// different commit never installs a wrong graph (the hook then rebuilds).
        #[arg(long)]
        force: bool,
    },
    /// Import from an external knowledge graph (graphify, lat), or compare
    /// against a codegraph snapshot as a validation oracle.
    Import {
        /// Source: graphify | lat (imported), or codegraph (compared, oracle-only).
        #[arg(long)]
        from: String,
        /// Path to the source: a Graphify dir/`graph.json`, a `lat.md/` dir, or a
        /// codegraph `.db` snapshot.
        path: String,
        /// Emit the migration report as JSON.
        #[arg(long)]
        json: bool,
    },
    /// Render the graph: docs site or Obsidian vault.
    Render {
        /// Target: docs | obsidian
        target: String,
        /// Output directory (default: `website/dist` for docs, `vault` for obsidian).
        #[arg(long)]
        out: Option<String>,
    },
    /// Graph-grounded spec/blueprint authoring (ADR-0004). Tier 0: offline,
    /// deterministic — no model required.
    Spec {
        #[command(subcommand)]
        action: SpecAction,
    },
    /// Suggest `inferred` similarity edges (built with `--features inference`).
    #[cfg(feature = "inference")]
    Infer {
        /// Minimum confidence (cosine similarity) for a suggestion, `0.0..=1.0`.
        /// Overrides `[infer] min_confidence` in config; default 0.4.
        #[arg(long)]
        min_confidence: Option<f64>,
        /// Maximum suggestions per node. Overrides `[infer] top_k`; default 5.
        #[arg(long)]
        top_k: Option<usize>,
        /// Use a pulled local model by name instead of the offline default
        /// (requires `--features inference-local-models`; falls back to the
        /// hashing embedder if the model is not installed). Overrides
        /// `[models] embedding`.
        #[arg(long, value_name = "NAME")]
        model: Option<String>,
        /// Emit the report as JSON.
        #[arg(long)]
        json: bool,
    },
    /// Report likely-duplicate content: nodes with identical content (same git
    /// blob) or near-identical embeddings (built with `--features inference`).
    #[cfg(feature = "inference")]
    #[command(visible_alias = "dup")]
    Duplicates {
        /// Minimum cosine similarity for a near-duplicate pair, `0.0..=1.0`.
        /// Exact (same-blob) duplicates are always reported. Overrides
        /// `[duplicates] min_similarity`; default 0.9.
        #[arg(long)]
        min_similarity: Option<f64>,
        /// Maximum pairs to report. Overrides `[duplicates] limit`; default 50.
        #[arg(long)]
        limit: Option<usize>,
        /// Emit the report as JSON.
        #[arg(long)]
        json: bool,
    },
    /// Manage pluggable local models: list the registry, pull with consent
    /// (`--features models`).
    #[cfg(feature = "models")]
    Model {
        #[command(subcommand)]
        action: ModelAction,
    },
    /// Start a server: the MCP graph server (`--features mcp`) or the local
    /// OpenAI-compatible model endpoint (`--models`, `--features serve`).
    #[cfg(any(feature = "mcp", feature = "serve"))]
    Serve {
        /// Serve the OpenAI-compatible `/v1` endpoint over installed models
        /// (ADR-0006), instead of the MCP graph server. Needs `--features serve`.
        #[arg(long)]
        models: bool,
        /// MCP server: serve networked over streamable HTTP at ADDR (e.g.
        /// `127.0.0.1:8080`) instead of stdio. Terminate TLS at a reverse proxy.
        /// For the MCP-only server; with `--models`, use `--mcp` (+ `--addr`).
        #[arg(long, value_name = "ADDR", conflicts_with = "models")]
        http: Option<String>,
        /// Model server (`--models`): bind ADDR (default `127.0.0.1:8017`). A
        /// non-loopback address is warned about (no auth — front with a proxy).
        #[arg(long, value_name = "ADDR")]
        addr: Option<String>,
        /// Model server (`--models`): terminate TLS in-process using this PEM
        /// certificate-chain file (paired with `--tls-key`). Overrides
        /// `[serve] tls_cert`. Set both `--tls-cert` and `--tls-key` for HTTPS,
        /// or neither for plain HTTP; setting only one is an error.
        #[arg(long, value_name = "FILE")]
        tls_cert: Option<String>,
        /// Model server (`--models`): the PEM private-key file for `--tls-cert`.
        #[arg(long, value_name = "FILE")]
        tls_key: Option<String>,
        /// Workspace mode (ADR-0008): host every git repo under ROOT
        /// (repeatable), so one server — holding the model once — answers
        /// questions about many projects, selected per call by `project`.
        /// Combined with `[workspace]` config. Omit for single-repo serving
        /// (the current directory's repo).
        #[arg(long, value_name = "ROOT")]
        workspace: Vec<String>,
        /// Select a **named** workspace from config (`[[workspaces]]`/`[standalone]`,
        /// else the legacy `[workspace]` folded to `default`) as the default the flat
        /// `/v1/graph/*` routes bind to. Default: the workspace containing the current
        /// repo, else the sole configured workspace. Nested
        /// `/v1/graph/workspaces/{ws}/…` routes address a workspace explicitly and
        /// ignore this. An unknown name fails fast, listing the known ones.
        #[arg(long = "workspace-name", short = 'w', value_name = "NAME")]
        workspace_name: Option<String>,
        /// Workspace mode: (re)build each project's graph the first time it is
        /// queried, instead of serving whatever its hooks last left. Slower on
        /// first touch, but never serves a stale or missing graph (ADR-0008).
        #[arg(long)]
        sync_on_access: bool,
        /// With `--models`: also mount the MCP graph server at `/mcp` on the
        /// **same port**, so one process serves both `/v1` and `/mcp` over one
        /// Workspace (needs `--features serve,mcp`). Only meaningful with
        /// `--models` — the plain `serve` already is the MCP server.
        #[arg(long, requires = "models")]
        mcp: bool,
    },
    /// Serve the read-only graph explorer JSON API (`/v1/graph/*`) over HTTP,
    /// **llama-free** (ADR-0008): axum only — no model, no MCP, no C/C++
    /// toolchain. Multi-workspace aware — it builds a `WorkspaceSet` from config
    /// (`[[workspaces]]` / `[standalone]`, else the current repo alone), lists it
    /// at `GET /v1/graph/workspaces`, and serves each workspace's graph both under
    /// `/v1/graph/workspaces/{ws}/…` and, for the default workspace, flat under
    /// `/v1/graph/…`. Read-only: serves whatever each repo's graph currently holds
    /// (run `roteiro sync` to refresh). It also serves the interactive
    /// **workspace-explorer web app** at `GET /` (ADR-0010, same-origin over this
    /// API). The **Ask** tab remains out of scope; it needs the `serve` build's
    /// `/v1/chat/completions`, which this server deliberately does not offer. Needs
    /// `--features explorer`.
    #[cfg(feature = "explorer")]
    Explorer {
        /// Bind address (default `[serve] addr`, else `127.0.0.1:8017`). A
        /// non-loopback address is warned about — the API has no auth, so front it
        /// with a reverse proxy.
        #[arg(long, value_name = "ADDR")]
        addr: Option<String>,
        /// The workspace the flat `/v1/graph/*` routes operate on. Default: the
        /// sole configured workspace, else the one containing the current repo.
        /// Nested `/v1/graph/workspaces/{ws}/…` routes always address a workspace
        /// explicitly and ignore this.
        #[arg(long = "workspace-name", short = 'w', value_name = "NAME")]
        workspace_name: Option<String>,
    },
}

/// `roteiro spec` actions (ADR-0004).
#[derive(Subcommand)]
enum SpecAction {
    /// Assemble graph-grounded context for a topic: related symbols (with their
    /// callers/callees and governing ADRs) and related docs. The grounding to
    /// start authoring from.
    Context {
        /// Topic to search the graph for (e.g. a symbol, module, or concept).
        topic: String,
        /// Maximum symbols and docs to include.
        #[arg(long, default_value_t = 10)]
        limit: usize,
        /// Emit the context as JSON.
        #[arg(long)]
        json: bool,
    },
    /// Emit a house-style, graph-grounded, `check`-clean ADR/blueprint skeleton
    /// for a topic — with an interview checklist and a build-plan outline.
    Scaffold {
        /// Topic the artifact is about (grounds the skeleton against the graph).
        topic: String,
        /// Title (defaults to the topic).
        #[arg(long)]
        title: Option<String>,
        /// Artifact kind: `adr` (numbered decision) or `blueprint` (technical
        /// implementation plan).
        #[arg(long, default_value = "adr")]
        kind: String,
        /// Write to this file instead of stdout.
        #[arg(long)]
        out: Option<String>,
    },
    /// Scaffold, then draft the unfilled sections offline with a small local
    /// instruct model (ADR-0004 Tier 1). Needs a generation backend
    /// (`--features serve` or `--features inference-local-models`, both
    /// llama.cpp) and a pulled generative model; falls back to the plain
    /// scaffold otherwise.
    Draft {
        /// Topic the artifact is about (grounds the draft against the graph).
        topic: String,
        /// Title (defaults to the topic).
        #[arg(long)]
        title: Option<String>,
        /// Artifact kind: `adr` or `blueprint`.
        #[arg(long, default_value = "adr")]
        kind: String,
        /// Write to this file instead of stdout.
        #[arg(long)]
        out: Option<String>,
    },
}

/// `roteiro model` actions.
#[cfg(feature = "models")]
#[derive(Subcommand)]
enum ModelAction {
    /// List registry models and which are installed for this platform.
    List,
    /// Download a model into `~/.roteiro/models` (asks before fetching).
    Pull {
        /// Registry model name (see `roteiro model list`).
        name: String,
        /// Skip the confirmation prompt and download immediately.
        #[arg(long)]
        yes: bool,
    },
}

// `main` is a one-arm-per-subcommand dispatcher; splitting the match further just
// scatters the CLI wiring, so the line-count lint is noise here.
#[allow(clippy::too_many_lines)]
fn main() -> anyhow::Result<()> {
    // Restore the default SIGPIPE disposition before any output. Rust sets
    // SIGPIPE to `SIG_IGN` at startup, so writing to a closed stdout pipe
    // (`roteiro query … | head`) returns EPIPE and the `println!` family panics
    // with a broken-pipe backtrace instead of the process exiting quietly like a
    // normal Unix CLI. Resetting to `SIG_DFL` here — first line, before
    // `Cli::parse()` (which may itself print `--help`/`--version`) and before
    // dispatch, so every subcommand is covered — makes a closed pipe terminate
    // the process by signal, as expected. A no-op off Unix. The long-running
    // `serve`/`explorer` paths never write to a closing stdout pipe in normal
    // operation, so this does not affect them. (We forbid `unsafe` workspace-wide,
    // hence the `sigpipe` wrapper rather than a raw `libc::signal` call.)
    sigpipe::reset();
    let cli = Cli::parse();
    // Load layered config once (project `roteiro.toml` + user `~/.roteiro/
    // config.toml`); a malformed file is a hard error for any command (ADR-0007).
    let cwd = std::env::current_dir()?;
    let cfg = config::load(&cwd)?;
    // Resolve the ingestion toggles once; every command that (re)builds the graph
    // extracts with the same set so they share one cache, never thrashing it.
    let ingest = cfg.effective.ingest.resolve();
    // Paths excluded from the intent-debt scan (`[debt] ignore`), shared by
    // `debt` and `check`'s debt summary.
    let debt_ignore: &[String] = cfg.effective.debt.ignore.as_deref().unwrap_or(&[]);
    // Honour `[paths] model_store` before any command touches the model store.
    // The registry lives behind the `models` feature; on a build without it a
    // configured path is inert, so we warn rather than silently ignore it.
    if let Some(dir) = cfg.effective.paths.model_store.as_deref() {
        let dir = config::expand_tilde(dir).into_owned();
        #[cfg(feature = "models")]
        rto_graph::set_model_store(dir);
        #[cfg(not(feature = "models"))]
        {
            let _ = dir;
            eprintln!(
                "warning: `[paths] model_store` is set but this build lacks the \
                 `models` feature; the setting has no effect"
            );
        }
    }
    match cli.command {
        Command::Sync { json, committed } => run_sync(ingest, json, committed),
        Command::Check {
            json,
            committed,
            staged,
        } => run_check(ingest, json, committed, staged, debt_ignore),
        Command::Review { json, base } => run_review(ingest, json, base.as_deref()),
        Command::Query {
            key,
            kind,
            app_config_only,
            json,
        } => run_query(ingest, key, kind, app_config_only, json),
        Command::Search { query, limit, json } => run_search(ingest, &query, limit, json),
        Command::Context { key, refresh, json } => run_context(ingest, key, refresh, json),
        Command::Debt { kind, json } => run_debt(ingest, &kind, json, debt_ignore),
        Command::Path { from, to, json } => run_path(ingest, &from, &to, json),
        Command::Links {
            workspace,
            workspace_name,
            infer,
            matrix,
            hub,
            hub_rev,
            pinned,
            write,
            html,
            out,
            app_config_only,
            json,
        } => {
            let pin = PinnedHub {
                rev: hub_rev.as_deref(),
                auto: pinned,
                ingest,
            };
            let scope = LinksScope {
                cli_roots: &workspace,
                workspace_name: workspace_name.as_deref(),
            };
            let opts = InferOptions {
                hub: hub.as_deref(),
                pin,
                app_config_only,
            };
            if matrix {
                run_links_matrix(&cfg.effective, &scope, opts, html, out, json)
            } else if infer {
                run_links_infer(&cfg.effective, &scope, opts, write, json)
            } else {
                // `--app-config-only` only filters config-key matching, which the
                // plain authored-links report doesn't do. Reject it here rather than
                // silently ignoring it, so the flag never looks like it took effect.
                if app_config_only {
                    anyhow::bail!(
                        "`--app-config-only` applies only to `roteiro links --infer` / `--matrix` \
                         (it filters cross-repo config-key matching); \
                         `roteiro query --kind config_key --app-config-only` supports it too"
                    );
                }
                run_links(&cfg.effective, &scope, json)
            }
        }
        Command::Export { out } => run_export(ingest, out),
        Command::Load { file, force } => run_load(&file, force),
        Command::Init { fetch, vault } => run_init(ingest, fetch, vault),
        Command::Render { target, out } => run_render(ingest, &target, out),
        Command::Import { from, path, json } => run_import(ingest, &from, &path, json),
        Command::Spec { action } => run_spec(&cfg.effective, ingest, action),
        Command::Config { json } => run_config(&cfg, json),
        #[cfg(feature = "inference")]
        Command::Infer {
            min_confidence,
            top_k,
            model,
            json,
        } => run_infer(&cfg.effective, ingest, min_confidence, top_k, model, json),
        #[cfg(feature = "inference")]
        Command::Duplicates {
            min_similarity,
            limit,
            json,
        } => run_duplicates(&cfg.effective, ingest, min_similarity, limit, json),
        #[cfg(feature = "models")]
        Command::Model { action } => run_model(action),
        #[cfg(any(feature = "mcp", feature = "serve"))]
        Command::Serve {
            models,
            http,
            addr,
            tls_cert,
            tls_key,
            workspace,
            workspace_name,
            sync_on_access,
            mcp,
        } => run_serve(
            ingest,
            &cfg.effective,
            ServeOptions {
                models,
                http,
                addr,
                tls_cert,
                tls_key,
                mcp,
            },
            &workspace,
            workspace_name.as_deref(),
            sync_on_access,
        ),
        #[cfg(feature = "explorer")]
        Command::Explorer {
            addr,
            workspace_name,
        } => run_explorer(&cfg.effective, addr, workspace_name.as_deref()),
    }
}

/// Which layer set a value, given whether the project/user layers carry it.
fn provenance(proj: bool, usr: bool) -> &'static str {
    if proj {
        "project"
    } else if usr {
        "user"
    } else {
        "default"
    }
}

/// Print `value` as pretty JSON to stdout — the shared `--json` output path for
/// every subcommand.
fn emit_json<T: serde::Serialize>(value: &T) -> anyhow::Result<()> {
    println!("{}", serde_json::to_string_pretty(value)?);
    Ok(())
}

/// Print the effective, merged configuration and each value's provenance
/// (`project` / `user` / `default`) — the answer to "why did it use that?".
fn run_config(loaded: &config::Loaded, json: bool) -> anyhow::Result<()> {
    if json {
        emit_json(&loaded.effective)?;
        return Ok(());
    }
    println!(
        "project config: {}",
        loaded
            .project_path
            .as_deref()
            .map_or_else(|| "(none)".to_owned(), |p| p.display().to_string())
    );
    println!(
        "user config:    {}",
        loaded
            .user_path
            .as_deref()
            .map_or_else(|| "(none)".to_owned(), |p| p.display().to_string())
    );
    print_config_sections(loaded);
    println!("\n(unset values fall back to built-in defaults; a CLI flag overrides config)");
    Ok(())
}

/// Print each config section's values with provenance labels.
fn print_config_sections(loaded: &config::Loaded) {
    let source = provenance;
    let e = &loaded.effective;
    let (p, u) = (&loaded.project, &loaded.user);
    println!("\n[models]");
    println!(
        "  embedding  = {:?}  ({})",
        e.models.embedding,
        source(p.models.embedding.is_some(), u.models.embedding.is_some())
    );
    println!(
        "  generative = {:?}  ({})",
        e.models.generative,
        source(p.models.generative.is_some(), u.models.generative.is_some())
    );
    println!("[infer]");
    println!(
        "  min_confidence = {:?}  ({})",
        e.infer.min_confidence,
        source(
            p.infer.min_confidence.is_some(),
            u.infer.min_confidence.is_some()
        )
    );
    println!(
        "  top_k          = {:?}  ({})",
        e.infer.top_k,
        source(p.infer.top_k.is_some(), u.infer.top_k.is_some())
    );
    println!("[duplicates]");
    println!(
        "  min_similarity = {:?}  ({})",
        e.duplicates.min_similarity,
        source(
            p.duplicates.min_similarity.is_some(),
            u.duplicates.min_similarity.is_some()
        )
    );
    println!(
        "  limit          = {:?}  ({})",
        e.duplicates.limit,
        source(p.duplicates.limit.is_some(), u.duplicates.limit.is_some())
    );
    println!("[ingest]");
    println!(
        "  prose  = {:?}  ({})",
        e.ingest.prose,
        source(p.ingest.prose.is_some(), u.ingest.prose.is_some())
    );
    println!(
        "  pdf    = {:?}  ({})",
        e.ingest.pdf,
        source(p.ingest.pdf.is_some(), u.ingest.pdf.is_some())
    );
    println!(
        "  ocr    = {:?}  ({})",
        e.ingest.ocr,
        source(p.ingest.ocr.is_some(), u.ingest.ocr.is_some())
    );
    println!(
        "  vision = {:?}  ({})",
        e.ingest.vision,
        source(p.ingest.vision.is_some(), u.ingest.vision.is_some())
    );
    println!(
        "  audio  = {:?}  ({})",
        e.ingest.audio,
        source(p.ingest.audio.is_some(), u.ingest.audio.is_some())
    );
    println!("[serve]");
    println!(
        "  addr   = {:?}  ({})",
        e.serve.addr,
        source(p.serve.addr.is_some(), u.serve.addr.is_some())
    );
    println!(
        "  models = {:?}  ({})",
        e.serve.models,
        source(p.serve.models.is_some(), u.serve.models.is_some())
    );
    println!(
        "  tools  = {:?}  ({})",
        e.serve.tools,
        source(p.serve.tools.is_some(), u.serve.tools.is_some())
    );

    print_workspace_section(e, p, u);
}

/// Print the `[workspace]` and `[[links]]` config sections (ADR-0008/0009), with
/// each value's provenance. Split out of [`print_config_sections`] to keep it
/// under the line budget.
fn print_workspace_section(e: &config::Config, p: &config::Config, u: &config::Config) {
    println!("[workspace]");
    println!(
        "  roots = {:?}  ({})",
        e.workspace.roots,
        provenance(p.workspace.roots.is_some(), u.workspace.roots.is_some())
    );
    println!(
        "  repos = {:?}  ({})",
        e.workspace.repos,
        provenance(p.workspace.repos.is_some(), u.workspace.repos.is_some())
    );
    if !e.links.is_empty() {
        println!(
            "[[links]]  ({} cross-repo link(s), ADR-0009)",
            e.links.len()
        );
        for l in &e.links {
            println!(
                "{}  ({})",
                l.to,
                l.kind.as_deref().unwrap_or("references")
            );
        }
    }
}

/// Sync the graph for the current repository, optionally including uncommitted
/// edits to tracked files.
fn run_sync(
    ingest: rto_graph::IngestConfig,
    json: bool,
    committed_only: bool,
) -> anyhow::Result<()> {
    use rto_graph::{ObjectCache, Registry, Repo, Store, sync, sync_worktree};

    let cwd = std::env::current_dir()?;
    let repo = Repo::discover(&cwd)?;

    // Graph DB is per-worktree (under the worktree git dir); the extraction
    // cache is shared across worktrees (under the common git dir).
    let store_dir = repo.git_dir().join("roteiro");
    std::fs::create_dir_all(&store_dir)?;
    let mut store = Store::open(&store_dir.join("graph.db"))?;
    let cache = ObjectCache::open(repo.common_dir().join("roteiro").join("objects"))?;

    let registry = Registry::new(ingest);
    let report = if committed_only {
        sync(&mut store, &repo, &cache, &registry)?
    } else {
        sync_worktree(&mut store, &repo, &cache, &registry)?
    };

    if json {
        emit_json(&report)?;
    } else {
        let tree = &report.tree[..report.tree.len().min(12)];
        let dirty = if report.blobs_dirty > 0 {
            format!(" +{} uncommitted", report.blobs_dirty)
        } else {
            String::new()
        };
        if report.no_op {
            println!(
                "up to date (tree {tree}{dirty}) — {} nodes, {} edges",
                report.nodes, report.edges
            );
        } else {
            println!(
                "synced tree {tree}{dirty}{} blobs ({} extracted, {} cached) → {} nodes, {} edges",
                report.blobs_total,
                report.blobs_extracted,
                report.blobs_cached,
                report.nodes,
                report.edges
            );
        }
    }
    Ok(())
}

/// Open the repository and its per-worktree store and shared object cache.
fn open_graph() -> anyhow::Result<(rto_graph::Repo, rto_graph::Store, rto_graph::ObjectCache)> {
    use rto_graph::{ObjectCache, Repo, Store};
    let cwd = std::env::current_dir()?;
    let repo = Repo::discover(&cwd)?;
    let store_dir = repo.git_dir().join("roteiro");
    std::fs::create_dir_all(&store_dir)?;
    let store = Store::open(&store_dir.join("graph.db"))?;
    let cache = ObjectCache::open(repo.common_dir().join("roteiro").join("objects"))?;
    Ok((repo, store, cache))
}

/// The bytes of a tracked file's authored source: the committed `HEAD` blob when
/// `committed`, otherwise its **working-tree** copy — the file as it is on disk,
/// which includes any unstaged edits and is *not* the git index. (This matches
/// [`rto_graph::sync_worktree`], which the derived graph is built from, so the
/// authored and derived layers stay consistent.) Returns `Ok(None)` when a
/// worktree file has been deleted, so the caller drops it.
fn read_source(
    repo: &rto_graph::Repo,
    blob: &rto_graph::BlobRef,
    source: GraphSource,
) -> anyhow::Result<Option<Vec<u8>>> {
    match source {
        // Worktree: the file as it stands on disk (unstaged edits included), or
        // `None` if it was deleted there.
        GraphSource::Worktree => match repo.workdir() {
            Some(workdir) => match std::fs::read(workdir.join(&blob.path)) {
                Ok(bytes) => Ok(Some(bytes)),
                Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
                Err(e) => Err(e.into()),
            },
            None => Ok(Some(repo.read_blob(&blob.oid)?)),
        },
        // Committed reads the `HEAD` blob; Index reads the staged blob — for both,
        // `blob.oid` is already the right object (the blob list came from that
        // tree), so read it directly.
        GraphSource::Committed | GraphSource::Index => Ok(Some(repo.read_blob(&blob.oid)?)),
    }
}

/// Which tree the graph is built from: the committed `HEAD`, the working tree
/// (uncommitted edits on disk), or the git index (the staged tree a commit would
/// record). Selects the sync engine and the authored-layer source together.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum GraphSource {
    /// The committed `HEAD` tree (the CI merge gate).
    Committed,
    /// The working tree: `HEAD` plus uncommitted edits to tracked files on disk.
    Worktree,
    /// The git index — exactly what a commit would record (the pre-commit gate).
    Index,
}

/// Build the full graph into `store`: the derived code graph plus the authored
/// ADR layer, both from the tree named by `source`. Returns the authored-layer
/// check report (used by `check`; ignored by `query`).
fn build_graph(
    repo: &rto_graph::Repo,
    store: &mut rto_graph::Store,
    cache: &rto_graph::ObjectCache,
    ingest: rto_graph::IngestConfig,
    source: GraphSource,
) -> anyhow::Result<rto_spec::CheckReport> {
    use rto_graph::{Registry, sync, sync_index, sync_worktree};
    let registry = Registry::new(ingest);
    match source {
        GraphSource::Committed => sync(store, repo, cache, &registry)?,
        GraphSource::Worktree => sync_worktree(store, repo, cache, &registry)?,
        GraphSource::Index => sync_index(store, repo, cache, &registry)?,
    };

    // The authored-layer file set must match the derived tree: the staged files
    // in Index mode (so a staged-new ADR is seen), else the `HEAD` tree.
    let blobs = match source {
        GraphSource::Index => repo.index_files()?,
        GraphSource::Committed | GraphSource::Worktree => repo.walk_blobs()?,
    };
    let mut docs = Vec::new();
    let mut blueprints = Vec::new();
    let mut annotations = Vec::new();
    let mut malformed = Vec::new();
    for blob in blobs {
        // Parse the authored source from the same tree the derived layer used.
        let Some(bytes) = read_source(repo, &blob, source)? else {
            continue;
        };
        let text = String::from_utf8_lossy(&bytes);
        let file = std::path::Path::new(&blob.path);
        let is_md = file
            .extension()
            .and_then(|e| e.to_str())
            .is_some_and(|e| e.eq_ignore_ascii_case("md"));
        let name = file
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or_default();
        let is_adr = blob.path.starts_with("docs/adr/") && is_md && name != "README.md";
        if is_adr {
            match rto_spec::parse_adr(&blob.path, &text) {
                Ok(doc) => docs.push(doc),
                // A malformed ADR is drift, not a skippable warning: it would let
                // the gate pass while silently dropping authored intent.
                Err(e) => malformed.push(rto_spec::Violation {
                    kind: rto_spec::ViolationKind::MalformedAdr,
                    message: format!("{}: cannot parse ADR: {e}", blob.path),
                }),
            }
        } else if is_md && rto_spec::is_blueprint(&blob.path, &text) {
            // House-style blueprints (no frontmatter) author `[[…]]` links like
            // ADRs; their links are drift-checked against the derived graph too.
            blueprints.push(rto_spec::parse_blueprint(&blob.path, &text));
        } else {
            annotations.extend(rto_spec::scan_annotations(&blob.path, &text));
        }
    }

    let mut report = rto_spec::run(store, &docs, &blueprints, &annotations)?;
    report.violations.extend(malformed);

    // Re-apply any persisted import layers (Graphify, lat.md, …) on top of the
    // freshly-rebuilt derived + authored graph, so imported knowledge is durable
    // across code-changing syncs. Dangling edges (endpoints removed by a sync)
    // are tolerated.
    store.reapply_imports()?;
    Ok(report)
}

/// Validate the authored layer (ADR `[[…]]` links and `@rto:` annotations)
/// against the derived graph; exit non-zero on drift.
fn run_check(
    ingest: rto_graph::IngestConfig,
    json: bool,
    committed: bool,
    staged: bool,
    debt_ignore: &[String],
) -> anyhow::Result<()> {
    let source = if staged {
        GraphSource::Index
    } else if committed {
        GraphSource::Committed
    } else {
        GraphSource::Worktree
    };
    let (repo, mut store, cache) = open_graph()?;
    let report = build_graph(&repo, &mut store, &cache, ingest, source)?;

    if json {
        emit_json(&report)?;
    } else {
        for v in &report.violations {
            eprintln!("drift [{}]: {}", v.kind.label(), v.message);
        }
        println!(
            "checked {} ADR(s), {} blueprint(s): {} link(s) ok, {} annotation(s) ok, {} violation(s)",
            report.adrs,
            report.blueprints,
            report.links_ok,
            report.annotations_ok,
            report.violations.len(),
        );
        // Report intent debt alongside drift (a summary, not a gate).
        println!(
            "{}",
            debt_summary(&rto_graph::debt(&store, &[], debt_ignore)?)
        );
    }

    if report.has_violations() {
        std::process::exit(1);
    }
    Ok(())
}

/// Assemble a graph-grounded review and print it (human or `--json`); exit
/// non-zero if the change introduces drift. With `base`, review the commit range
/// `base..HEAD` against the committed graph; otherwise the working-tree change.
fn run_review(
    ingest: rto_graph::IngestConfig,
    json: bool,
    base: Option<&str>,
) -> anyhow::Result<()> {
    let (repo, mut store, cache) = open_graph()?;
    // Range review is over committed history, so build the committed (HEAD)
    // graph; a working-tree review overlays uncommitted edits so the graph and
    // the change set agree. Either way, capture the authored-layer drift.
    let source = if base.is_some() {
        GraphSource::Committed
    } else {
        GraphSource::Worktree
    };
    let report = build_graph(&repo, &mut store, &cache, ingest, source)?;
    let changed =
        if let Some(base) = base {
            repo.changed_between(base)?
        } else {
            // Working-tree review: tracked edits/deletes, plus brand-new untracked
            // files as additions — the overlaid graph already includes them, so the
            // change set must too or their symbols would go unreviewed.
            let mut changed = repo.changed_files()?;
            changed.extend(repo.untracked_files()?.into_iter().map(|path| {
                rto_graph::ChangedFile {
                    path,
                    status: rto_graph::ChangeStatus::Added,
                }
            }));
            changed.sort_by(|a, b| a.path.cmp(&b.path));
            // The two sets are normally disjoint (tracked vs untracked), but some
            // intermediate git states can overlap — dedupe by path so the review
            // never lists a file twice. A tracked entry sorts before its untracked
            // duplicate only by chance, so prefer keeping the first of each path.
            changed.dedup_by(|a, b| a.path == b.path);
            changed
        };
    let review = review::build(&store, &changed, &report.violations)?;

    if json {
        emit_json(&review)?;
    } else {
        print_review(&review, base);
    }
    if review.has_drift() {
        std::process::exit(1);
    }
    Ok(())
}

/// Render a review report as a compact, scannable summary.
fn print_review(review: &review::ReviewReport, base: Option<&str>) {
    if review.changed_files == 0 {
        match base {
            Some(base) => println!("no changes in {base}..HEAD to review"),
            None => println!("no working-tree changes to review"),
        }
        return;
    }
    for file in &review.files {
        println!("\n{} [{}]", file.path, file.status);
        for sym in &file.symbols {
            println!("  {} {}", sym.kind, sym.name);
            let show = |label: &str, keys: &[String]| {
                if !keys.is_empty() {
                    println!("    {label}: {}", keys.join(", "));
                }
            };
            show("called by", &sym.callers);
            show("calls", &sym.callees);
            show("governed by", &sym.governed_by);
            if !sym.related.is_empty() {
                let rel: Vec<String> = sym.related.iter().map(|r| r.node.clone()).collect();
                println!("    related: {}", rel.join(", "));
            }
        }
        if !file.debt.is_empty() {
            println!("  intent-debt: {}", file.debt.len());
        }
    }
    if !review.impacted.is_empty() {
        let names: Vec<&str> = review.impacted.iter().map(|i| i.key.as_str()).collect();
        println!("\nimpacted (blast radius): {}", names.join(", "));
    }
    if review.has_drift() {
        println!("\ndrift introduced by this change:");
        for d in &review.drift {
            println!("  [{}] {}", d.kind, d.message);
        }
    } else {
        println!("\nno authored-layer drift introduced");
    }
    println!(
        "\nreviewed {} changed file(s), {} impacted node(s), {} drift item(s)",
        review.changed_files,
        review.impacted.len(),
        review.drift.len()
    );
}

/// Scaffold Roteiro in the current repository: build the initial graph, install
/// the managed git hooks (`post-checkout`/`post-merge`/`post-commit` freshness +
/// a `pre-commit` drift gate), and add the `AGENTS.md` snippet.
fn run_init(ingest: rto_graph::IngestConfig, fetch: bool, vault: bool) -> anyhow::Result<()> {
    let (repo, mut store, cache) = open_graph()?;

    let report = build_graph(&repo, &mut store, &cache, ingest, GraphSource::Committed)?;
    let nodes = store.node_count()?;
    let edges = store.edge_count()?;

    // Install where git actually looks for hooks — honours `core.hooksPath`, and
    // otherwise the common git dir (shared across worktrees).
    let hooks_dir = repo.hooks_dir();
    for name in init::MANAGED_HOOKS {
        match init::install_hook(&hooks_dir, name, fetch, vault)? {
            init::HookOutcome::Installed => println!("installed hook: {name}"),
            init::HookOutcome::Updated => println!("refreshed hook: {name}"),
            init::HookOutcome::SkippedForeign => {
                let advice = if *name == "pre-commit" {
                    "add `roteiro check` to it to gate drift-introducing commits"
                } else {
                    "add `roteiro sync --committed` to it to keep the graph fresh"
                };
                eprintln!("warning: existing non-Roteiro `{name}` hook left untouched; {advice}");
            }
        }
    }

    if let Some(workdir) = repo.workdir() {
        let path = workdir.join("AGENTS.md");
        if init::ensure_agents(&path)? {
            println!("wrote Roteiro section to {}", path.display());
        }

        // Install the agent skill (the on-demand operational guide). Always the
        // cross-tool `.agents/skills` location; also GitHub's `.github/skills`
        // when the repo already uses `.github`, since its Copilot reviewer reads
        // that path.
        let mut skill_bases = vec![workdir.join(".agents")];
        if workdir.join(".github").is_dir() {
            skill_bases.push(workdir.join(".github"));
        }
        for base in &skill_bases {
            let full = init::skill_path(base);
            let rel = full.strip_prefix(workdir).unwrap_or(&full);
            match init::install_skill(base)? {
                init::HookOutcome::Installed => println!("installed skill: {}", rel.display()),
                init::HookOutcome::Updated => println!("refreshed skill: {}", rel.display()),
                init::HookOutcome::SkippedForeign => {
                    eprintln!(
                        "warning: existing non-Roteiro `{}` left untouched",
                        rel.display()
                    );
                }
            }
        }
    }

    // With `--vault`, render the vault once now so it exists immediately (the
    // installed hooks keep it fresh thereafter).
    if vault {
        render_obsidian(ingest, None)?;
    }

    println!("roteiro initialised — graph has {nodes} nodes, {edges} edges");
    if report.has_violations() {
        eprintln!(
            "note: {} authored-layer violation(s); run `roteiro check` for details",
            report.violations.len()
        );
    }
    Ok(())
}

/// Resolve a config-sourced embedding model name against this binary's feature
/// set. When built with `inference-local-models`, the name is honoured; when
/// built without it, a config-set model can't be loaded, so — per ADR-0007's
/// "missing-feature keys warn" rule — emit a warning and fall back to the
/// offline default (returning `None`) rather than hard-failing. An explicit
/// `--model` flag bypasses this and is validated directly by the embedder.
#[cfg(feature = "inference-local-models")]
fn config_embedding_model(name: Option<&str>) -> Option<String> {
    name.map(str::to_owned)
}

/// See the `inference-local-models` variant: without local models a
/// config-sourced embedding model is warned about and ignored.
#[cfg(all(feature = "inference", not(feature = "inference-local-models")))]
fn config_embedding_model(name: Option<&str>) -> Option<String> {
    if let Some(name) = name {
        eprintln!(
            "warning: config `[models] embedding = {name:?}` needs the \
             `inference-local-models` feature; this build ignores it and uses \
             the offline default (pass `--model` to force an error instead)"
        );
    }
    None
}

/// Suggest `inferred` similarity edges over the graph and apply them. Builds the
/// full derived + authored graph first, then adds the fuzzy suggestion layer.
#[cfg(feature = "inference")]
fn run_infer(
    cfg: &config::Config,
    ingest: rto_graph::IngestConfig,
    min_confidence: Option<f64>,
    top_k: Option<usize>,
    model: Option<String>,
    json: bool,
) -> anyhow::Result<()> {
    use rto_graph::{FactSet, InferenceConfig};

    // Precedence: CLI flag > config > built-in default.
    let min_confidence = min_confidence.or(cfg.infer.min_confidence).unwrap_or(0.4);
    let top_k = top_k.or(cfg.infer.top_k).unwrap_or(5);
    // An explicit `--model` flag is always honoured (and errors below if this
    // binary lacks local-model support). A model coming *only* from config must
    // degrade gracefully per ADR-0007: warn and fall back to the offline default
    // rather than hard-failing a build that can't use it.
    let model = model.or_else(|| config_embedding_model(cfg.models.embedding.as_deref()));

    if !(0.0..=1.0).contains(&min_confidence) {
        anyhow::bail!("--min-confidence must be in 0.0..=1.0 (got {min_confidence})");
    }

    let (repo, mut store, cache) = open_graph()?;
    build_graph(&repo, &mut store, &cache, ingest, GraphSource::Committed)?;

    // Inference is authoritative over *its own* suggestions: clear prior
    // embedding-produced edges first so the result reflects exactly the current
    // flags (build_graph may no-op on an unchanged tree, which would otherwise
    // leave stale suggestions). Edges from other producers (e.g. a Graphify
    // import) carry a different src_ref and are left untouched.
    store.delete_edges_by_src_ref(rto_graph::EMBED_REF)?;

    let config = InferenceConfig {
        min_confidence,
        top_k,
    };

    // Choose the embedder: a pulled local model if requested and installed,
    // otherwise the offline hashing default.
    let (edges, embedder_label) = infer_with_embedder(&store, config, model.as_deref())?;
    let count = edges.len();
    // Inferred edges are additive suggestions; applying them never alters the
    // derived/authored facts already in the store.
    store.apply_factset(&FactSet {
        nodes: vec![],
        edges,
    })?;

    if json {
        let report = serde_json::json!({
            "min_confidence": min_confidence,
            "top_k": top_k,
            "embedder": embedder_label,
            "inferred_edges": count,
        });
        emit_json(&report)?;
    } else {
        println!(
            "inferred {count} similarity edge(s) via {embedder_label} \
             (min-confidence {min_confidence}, top-k {top_k}); \
             query them with `roteiro query <key>`",
        );
    }
    Ok(())
}

/// Report likely-duplicate content (identical blobs + near-identical
/// embeddings) over the current graph. Read-only: builds the graph but applies
/// nothing. Uses the offline hashing embedder.
#[cfg(feature = "inference")]
fn run_duplicates(
    cfg: &config::Config,
    ingest: rto_graph::IngestConfig,
    min_similarity: Option<f64>,
    limit: Option<usize>,
    json: bool,
) -> anyhow::Result<()> {
    use rto_graph::DuplicateConfig;

    // Precedence: CLI flag > config > built-in default.
    let min_similarity = min_similarity
        .or(cfg.duplicates.min_similarity)
        .unwrap_or(0.9);
    let limit = limit.or(cfg.duplicates.limit).unwrap_or(50);

    if !(0.0..=1.0).contains(&min_similarity) {
        anyhow::bail!("--min-similarity must be in 0.0..=1.0 (got {min_similarity})");
    }

    let (repo, mut store, cache) = open_graph()?;
    build_graph(&repo, &mut store, &cache, ingest, GraphSource::Committed)?;

    let report = rto_graph::duplicates(
        &store,
        DuplicateConfig {
            min_similarity,
            limit,
        },
    )?;

    if json {
        emit_json(&report)?;
    } else if report.pairs.is_empty() {
        println!("no duplicate content found (min-similarity {min_similarity})");
    } else {
        let shown = if report.total > report.pairs.len() {
            format!(" (showing top {})", report.pairs.len())
        } else {
            String::new()
        };
        println!("{} duplicate pair(s){shown}:", report.total);
        for p in &report.pairs {
            let tag = if p.exact { "exact" } else { "~sim " };
            println!("  [{tag} {:.2}] {}  <->  {}", p.similarity, p.a, p.b);
        }
    }
    Ok(())
}

/// Run inference with the requested embedder, returning the edges and a label
/// describing which embedder was used. Without the `inference-local-models`
/// feature, only the hashing embedder exists.
#[cfg(all(feature = "inference", not(feature = "inference-local-models")))]
fn infer_with_embedder(
    store: &rto_graph::Store,
    config: rto_graph::InferenceConfig,
    model: Option<&str>,
) -> anyhow::Result<(Vec<rto_graph::Edge>, String)> {
    use rto_graph::infer_edges_with;
    if model.is_some() {
        anyhow::bail!(
            "--model requires the `inference-local-models` feature; \
             rebuild with `--features inference-local-models`"
        );
    }
    Ok((
        infer_edges_with(store, config, &rto_graph::HashEmbedder)?,
        "hashing embedder (offline default)".to_owned(),
    ))
}

/// Feature-rich variant: honour `--model` by loading a local **GGUF** embedding
/// model through the shared llama.cpp engine (ADR-0003 v1.2) — no candle.
#[cfg(feature = "inference-local-models")]
fn infer_with_embedder(
    store: &rto_graph::Store,
    config: rto_graph::InferenceConfig,
    model: Option<&str>,
) -> anyhow::Result<(Vec<rto_graph::Edge>, String)> {
    use rto_graph::{HashEmbedder, Platform, infer_edges_with};

    let Some(name) = model else {
        return Ok((
            infer_edges_with(store, config, &HashEmbedder)?,
            "hashing embedder (offline default)".to_owned(),
        ));
    };
    // Only accept a known registry model whose host-variant files are all
    // present — never an arbitrary directory under the store root.
    let spec = rto_graph::find_model(name)
        .ok_or_else(|| anyhow::anyhow!("unknown model `{name}` (see `roteiro model list`)"))?;
    // Reject non-embedding models upfront: a generative/OCR/vision model would
    // otherwise be "accepted", then fail every embed call — and because embed
    // errors degrade to empty vectors (see `LlamaEmbedder`), that would surface
    // silently as "no suggestions" rather than a clear error.
    if spec.kind != rto_graph::ModelKind::Embedding {
        anyhow::bail!(
            "model `{name}` is a {} model, not an embedding model — \
             `infer --model` needs an embedding model (see `roteiro model list`)",
            spec.kind.as_str()
        );
    }
    let variant = spec
        .variant_for(Platform::host())
        .ok_or_else(|| anyhow::anyhow!("no variant of `{name}` for this platform"))?;
    if !rto_graph::is_installed(name, variant) {
        anyhow::bail!(
            "model `{name}` is not installed — run `roteiro model pull {name}` \
             (or omit --model to use the offline default)"
        );
    }
    let embedder = LlamaEmbedder::new(name)?;
    let edges = infer_edges_with(store, config, &embedder)?;
    Ok((edges, format!("local model `{name}` (llama.cpp)")))
}

/// A GGUF embedding model behind the [`rto_graph::Embedder`] trait, backed by the
/// shared llama.cpp engine. On an embedding failure it returns an **empty**
/// vector rather than aborting the run — an empty vector shares no length with a
/// real embedding, so [`rto_graph::similarity`] scores it `0.0` against every
/// node (that node simply receives no suggestions).
#[cfg(feature = "inference-local-models")]
struct LlamaEmbedder {
    engine: rto_llama::llama::LlamaEngine,
    model: String,
}

#[cfg(feature = "inference-local-models")]
impl LlamaEmbedder {
    fn new(name: &str) -> anyhow::Result<Self> {
        let engine = rto_llama::llama::LlamaEngine::new(
            vec![rto_llama::llama::Served {
                name: name.to_owned(),
                path: rto_graph::model_dir(name).join("model.gguf"),
                mmproj: None,
            }],
            0,
        )
        .map_err(|e| anyhow::anyhow!("loading model `{name}`: {e}"))?;
        Ok(Self {
            engine,
            model: name.to_owned(),
        })
    }
}

#[cfg(feature = "inference-local-models")]
impl rto_graph::Embedder for LlamaEmbedder {
    fn embed(&self, text: &str) -> Vec<f32> {
        use rto_llama::Engine as _;
        self.engine
            .embed(&self.model, &[text.to_owned()])
            .ok()
            .and_then(|mut v| v.pop())
            .unwrap_or_default()
    }
}

/// Manage pluggable local embedding models: list the registry or pull a model.
#[cfg(feature = "models")]
fn run_model(action: ModelAction) -> anyhow::Result<()> {
    match action {
        ModelAction::List => {
            run_model_list();
            Ok(())
        }
        ModelAction::Pull { name, yes } => run_model_pull(&name, yes),
    }
}

/// Print the registry, marking which models are installed for this host.
#[cfg(feature = "models")]
fn run_model_list() {
    use rto_graph::{ModelKind, Platform, REGISTRY, ResourceTier};

    // Fixed-width, ASCII-safe status markers (same length either way) keep the
    // columns aligned regardless of a terminal's wide/ambiguous glyph handling.
    const MARK_INSTALLED: &str = "[installed]";
    const MARK_AVAILABLE: &str = "[available]";
    const _: () = assert!(MARK_INSTALLED.len() == MARK_AVAILABLE.len());

    let host = Platform::host();
    println!(
        "platform: {}   model store: {}",
        host.as_str(),
        rto_graph::store_root().display()
    );
    println!("(the built-in hashing embedder is always available with no model)");

    // Group the opinionated picks by section, then by resource tier, so the
    // "which should I pull?" answer reads off a machine's resources.
    let sections = [
        (ModelKind::Embedding, "Embedding (`roteiro infer --model`)"),
        (ModelKind::Generative, "Generative (`roteiro spec draft`)"),
        (
            ModelKind::Ocr,
            "OCR — image text (`roteiro sync` with --features image-ocr)",
        ),
        (
            ModelKind::Vision,
            "Vision — image description (`roteiro sync` with --features image-vision)",
        ),
        (
            ModelKind::Audio,
            "Audio — speech transcription (`roteiro sync` with --features audio-transcribe)",
        ),
    ];
    // Tier acts as a sub-heading, so it reads once per group instead of being
    // repeated as a prefix on every row.
    let tiers = [
        (ResourceTier::Low, "low  (any laptop)"),
        (ResourceTier::Mid, "mid  (~16 GB)"),
        (ResourceTier::High, "high (workstation / 64 GB)"),
    ];

    // Pad the name column to the widest registry name so metadata lines up, and
    // indent description continuation lines to start under the name column.
    let name_w = REGISTRY.iter().map(|s| s.name.len()).max().unwrap_or(0);
    let desc_indent = 4 + MARK_AVAILABLE.len() + 1;

    for (kind, heading) in sections {
        println!("\n{heading}:");
        for (tier, tier_label) in tiers {
            let mut specs = REGISTRY
                .iter()
                .filter(|s| s.kind == kind && s.tier == tier)
                .peekable();
            // Skip a tier with no picks in this section rather than print an
            // empty sub-heading.
            if specs.peek().is_none() {
                continue;
            }
            println!("  {tier_label}");
            for spec in specs {
                let variant = spec.variant_for(host);
                let installed = variant.is_some_and(|v| rto_graph::is_installed(spec.name, v));
                let mark = if installed {
                    MARK_INSTALLED
                } else {
                    MARK_AVAILABLE
                };
                let dim = if spec.dim > 0 {
                    format!(", dim {}", spec.dim)
                } else {
                    String::new()
                };
                // Generative sub-role (instruct/coding/reasoning); empty otherwise.
                let role = spec
                    .role
                    .as_str()
                    .map(|r| format!(", {r}"))
                    .unwrap_or_default();
                println!(
                    "    {mark} {name:<name_w$}  {licence}{role}{dim}, ~{size} MiB",
                    name = spec.name,
                    licence = spec.licence,
                    size = spec.size_mib,
                );
                println!("{:desc_indent$}{desc}", "", desc = spec.description);
            }
        }
    }
}

/// Download a model into the store, asking for consent first (unless `--yes` or
/// non-interactive, in which case the manual command is printed instead).
#[cfg(feature = "models")]
fn run_model_pull(name: &str, yes: bool) -> anyhow::Result<()> {
    use rto_graph::{Platform, ensure_model_dir, find_model};
    use std::io::Write as _;

    let spec = find_model(name)
        .ok_or_else(|| anyhow::anyhow!("unknown model `{name}` (see `roteiro model list`)"))?;
    let variant = spec
        .variant_for(Platform::host())
        .ok_or_else(|| anyhow::anyhow!("no variant of `{name}` for this platform"))?;

    let stdin_is_tty = std::io::IsTerminal::is_terminal(&std::io::stdin());
    if !yes {
        // Print exactly what would be fetched — source + licence + size.
        eprintln!(
            "roteiro would download model `{name}` (~{} MiB, {}) from:",
            spec.size_mib, spec.licence
        );
        for f in variant.files {
            eprintln!("  {}", f.url);
        }
        if !stdin_is_tty {
            // Never fetch without an explicit human yes; print the manual route.
            eprintln!(
                "\nnon-interactive: not downloading. Re-run with `--yes`, or fetch manually into {}",
                rto_graph::model_dir(name).display()
            );
            anyhow::bail!("download declined (non-interactive)");
        }
        eprint!("Download now? [y/N] ");
        std::io::stderr().flush().ok();
        let mut answer = String::new();
        std::io::stdin().read_line(&mut answer)?;
        if !matches!(answer.trim(), "y" | "Y" | "yes" | "Yes") {
            anyhow::bail!("download declined");
        }
    }

    let dir = ensure_model_dir(name)?;
    for f in variant.files {
        let dest = dir.join(f.name);
        eprintln!("fetching {}", f.name);
        if f.sha256.is_empty() {
            // Make the absence of a pinned hash explicit rather than silently
            // "passing" verification (an empty hash is treated as unpinned).
            eprintln!(
                "  warning: no checksum pinned for {} — integrity NOT verified",
                f.name
            );
        }
        // Stream the response straight to disk, hashing as it writes and
        // installing atomically — so a 20 GiB model never buffers in memory.
        let reader = http_reader(f.url)?;
        rto_graph::download_verified(reader, &dest, f.sha256)
            .map_err(|e| anyhow::anyhow!("downloading {}: {e}", f.name))?;
    }
    let use_hint = match spec.kind {
        rto_graph::ModelKind::Embedding => format!("roteiro infer --model {name}"),
        rto_graph::ModelKind::Generative => "roteiro spec draft <topic>".to_owned(),
        rto_graph::ModelKind::Ocr => {
            "roteiro sync (a build with --features image-ocr OCRs images)".to_owned()
        }
        rto_graph::ModelKind::Vision => {
            "roteiro sync (a build with --features image-vision describes images)".to_owned()
        }
        rto_graph::ModelKind::Audio => {
            "roteiro sync (a build with --features audio-transcribe transcribes audio)".to_owned()
        }
    };
    println!(
        "installed `{name}` → {}  (use it with `{use_hint}`)",
        dir.display()
    );
    Ok(())
}

/// Open a streaming HTTPS reader for `url` (the body is not buffered whole).
#[cfg(feature = "models")]
fn http_reader(url: &str) -> anyhow::Result<impl std::io::Read> {
    Ok(ureq::get(url)
        .call()
        .map_err(|e| anyhow::anyhow!("GET {url}: {e}"))?
        .into_body()
        .into_reader())
}

/// Import an external knowledge graph into the store (or, for codegraph, compare
/// against it as a validation oracle).
fn run_import(
    ingest: rto_graph::IngestConfig,
    from: &str,
    path: &str,
    json: bool,
) -> anyhow::Result<()> {
    match from {
        "graphify" => run_import_graphify(ingest, path, json),
        "lat" => run_import_lat(ingest, path, json),
        "codegraph" => run_compare_codegraph(ingest, path, json),
        other => {
            anyhow::bail!("unknown import source `{other}` (expected: graphify | lat | codegraph)")
        }
    }
}

/// Compare Roteiro's derived graph against a codegraph `SQLite` snapshot and report
/// agreement/divergence. codegraph is a **validation oracle only** — its
/// structural edges are not imported (Roteiro re-derives them). Exits zero; the
/// report is informational.
fn run_compare_codegraph(
    ingest: rto_graph::IngestConfig,
    path: &str,
    json: bool,
) -> anyhow::Result<()> {
    let (repo, mut store, cache) = open_graph()?;
    // Build the derived graph so there is something to compare against.
    build_graph(&repo, &mut store, &cache, ingest, GraphSource::Committed)?;

    let report = rto_graph::compare_codegraph(std::path::Path::new(path), &store)?;

    if json {
        emit_json(&report)?;
    } else {
        if let Some(commit) = &report.source_commit {
            let short = &commit[..commit.len().min(12)];
            println!("codegraph oracle — snapshot indexed at {short}");
        }
        println!(
            "symbols: {} matched, {} scope-only diffs (same symbol, different \
             module scope), {} codegraph-only, {} roteiro-only \
             (codegraph {}, roteiro {}; {} constants are a known Roteiro gap)",
            report.symbols_matched,
            report.symbols_scope_diff,
            report.codegraph_only,
            report.roteiro_only,
            report.symbols_codegraph,
            report.symbols_roteiro,
            report.constants_codegraph,
        );
        println!(
            "calls: {}/{} codegraph internal calls agree ({} not re-derived — \
             Roteiro links only unambiguous calls)",
            report.calls_agree, report.calls_codegraph, report.calls_codegraph_only,
        );
        for key in report.codegraph_only_sample.iter().take(10) {
            println!("  codegraph-only: {key}");
        }
        for key in report.roteiro_only_sample.iter().take(10) {
            println!("  roteiro-only:   {key}");
        }
    }
    Ok(())
}

/// Import a lat.md directory: its markdown sections and `[[…]]` links become an
/// `authored` layer over the code graph (a doc node per file, a section node per
/// heading, `contains`/`references` edges). Durable and validated: links into
/// code that no longer exists are pruned by [`rto_graph::Store::apply_import_layer`].
fn run_import_lat(ingest: rto_graph::IngestConfig, path: &str, json: bool) -> anyhow::Result<()> {
    let (repo, mut store, cache) = open_graph()?;
    let root = repo
        .workdir()
        .ok_or_else(|| anyhow::anyhow!("cannot import into a bare repository"))?;

    let cwd = std::env::current_dir()?;
    let dir = {
        let p = std::path::Path::new(path);
        if p.is_absolute() {
            p.to_path_buf()
        } else {
            cwd.join(p)
        }
    };
    if !dir.is_dir() {
        anyhow::bail!(
            "lat directory not found: {} (expected a lat.md/ dir)",
            dir.display()
        );
    }

    // Collect every markdown file under the directory, keyed by its repo-relative
    // path so node keys (`lat:<path>`) are stable and links resolve consistently.
    let mut files = Vec::new();
    collect_markdown(&dir, root, &mut files)?;
    // Sort by path only; the content is never a tie-breaker (paths are unique).
    files.sort_by(|a, b| a.0.cmp(&b.0));
    if files.is_empty() {
        anyhow::bail!("no .md files under {}", dir.display());
    }

    let mut imported = rto_spec::import_lat(&files);

    // Also import `@lat:` backlinks from source comments across the committed
    // tree: each resolved reference becomes an authored `file → lat section`
    // edge folded into the same lat layer, so it persists and is re-derived with
    // the rest of the import (and pruned on re-import).
    let mut backlinks = Vec::new();
    for blob in repo.walk_blobs()? {
        let bytes = repo.read_blob(&blob.oid)?;
        let text = String::from_utf8_lossy(&bytes);
        backlinks.extend(rto_spec::scan_lat_annotations(&blob.path, &text));
    }
    let (backlink_edges, unresolved) = rto_spec::import_lat_backlinks(&files, &backlinks);
    imported.report.backlinks_resolved = backlink_edges.len();
    imported.report.backlinks_unresolved = unresolved;
    imported.facts.edges.extend(backlink_edges);

    // Build the derived + authored graph first so code links validate against it.
    build_graph(&repo, &mut store, &cache, ingest, GraphSource::Committed)?;
    let applied = store.apply_import_layer(rto_spec::LAT_REF, &imported.facts)?;

    let r = &imported.report;
    if json {
        let mut report = serde_json::to_value(r)?;
        report["edges_applied"] = serde_json::json!(applied.edges_applied);
        report["edges_pruned_stale"] = serde_json::json!(applied.edges_pruned);
        report["durable"] = serde_json::json!(true);
        emit_json(&report)?;
    } else {
        println!(
            "imported lat.md: {} file(s), {} section(s), {} link(s) \
             ({} to sections, {} to code), {} backlink(s) ({} unresolved); \
             {} edge(s) applied, {} stale pruned — persisted (durable)",
            r.files,
            r.sections,
            r.links_total,
            r.links_to_sections,
            r.links_to_code,
            r.backlinks_resolved,
            r.backlinks_unresolved,
            applied.edges_applied,
            applied.edges_pruned,
        );
    }
    Ok(())
}

/// Recursively collect `*.md` files under `dir`, pushing `(repo-relative path,
/// contents)` pairs. Paths use `/` separators for stable, portable node keys.
/// Errors if a file is outside the repository `root`, since a non-repo-relative
/// key would be unstable and would import content from outside the repo.
///
/// Symlinks are **not** followed (checked via [`std::fs::DirEntry::file_type`],
/// which does not traverse the link): a symlinked directory or file could
/// otherwise pull in out-of-repo content behind a repo-relative-looking key.
fn collect_markdown(
    dir: &std::path::Path,
    root: &std::path::Path,
    out: &mut Vec<(String, String)>,
) -> anyhow::Result<()> {
    for entry in std::fs::read_dir(dir)? {
        let entry = entry?;
        let file_type = entry.file_type()?;
        if file_type.is_symlink() {
            continue;
        }
        let path = entry.path();
        if file_type.is_dir() {
            collect_markdown(&path, root, out)?;
        } else if file_type.is_file() && path.extension().and_then(|e| e.to_str()) == Some("md") {
            let rel = path.strip_prefix(root).map_err(|_| {
                anyhow::anyhow!(
                    "lat file {} is outside the repository ({}); the lat.md \
                     directory must live inside the repo",
                    path.display(),
                    root.display()
                )
            })?;
            let rel = rel.to_string_lossy().replace('\\', "/");
            out.push((rel, std::fs::read_to_string(&path)?));
        }
    }
    Ok(())
}

/// Import a Graphify export: keep doc/concept/inferred knowledge, drop its code
/// structure (Roteiro re-derives that), and ground imported docs to real files.
/// The import is **durable**: its facts are persisted (keyed by
/// [`rto_spec::GRAPHIFY_REF`]) and re-applied by `build_graph` after every sync,
/// so they survive a later code-changing sync (dangling edges are tolerated).
fn run_import_graphify(
    ingest: rto_graph::IngestConfig,
    path: &str,
    json: bool,
) -> anyhow::Result<()> {
    use rto_graph::{Edge, EdgeKind};

    // Accept either the Graphify output directory or a graph.json directly.
    let p = std::path::Path::new(path);
    let graph_json = if p.is_dir() {
        p.join("graph.json")
    } else {
        p.to_path_buf()
    };
    let text = std::fs::read_to_string(&graph_json)
        .map_err(|e| anyhow::anyhow!("reading {}: {e}", graph_json.display()))?;
    let imported = rto_spec::import_graphify(&text)?;

    let (repo, mut store, cache) = open_graph()?;
    build_graph(&repo, &mut store, &cache, ingest, GraphSource::Committed)?;

    // Assemble the full import layer: Graphify's own nodes/edges plus grounding
    // links. When an imported node's `source_file` matches a `file:<path>` node
    // already in the graph, add an inferred edge linking the imported knowledge
    // to the derived file.
    let mut facts = imported.facts.clone();
    let mut linked = 0usize;
    for node in &imported.facts.nodes {
        if let Some(path) = &node.path {
            let file_key = format!("file:{path}");
            if store.get_node(&file_key)?.is_some() {
                let mut edge =
                    Edge::inferred(node.key.clone(), file_key, EdgeKind::References, 0.9);
                edge.src_ref = Some(rto_spec::GRAPHIFY_REF.to_owned());
                facts.edges.push(edge);
                linked += 1;
            }
        }
    }

    // Apply and persist the whole Graphify layer authoritatively: this replaces
    // any prior Graphify import (its edges, including grounding links), validates
    // each edge against the current graph — dropping cross-references to code
    // that is not present — and stores only the validated layer, so it is durable
    // across future syncs without keeping stale data.
    let applied = store.apply_import_layer(rto_spec::GRAPHIFY_REF, &facts)?;

    let r = &imported.report;
    if json {
        let mut report = serde_json::to_value(r)?;
        report["docs_linked_to_files"] = serde_json::json!(linked);
        report["edges_pruned_stale"] = serde_json::json!(applied.edges_pruned);
        report["durable"] = serde_json::json!(true);
        emit_json(&report)?;
    } else {
        println!(
            "imported graphify: {} node(s) ({} dropped as code), {} inferred edge(s) \
             ({} ast dropped, {} dangling skipped), {} hyperedge group(s); \
             {linked} doc(s) linked to files, {} stale pruned — persisted (durable)",
            r.nodes_imported,
            r.nodes_dropped_code,
            r.edges_imported,
            r.edges_dropped_ast,
            r.edges_skipped_dangling,
            r.hyperedges_imported,
            applied.edges_pruned,
        );
    }
    Ok(())
}

/// Graph-grounded spec/blueprint authoring (ADR-0004).
fn run_spec(
    cfg: &config::Config,
    ingest: rto_graph::IngestConfig,
    action: SpecAction,
) -> anyhow::Result<()> {
    match action {
        SpecAction::Context { topic, limit, json } => run_spec_context(ingest, &topic, limit, json),
        SpecAction::Scaffold {
            topic,
            title,
            kind,
            out,
        } => run_spec_scaffold(ingest, &topic, title.as_deref(), &kind, out.as_deref()),
        SpecAction::Draft {
            topic,
            title,
            kind,
            out,
        } => run_spec_draft(cfg, ingest, &topic, title.as_deref(), &kind, out.as_deref()),
    }
}

/// Build the derived+authored graph, then a house-style, grounded scaffold for
/// `topic` of the given `kind` (`adr` | `blueprint`). Returns the scaffold
/// markdown, its label (e.g. `ADR-0007`), and the grounded context — shared by
/// `spec scaffold` (Tier 0) and `spec draft` (Tier 1).
fn build_scaffold(
    ingest: rto_graph::IngestConfig,
    topic: &str,
    title: Option<&str>,
    kind: &str,
) -> anyhow::Result<(String, String, rto_spec::SpecContext)> {
    if kind != "adr" && kind != "blueprint" {
        anyhow::bail!("unknown --kind `{kind}` (expected: adr | blueprint)");
    }
    let (repo, mut store, cache) = open_graph()?;
    build_graph(&repo, &mut store, &cache, ingest, GraphSource::Committed)?;
    let root = repo
        .workdir()
        .ok_or_else(|| anyhow::anyhow!("cannot scaffold in a bare repository"))?;
    let ctx = rto_spec::context(&store, topic, 10)?;

    let (md, label) = if kind == "adr" {
        let adr_id = next_adr_id(&root.join("docs/adr"));
        (
            rto_spec::scaffold_adr(topic, title, &adr_id, &today_utc(), &ctx),
            format!("ADR-{adr_id}"),
        )
    } else {
        (
            rto_spec::scaffold_blueprint(topic, title, &ctx),
            "blueprint".to_owned(),
        )
    };
    Ok((md, label, ctx))
}

/// Write `md` to `out` (or stdout), announcing `label` on stderr when writing.
fn emit_artifact(md: &str, label: &str, out: Option<&str>) -> anyhow::Result<()> {
    match out {
        Some(path) => {
            std::fs::write(path, md)?;
            eprintln!("wrote {label}{path}");
        }
        None => print!("{md}"),
    }
    Ok(())
}

/// Emit a graph-grounded, house-style ADR or blueprint skeleton (ADR-0004 Tier 0).
fn run_spec_scaffold(
    ingest: rto_graph::IngestConfig,
    topic: &str,
    title: Option<&str>,
    kind: &str,
    out: Option<&str>,
) -> anyhow::Result<()> {
    let (md, label, _ctx) = build_scaffold(ingest, topic, title, kind)?;
    emit_artifact(&md, &format!("{label} scaffold"), out)
}

/// Draft the scaffold's unfilled sections with a small local instruct model
/// (ADR-0004 Tier 1). Needs a generation backend (`serve` or
/// `inference-local-models`, both llama.cpp) and a pulled generative model;
/// without a model it emits the plain scaffold + a hint.
// Stage 20: `spec draft` generation runs on **llama.cpp** (the shared `rto-llama`
// engine, ADR-0006) — available whenever either the `serve` or the
// `inference-local-models` feature is on.
#[cfg(any(feature = "serve", feature = "inference-local-models"))]
fn run_spec_draft(
    cfg: &config::Config,
    ingest: rto_graph::IngestConfig,
    topic: &str,
    title: Option<&str>,
    kind: &str,
    out: Option<&str>,
) -> anyhow::Result<()> {
    use rto_graph::{
        ModelKind, ModelRole, Platform, REGISTRY, ResourceTier, find_model, is_installed,
    };

    let (scaffold, label, ctx) = build_scaffold(ingest, topic, title, kind)?;

    // Model pick: `[models] generative` from config if set (and a real generative
    // entry), otherwise the low-tier default (runs anywhere).
    let Some(spec) = cfg
        .models
        .generative
        .as_deref()
        .and_then(find_model)
        .filter(|m| m.kind == ModelKind::Generative)
        .or_else(|| {
            // Deterministic default as the registry grows: the low-tier *instruct*
            // model (qwen3-0.6b), not just any low-tier generative (which now
            // includes coding/reasoning picks).
            REGISTRY.iter().find(|m| {
                m.kind == ModelKind::Generative
                    && m.role == ModelRole::Instruct
                    && m.tier == ResourceTier::Low
            })
        })
    else {
        anyhow::bail!("no generative model in the registry");
    };
    let installed = spec
        .variant_for(Platform::host())
        .is_some_and(|v| is_installed(spec.name, v));
    if !installed {
        eprintln!(
            "note: generative model `{0}` is not installed — emitting the scaffold. \
             Draft prose with: roteiro model pull {0}",
            spec.name
        );
        return emit_artifact(&scaffold, &format!("{label} scaffold"), out);
    }

    if cfg!(debug_assertions) {
        eprintln!(
            "note: unoptimized build — local generation is very slow; use a \
             release build (`cargo build --release`) for usable speed."
        );
    }
    let drafts = draft_sections(spec.name, &scaffold, topic, &ctx)?;
    eprintln!(
        "drafted {} section(s) with {} (via {GEN_BACKEND})",
        drafts.len(),
        spec.name
    );
    let md = rto_spec::apply_drafts(&scaffold, &drafts);
    emit_artifact(&md, &format!("{label} draft"), out)
}

/// The generation backend label shown after drafting.
#[cfg(any(feature = "serve", feature = "inference-local-models"))]
const GEN_BACKEND: &str = "llama.cpp";

/// Max tokens generated per drafted section.
#[cfg(any(feature = "serve", feature = "inference-local-models"))]
const DRAFT_MAX_TOKENS: u32 = 800;

/// Draft each unfilled section of `scaffold` with the local generative model
/// through the shared **llama.cpp** engine (`rto-llama`, ADR-0003 v1.2) — no
/// candle. Available under either `serve` or `inference-local-models`.
#[cfg(any(feature = "serve", feature = "inference-local-models"))]
fn draft_sections(
    model: &str,
    scaffold: &str,
    topic: &str,
    ctx: &rto_spec::SpecContext,
) -> anyhow::Result<Vec<(String, String)>> {
    use rto_llama::Engine as _; // brings `.chat` into scope

    let engine = rto_llama::llama::LlamaEngine::new(
        vec![rto_llama::llama::Served {
            name: model.to_owned(),
            path: rto_graph::model_dir(model).join("model.gguf"),
            mmproj: None,
        }],
        0,
    )
    .map_err(|e| anyhow::anyhow!("starting llama.cpp: {e}"))?;

    let mut drafts = Vec::new();
    for (heading, hint) in rto_spec::draft_targets(scaffold) {
        let prompt = rto_spec::draft_prompt(topic, ctx, &heading, &hint);
        let completion = engine
            .chat(&rto_llama::ChatRequest {
                model: model.to_owned(),
                messages: vec![rto_llama::Message {
                    role: "user".to_owned(),
                    content: prompt,
                }],
                images: vec![],
                audio: vec![],
                temperature: 0.0,
                max_tokens: DRAFT_MAX_TOKENS,
            })
            .map_err(|e| anyhow::anyhow!("drafting `{heading}`: {e}"))?;
        // A reasoning-capable GGUF (Qwen3, DeepSeek-R1, …) emits a
        // `<think>…</think>` block before its answer; keep only the answer so the
        // reasoning never lands in the drafted document.
        let prose = strip_thinking(&completion.content);
        if !prose.trim().is_empty() {
            drafts.push((heading, prose));
        }
    }
    Ok(drafts)
}

/// Drop a leading `<think>…</think>` reasoning block, returning the answer that
/// follows it. Text with no closing `</think>` is returned unchanged.
#[cfg(any(feature = "serve", feature = "inference-local-models"))]
fn strip_thinking(text: &str) -> String {
    match text.find("</think>") {
        Some(end) => text[end + "</think>".len()..].trim_start().to_owned(),
        None => text.to_owned(),
    }
}

/// `spec draft` without a generation backend: guide the user to enable one.
#[cfg(not(any(feature = "serve", feature = "inference-local-models")))]
fn run_spec_draft(
    _cfg: &config::Config,
    _ingest: rto_graph::IngestConfig,
    _topic: &str,
    _title: Option<&str>,
    _kind: &str,
    _out: Option<&str>,
) -> anyhow::Result<()> {
    anyhow::bail!(
        "`spec draft` needs a generation backend: build with `--features serve` \
         or `--features inference-local-models` (both llama.cpp), then \
         `roteiro model pull qwen3-0.6b`. (`spec scaffold` works with no model.)"
    )
}

/// The next zero-padded ADR id: one past the highest `NNNN-*.md` under `adr_dir`
/// (or `0001` if none/absent).
fn next_adr_id(adr_dir: &std::path::Path) -> String {
    let mut max = 0u32;
    if let Ok(entries) = std::fs::read_dir(adr_dir) {
        for entry in entries.flatten() {
            if let Some(name) = entry.file_name().to_str() {
                let digits: String = name.chars().take_while(char::is_ascii_digit).collect();
                if let Ok(n) = digits.parse::<u32>() {
                    max = max.max(n);
                }
            }
        }
    }
    format!("{:04}", max + 1)
}

/// Today's UTC date as `YYYY-MM-DD`, dependency-free (Hinnant's civil-from-days).
fn today_utc() -> String {
    let secs = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map_or(0, |d| d.as_secs());
    let days = i64::try_from(secs / 86_400).unwrap_or(0) + 719_468;
    let era = if days >= 0 { days } else { days - 146_096 } / 146_097;
    let doe = days - era * 146_097;
    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
    let year = yoe + era * 400;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let day = doy - (153 * mp + 2) / 5 + 1;
    let month = if mp < 10 { mp + 3 } else { mp - 9 };
    let year = year + i64::from(month <= 2);
    format!("{year:04}-{month:02}-{day:02}")
}

/// Assemble and print graph-grounded context for a topic (ADR-0004 Tier 0): the
/// related symbols with their neighbourhood and governing ADRs, plus related
/// docs. Builds the full derived + authored graph first so results are grounded.
fn run_spec_context(
    ingest: rto_graph::IngestConfig,
    topic: &str,
    limit: usize,
    json: bool,
) -> anyhow::Result<()> {
    let (repo, mut store, cache) = open_graph()?;
    build_graph(&repo, &mut store, &cache, ingest, GraphSource::Committed)?;

    let ctx = rto_spec::context(&store, topic, limit)?;
    if json {
        emit_json(&ctx)?;
    } else {
        println!("context for \"{}\":", ctx.topic);
        if ctx.symbols.is_empty() && ctx.docs.is_empty() {
            println!("  (nothing in the graph matches — try `roteiro query --kind fn` to browse)");
        }
        if !ctx.symbols.is_empty() {
            println!("  symbols:");
            for s in &ctx.symbols {
                println!("    {}  ({})", s.node.key, s.node.kind);
                if let Some(c) = &s.container {
                    println!("      in: {c}");
                }
                if !s.called_by.is_empty() {
                    println!("      called by: {}", s.called_by.join(", "));
                }
                if !s.calls.is_empty() {
                    println!("      calls: {}", s.calls.join(", "));
                }
                if !s.authored_by.is_empty() {
                    println!("      governed by: {}", s.authored_by.join(", "));
                }
            }
        }
        if !ctx.docs.is_empty() {
            println!("  docs:");
            for d in &ctx.docs {
                println!("    {}  {}", d.key, d.name);
            }
        }
        if !ctx.related_adrs.is_empty() {
            println!("  related ADRs: {}", ctx.related_adrs.join(", "));
        }
    }
    Ok(())
}

/// Query the graph: explain a node's provenance-labelled neighbourhood, or list
/// all nodes of a kind. Builds the full (derived + authored) graph first so
/// results reflect the current source and ADRs.
/// The source-file component of a `config_key` node key (`cfgkey:<file>#<dotted>`),
/// or `None` for any other node key. Neither the file path nor the dotted key
/// contains `#`, so the first `#` cleanly separates them. Used to classify a
/// config key as app vs tooling config for `--app-config-only`.
fn cfgkey_file(node_key: &str) -> Option<&str> {
    node_key
        .strip_prefix("cfgkey:")
        .map(|rest| rest.split_once('#').map_or(rest, |(file, _)| file))
}

fn run_query(
    ingest: rto_graph::IngestConfig,
    key: Option<String>,
    kind: Option<String>,
    app_config_only: bool,
    json: bool,
) -> anyhow::Result<()> {
    use rto_graph::{NodeKind, explain, list_kind};

    let (repo, mut store, cache) = open_graph()?;
    build_graph(&repo, &mut store, &cache, ingest, GraphSource::Committed)?;

    match (key, kind) {
        (Some(key), _) => {
            let Some(ex) = explain(&store, &key)? else {
                anyhow::bail!(
                    "no node with key `{key}` (try `roteiro query --kind <kind>` to list nodes)"
                );
            };
            if json {
                emit_json(&ex)?;
            } else {
                println!("{}  ({})  {}", ex.node.key, ex.node.kind, ex.node.name);
                if let Some(path) = &ex.node.path {
                    println!("  path: {path}");
                }
                if !ex.outgoing.is_empty() {
                    println!("  outgoing:");
                    for e in &ex.outgoing {
                        println!("    -[{}/{}]-> {}", e.kind, e.provenance, e.node);
                    }
                }
                if !ex.incoming.is_empty() {
                    println!("  incoming:");
                    for e in &ex.incoming {
                        println!("    <-[{}/{}]- {}", e.kind, e.provenance, e.node);
                    }
                }
            }
        }
        (None, Some(kind)) => {
            let mut listing = list_kind(&store, &NodeKind::from_token(&kind))?;
            // `--app-config-only`: drop config keys sourced from build/tooling/CI
            // files, keeping only real app config. Opt-in — off by default, so the
            // listing is unchanged unless the flag is passed. A config-key node's
            // key is `cfgkey:<file>#<dotted>`, so classify from that file component.
            if app_config_only {
                listing.nodes.retain(|n| match cfgkey_file(&n.key) {
                    Some(file) => !rto_graph::is_tooling_config_path(file),
                    None => true,
                });
            }
            if json {
                emit_json(&listing)?;
            } else {
                println!("{} ({}):", listing.kind, listing.nodes.len());
                for n in &listing.nodes {
                    println!("  {}  {}", n.key, n.name);
                }
            }
        }
        (None, None) => {
            anyhow::bail!("provide a node key to explain, or `--kind <kind>` to list nodes");
        }
    }
    Ok(())
}

/// Search the graph by text and print ranked hits (highest score first). A
/// read-only report: it exits zero even when nothing matches, keeping stdout
/// empty (or an empty JSON array) so it composes in scripts.
fn run_search(
    ingest: rto_graph::IngestConfig,
    query: &str,
    limit: usize,
    json: bool,
) -> anyhow::Result<()> {
    let (repo, mut store, cache) = open_graph()?;
    build_graph(&repo, &mut store, &cache, ingest, GraphSource::Committed)?;

    let hits = rto_graph::search(&store, query, limit)?;
    if json {
        emit_json(&hits)?;
    } else if hits.is_empty() {
        // Keep stdout empty on a miss; report to stderr.
        eprintln!("no matches for `{query}`");
    } else {
        for hit in &hits {
            println!("  {:>4}  {:<8}  {}", hit.score, hit.node.kind, hit.node.key);
        }
        println!("{} hit(s)", hits.len());
    }
    Ok(())
}

/// Fetch a node's cached context bundle, or (`--refresh`) reconcile all cached
/// contexts with the current graph — rebuilding stale ones and pruning entries
/// for deleted nodes. The cache is dependency-aware: a change to a node or any of
/// its neighbours invalidates its cached context (see `rto_graph::context`).
fn run_context(
    ingest: rto_graph::IngestConfig,
    key: Option<String>,
    refresh: bool,
    json: bool,
) -> anyhow::Result<()> {
    use rto_graph::{context, refresh_contexts};

    let (repo, mut store, cache) = open_graph()?;
    build_graph(&repo, &mut store, &cache, ingest, GraphSource::Committed)?;

    if refresh {
        let report = refresh_contexts(&store)?;
        if json {
            emit_json(&report)?;
        } else {
            println!(
                "context cache refreshed: {} rebuilt, {} reused, {} pruned",
                report.rebuilt, report.reused, report.pruned
            );
        }
        return Ok(());
    }

    let Some(key) = key else {
        anyhow::bail!("provide a node key, or `--refresh` to refresh all cached contexts");
    };
    let Some(ctx) = context(&store, &key)? else {
        anyhow::bail!("no node with key `{key}` (try `roteiro query --kind <kind>` to list nodes)");
    };
    if json {
        emit_json(&ctx)?;
    } else {
        println!("{}  ({})  {}", ctx.node.key, ctx.node.kind, ctx.node.name);
        println!("  fingerprint: {}", ctx.fingerprint);
        if !ctx.outgoing.is_empty() {
            println!("  outgoing:");
            for e in &ctx.outgoing {
                println!("    -[{}/{}]-> {}", e.kind, e.provenance, e.node);
            }
        }
        if !ctx.incoming.is_empty() {
            println!("  incoming:");
            for e in &ctx.incoming {
                println!("    <-[{}/{}]- {}", e.kind, e.provenance, e.node);
            }
        }
    }
    Ok(())
}

/// List intent-debt markers in the graph, grouped
/// by category. A report, not a gate: it always exits zero.
fn run_debt(
    ingest: rto_graph::IngestConfig,
    kinds: &[String],
    json: bool,
    debt_ignore: &[String],
) -> anyhow::Result<()> {
    let (repo, mut store, cache) = open_graph()?;
    build_graph(&repo, &mut store, &cache, ingest, GraphSource::Committed)?;

    let report = rto_graph::debt(&store, kinds, debt_ignore)?;
    if json {
        emit_json(&report)?;
    } else {
        for item in &report.items {
            let loc = match (&item.path, item.line) {
                (Some(p), Some(l)) => format!("{p}:{l}"),
                (Some(p), None) => p.clone(),
                _ => item.key.clone(),
            };
            println!("  [{}] {loc}  {}", item.category, item.text);
        }
        println!("{}", debt_summary(&report));
    }
    Ok(())
}

/// A one-line summary of a [`rto_graph::DebtReport`], e.g.
/// `intent debt: 12 marker(s) (deferred 5, stub 4, todo 3)`.
fn debt_summary(report: &rto_graph::DebtReport) -> String {
    if report.total == 0 {
        return "intent debt: none".to_owned();
    }
    let breakdown: Vec<String> = report
        .by_category
        .iter()
        .map(|(cat, n)| format!("{cat} {n}"))
        .collect();
    format!(
        "intent debt: {} marker(s) ({})",
        report.total,
        breakdown.join(", ")
    )
}

/// Find and print a shortest path between two nodes. Exits non-zero if the two
/// nodes are not connected, so it is usable as a reachability assertion.
fn run_path(
    ingest: rto_graph::IngestConfig,
    from: &str,
    to: &str,
    json: bool,
) -> anyhow::Result<()> {
    let (repo, mut store, cache) = open_graph()?;
    build_graph(&repo, &mut store, &cache, ingest, GraphSource::Committed)?;

    let result = rto_graph::path(&store, from, to)?;
    if json {
        emit_json(&result)?;
    } else if result.found {
        println!("{from}");
        for hop in &result.hops {
            let arrow = if hop.direction == "outgoing" {
                "->"
            } else {
                "<-"
            };
            println!("  {arrow}[{}/{}] {}", hop.kind, hop.provenance, hop.node);
        }
        println!("({} hop(s))", result.length);
    } else {
        // Keep stdout machine-readable/empty on failure; report to stderr.
        eprintln!("no path from `{from}` to `{to}`");
    }

    if !result.found {
        std::process::exit(1);
    }
    Ok(())
}

/// The outcome of resolving one authored cross-repo link (ADR-0009).
#[derive(serde::Serialize)]
struct LinkResult {
    /// The repo (project) the link was declared in.
    repo: String,
    /// The declared local anchor (`from`), if any.
    from: Option<String>,
    /// The project-qualified target (`to`).
    to: String,
    /// The relationship label.
    kind: String,
    /// `ok` (resolved) or `drift` (target unresolved).
    status: &'static str,
    /// For a resolved link: the target node's kind and name; for drift: why.
    detail: String,
}

/// Project (display) names for `paths`, matching how [`rto_graph::Workspace`]
/// names them — the repo directory name, with `-2`/`-3`/… suffixes disambiguating
/// collisions — so a report's `repo` label (and the `<project>` used in a link
/// key) never diverge when two repos share a directory name.
fn workspace_project_names(paths: &[std::path::PathBuf]) -> Vec<(&std::path::PathBuf, String)> {
    use std::collections::HashMap;
    let mut counts: HashMap<String, usize> = HashMap::new();
    paths
        .iter()
        .map(|p| {
            let base = p
                .file_name()
                .map_or_else(|| "repo".to_owned(), |s| s.to_string_lossy().into_owned());
            let n = counts.entry(base.clone()).or_insert(0);
            *n += 1;
            let name = if *n == 1 { base } else { format!("{base}-{n}") };
            (p, name)
        })
        .collect()
}

/// How a `roteiro links` invocation is scoped: the additive `--workspace <ROOT>`
/// paths and the optional `--workspace-name` selector. Threaded through the
/// authored-links, `--infer`, and `--matrix` reports together.
struct LinksScope<'a> {
    /// Repeatable `--workspace <ROOT>` roots, always unioned into the scope.
    cli_roots: &'a [String],
    /// `--workspace-name <NAME>`: select a configured workspace, or `None` to
    /// default to the one containing the cwd (else today's flat `[workspace]`).
    workspace_name: Option<&'a str>,
}

/// The current repo's working-tree directory (canonicalised), or `None` when the
/// cwd is not inside a git repo. Used to find which configured workspace owns the
/// cwd, at the path level — no graph is opened.
fn cwd_repo_workdir() -> Option<std::path::PathBuf> {
    let cwd = std::env::current_dir().ok()?;
    let repo = rto_graph::Repo::discover(&cwd).ok()?;
    let wd = repo.workdir()?.to_path_buf();
    Some(wd.canonicalize().unwrap_or(wd))
}

/// The configured workspace whose **discovered member repos** include `cwd_wd`, or
/// `None` if none do. Membership is decided purely at the path level
/// ([`rto_graph::discover_repos_under`] + explicit repos) — no `Workspace` is built
/// and no graph is opened — so one unrelated **misconfigured** group (an unreadable
/// root) is skipped here rather than aborting selection.
fn workspace_containing_cwd<'a>(
    resolved: &'a [rto_graph::ResolvedWorkspace],
    cwd_wd: &std::path::Path,
) -> Option<&'a rto_graph::ResolvedWorkspace> {
    let canon = |p: &std::path::Path| p.canonicalize().unwrap_or_else(|_| p.to_path_buf());
    let is_cwd = |p: &std::path::Path| canon(p).as_path() == cwd_wd;
    resolved.iter().find(|rw| {
        // A broken root must not break selection: skip a root that won't read.
        let in_root = rw.roots.iter().any(|root| {
            rto_graph::discover_repos_under(std::path::Path::new(root))
                .is_ok_and(|repos| repos.iter().any(|r| is_cwd(r)))
        });
        in_root
            || rw
                .repos
                .iter()
                .any(|repo| is_cwd(std::path::Path::new(repo)))
    })
}

/// The repos `roteiro links` operates on: the selected workspace's members
/// (`--workspace-name`, else the workspace containing the cwd, else today's flat
/// `[workspace]` scope), unioned with any additive `--workspace <ROOT>` paths and
/// the current repo (so links run inside a spoke resolve against its siblings).
/// Shared by the authored-links, `--infer`, and `--matrix` reports.
///
/// Selection is short-circuited so the **legacy-fallback** path builds and
/// validates nothing beyond today's `[workspace]` scope: only the *one* selected
/// group is discovered, never the whole configured set. So a single unrelated
/// misconfigured `[[workspaces]]` never breaks `links` in directories that should
/// just fall back — a configured workspace is only used when explicitly named or
/// when the cwd actually belongs to it. (For a legacy `[workspace]`-only config the
/// fallback *is* the `default` group's scope, so behaviour is unchanged.)
fn links_scope_paths(
    cfg: &config::Config,
    scope: &LinksScope<'_>,
) -> anyhow::Result<Vec<std::path::PathBuf>> {
    use std::collections::BTreeSet;

    let cli_roots = scope.cli_roots;
    let resolved = cfg.resolved_workspaces()?;

    // Pick the one group to scope to (by name, else cwd-containment) — WITHOUT
    // building/validating the whole set; anything else falls back to the flat scope.
    let chosen: Option<&rto_graph::ResolvedWorkspace> = if let Some(name) = scope.workspace_name {
        // Explicit selection: it must name a configured workspace, else a clear
        // error listing the known ones.
        Some(resolved.iter().find(|r| r.name == name).ok_or_else(|| {
            let known = resolved
                .iter()
                .map(|r| r.name.as_str())
                .collect::<Vec<_>>()
                .join(", ");
            anyhow::anyhow!("no workspace named `{name}` (known: {known})")
        })?)
    } else if resolved.is_empty() {
        None
    } else {
        // Default: the workspace containing the cwd repo, else fall back (build
        // nothing) — never eagerly select/validate an unrelated configured group.
        cwd_repo_workdir().and_then(|wd| workspace_containing_cwd(&resolved, &wd))
    };

    let mut paths: BTreeSet<std::path::PathBuf> = BTreeSet::new();
    match chosen {
        Some(rw) => {
            // Discover only the selected group's repo dirs (needed to load each
            // repo's config downstream), unioning the additive `--workspace` roots.
            for root in rw
                .roots
                .iter()
                .map(String::as_str)
                .chain(cli_roots.iter().map(String::as_str))
            {
                paths.extend(rto_graph::discover_repos_under(std::path::Path::new(root))?);
            }
            for repo in &rw.repos {
                paths.insert(std::path::PathBuf::from(repo));
            }
        }
        // No configured workspace selected ⇒ today's flat `[workspace]` + `--workspace`.
        None => paths.extend(collect_workspace_repo_paths(&cfg.workspace, cli_roots)?),
    }

    // Always include the current repo so links run inside a spoke resolve against
    // its siblings.
    if let Ok(cwd) = std::env::current_dir()
        && let Ok(repo) = rto_graph::Repo::discover(&cwd)
        && let Some(wd) = repo.workdir()
    {
        paths.insert(wd.to_path_buf());
    }

    Ok(paths.into_iter().collect())
}

/// Verify a workspace's authored cross-repo links (ADR-0009). For every repo in
/// the workspace (the cwd repo plus any `--workspace`/`[workspace]` roots), read
/// its `[[links]]` and resolve each project-qualified `to` against the other
/// repos' graphs. A target that no longer resolves is **drift** — the cross-repo
/// form of `roteiro check`. Exits non-zero if any link drifts.
fn run_links(cfg: &config::Config, scope: &LinksScope<'_>, json: bool) -> anyhow::Result<()> {
    let paths = links_scope_paths(cfg, scope)?;
    if paths.is_empty() {
        anyhow::bail!(
            "no repos in scope — run inside a repo, pass `--workspace <root>`, or set \
             `[workspace]` in roteiro.toml"
        );
    }
    let workspace = rto_graph::Workspace::from_repo_paths(&paths)?;

    // Collect each repo's declared links from its own config.
    let mut results: Vec<LinkResult> = Vec::new();
    for (path, repo_name) in workspace_project_names(&paths) {
        let repo_cfg = config::load(path)?.effective;
        for link in &repo_cfg.links {
            let kind = link.kind.clone().unwrap_or_else(|| "references".to_owned());
            let (status, detail) = match workspace.resolve_qualified(&link.to) {
                Ok(Some(node)) => ("ok", format!("{} {}", node.kind.as_str(), node.name)),
                Ok(None) => ("drift", "no such node in the target project".to_owned()),
                Err(e) => ("drift", e.to_string()),
            };
            results.push(LinkResult {
                repo: repo_name.clone(),
                from: link.from.clone(),
                to: link.to.clone(),
                kind,
                status,
                detail,
            });
        }
    }

    let drift = results.iter().filter(|r| r.status == "drift").count();
    if json {
        emit_json(&results)?;
    } else if results.is_empty() {
        println!(
            "no cross-repo links declared across {} repo(s) (add `[[links]]` to a repo's roteiro.toml)",
            paths.len()
        );
    } else {
        for r in &results {
            let marker = if r.status == "ok" { "ok   " } else { "DRIFT" };
            println!("  [{marker}] {}{}  ({})", r.repo, r.to, r.detail);
        }
        println!(
            "{} link(s) across {} repo(s): {} ok, {} drift",
            results.len(),
            paths.len(),
            results.len() - drift,
            drift
        );
    }

    if drift > 0 {
        std::process::exit(1);
    }
    Ok(())
}

/// One spoke project's inferred config correspondences with the hub (ADR-0009).
#[derive(serde::Serialize)]
struct InferredRepo {
    /// The spoke project (repo dir name).
    repo: String,
    /// Config keys that matched a hub key.
    matches: Vec<infer_links::KeyMatch>,
    /// Config keys with no hub counterpart — likely drift.
    orphans: Vec<infer_links::ConfigKey>,
    /// The hub rev this spoke resolved against, when it pins one (`--pinned`,
    /// ADR-0009 step 8b); `None` means the hub's `HEAD`.
    #[serde(skip_serializing_if = "Option::is_none")]
    hub_rev: Option<String>,
    /// Where the pin came from (e.g. `submodule vendor/app`), when auto-detected.
    #[serde(skip_serializing_if = "Option::is_none")]
    pin_via: Option<String>,
}

/// The `graph.db` path for the repo at `path` (`<repo>/.git/roteiro/graph.db`).
fn graph_db_path(path: &std::path::Path) -> anyhow::Result<std::path::PathBuf> {
    let repo = rto_graph::Repo::discover(path)?;
    Ok(repo.git_dir().join("roteiro").join("graph.db"))
}

/// The config keys of every in-scope repo, read **from each repo's graph** (its
/// `config_key` nodes), keyed by project name (dir name, `-2`/`-3` on collision),
/// alongside a name→path map for persistence and the names of repos with no graph
/// yet (noted, not fatal). Reading from the graph — not re-parsing files — keeps
/// the matcher and the stored nodes in lock-step (ADR-0009 feature 2b).
type WorkspaceConfigKeys = (
    std::collections::BTreeMap<String, Vec<infer_links::ConfigKey>>,
    std::collections::BTreeMap<String, std::path::PathBuf>,
    Vec<String>,
);
fn collect_workspace_config_keys(
    paths: &[std::path::PathBuf],
) -> anyhow::Result<WorkspaceConfigKeys> {
    let mut by_project = std::collections::BTreeMap::new();
    let mut project_paths = std::collections::BTreeMap::new();
    let mut unsynced = Vec::new();
    for (path, name) in workspace_project_names(paths) {
        project_paths.insert(name.clone(), path.clone());
        let db = graph_db_path(path)?;
        if !db.exists() {
            unsynced.push(name);
            continue;
        }
        let keys = rto_graph::Store::open(&db)?.config_keys()?;
        if !keys.is_empty() {
            by_project.insert(name, keys);
        }
    }
    Ok((by_project, project_paths, unsynced))
}

/// Drop build/tooling/CI config keys (see [`rto_graph::is_tooling_config_path`])
/// from every project, then discard any project left with no keys — so
/// `--app-config-only` matches and drift-checks only application config. Used by
/// `roteiro links --infer`/`--matrix`; a no-op unless the flag is set.
fn retain_app_config_keys(
    by_project: &mut std::collections::BTreeMap<String, Vec<infer_links::ConfigKey>>,
) {
    for keys in by_project.values_mut() {
        keys.retain(|k| !rto_graph::is_tooling_config_path(&k.file));
    }
    by_project.retain(|_, keys| !keys.is_empty());
}

/// A ready cross-repo inference over the workspace, or a reason there's nothing to
/// show (an informational no-op the caller reports without failing).
enum InferScan {
    /// Nothing to infer/show, with a human reason (empty or single-repo workspace).
    Nothing(String),
    /// A hub was picked and every spoke matched against it.
    Ready(InferReady),
}

/// The result of a successful workspace scan: the hub, each spoke's matches, and
/// the raw per-project config keys (for values) and paths (for persistence).
struct InferReady {
    hub_name: String,
    /// The pinned hub rev the match was resolved against, if any (ADR-0009 step 8).
    hub_rev: Option<String>,
    report: Vec<InferredRepo>,
    by_project: std::collections::BTreeMap<String, Vec<infer_links::ConfigKey>>,
    project_paths: std::collections::BTreeMap<String, std::path::PathBuf>,
}

/// How to source the hub's config keys (ADR-0009 step 8): its `HEAD` graph (`rev`
/// `None`, `auto` false), one **explicit pinned version** for all spokes (`rev`
/// set, `--hub-rev`), or **each spoke's own pin** auto-detected (`auto`,
/// `--pinned`). Extracted in-memory with `ingest`.
#[derive(Clone, Copy)]
struct PinnedHub<'a> {
    rev: Option<&'a str>,
    auto: bool,
    ingest: rto_graph::IngestConfig,
}

/// The cross-repo inference inputs shared by `--infer` and `--matrix`: which repo
/// is the hub, how its version is pinned, and whether to consider only app config
/// (dropping build/tooling/CI keys). Grouped so the two entry points stay under
/// clippy's argument-count limit and thread one value.
#[derive(Clone, Copy)]
struct InferOptions<'a> {
    hub: Option<&'a str>,
    pin: PinnedHub<'a>,
    app_config_only: bool,
}

/// The config keys of the repo at `repo_path` **as of `rev`** (any git rev), read
/// from an ephemeral in-memory graph extracted at that point via
/// [`rto_graph::sync_tree`] — content-addressed, so unchanged blobs are cache hits.
/// Backs version-pin resolution (ADR-0009 step 8).
fn config_keys_at_rev(
    repo_path: &std::path::Path,
    rev: &str,
    ingest: rto_graph::IngestConfig,
) -> anyhow::Result<Vec<infer_links::ConfigKey>> {
    let repo = rto_graph::Repo::discover(repo_path)?;
    let cache = rto_graph::ObjectCache::open(repo.common_dir().join("roteiro").join("objects"))?;
    let reg = rto_graph::Registry::new(ingest);
    config_keys_at_rev_with(&repo, &cache, reg, rev)
}

/// The config keys of `repo` at `rev`, reusing a caller-owned repo and object cache
/// — the expensive-to-open resources — so resolving many pins under `--pinned` opens
/// them once and pays only the (cache-aware) `sync_tree` per distinct rev. (The
/// `Registry` is a `Copy` config, so it is passed by value.)
fn config_keys_at_rev_with(
    repo: &rto_graph::Repo,
    cache: &rto_graph::ObjectCache,
    reg: rto_graph::Registry,
    rev: &str,
) -> anyhow::Result<Vec<infer_links::ConfigKey>> {
    // Prefer a pre-published graph artifact for this version (ADR-0009 step 8c): it
    // resolves even when the pinned commit's blobs aren't present locally (a shallow
    // clone) and skips extraction entirely.
    if let Some(keys) = config_keys_from_artifact(repo, rev)? {
        return Ok(keys);
    }
    let mut store = rto_graph::Store::open_in_memory()?;
    rto_graph::sync_tree(&mut store, repo, cache, &reg, rev)?;
    Ok(store.config_keys()?)
}

/// Config keys from a pre-published graph artifact for `rev`, if one exists at the
/// conventional location (`<repo>/.git/roteiro/artifacts/<treeid>.json`) and its
/// recorded tree matches — a hub's CI can `roteiro export` there per release.
/// `None` when there is no usable artifact (the caller re-extracts).
fn config_keys_from_artifact(
    repo: &rto_graph::Repo,
    rev: &str,
) -> anyhow::Result<Option<Vec<infer_links::ConfigKey>>> {
    let tree = repo.tree_id_at(rev)?;
    let path = repo
        .common_dir()
        .join("roteiro")
        .join("artifacts")
        .join(format!("{tree}.json"));
    // A missing, unreadable, corrupt, or tree-mismatched artifact is "not usable" —
    // return `None` so the caller falls back to re-extraction rather than aborting.
    let Ok(json) = std::fs::read_to_string(&path) else {
        return Ok(None);
    };
    let Ok(artifact) = rto_graph::GraphArtifact::from_json(&json) else {
        return Ok(None);
    };
    if artifact.tree.as_deref() != Some(tree.as_str()) {
        return Ok(None);
    }
    let mut store = rto_graph::Store::open_in_memory()?;
    if store.rebuild(&artifact.facts, None).is_err() {
        return Ok(None);
    }
    Ok(Some(store.config_keys()?))
}

/// Scan the in-scope repos (workspace roots + the cwd repo), read each one's config
/// keys **from its graph**, pick the hub (named, else the repo with the most keys),
/// and match every spoke against it. With `pin.rev`, the hub's keys come from that
/// pinned version instead of its `HEAD` (ADR-0009 step 8). Shared by `--infer` and
/// `--matrix`. Bails only on a bad `--hub` (or an unresolvable pin); an empty or
/// single-repo workspace is a [`InferScan::Nothing`].
fn scan_workspace_infer(
    cfg: &config::Config,
    scope: &LinksScope<'_>,
    opts: InferOptions<'_>,
) -> anyhow::Result<InferScan> {
    let InferOptions {
        hub,
        pin,
        app_config_only,
    } = opts;
    // Repos in scope: the same selection as `roteiro links` (selected workspace,
    // else today's flat `[workspace]` scope, plus `--workspace` roots and the cwd).
    let paths = links_scope_paths(cfg, scope)?;
    if paths.is_empty() {
        return Ok(InferScan::Nothing(
            "no repos in scope; run inside a repo, pass `--workspace <root>`, or set `[workspace]`"
                .to_owned(),
        ));
    }

    let (mut by_project, project_paths, unsynced) = collect_workspace_config_keys(&paths)?;
    // `--app-config-only`: drop build/tooling/CI config keys from every repo before
    // matching, so cross-repo correspondences and drift compare only app config.
    // Opt-in — off by default, so matching is unchanged unless the flag is passed.
    if app_config_only {
        retain_app_config_keys(&mut by_project);
    }
    if by_project.len() < 2 {
        let hint = if unsynced.is_empty() {
            String::new()
        } else {
            format!(
                " ({} repo(s) not synced: {})",
                unsynced.len(),
                unsynced.join(", ")
            )
        };
        return Ok(InferScan::Nothing(format!(
            "need at least two synced repos with config files (TOML / JSON / .env) — found {}{hint}",
            by_project.len()
        )));
    }

    // Pick the hub: named, else the repo with the most config keys.
    let hub_name = match hub {
        Some(h) => {
            if !by_project.contains_key(h) {
                anyhow::bail!(
                    "no repo named `{h}` with config (have: {})",
                    by_project.keys().cloned().collect::<Vec<_>>().join(", ")
                );
            }
            h.to_owned()
        }
        None => by_project
            .iter()
            .max_by_key(|(_, v)| v.len())
            .map(|(k, _)| k.clone())
            .expect("non-empty"),
    };

    // Version-pin resolution: swap the hub's HEAD keys for those of the pinned
    // version the spokes actually deploy (ADR-0009 step 8), extracted in-memory.
    if let Some(rev) = pin.rev {
        let hub_path = project_paths
            .get(&hub_name)
            .ok_or_else(|| anyhow::anyhow!("no path for hub `{hub_name}`"))?;
        let mut keys = config_keys_at_rev(hub_path, rev, pin.ingest)
            .map_err(|e| anyhow::anyhow!("resolving hub `{hub_name}` at `{rev}`: {e}"))?;
        // Keep the pinned hub's keys consistent with the filtered spokes.
        if app_config_only {
            keys.retain(|k| !rto_graph::is_tooling_config_path(&k.file));
        }
        by_project.insert(hub_name.clone(), keys);
    }

    let report = resolve_infer_report(&by_project, &hub_name, &project_paths, pin)?;

    Ok(InferScan::Ready(InferReady {
        hub_name,
        hub_rev: pin.rev.map(str::to_owned),
        report,
        by_project,
        project_paths,
    }))
}

/// Open a spoke's graph and detect the hub version it pins (ADR-0009 step 8b),
/// or `None` if it is unsynced or pins nothing recognisable to the hub.
fn detect_spoke_pin(
    spoke_path: &std::path::Path,
    hub_dir: &str,
    hub_origin: Option<&str>,
    hub_repo: &rto_graph::Repo,
) -> anyhow::Result<Option<pins::SpokePin>> {
    let db = graph_db_path(spoke_path)?;
    if !db.exists() {
        return Ok(None);
    }
    let store = rto_graph::Store::open(&db)?;
    // The spoke's `[pins]` config supplies image/Helm → ref templates (ADR-0009 8c).
    // A malformed config is a hard error (the config contract), not silently ignored.
    let templates = config::load(spoke_path)?.effective.pins;
    pins::detect(&store, hub_dir, hub_origin, hub_repo, &templates)
}

/// Match every spoke against the right hub key set: the hub base (its `HEAD`, or the
/// explicit `--hub-rev` already swapped into `by_project`), or — under `--pinned`
/// (`pin.auto`) — the hub version each spoke *itself* pins, extracted per rev and
/// cached (ADR-0009 step 8b). Records per-spoke which pin, if any, was used.
fn resolve_infer_report(
    by_project: &std::collections::BTreeMap<String, Vec<infer_links::ConfigKey>>,
    hub_name: &str,
    project_paths: &std::collections::BTreeMap<String, std::path::PathBuf>,
    pin: PinnedHub<'_>,
) -> anyhow::Result<Vec<InferredRepo>> {
    let hub_base = by_project[hub_name].as_slice();
    // Under `--pinned`, set the hub up **once** — repo, object cache, extractor, its
    // real directory name (not the `-2`-suffixed workspace label) and origin — so
    // per-rev work is just the cache-aware `sync_tree`.
    let hub = if pin.auto {
        let hub_path = project_paths
            .get(hub_name)
            .ok_or_else(|| anyhow::anyhow!("no path for hub `{hub_name}`"))?;
        let repo = rto_graph::Repo::discover(hub_path)?;
        let cache =
            rto_graph::ObjectCache::open(repo.common_dir().join("roteiro").join("objects"))?;
        let reg = rto_graph::Registry::new(pin.ingest);
        let dir = hub_path
            .file_name()
            .and_then(|s| s.to_str())
            .unwrap_or(hub_name)
            .to_owned();
        let origin = repo.origin_url();
        Some((repo, cache, reg, dir, origin))
    } else {
        None
    };

    let mut rev_cache: std::collections::BTreeMap<String, Vec<infer_links::ConfigKey>> =
        std::collections::BTreeMap::new();
    let mut report = Vec::new();
    for (name, keys) in by_project.iter().filter(|(n, _)| n.as_str() != hub_name) {
        let (hub_rev, pin_via) = match &hub {
            // `--pinned`: resolve against the version this spoke pins, if any.
            Some((repo, cache, reg, dir, origin)) => {
                match detect_spoke_pin(&project_paths[name], dir, origin.as_deref(), repo)? {
                    Some(p) => {
                        if !rev_cache.contains_key(&p.rev) {
                            let k = config_keys_at_rev_with(repo, cache, *reg, &p.rev).map_err(
                                |e| {
                                    anyhow::anyhow!(
                                        "resolving hub `{hub_name}` at `{}`: {e}",
                                        p.rev
                                    )
                                },
                            )?;
                            rev_cache.insert(p.rev.clone(), k);
                        }
                        (Some(p.rev), Some(p.via))
                    }
                    None => (None, None),
                }
            }
            // Global: HEAD, or the explicit `--hub-rev` already in `hub_base`.
            None => (pin.rev.map(str::to_owned), None),
        };
        let hub_keys: &[infer_links::ConfigKey] = match &hub_rev {
            Some(rev) if pin.auto => rev_cache[rev].as_slice(),
            _ => hub_base,
        };
        let (matches, orphans) = infer_links::match_against_hub(keys, hub_keys);
        report.push(InferredRepo {
            repo: name.clone(),
            matches,
            orphans,
            hub_rev,
            pin_via,
        });
    }
    Ok(report)
}

/// `roteiro links --infer`: match each workspace repo's config keys (TOML / JSON
/// / `.env`) against a hub repo's, surfacing correspondences with no
/// hand-authored links and flagging orphan keys (drift candidates). Config keys
/// are read **from each repo's graph** (the `config_key` nodes a `sync` extracts),
/// so a repo must have been synced. Informational — always exits zero (these are
/// confidence-scored suggestions, not a gate).
///
/// With `write`, the correspondences are also persisted into each spoke's graph as
/// an `inferred` cross-repo import layer (external-ref target + `references` edge,
/// ADR-0009 feature 2b) that survives later syncs.
fn run_links_infer(
    cfg: &config::Config,
    scope: &LinksScope<'_>,
    opts: InferOptions<'_>,
    write: bool,
    json: bool,
) -> anyhow::Result<()> {
    // Having nothing to infer is a **successful no-op** (exit 0) — `--infer` is
    // informational, so a CI script can run it opportunistically in a single repo
    // without failing — but still say why.
    let ready = match scan_workspace_infer(cfg, scope, opts)? {
        InferScan::Nothing(reason) => {
            if json {
                emit_json(&serde_json::json!({ "hub": null, "spokes": [], "note": reason }))?;
            } else {
                eprintln!("nothing to infer — {reason}");
            }
            return Ok(());
        }
        InferScan::Ready(r) => r,
    };
    let hub_key_count = ready.by_project[&ready.hub_name].len();

    // Optionally persist the correspondences into each spoke's graph as a durable
    // `inferred` cross-repo import layer (ADR-0009 feature 2b).
    let written = if write {
        persist_inferred_links(&ready.hub_name, &ready.report, &ready.project_paths)?
    } else {
        0
    };

    if json {
        emit_json(&serde_json::json!({
            "hub": ready.hub_name,
            "hub_rev": ready.hub_rev,
            "spokes": ready.report,
            "written": written,
        }))?;
    } else {
        if let Some(rev) = &ready.hub_rev {
            println!(
                "resolved against {} @ {rev} (pinned version)",
                ready.hub_name
            );
        }
        print_infer_report(&ready.report, &ready.hub_name, hub_key_count);
        if write {
            println!("\npersisted {written} inferred cross-repo edge(s) into spoke graphs");
        }
    }
    Ok(())
}

/// `roteiro links --matrix`: render the cross-repo **config override matrix + drift**
/// view (ADR-0009 step 7). Reuses the `--infer` scan, then pivots the per-spoke
/// matches into a hub-key × spoke grid — as a text table, `--json`, or a
/// self-contained HTML page (`--html`, the "render web-graph" output).
fn run_links_matrix(
    cfg: &config::Config,
    scope: &LinksScope<'_>,
    opts: InferOptions<'_>,
    html: bool,
    out: Option<String>,
    json: bool,
) -> anyhow::Result<()> {
    let ready = match scan_workspace_infer(cfg, scope, opts)? {
        InferScan::Nothing(reason) => {
            if json {
                emit_json(
                    &serde_json::json!({ "hub": null, "rows": [], "drift": [], "note": reason }),
                )?;
            } else {
                eprintln!("nothing to show — {reason}");
            }
            return Ok(());
        }
        InferScan::Ready(r) => r,
    };

    // Hub key → value, so the matrix can flag which overrides actually differ.
    let hub_values: std::collections::BTreeMap<String, String> = ready.by_project[&ready.hub_name]
        .iter()
        .map(|c| (c.key.clone(), c.value.clone()))
        .collect();

    // Turn each spoke's matches/orphans into matrix inputs, looking its own values
    // back up from its config keys.
    let spokes = ready
        .report
        .iter()
        .map(|rep| {
            // Key values by (file, key): a `config_key` node is per-(file, key), so
            // the same key in two files must not collide to an arbitrary value.
            let vals: std::collections::HashMap<(&str, &str), &str> = ready.by_project[&rep.repo]
                .iter()
                .map(|c| ((c.file.as_str(), c.key.as_str()), c.value.as_str()))
                .collect();
            overview::SpokeInput {
                name: rep.repo.clone(),
                matches: rep
                    .matches
                    .iter()
                    .map(|m| overview::MatchInput {
                        hub_key: m.hub_key.clone(),
                        // The hub key's source file, so the matrix row can be
                        // classified as app vs tooling config (parity with the API).
                        file: m.hub_file.clone(),
                        spoke_key: m.spoke_key.clone(),
                        spoke_value: vals
                            .get(&(m.spoke_file.as_str(), m.spoke_key.as_str()))
                            .copied()
                            .unwrap_or("")
                            .to_owned(),
                        confidence: m.confidence,
                        // `links --infer` matches are, by definition, inferred.
                        provenance: rto_graph::Provenance::Inferred,
                    })
                    .collect(),
                orphans: rep
                    .orphans
                    .iter()
                    .map(|o| (o.key.clone(), o.value.clone()))
                    .collect(),
            }
        })
        .collect();

    // When resolving a pinned version, label the hub with its rev so every output
    // (text header, HTML title, JSON `hub`) says which version drift was measured
    // against.
    let hub_label = match &ready.hub_rev {
        Some(rev) => format!("{} @ {rev}", ready.hub_name),
        None => ready.hub_name.clone(),
    };
    let matrix = overview::build(&hub_label, &hub_values, spokes);

    if json {
        emit_json(&matrix)?;
    } else if html {
        let page = overview::render_html(&matrix);
        let out = out.unwrap_or_else(|| "roteiro-overview.html".to_owned());
        if out == "-" {
            println!("{page}");
        } else {
            std::fs::write(&out, page)?;
            eprintln!(
                "wrote override matrix ({} row(s), {} drift) → {out}",
                matrix.rows.len(),
                matrix.drift.len()
            );
        }
    } else {
        print!("{}", overview::render_text(&matrix));
    }
    Ok(())
}

/// Persist each spoke's inferred correspondences into that spoke's graph as an
/// `inferred` import layer (external-ref target nodes + `references` edges, under
/// [`rto_graph::LINKS_REF`]), returning how many edges were applied. Re-applying
/// is authoritative — the layer replaces any prior inferred links — and the layer
/// survives later syncs (dangling edges pruned when a config key is removed).
fn persist_inferred_links(
    hub_name: &str,
    report: &[InferredRepo],
    project_paths: &std::collections::BTreeMap<String, std::path::PathBuf>,
) -> anyhow::Result<usize> {
    let mut written = 0usize;
    for spoke in report {
        // Apply the layer for *every* spoke, even with no matches: `apply_import_layer`
        // is what clears this ref's prior edges, so a spoke whose matches have since
        // disappeared must still be re-applied (with an empty layer) to remove its
        // stale inferred links — otherwise the "authoritative re-apply" would leak them.
        let facts = infer_links::link_facts(hub_name, &spoke.matches);
        let path = project_paths
            .get(&spoke.repo)
            .ok_or_else(|| anyhow::anyhow!("no path for spoke `{}`", spoke.repo))?;
        let db = graph_db_path(path)?;
        if !db.exists() {
            continue; // unsynced spoke: nothing to attach edges to
        }
        let mut store = rto_graph::Store::open(&db)?;
        let applied = store.apply_import_layer(rto_graph::LINKS_REF, &facts)?;
        written += applied.edges_applied;
    }
    Ok(written)
}

/// Human-readable rendering of the inferred cross-repo config report.
/// Abbreviate a 40-hex commit sha to 10 chars; leave short refs (tags) as-is.
fn short_rev(rev: &str) -> &str {
    if rev.len() == 40 && rev.bytes().all(|b| b.is_ascii_hexdigit()) {
        &rev[..10]
    } else {
        rev
    }
}

fn print_infer_report(report: &[InferredRepo], hub_name: &str, hub_keys: usize) {
    println!("inferred config links (hub: {hub_name}, {hub_keys} keys)");
    let (mut nm, mut no) = (0usize, 0usize);
    for r in report {
        // Under `--pinned`, say which hub version this spoke resolved against.
        let pin = match (&r.hub_rev, &r.pin_via) {
            (Some(rev), Some(via)) => format!("  @ {} (via {via})", short_rev(rev)),
            (Some(rev), None) => format!("  @ {}", short_rev(rev)),
            _ => String::new(),
        };
        println!(
            "\n  {}{} match(es), {} orphan(s){pin}",
            r.repo,
            r.matches.len(),
            r.orphans.len()
        );
        for m in &r.matches {
            println!(
                "    {:<28} ~ {hub_name}::{:<24} ({:.2})",
                m.spoke_key, m.hub_key, m.confidence
            );
            nm += 1;
        }
        for o in &r.orphans {
            println!(
                "    {:<28} orphan — no {hub_name} counterpart (drift?)",
                o.key
            );
            no += 1;
        }
    }
    println!(
        "\n{nm} match(es), {no} orphan(s) across {} spoke(s)",
        report.len()
    );
}

/// Assemble the full graph and write it as a portable JSON artifact.
fn run_export(ingest: rto_graph::IngestConfig, out: Option<String>) -> anyhow::Result<()> {
    use rto_graph::GraphArtifact;

    let (repo, mut store, cache) = open_graph()?;
    build_graph(&repo, &mut store, &cache, ingest, GraphSource::Committed)?;
    let artifact = GraphArtifact::from_store(&store)?;
    let json = artifact.to_json()?;

    let out = out.unwrap_or_else(|| "roteiro-graph.json".to_owned());
    if out == "-" {
        println!("{json}");
    } else {
        std::fs::write(&out, format!("{json}\n"))?;
        eprintln!(
            "exported {} nodes, {} edges → {out}",
            artifact.facts.nodes.len(),
            artifact.facts.edges.len()
        );
    }
    Ok(())
}

/// Load a graph artifact into the local store, replacing its contents. Lets a
/// fresh clone (or a `post-merge`/`post-checkout` hook) obtain a ready-made graph
/// without re-extraction. Unless `force`, the artifact's tree must match the
/// working `HEAD` — so a CI artifact fetched for a different commit is refused
/// (non-zero exit) and the caller rebuilds instead. A matching load also sets the
/// sync state to that tree, so a following `sync` no-ops.
fn run_load(file: &str, force: bool) -> anyhow::Result<()> {
    use rto_graph::{GraphArtifact, Repo, Store};

    let json = if file == "-" {
        std::io::read_to_string(std::io::stdin())?
    } else {
        std::fs::read_to_string(file)?
    };
    let artifact = GraphArtifact::from_json(&json)?;

    let cwd = std::env::current_dir()?;
    let repo = Repo::discover(&cwd)?;

    // Refuse an artifact that isn't provably for the current HEAD, so a fetched
    // artifact never installs a graph that doesn't match the checkout. A missing
    // tree can't be verified, so it is refused too (both overridable with --force).
    if !force {
        let head = repo.head_tree_id()?;
        let short = |t: &str| t[..t.len().min(12)].to_owned();
        match artifact.tree.as_deref() {
            Some(tree) if tree == head => {}
            Some(tree) => anyhow::bail!(
                "artifact tree {} does not match HEAD tree {} — refusing to load a mismatched graph (pass --force to override, or run `roteiro sync`)",
                short(tree),
                short(&head)
            ),
            None => anyhow::bail!(
                "artifact records no tree, so it cannot be verified against HEAD — pass --force to load it anyway, or run `roteiro sync`"
            ),
        }
    }

    let store_dir = repo.git_dir().join("roteiro");
    std::fs::create_dir_all(&store_dir)?;
    let mut store = Store::open(&store_dir.join("graph.db"))?;
    artifact.load_into(&mut store)?;

    println!(
        "loaded {} nodes, {} edges from {file}",
        store.node_count()?,
        store.edge_count()?
    );
    Ok(())
}

/// Serve the read-only graph explorer JSON API over HTTP, **llama-free**
/// (ADR-0008). Builds a [`rto_graph::WorkspaceSet`] from config and serves
/// [`graph_api`]'s router directly on a small tokio runtime — axum only, no
/// `rto-serve`, no model, no MCP, no C/C++ toolchain. No graph is (re)built here:
/// it serves whatever each repo's store already holds (a read-only view;
/// `roteiro sync` refreshes it). The **Ask** tab is deliberately absent — it
/// needs the `serve` build's `/v1/chat/completions`, which this server does not
/// offer.
#[cfg(feature = "explorer")]
fn run_explorer(
    cfg: &config::Config,
    addr: Option<String>,
    workspace_name: Option<&str>,
) -> anyhow::Result<()> {
    use std::sync::Arc;

    // Build the workspace set from config (ADR-0008). When no workspace is
    // configured (the common single-repo case), fall back to hosting the current
    // directory's repo alone, so `roteiro explorer` "just works" with no config.
    let resolved = cfg.resolved_workspaces()?;
    let set = if resolved.is_empty() {
        explorer_cwd_set()?
    } else {
        rto_graph::WorkspaceSet::from_resolved(resolved)?
    };
    if set.names().is_empty() {
        anyhow::bail!(
            "no workspaces to serve — run inside a repo, or configure \
             `[[workspaces]]` / `[standalone]` in roteiro.toml"
        );
    }
    let set = Arc::new(set);

    // Validate an explicit `--workspace-name` once, up front: an unknown name must
    // fail fast — with the existing `UnknownWorkspace` message that lists the known
    // workspaces — rather than booting a server whose flat `/v1/graph/*` routes
    // would then 404 on every request. The cwd-default / single-workspace paths
    // pass no name and are unaffected.
    if let Some(name) = workspace_name {
        set.select(Some(name))?;
    }

    // The default workspace for the flat `/v1/graph/*` routes: the (now-validated)
    // `--workspace-name`, else the workspace containing the current repo. A lone
    // configured workspace resolves itself, so `None` is fine there (see
    // `WorkspaceSet::select`).
    let default = explorer_default_workspace(&set, workspace_name);

    // Address precedence: CLI flag > `[serve] addr` > default loopback.
    let addr = addr
        .or_else(|| cfg.serve.addr.clone())
        .unwrap_or_else(|| "127.0.0.1:8017".to_owned());
    let socket: std::net::SocketAddr = addr
        .parse()
        .map_err(|e| anyhow::anyhow!("invalid explorer address `{addr}`: {e}"))?;
    if !socket.ip().is_loopback() {
        eprintln!(
            "warning: binding a non-loopback address ({socket}) — the explorer API \
             has no auth; front it with a reverse proxy"
        );
    }

    // The read-only data API plus the served web app (HTML shell, our ES app, and
    // the vendored cytoscape.js) — same-origin, so the app fetches `/v1/graph/*`
    // with no CORS. The UI routes live only on this llama-free explorer server; a
    // full `serve` build keeps serving just the JSON API (no bundled UI).
    let router = graph_api::router(set.clone(), default.clone()).merge(explorer_app::router());

    // A small current-thread runtime is all the axum server needs; no rto-serve,
    // no llama.cpp runtime. Blocks until shutdown.
    let rt = tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()?;
    rt.block_on(async move {
        let listener = tokio::net::TcpListener::bind(socket).await?;
        let default_note = default
            .as_deref()
            .map_or_else(String::new, |d| format!(" (default workspace: {d})"));
        eprintln!(
            "roteiro explorer listening on http://{socket}/ (UI) — \
             API at http://{socket}/v1/graph — {} workspace(s): {}{default_note}",
            set.names().len(),
            set.names().join(", "),
        );
        axum::serve(listener, router)
            .await
            .map_err(anyhow::Error::from)
    })
}

/// The single-repo fallback for `roteiro explorer`: host the current directory's
/// repo as a lone standalone (`linked:false`) workspace, named after its
/// working-tree directory. Its `graph.db` is opened on demand (read-only) — the
/// explorer never builds a graph, so an unsynced repo simply reports "no graph"
/// per project rather than being silently rebuilt.
#[cfg(feature = "explorer")]
fn explorer_cwd_set() -> anyhow::Result<rto_graph::WorkspaceSet> {
    let cwd = std::env::current_dir()?;
    let repo = rto_graph::Repo::discover(&cwd)?;
    let workdir = repo.workdir().unwrap_or(&cwd);
    let name = workdir
        .file_name()
        .map_or_else(|| "repo".to_owned(), |s| s.to_string_lossy().into_owned());
    let ws = rto_graph::Workspace::from_repo_paths([workdir])?;
    Ok(rto_graph::WorkspaceSet::from_workspaces([(
        name, ws, false,
    )]))
}

/// The default workspace the flat `/v1/graph/*` routes bind to: an explicit
/// `--workspace-name` if given (already validated against `set` at startup, so it
/// is passed through here), else the workspace whose discovered members include
/// the current repo's `graph.db`. `None` lets a single-workspace set resolve its
/// sole workspace (and a multi-workspace set report "ambiguous" until a nested
/// `/workspaces/{ws}/…` route is used).
#[cfg(feature = "explorer")]
fn explorer_default_workspace(
    set: &rto_graph::WorkspaceSet,
    workspace_name: Option<&str>,
) -> Option<String> {
    if let Some(name) = workspace_name {
        return Some(name.to_owned());
    }
    // Reuse the one place the on-disk `<repo>/.git/roteiro/graph.db` layout lives.
    let db = graph_db_path(&std::env::current_dir().ok()?).ok()?;
    set.containing(&db).map(str::to_owned)
}

/// The parsed `serve` flags (from the clap `Command::Serve` arm), bundled so the
/// dispatch stays a single struct rather than a long argument list.
#[cfg(any(feature = "mcp", feature = "serve"))]
// Several fields (addr/TLS/mcp) are only read on the `serve` path; in an
// mcp-only build the model endpoint is a stub, so they are legitimately unused.
#[cfg_attr(not(feature = "serve"), allow(dead_code))]
struct ServeOptions {
    /// Serve the OpenAI-compatible `/v1` model endpoint (`--models`).
    models: bool,
    /// MCP-only HTTP bind address (`--http`), when not serving `--models`.
    http: Option<String>,
    /// Model-server bind address (`--addr`).
    addr: Option<String>,
    /// In-process TLS certificate chain (`--tls-cert`).
    tls_cert: Option<String>,
    /// In-process TLS private key (`--tls-key`).
    tls_key: Option<String>,
    /// With `--models`, also mount `/mcp` on the same port (`--mcp`).
    mcp: bool,
}

/// Dispatch `roteiro serve`: the OpenAI-compatible model endpoint (`--models`,
/// ADR-0006) or the MCP graph server — optionally **both on one port** (`--models
/// --mcp`, ADR-0008). Each backend is feature-gated; a build lacking the relevant
/// feature reports how to enable it.
#[cfg(any(feature = "mcp", feature = "serve"))]
fn run_serve(
    ingest: rto_graph::IngestConfig,
    cfg: &config::Config,
    opts: ServeOptions,
    workspace_roots: &[String],
    workspace_name: Option<&str>,
    sync_on_access: bool,
) -> anyhow::Result<()> {
    use std::sync::Arc;

    // Build the full multi-workspace set from config — the same source of truth
    // `roteiro explorer` uses (`Config::resolved_workspaces()`: the legacy
    // `[workspace]` folded to `default`, every `[[workspaces]]`, and `[standalone]`),
    // plus any explicit `--workspace <ROOT>` folded into `default`. So `serve` hosts
    // ALL configured workspaces (and CLI roots) and runs from ANY directory, with no
    // git cwd required.
    let resolved = cfg.resolved_workspaces()?;

    // The true single-repo fallback fires ONLY when nothing selects a workspace: no
    // configured workspaces, no `--workspace <ROOT>`, and no `--workspace-name`. Then
    // build the current repo's graph now and host it alone as `default` (this is the
    // one path that still needs a git cwd — a lone repo with no config still "just
    // works", sharing the one store handle between `set` and `flat`).
    let ServeWorkspaces { set, flat } =
        if resolved.is_empty() && workspace_roots.is_empty() && workspace_name.is_none() {
            let (repo, mut store, cache) = open_graph()?;
            build_graph(&repo, &mut store, &cache, ingest, GraphSource::Committed)?;
            let name = repo
                .workdir()
                .and_then(std::path::Path::file_name)
                .map_or_else(|| "repo".to_owned(), |s| s.to_string_lossy().into_owned());
            let flat = Arc::new(rto_graph::Workspace::single(name, store));
            let set = Arc::new(rto_graph::WorkspaceSet::from_single(
                "default",
                flat.clone(),
                flat.is_multi(),
            ));
            ServeWorkspaces { set, flat }
        } else {
            // Multi-workspace serve: host every configured workspace, plus any explicit
            // `--workspace <ROOT>` (folded into `default`). `set` (built the same way
            // `run_explorer` builds it) backs the read-only `/v1/graph/*` API and the
            // served UI, workspace-aware. `flat` is one workspace over EVERY project
            // across ALL those workspaces, backing the model tool registry, the
            // `/v1/{project}/…` routing, and the MCP router — so the served model can
            // query any hosted project. Existing graphs are opened on demand; SIGHUP
            // reloads the set of repos, and `--sync-on-access` (re)builds a project's
            // graph on first touch (ADR-0008).
            let effective = fold_cli_roots(resolved, workspace_roots);
            let set = Arc::new(rto_graph::WorkspaceSet::from_resolved(effective.clone())?);
            // A friendly error when nothing resolves — an empty config, only stale roots,
            // or a `-w` naming nothing to serve — BEFORE `from_repo_paths` would surface a
            // raw `WorkspaceError::Empty`. Mirrors `run_explorer`'s message.
            if set.names().is_empty() {
                anyhow::bail!(
                    "no workspaces to serve — run inside a repo, pass `--workspace <ROOT>`, \
                 or configure `[[workspaces]]` / `[standalone]` in roteiro.toml"
                );
            }
            // Validate `--workspace-name` once, up front: an unknown name fails fast
            // (listing the known workspaces) rather than booting a server whose flat
            // routes would 404. Mirrors `run_explorer`.
            if let Some(name) = workspace_name {
                set.select(Some(name))?;
            }
            let paths = resolved_repo_paths(&effective, &[])?;
            let mut ws = rto_graph::Workspace::from_repo_paths(&paths)?;
            if sync_on_access {
                ws = ws.with_on_open(Arc::new(move |db: &std::path::Path| {
                    sync_project_graph(db, ingest).map_err(|e| e.to_string())
                }));
            }
            let flat = Arc::new(ws);
            eprintln!(
                "roteiro serve: {} workspace(s) [{}] — {} project(s){}{}",
                set.names().len(),
                set.names().join(", "),
                flat.names().len(),
                if sync_on_access {
                    ", sync-on-access"
                } else {
                    ""
                },
                flat.names().join(", ")
            );
            install_workspace_reload(&flat, cfg.clone(), workspace_roots.to_vec());
            ServeWorkspaces { set, flat }
        };

    if opts.models {
        serve_models_endpoint(cfg, set, flat, workspace_name, &opts)
    } else {
        serve_mcp(flat, opts.http)
    }
}

/// The two workspace views a `serve` process holds. `set` is the full
/// multi-workspace [`rto_graph::WorkspaceSet`] (ADR-0008) that backs the read-only
/// `/v1/graph/*` API and the served explorer UI — workspace-aware, listed at
/// `GET /v1/graph/workspaces`. `flat` is a single [`rto_graph::Workspace`] over
/// **every** project across all those workspaces, backing the model tool registry,
/// the `/v1/{project}/…` chat routing, and the MCP router — so the served model can
/// query any hosted project by name. For the single-repo fallback the two share the
/// one store handle; otherwise `flat` opens each project's store on demand.
#[cfg(any(feature = "mcp", feature = "serve"))]
struct ServeWorkspaces {
    /// The full multi-workspace set (read-only graph API + UI).
    set: std::sync::Arc<rto_graph::WorkspaceSet>,
    /// One flattened workspace over every hosted project (model tools + MCP).
    flat: std::sync::Arc<rto_graph::Workspace>,
}

/// The union of member repo paths across every resolved workspace group, plus any
/// additive `--workspace <ROOT>` paths — the repo set the flattened model
/// [`rto_graph::Workspace`] hosts (and the SIGHUP reload re-scans). Discovered the
/// same way [`rto_graph::WorkspaceSet::from_resolved`] discovers each group's repos
/// (roots scanned + explicit repos), deduplicated by path so a repo named in two
/// groups is hosted once.
#[cfg(any(feature = "mcp", feature = "serve"))]
fn resolved_repo_paths(
    resolved: &[rto_graph::ResolvedWorkspace],
    cli_roots: &[String],
) -> anyhow::Result<Vec<std::path::PathBuf>> {
    use std::collections::BTreeSet;
    let mut seen: BTreeSet<std::path::PathBuf> = BTreeSet::new();
    let mut out: Vec<std::path::PathBuf> = Vec::new();
    let mut push = |p: std::path::PathBuf, out: &mut Vec<std::path::PathBuf>| {
        // Dedupe by the canonical path where possible, so the same repo reached via
        // two groups (or a root + an explicit repo) is hosted once.
        let key = p.canonicalize().unwrap_or_else(|_| p.clone());
        if seen.insert(key) {
            out.push(p);
        }
    };
    for root in cli_roots {
        for repo in rto_graph::discover_repos_under(std::path::Path::new(root))? {
            push(repo, &mut out);
        }
    }
    for rw in resolved {
        for root in &rw.roots {
            for repo in rto_graph::discover_repos_under(std::path::Path::new(root))? {
                push(repo, &mut out);
            }
        }
        for repo in &rw.repos {
            push(std::path::PathBuf::from(repo), &mut out);
        }
    }
    Ok(out)
}

/// Fold explicit `--workspace <ROOT>` CLI roots into the resolved workspace groups as
/// the `default` workspace (ADR-0008): unioned into an existing `default` (the legacy
/// `[workspace]`), else added as a new linked `default` group. So repos a user names
/// on the command line are hosted as a first-class named workspace — surfaced by the
/// read-only graph API AND reachable by the served model — exactly like configured
/// workspaces, rather than being merged only into the flat model view. No roots ⇒ the
/// groups are returned unchanged. `default` is the only name derivable from CLI roots
/// (it never collides with a `[[workspaces]]`/`[standalone]` name, which are distinct
/// and, for a legacy `[workspace]`, already fold to `default`).
#[cfg(any(feature = "mcp", feature = "serve"))]
fn fold_cli_roots(
    mut resolved: Vec<rto_graph::ResolvedWorkspace>,
    cli_roots: &[String],
) -> Vec<rto_graph::ResolvedWorkspace> {
    if cli_roots.is_empty() {
        return resolved;
    }
    match resolved.iter_mut().find(|r| r.name == "default") {
        Some(default) => default.roots.extend(cli_roots.iter().cloned()),
        None => resolved.push(rto_graph::ResolvedWorkspace {
            name: "default".to_owned(),
            roots: cli_roots.to_vec(),
            repos: Vec::new(),
            linked: true,
        }),
    }
    resolved
}

/// Repo paths a workspace `serve` hosts: everything under the CLI `--workspace`
/// roots and `[workspace]` config `roots` (each scanned), plus any explicit
/// `repos`. Empty ⇒ single-repo serving of the current directory's repo. Shared
/// by `serve` startup, SIGHUP reload, and `roteiro links` (ADR-0009).
fn collect_workspace_repo_paths(
    ws_cfg: &config::WorkspaceConfig,
    cli_roots: &[String],
) -> anyhow::Result<Vec<std::path::PathBuf>> {
    let mut repo_paths: Vec<std::path::PathBuf> = Vec::new();
    let roots = cli_roots
        .iter()
        .map(String::as_str)
        .chain(ws_cfg.roots.iter().flatten().map(String::as_str));
    // Expand a leading `~` in every root/repo (config- or CLI-sourced) so git
    // never receives a literal `~`, matching the new multi-workspace path
    // (`Config::resolved_workspaces`).
    for root in roots {
        repo_paths.extend(rto_graph::discover_repos_under(&config::expand_tilde(
            root,
        ))?);
    }
    for repo in ws_cfg.repos.iter().flatten() {
        repo_paths.push(config::expand_tilde(repo).into_owned());
    }
    Ok(repo_paths)
}

/// `serve --sync-on-access` hook: (re)build the graph for the repo whose store
/// is `graph_db` (`<repo>/.git/roteiro/graph.db`), before it is first served.
/// Rebuilds from the committed tree, matching how the freshness hooks sync.
#[cfg(any(feature = "mcp", feature = "serve"))]
fn sync_project_graph(
    graph_db: &std::path::Path,
    ingest: rto_graph::IngestConfig,
) -> anyhow::Result<()> {
    use rto_graph::{ObjectCache, Repo, Store};
    // graph.db → roteiro → .git → repo directory (three parents up).
    let repo_dir = graph_db
        .parent()
        .and_then(std::path::Path::parent)
        .and_then(std::path::Path::parent)
        .ok_or_else(|| anyhow::anyhow!("unexpected graph.db path: {}", graph_db.display()))?;
    let repo = Repo::discover(repo_dir)?;
    let store_dir = repo.git_dir().join("roteiro");
    std::fs::create_dir_all(&store_dir)?;
    let mut store = Store::open(&store_dir.join("graph.db"))?;
    let cache = ObjectCache::open(repo.common_dir().join("roteiro").join("objects"))?;
    build_graph(&repo, &mut store, &cache, ingest, GraphSource::Committed)?;
    Ok(())
}

/// Install a SIGHUP handler that re-scans the workspace roots and reloads the
/// registry in place, so a running server picks up added/removed repos without a
/// restart (ADR-0008). Runs on a dedicated thread with its own tokio runtime,
/// independent of the serve runtime; reload is thread-safe (the `Workspace`
/// serialises its own state). Best-effort: if SIGHUP cannot be registered, the
/// server still runs, just without live reload.
#[cfg(all(unix, any(feature = "mcp", feature = "serve")))]
fn install_workspace_reload(
    ws: &std::sync::Arc<rto_graph::Workspace>,
    cfg: config::Config,
    cli_roots: Vec<String>,
) {
    let ws = ws.clone();
    std::thread::spawn(move || {
        // A current-thread runtime with just the I/O driver — all unix signal
        // handling needs (no timers), keeping this self-contained.
        let Ok(rt) = tokio::runtime::Builder::new_current_thread()
            .enable_io()
            .build()
        else {
            return;
        };
        rt.block_on(async move {
            let mut hup =
                match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::hangup()) {
                    Ok(sig) => sig,
                    Err(e) => {
                        eprintln!("workspace reload disabled (cannot watch SIGHUP): {e}");
                        return;
                    }
                };
            eprintln!("send SIGHUP to reload the workspace (pick up added/removed repos)");
            while hup.recv().await.is_some() {
                // Re-derive the full repo set the same way startup did: every
                // configured workspace's members (`resolved_workspaces()`) plus the
                // additive `--workspace <ROOT>` paths — so a SIGHUP picks up repos
                // added/removed across ALL workspaces, not just the legacy block.
                let result = cfg
                    .resolved_workspaces()
                    .and_then(|resolved| resolved_repo_paths(&resolved, &cli_roots))
                    .and_then(|paths| ws.reload_from(paths).map_err(anyhow::Error::from));
                match result {
                    Ok(names) => eprintln!(
                        "workspace reloaded: {} project(s) — {}",
                        names.len(),
                        names.join(", ")
                    ),
                    Err(e) => eprintln!("workspace reload failed (registry unchanged): {e}"),
                }
            }
        });
    });
}

/// On non-Unix, SIGHUP reload is unavailable; the server runs without it.
#[cfg(all(not(unix), any(feature = "mcp", feature = "serve")))]
fn install_workspace_reload(
    _ws: &std::sync::Arc<rto_graph::Workspace>,
    _cfg: config::Config,
    _cli_roots: Vec<String>,
) {
}

/// Serve the graph over the Model Context Protocol, over stdio (default) or
/// streamable HTTP (`--http <addr>`). The `workspace` hosts one project
/// (single-repo, already synced) or many (opened on demand); tools select one
/// with `project` (ADR-0008).
#[cfg(feature = "mcp")]
fn serve_mcp(
    workspace: std::sync::Arc<rto_graph::Workspace>,
    http: Option<String>,
) -> anyhow::Result<()> {
    match http {
        Some(addr) => {
            let addr: std::net::SocketAddr = addr
                .parse()
                .map_err(|e| anyhow::anyhow!("invalid --http address `{addr}`: {e}"))?;
            eprintln!("roteiro MCP server listening on http://{addr}/mcp");
            rto_render::mcp::serve_http(workspace, addr).map_err(|e| anyhow::anyhow!("{e}"))
        }
        None => rto_render::mcp::serve_stdio(workspace).map_err(|e| anyhow::anyhow!("{e}")),
    }
}

/// MCP serving is unavailable without the `mcp` feature.
#[cfg(all(not(feature = "mcp"), feature = "serve"))]
fn serve_mcp(
    _workspace: std::sync::Arc<rto_graph::Workspace>,
    _http: Option<String>,
) -> anyhow::Result<()> {
    anyhow::bail!(
        "MCP serving needs the `mcp` feature (build with `--features mcp`); \
         use `--models` for the OpenAI-compatible model endpoint"
    )
}

/// Serve installed generative models over the loopback, OpenAI-compatible `/v1`
/// endpoint (ADR-0006). Serves only installed models; never downloads.
/// Collect the installed GGUF models eligible to serve over `/v1` (ADR-0006):
/// generative and embedding always, vision only with its `mmproj` projector;
/// OCR/audio are sync-time ingestion models, not endpoints. Narrowed by the
/// `[serve] models` allow-list if set. Returns the list; serving is the caller's.
#[cfg(feature = "serve")]
fn served_models(cfg: &config::Config) -> Vec<rto_serve::llama::Served> {
    use rto_graph::{ModelKind, Platform, REGISTRY, is_installed, model_dir};
    let host = Platform::host();
    let wanted = cfg.serve.models.as_deref();
    let has_file = |m: &rto_graph::ModelSpec, name: &str| {
        m.variant_for(host)
            .is_some_and(|v| v.files.iter().any(|f| f.name == name))
    };
    REGISTRY
        .iter()
        .filter(|m| wanted.is_none_or(|w| w.iter().any(|n| n == m.name)))
        .filter(|m| has_file(m, "model.gguf"))
        .filter(|m| match m.kind {
            ModelKind::Generative | ModelKind::Embedding => true,
            // A vision model is only servable with its multimodal projector.
            ModelKind::Vision => has_file(m, "mmproj.gguf"),
            // OCR and audio are sync-time ingestion models, not `/v1` endpoints.
            ModelKind::Ocr | ModelKind::Audio => false,
        })
        .filter(|m| m.variant_for(host).is_some_and(|v| is_installed(m.name, v)))
        .map(|m| rto_serve::llama::Served {
            name: m.name.to_owned(),
            path: model_dir(m.name).join("model.gguf"),
            mmproj: has_file(m, "mmproj.gguf").then(|| model_dir(m.name).join("mmproj.gguf")),
        })
        .collect()
}

#[cfg(feature = "serve")]
fn serve_models_endpoint(
    cfg: &config::Config,
    set: std::sync::Arc<rto_graph::WorkspaceSet>,
    flat: std::sync::Arc<rto_graph::Workspace>,
    workspace_name: Option<&str>,
    opts: &ServeOptions,
) -> anyhow::Result<()> {
    let (addr, tls_cert, tls_key) = (
        opts.addr.clone(),
        opts.tls_cert.clone(),
        opts.tls_key.clone(),
    );

    let served = served_models(cfg);
    if served.is_empty() {
        anyhow::bail!(
            "no installed GGUF models to serve — pull one first \
             (`roteiro model pull qwen3-0.6b` for chat, \
             `roteiro model pull bge-small-en-v1.5-gguf` for embeddings, or \
             `roteiro model pull smolvlm-500m-gguf` for vision; \
             see `roteiro model list`)"
        );
    }

    // Address precedence: CLI flag > `[serve] addr` > default loopback.
    let addr = addr
        .or_else(|| cfg.serve.addr.clone())
        .unwrap_or_else(|| "127.0.0.1:8017".to_owned());
    let socket: std::net::SocketAddr = addr
        .parse()
        .map_err(|e| anyhow::anyhow!("invalid serve address `{addr}`: {e}"))?;
    if !socket.ip().is_loopback() {
        eprintln!(
            "warning: binding a non-loopback address ({socket}) — the endpoint \
             has no auth; front it with a reverse proxy (ADR-0006)"
        );
    }

    let names = served
        .iter()
        .map(|s| s.name.clone())
        .collect::<Vec<_>>()
        .join(", ");
    // Keep models resident up to the configured budget (MiB → bytes), loading on
    // demand and unloading the least-recently-used past it (ADR-0006). Unset ⇒ 0
    // ⇒ a single resident model.
    let budget_bytes = cfg
        .serve
        .memory_budget_mb
        .unwrap_or(0)
        .saturating_mul(1024 * 1024);
    let engine = rto_serve::llama::LlamaEngine::new_with_budget(served, 0, budget_bytes)
        .map_err(|e| anyhow::anyhow!("starting llama.cpp: {e}"))?;
    let engine: std::sync::Arc<dyn rto_serve::Engine> = std::sync::Arc::new(engine);

    // TLS precedence mirrors `addr`: CLI flag > `[serve]` config.
    let tls = resolve_serve_tls(
        tls_cert.or_else(|| cfg.serve.tls_cert.clone()),
        tls_key.or_else(|| cfg.serve.tls_key.clone()),
    )?;
    serve_v1_tail(
        cfg,
        ServeSurfaces {
            set,
            flat,
            workspace_name,
        },
        opts,
        engine,
        socket,
        tls,
        &names,
    )
}

/// Resolve the in-process TLS pair: both a cert and a key give HTTPS, neither
/// gives plain HTTP, exactly one is an error. (CLI-over-config precedence is
/// applied by the caller.)
#[cfg(feature = "serve")]
fn resolve_serve_tls(
    cert: Option<String>,
    key: Option<String>,
) -> anyhow::Result<Option<(std::path::PathBuf, std::path::PathBuf)>> {
    match (cert, key) {
        (Some(cert), Some(key)) => Ok(Some((
            std::path::PathBuf::from(cert),
            std::path::PathBuf::from(key),
        ))),
        (Some(_), None) | (None, Some(_)) => anyhow::bail!(
            "TLS needs both a certificate and a key — set both `--tls-cert`/`--tls-key` \
             (or `[serve] tls_cert`/`tls_key`), or neither for plain HTTP"
        ),
        (None, None) => Ok(None),
    }
}

/// The workspace surfaces a `serve --models` process serves, bundled so
/// [`serve_v1_tail`] stays within the argument-count budget: the full multi-workspace
/// `set` (read-only `/v1/graph/*` API + UI, explorer builds) and the flattened `flat`
/// workspace over every hosted project (model tools + MCP), plus the validated
/// `--workspace-name` that picks the default flat-route workspace.
#[cfg(feature = "serve")]
struct ServeSurfaces<'a> {
    /// The full configured workspace set (read-only graph API + served UI).
    set: std::sync::Arc<rto_graph::WorkspaceSet>,
    /// One flattened workspace over every hosted project (model tools + MCP).
    flat: std::sync::Arc<rto_graph::Workspace>,
    /// The validated `--workspace-name` the flat `/v1/graph/*` routes default to.
    workspace_name: Option<&'a str>,
}

/// Assemble the graph tools and serve the endpoint: `/v1` alone, or — with
/// `--mcp` — `/v1` **and** `/mcp` merged on one port (ADR-0008). Blocks until
/// shutdown.
#[cfg(feature = "serve")]
fn serve_v1_tail(
    cfg: &config::Config,
    surfaces: ServeSurfaces<'_>,
    opts: &ServeOptions,
    engine: std::sync::Arc<dyn rto_serve::Engine>,
    socket: std::net::SocketAddr,
    tls: Option<(std::path::PathBuf, std::path::PathBuf)>,
    names: &str,
) -> anyhow::Result<()> {
    let ServeSurfaces {
        set,
        flat,
        workspace_name,
    } = surfaces;
    // `set` (the full workspace set) and `workspace_name` back the read-only
    // `/v1/graph/*` API + UI, which are only mounted in an `explorer` build; the
    // model tools and MCP router use the flattened `flat` workspace regardless.
    #[cfg(not(feature = "explorer"))]
    let _ = (&set, workspace_name);
    let scheme = if tls.is_some() { "https" } else { "http" };
    // Auto-register the graph tools (ADR-0006) unless disabled, so the served
    // model can `explain`/`search`/`path`/`debt` — across every hosted project
    // of every configured workspace (ADR-0008), selected by a `project` argument.
    let tools: Option<std::sync::Arc<dyn rto_serve::ToolRegistry>> =
        if cfg.serve.tools.unwrap_or(true) {
            Some(std::sync::Arc::new(GraphToolRegistry::new(flat.clone())))
        } else {
            None
        };
    let tools_note = if tools.is_some() {
        " (graph tools on)"
    } else {
        ""
    };

    // The served model ids, captured before the engine is moved into the router,
    // so an explorer build can advertise them as the Ask capability (below).
    #[cfg(feature = "explorer")]
    let model_ids: Vec<String> = engine.models().into_iter().map(|m| m.id).collect();

    // Build the `/v1` model router, then merge any extra read-only/MCP surfaces
    // onto it — all sharing one port and one Workspace (ADR-0008). `/v1/graph` and
    // `/mcp` are just axum path prefixes, so the routers merge. Serving the router
    // directly is equivalent to `serve_blocking[_with_tools]` (they build the same
    // app), so this path also covers the plain (`/v1`-only) case.
    let router = match tools {
        Some(tools) => rto_serve::app_with_tools(engine, tools),
        None => rto_serve::app(engine),
    };

    // With the explorer UI compiled in (`--features serve,explorer`), a full
    // `serve --models` process is the single coherent way to run the whole
    // explorer + Ask experience (ADR-0010): mount the read-only `/v1/graph/*` data
    // API AND the static web app beside `/v1`, and advertise the chat endpoint the
    // model router already exposes so the UI enables its Ask tab. The engine built
    // above backs both `/v1/chat/completions` and the graph tools — nothing is
    // duplicated; the pure `explorer` build never reaches here and keeps Ask off.
    #[cfg(feature = "explorer")]
    let router = {
        // The workspace the flat `/v1/graph/*` routes bind to: the validated
        // `--workspace-name`, else the one containing the cwd, else the sole
        // configured workspace (mirrors `run_explorer`).
        let default = explorer_default_workspace(&set, workspace_name);
        mount_explorer_surfaces(router, set, default, model_ids)
    };
    #[cfg(feature = "explorer")]
    let graph_note = " + /v1/graph + / (UI, Ask on)";
    #[cfg(not(feature = "explorer"))]
    let graph_note = "";

    // `--models --mcp`: also mount the MCP graph server at `/mcp` on the SAME port.
    if opts.mcp {
        #[cfg(feature = "mcp")]
        {
            let combined = router.merge(rto_render::mcp::mcp_router(flat));
            eprintln!(
                "roteiro server listening on {scheme}://{socket} — /v1{tools_note}{graph_note} + /mcp — serving: {names}"
            );
            return match tls {
                Some((cert, key)) => {
                    rto_serve::serve_blocking_router_tls(combined, socket, &cert, &key)
                }
                None => rto_serve::serve_blocking_router(combined, socket),
            };
        }
        #[cfg(not(feature = "mcp"))]
        anyhow::bail!(
            "`serve --models --mcp` needs the `mcp` feature (build with `--features serve,mcp`)"
        );
    }

    eprintln!(
        "roteiro model server listening on {scheme}://{socket}/v1{tools_note}{graph_note} — serving: {names}"
    );
    match tls {
        Some((cert, key)) => rto_serve::serve_blocking_router_tls(router, socket, &cert, &key),
        None => rto_serve::serve_blocking_router(router, socket),
    }
}

/// Merge the explorer's read-only data API and its static web app onto a full
/// `serve --models` router, advertising the mounted Ask (chat) endpoint. The graph
/// API is multi-workspace-aware (ADR-0008): `set` is the FULL configured
/// [`rto_graph::WorkspaceSet`], so `GET /v1/graph/workspaces` lists every hosted
/// workspace and each is reachable both flat (via `default`) and under
/// `/v1/graph/workspaces/{ws}/…`. `default` names the workspace the flat routes
/// bind to (`--workspace-name`, else the cwd's, else the sole one). `model_ids` are
/// the served generative models, surfaced in `/v1/graph/capabilities` so the web
/// app can name the model backing Ask. Factored out so the wiring is unit-testable
/// with a mock engine (no llama.cpp).
#[cfg(all(feature = "serve", feature = "explorer"))]
fn mount_explorer_surfaces(
    router: axum::Router,
    set: std::sync::Arc<rto_graph::WorkspaceSet>,
    default: Option<String>,
    model_ids: Vec<String>,
) -> axum::Router {
    let caps = crate::graph_api::Capabilities {
        ask: true,
        models: model_ids,
    };
    router
        .merge(crate::graph_api::router_with_capabilities(
            set, default, caps,
        ))
        .merge(crate::explorer_app::router())
}

/// Resolve a tool-call key against a `project`: a project-qualified key
/// (`<project>::<key>`) follows a **cross-repo link** into that project (ADR-0009),
/// overriding the call's `project`; a bare key uses `project`. Owned parts, so a
/// query closure can capture them.
#[cfg(feature = "serve")]
fn qualified_or(key: &str, project: Option<&str>) -> (Option<String>, String) {
    match rto_graph::parse_qualified(key) {
        Some((p, bare)) => (Some(p.to_owned()), bare.to_owned()),
        None => (project.map(str::to_owned), key.to_owned()),
    }
}

/// A [`rto_serve::ToolRegistry`] backing the served model with Roteiro's graph
/// query tools (ADR-0006), over a [`rto_graph::Workspace`] of one or more
/// projects (ADR-0008). When several projects are hosted, every tool takes a
/// `project` selector and a `list_projects` tool is offered; a single-project
/// workspace behaves exactly as before (no `project` needed).
#[cfg(feature = "serve")]
struct GraphToolRegistry {
    workspace: std::sync::Arc<rto_graph::Workspace>,
}

#[cfg(feature = "serve")]
impl GraphToolRegistry {
    fn new(workspace: std::sync::Arc<rto_graph::Workspace>) -> Self {
        Self { workspace }
    }

    /// Resolve `project` (if hosting several) and run `query` against its store,
    /// serialising the result to JSON. Flattens the workspace/store/serialise
    /// error layers into the registry's `String` error.
    fn run<T: serde::Serialize>(
        &self,
        project: Option<&str>,
        query: impl FnOnce(&rto_graph::Store) -> Result<T, rto_graph::StoreError>,
    ) -> Result<String, String> {
        let result = self
            .workspace
            .with_store(project, query)
            .map_err(|e| e.to_string())?;
        let value = result.map_err(|e| e.to_string())?;
        serde_json::to_string(&value).map_err(|e| e.to_string())
    }
}

#[cfg(feature = "serve")]
impl rto_serve::ToolRegistry for GraphToolRegistry {
    fn tools(&self) -> Vec<rto_serve::ToolDef> {
        use serde_json::json;
        // `project` is an optional selector on every tool, and `list_projects` is
        // always offered — matching the MCP surface (whose schema the rmcp macro
        // generates statically, so it can't hide them). Uniform beats an
        // asymmetric surface; a single-project server resolves the sole project
        // for a bare call, and `list_projects` simply returns that one.
        let with_project = |mut props: serde_json::Value| {
            let obj = props.as_object_mut().expect("object schema");
            obj.insert(
                "project".to_owned(),
                json!({
                    "type": "string",
                    "description": "Optional: which hosted project to query (see \
                                    `list_projects`); omit if the server hosts one.",
                }),
            );
            props
        };

        let mut tools = vec![
            rto_serve::ToolDef {
                name: "explain".to_owned(),
                description: "Explain a graph node by key (its record and immediate \
                              neighbours), e.g. `fn:foo` or `file:src/main.rs`. A key may be \
                              project-qualified (`<project>::<key>`) to follow a cross-repo \
                              link into another hosted project (see `list_projects`)."
                    .to_owned(),
                parameters: json!({
                    "type": "object",
                    "properties": with_project(json!({ "key": { "type": "string" } })),
                    "required": ["key"],
                }),
            },
            rto_serve::ToolDef {
                name: "search".to_owned(),
                description: "Search graph nodes by text — names, keys, paths, and captured \
                              content (doc comments, README/ADR/blueprint prose). Returns the \
                              top matches with keys; curated ADRs/blueprints and READMEs rank \
                              first, so this is the entry point for \"what is X / why\" questions. \
                              Then call `explain` on a returned key for detail."
                    .to_owned(),
                parameters: json!({
                    "type": "object",
                    "properties": with_project(json!({
                        "query": { "type": "string" },
                        "limit": { "type": "integer", "minimum": 1, "maximum": 25 },
                    })),
                    "required": ["query"],
                }),
            },
            rto_serve::ToolDef {
                name: "path".to_owned(),
                description: "Find a shortest path between two node keys. A path lives \
                              within one project; a project-qualified `from` \
                              (`<project>::<key>`) selects it (see `list_projects`)."
                    .to_owned(),
                parameters: json!({
                    "type": "object",
                    "properties": with_project(json!({
                        "from": { "type": "string" },
                        "to": { "type": "string" },
                    })),
                    "required": ["from", "to"],
                }),
            },
            rto_serve::ToolDef {
                name: "debt".to_owned(),
                description: "List intent-debt markers (todo/fixme/hack/stub/deferred), \
                              optionally filtered by category."
                    .to_owned(),
                parameters: json!({
                    "type": "object",
                    "properties": with_project(json!({
                        "categories": { "type": "array", "items": { "type": "string" } },
                    })),
                }),
            },
        ];
        tools.push(rto_serve::ToolDef {
            name: "list_projects".to_owned(),
            description: "List the projects this server hosts (often just one). Pass one as \
                          `project` to the other tools to query it (ADR-0008)."
                .to_owned(),
            parameters: json!({ "type": "object", "properties": {} }),
        });
        tools
    }

    fn projects(&self) -> Vec<String> {
        self.workspace.names()
    }

    fn call(&self, name: &str, args: &serde_json::Value) -> Result<String, String> {
        let str_arg = |k: &str| args.get(k).and_then(serde_json::Value::as_str);
        let project = str_arg("project");
        match name {
            "list_projects" => serde_json::to_string(&serde_json::json!({
                "projects": self.workspace.names(),
            }))
            .map_err(|e| e.to_string()),
            "explain" => {
                let key = str_arg("key").ok_or("`explain` needs a string `key`")?;
                // A project-qualified key (`<project>::<key>`) follows a cross-repo
                // link into that project, overriding the `project` argument (ADR-0009).
                let (proj, bare) = qualified_or(key, project);
                self.run(proj.as_deref(), move |store| {
                    rto_graph::explain(store, &bare)
                })
            }
            "search" => {
                let query = str_arg("query")
                    .ok_or("`search` needs a string `query`")?
                    .to_owned();
                // `limit` is model-controlled: clamp to 1..=25 (results are
                // truncated before feed-back anyway) so a huge value can't
                // waste work; the schema advertises the same bound.
                let limit = args
                    .get("limit")
                    .and_then(serde_json::Value::as_u64)
                    .and_then(|n| usize::try_from(n).ok())
                    .unwrap_or(10)
                    .clamp(1, 25);
                self.run(project, |store| rto_graph::search(store, &query, limit))
            }
            "path" => {
                let from = str_arg("from").ok_or("`path` needs a string `from`")?;
                let to = str_arg("to").ok_or("`path` needs a string `to`")?;
                // A path lives within one graph; a qualified `from` selects the
                // project, and a qualifier on either endpoint is stripped to a
                // bare, in-store key (ADR-0009).
                let (proj, from_bare) = qualified_or(from, project);
                let to_bare = rto_graph::parse_qualified(to)
                    .map_or_else(|| to.to_owned(), |(_, b)| b.to_owned());
                self.run(proj.as_deref(), move |store| {
                    rto_graph::path(store, &from_bare, &to_bare)
                })
            }
            "debt" => {
                let categories: Vec<String> = args
                    .get("categories")
                    .and_then(serde_json::Value::as_array)
                    .map(|a| {
                        a.iter()
                            .filter_map(|x| x.as_str().map(str::to_owned))
                            .collect()
                    })
                    .unwrap_or_default();
                self.run(project, |store| rto_graph::debt(store, &categories, &[]))
            }
            other => Err(format!("unknown tool `{other}`")),
        }
    }
}

/// The model endpoint is unavailable without the `serve` feature.
#[cfg(all(not(feature = "serve"), feature = "mcp"))]
fn serve_models_endpoint(
    _cfg: &config::Config,
    _set: std::sync::Arc<rto_graph::WorkspaceSet>,
    _flat: std::sync::Arc<rto_graph::Workspace>,
    _workspace_name: Option<&str>,
    _opts: &ServeOptions,
) -> anyhow::Result<()> {
    anyhow::bail!(
        "`serve --models` needs the `serve` feature (build with `--features serve`, \
         which pulls the llama.cpp engine)"
    )
}

/// Render a build-output of the graph: the docs site or an Obsidian vault.
fn run_render(
    ingest: rto_graph::IngestConfig,
    target: &str,
    out: Option<String>,
) -> anyhow::Result<()> {
    match rto_render::Target::parse(target) {
        Some(rto_render::Target::DocsSite) => render_docs(out),
        Some(rto_render::Target::ObsidianVault) => render_obsidian(ingest, out),
        None => anyhow::bail!("unknown render target `{target}` (expected: docs | obsidian)"),
    }
}

/// Render the documentation site: copy static assets, then render each ADR and
/// the ADR index into `<out>` (default `website/dist`).
fn render_docs(out: Option<String>) -> anyhow::Result<()> {
    let cwd = std::env::current_dir()?;
    let repo = rto_graph::Repo::discover(&cwd)?;
    let root = repo
        .workdir()
        .ok_or_else(|| anyhow::anyhow!("cannot render docs in a bare repository"))?;
    let out = out.map_or_else(|| root.join("website/dist"), std::path::PathBuf::from);

    if out.exists() {
        std::fs::remove_dir_all(&out)?;
    }
    std::fs::create_dir_all(out.join("adr"))?;
    copy_dir(&root.join("website/public"), &out)?;

    // Render each ADR (skip the directory README), in a deterministic order.
    let adr_dir = root.join("docs/adr");
    let mut files: Vec<_> = std::fs::read_dir(&adr_dir)?
        .filter_map(Result::ok)
        .map(|e| e.path())
        .filter(|p| p.extension().and_then(|e| e.to_str()) == Some("md"))
        .filter(|p| p.file_name().and_then(|n| n.to_str()) != Some("README.md"))
        .collect();
    files.sort();

    let mut entries = Vec::new();
    for path in &files {
        let stem = path.file_stem().and_then(|s| s.to_str()).unwrap_or("adr");
        let md = std::fs::read_to_string(path)?;
        let rendered = rto_render::render_adr(&md, stem);
        std::fs::write(out.join("adr").join(format!("{stem}.html")), &rendered.html)?;
        entries.push(rto_render::IndexEntry {
            href: format!("{stem}.html"),
            title: rendered.title,
        });
    }

    // Render lifetime docs (the Build Plan and the house-style blueprints) as
    // first-class root-level pages, and list them above the ADRs on the index.
    // Their `[[docs/adr/…]]` links resolve into the `adr/` subdirectory (the
    // `render_doc` prefix), which is correct for a root-level page.
    let mut lifetime = Vec::new();
    let build_plan = root.join("docs/BUILD_PLAN.md");
    if build_plan.is_file() {
        let md = std::fs::read_to_string(&build_plan)?;
        let rendered = rto_render::render_doc(&md, "Build Plan");
        std::fs::write(out.join("build-plan.html"), &rendered.html)?;
        lifetime.push(rto_render::IndexEntry {
            // The index lives under adr/, so link up one level.
            href: "../build-plan.html".to_owned(),
            title: rendered.title,
        });
    }
    // Blueprints live under docs/blueprint(s)/ (ADR-0004); the overall project
    // blueprint is one. Render each to a root-level page like the Build Plan.
    for dir in ["docs/blueprint", "docs/blueprints"] {
        let bp_dir = root.join(dir);
        if !bp_dir.is_dir() {
            continue;
        }
        let mut bps: Vec<_> = std::fs::read_dir(&bp_dir)?
            .filter_map(Result::ok)
            .map(|e| e.path())
            .filter(|p| p.extension().and_then(|e| e.to_str()) == Some("md"))
            .filter(|p| p.file_name().and_then(|n| n.to_str()) != Some("README.md"))
            .collect();
        bps.sort();
        for path in &bps {
            let stem = path
                .file_stem()
                .and_then(|s| s.to_str())
                .unwrap_or("blueprint");
            let md = std::fs::read_to_string(path)?;
            let rendered = rto_render::render_doc(&md, stem);
            std::fs::write(out.join(format!("{stem}.html")), &rendered.html)?;
            lifetime.push(rto_render::IndexEntry {
                href: format!("../{stem}.html"),
                title: rendered.title,
            });
        }
    }

    std::fs::write(
        out.join("adr").join("index.html"),
        rto_render::render_adr_index(&lifetime, &entries),
    )?;

    println!(
        "rendered docs → {} ({} ADR page(s), {} lifetime doc(s))",
        out.display(),
        entries.len(),
        lifetime.len(),
    );
    Ok(())
}

/// Render an Obsidian vault: one linked markdown note per graph node in `<out>`
/// (default `vault`).
fn render_obsidian(ingest: rto_graph::IngestConfig, out: Option<String>) -> anyhow::Result<()> {
    let (repo, mut store, cache) = open_graph()?;
    build_graph(&repo, &mut store, &cache, ingest, GraphSource::Committed)?;
    let out = out.map_or_else(
        || std::path::PathBuf::from("vault"),
        std::path::PathBuf::from,
    );
    if out.exists() {
        std::fs::remove_dir_all(&out)?;
    }
    std::fs::create_dir_all(&out)?;

    // A web "blob" base for clickable Source links, from the origin remote + the
    // rendered commit (an absolute URL, so it works in the downloaded vault too).
    // `None` when there is no mappable remote — notes then omit the link.
    let commit = repo.head_commit_id().ok();
    let remote = repo.origin_url();
    let source_base = match (remote.as_deref(), commit.as_deref()) {
        (Some(r), Some(c)) => source_blob_base(r, c),
        _ => None,
    };

    let mut count = 0usize;
    for key in store.all_keys()? {
        if let Some(ex) = rto_graph::explain(&store, &key)? {
            let note = rto_render::render_note(&ex, source_base.as_deref());
            std::fs::write(out.join(&note.filename), &note.content)?;
            count += 1;
        }
    }

    // The overview note: what was scanned, structure, provenance, ADRs, debt.
    let repo_url = remote.as_deref().and_then(repo_web_root);
    let home = rto_render::render_home(&vault_summary(&repo, &store, repo_url, commit)?);
    std::fs::write(out.join(&home.filename), &home.content)?;

    println!(
        "rendered obsidian vault → {} ({count} note(s) + {})",
        out.display(),
        rto_render::HOME_NOTE
    );
    Ok(())
}

/// Aggregate the store into the figures the vault's `_Home` overview shows.
fn vault_summary(
    repo: &rto_graph::Repo,
    store: &rto_graph::Store,
    repo_url: Option<String>,
    commit: Option<String>,
) -> anyhow::Result<rto_render::VaultSummary> {
    use rto_graph::{NodeKind, Provenance};

    let project = repo
        .workdir()
        .and_then(|p| p.file_name())
        .and_then(|n| n.to_str())
        .unwrap_or("this project")
        .to_owned();

    // Node counts by kind, most-frequent first (ties broken by kind for stability).
    let mut by_kind: std::collections::BTreeMap<String, usize> = std::collections::BTreeMap::new();
    for node in store.all_nodes()? {
        *by_kind.entry(node.kind.as_str().to_owned()).or_default() += 1;
    }
    let mut node_counts: Vec<(String, usize)> = by_kind.into_iter().collect();
    node_counts.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));

    // Edge counts per provenance (only non-zero classes). Store errors propagate
    // rather than silently reporting a zero count.
    let mut edge_provenance = Vec::new();
    for p in [
        Provenance::Derived,
        Provenance::Authored,
        Provenance::Inferred,
    ] {
        let n = store.edges_by_provenance(p)?.len();
        if n > 0 {
            edge_provenance.push((p.as_str().to_owned(), n));
        }
    }

    // ADRs with their lifecycle status.
    let adrs = store
        .nodes_by_kind(&NodeKind::Adr)?
        .into_iter()
        .map(|n| rto_render::AdrEntry {
            key: n.key,
            name: n.name,
            status: n
                .meta
                .get("status")
                .and_then(|v| v.as_str())
                .map(ToOwned::to_owned),
        })
        .collect();

    let debt = rto_graph::debt(store, &[], &[])?
        .by_category
        .into_iter()
        .collect();

    Ok(rto_render::VaultSummary {
        project,
        total_nodes: usize::try_from(store.node_count()?)?,
        total_edges: usize::try_from(store.edge_count()?)?,
        node_counts,
        edge_provenance,
        adrs,
        debt,
        repo_url,
        commit,
    })
}

/// Web root for a git remote URL (`https://<host>/<owner>/<repo>`), or `None` if
/// it isn't a URL shape we can map. Handles `git@host:owner/repo(.git)`,
/// `ssh://[user@]host/owner/repo(.git)`, and `http(s)://[user@]host/owner/repo(.git)`.
fn repo_web_root(remote: &str) -> Option<String> {
    let s = remote.trim();
    // Normalise the remote's various spellings to `host/owner/repo…`.
    let hostpath = if let Some(rest) = s.strip_prefix("git@") {
        // `github.com:owner/repo` → `github.com/owner/repo`
        rest.replacen(':', "/", 1)
    } else {
        let rest = s
            .strip_prefix("ssh://")
            .or_else(|| s.strip_prefix("https://"))
            .or_else(|| s.strip_prefix("http://"))?;
        // Strip any `user@` credentials prefix.
        rest.rsplit_once('@').map_or(rest, |(_, r)| r).to_owned()
    };
    let hostpath = hostpath
        .strip_suffix(".git")
        .unwrap_or(&hostpath)
        .trim_end_matches('/');
    // Require at least `host/segment` so a bare host doesn't produce a broken link.
    if hostpath.split('/').filter(|s| !s.is_empty()).count() < 2 {
        return None;
    }
    Some(format!("https://{hostpath}"))
}

/// Web "blob" base for a file at `commit` on the `remote`'s host — e.g.
/// `https://github.com/owner/repo/blob/<commit>` — so `<base>/<path>` links to the
/// exact file. GitLab uses the `/-/blob/` infix; other hosts (GitHub, Gitea,
/// Codeberg, …) use `/blob/`. `None` for an unmappable remote.
fn source_blob_base(remote: &str, commit: &str) -> Option<String> {
    let root = repo_web_root(remote)?;
    let infix = if root.contains("gitlab") {
        "/-/blob/"
    } else {
        "/blob/"
    };
    Some(format!("{root}{infix}{commit}"))
}

/// Recursively copy the contents of `src` into `dst`.
fn copy_dir(src: &std::path::Path, dst: &std::path::Path) -> std::io::Result<()> {
    std::fs::create_dir_all(dst)?;
    for entry in std::fs::read_dir(src)? {
        let entry = entry?;
        let from = entry.path();
        let to = dst.join(entry.file_name());
        if entry.file_type()?.is_dir() {
            copy_dir(&from, &to)?;
        } else {
            std::fs::copy(&from, &to)?;
        }
    }
    Ok(())
}

#[cfg(test)]
mod url_tests {
    use super::{repo_web_root, source_blob_base};

    #[test]
    fn repo_web_root_maps_common_remote_forms() {
        let want = Some("https://github.com/OffeneDatenmodellierung/Roteiro".to_owned());
        for remote in [
            "git@github.com:OffeneDatenmodellierung/Roteiro.git",
            "https://github.com/OffeneDatenmodellierung/Roteiro.git",
            "https://github.com/OffeneDatenmodellierung/Roteiro",
            "ssh://git@github.com/OffeneDatenmodellierung/Roteiro.git",
            "https://user:tok@github.com/OffeneDatenmodellierung/Roteiro.git",
        ] {
            assert_eq!(repo_web_root(remote), want, "{remote}");
        }
        // Unmappable / degenerate remotes yield no link rather than a broken one.
        assert_eq!(repo_web_root("file:///tmp/x.git"), None);
        assert_eq!(repo_web_root("git@github.com:"), None, "no owner/repo");
    }

    #[test]
    fn source_blob_base_uses_host_specific_infix() {
        assert_eq!(
            source_blob_base("git@github.com:o/r.git", "abc123"),
            Some("https://github.com/o/r/blob/abc123".to_owned())
        );
        // GitLab's blob path is `/-/blob/`.
        assert_eq!(
            source_blob_base("git@gitlab.com:o/r.git", "abc123"),
            Some("https://gitlab.com/o/r/-/blob/abc123".to_owned())
        );
    }
}

// The full explorer + Ask wiring a `serve --models` build stands up: the UI, the
// `/v1/graph/capabilities` signal (ask:true + served models), and the graph-tools
// chat route — all mounted by `mount_explorer_surfaces` over the one engine.
// Gated on `serve,explorer` and driven with a mock engine (no llama.cpp, no
// model download, no real inference — we prove the routing, not generation).
#[cfg(all(test, feature = "serve", feature = "explorer"))]
mod serve_explorer_wiring {
    use super::{GraphToolRegistry, mount_explorer_surfaces};
    use axum::body::Body;
    use axum::http::{Request, StatusCode};
    use http_body_util::BodyExt as _;
    use tower::ServiceExt as _; // for `oneshot`

    /// A stand-in [`rto_serve::Engine`] that serves one model and echoes a fixed
    /// reply — enough to exercise the HTTP wiring without building llama.cpp.
    struct MockEngine;

    impl rto_serve::Engine for MockEngine {
        fn models(&self) -> Vec<rto_serve::ModelInfo> {
            vec![rto_serve::ModelInfo {
                id: "qwen3-0.6b".to_owned(),
            }]
        }

        fn chat_stream(
            &self,
            _req: &rto_serve::ChatRequest,
            on_token: &mut dyn FnMut(&str),
        ) -> Result<rto_serve::CompletionStats, rto_serve::EngineError> {
            on_token("a grounded answer");
            Ok(rto_serve::CompletionStats {
                prompt_tokens: 1,
                completion_tokens: 3,
                finish_reason: rto_serve::FinishReason::Stop,
            })
        }
    }

    /// The merged router exactly as `serve_v1_tail` assembles it — parameterised
    /// over the `set` (the workspace-aware graph API) and `flat` (the model tool
    /// registry over every hosted project). `/v1` model app (graph tools on) +
    /// `/v1/graph/*` (capabilities ask:true) + the static web app.
    fn serve_router_for(
        set: std::sync::Arc<rto_graph::WorkspaceSet>,
        flat: std::sync::Arc<rto_graph::Workspace>,
        default: Option<String>,
    ) -> axum::Router {
        let engine: std::sync::Arc<dyn rto_serve::Engine> = std::sync::Arc::new(MockEngine);
        let tools: std::sync::Arc<dyn rto_serve::ToolRegistry> =
            std::sync::Arc::new(GraphToolRegistry::new(flat));
        let model_ids = engine.models().into_iter().map(|m| m.id).collect();
        let base = rto_serve::app_with_tools(engine, tools);
        mount_explorer_surfaces(base, set, default, model_ids)
    }

    /// The legacy single-repo `serve` wiring: one `repo` workspace folded into a
    /// one-entry `default` set (as `run_serve`'s single-repo fallback does), sharing
    /// the one store handle.
    fn serve_router() -> axum::Router {
        let store = rto_graph::Store::open_in_memory().expect("in-memory store");
        let flat = std::sync::Arc::new(rto_graph::Workspace::single("repo", store));
        let set = std::sync::Arc::new(rto_graph::WorkspaceSet::from_single(
            "default",
            flat.clone(),
            flat.is_multi(),
        ));
        serve_router_for(set, flat, Some("default".to_owned()))
    }

    /// A multi-workspace `serve` wiring built entirely from in-memory stores — no
    /// git repo, no cwd, no `open_graph()`. Two configured workspaces (`api` linked,
    /// `docs` standalone), each with its own project store; `flat` unions every
    /// project so the model tools reach any of them. Proves `serve` hosts the full
    /// configured set from ANY directory.
    fn multi_serve_router() -> axum::Router {
        let ws_api =
            rto_graph::Workspace::single("api", rto_graph::Store::open_in_memory().expect("store"));
        let ws_docs = rto_graph::Workspace::single(
            "docs",
            rto_graph::Store::open_in_memory().expect("store"),
        );
        let set = std::sync::Arc::new(rto_graph::WorkspaceSet::from_workspaces([
            ("api".to_owned(), ws_api, true),
            ("docs".to_owned(), ws_docs, false),
        ]));
        // The flattened model workspace over every hosted project.
        let flat = std::sync::Arc::new(rto_graph::Workspace::from_stores([
            ("api", rto_graph::Store::open_in_memory().expect("store")),
            ("docs", rto_graph::Store::open_in_memory().expect("store")),
        ]));
        // Multi-workspace ⇒ no implicit default flat workspace (a client addresses
        // one via `/v1/graph/workspaces/{ws}/…`).
        serve_router_for(set, flat, None)
    }

    async fn get(uri: &str) -> (StatusCode, String, String) {
        get_on(serve_router(), uri).await
    }

    async fn get_on(router: axum::Router, uri: &str) -> (StatusCode, String, String) {
        let resp = router
            .oneshot(Request::builder().uri(uri).body(Body::empty()).unwrap())
            .await
            .unwrap();
        let status = resp.status();
        let ct = resp
            .headers()
            .get(axum::http::header::CONTENT_TYPE)
            .and_then(|v| v.to_str().ok())
            .unwrap_or_default()
            .to_owned();
        let body = resp.into_body().collect().await.unwrap().to_bytes();
        (status, ct, String::from_utf8_lossy(&body).into_owned())
    }

    #[tokio::test]
    async fn capabilities_report_ask_on_and_the_served_model() {
        let (status, ct, body) = get("/v1/graph/capabilities").await;
        assert_eq!(status, StatusCode::OK);
        assert!(ct.contains("application/json"), "content-type was {ct}");
        let json: serde_json::Value = serde_json::from_str(&body).unwrap();
        assert_eq!(json["ask"], true, "the serve build enables Ask");
        assert_eq!(
            json["models"],
            serde_json::json!(["qwen3-0.6b"]),
            "capabilities name the served model"
        );
    }

    #[tokio::test]
    async fn the_explorer_ui_is_served_beside_the_model_endpoint() {
        let (status, ct, body) = get("/").await;
        assert_eq!(status, StatusCode::OK);
        assert!(ct.starts_with("text/html"), "content-type was {ct}");
        assert!(body.contains("<!doctype html>"));
        assert!(body.contains("/app.js"), "the shell loads our app");
    }

    #[tokio::test]
    async fn the_graph_grounded_chat_route_is_mounted() {
        // Prove the project-scoped chat route the Ask tab posts to exists on this
        // merged router: a well-formed request reaches the (mock) engine and gets
        // a 200 completion — not a 404 that would mean the route is missing.
        let body = serde_json::json!({
            "model": "qwen3-0.6b",
            "messages": [{ "role": "user", "content": "what is this repo?" }],
            "stream": false,
        });
        let resp = serve_router()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/v1/repo/chat/completions")
                    .header("content-type", "application/json")
                    .body(Body::from(serde_json::to_vec(&body).unwrap()))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(
            resp.status(),
            StatusCode::OK,
            "the project-scoped chat route must be mounted and reachable"
        );
        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
        let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(
            json["choices"][0]["message"]["content"], "a grounded answer",
            "the mounted route returns the engine's completion"
        );
    }

    // -- multi-workspace serve (no git cwd, no `open_graph()`) --------------

    #[tokio::test]
    async fn serve_hosts_all_configured_workspaces_with_no_cwd_repo() {
        // The whole point of the change: a `serve --models` process built from
        // `[[workspaces]]`/`[standalone]` config hosts EVERY configured workspace
        // and lists them at `/v1/graph/workspaces` — with no repo discovered from
        // the current directory and no `open_graph()` on the cwd (this router is
        // assembled purely from in-memory stores).
        let (status, ct, body) = get_on(multi_serve_router(), "/v1/graph/workspaces").await;
        assert_eq!(status, StatusCode::OK);
        assert!(ct.contains("application/json"), "content-type was {ct}");
        let arr: serde_json::Value = serde_json::from_str(&body).unwrap();
        let arr = arr.as_array().expect("workspaces array");
        assert_eq!(arr.len(), 2, "both configured workspaces are hosted");
        // Stable (name) order: `api` (linked) then `docs` (standalone).
        assert_eq!(arr[0]["name"], "api");
        assert_eq!(arr[0]["linked"], true);
        assert_eq!(arr[1]["name"], "docs");
        assert_eq!(arr[1]["linked"], false, "a standalone repo is unlinked");
    }

    #[tokio::test]
    async fn nested_graph_routes_reach_each_configured_workspace() {
        // Every hosted workspace is reachable under its explicit path segment, so a
        // multi-workspace serve is not limited to a single default workspace: each
        // workspace's `/projects` route resolves within that named workspace.
        for (ws, project) in [("api", "api"), ("docs", "docs")] {
            let (status, _, body) = get_on(
                multi_serve_router(),
                &format!("/v1/graph/workspaces/{ws}/projects"),
            )
            .await;
            assert_eq!(
                status,
                StatusCode::OK,
                "workspace `{ws}` must be reachable via its nested route"
            );
            assert!(
                body.contains(project),
                "workspace `{ws}` hosts project `{project}` (was: {body})"
            );
        }
    }

    #[tokio::test]
    async fn the_model_tools_span_every_hosted_project() {
        // The graph-grounded chat route the served model uses must resolve a
        // project in ANY configured workspace — the flattened tool workspace unions
        // them all. Posting to `/v1/{project}/chat/completions` for a project drawn
        // from each workspace reaches the (mock) engine (200), not a 404.
        for project in ["api", "docs"] {
            let body = serde_json::json!({
                "model": "qwen3-0.6b",
                "messages": [{ "role": "user", "content": "what is this project?" }],
                "stream": false,
            });
            let resp = multi_serve_router()
                .oneshot(
                    Request::builder()
                        .method("POST")
                        .uri(format!("/v1/{project}/chat/completions"))
                        .header("content-type", "application/json")
                        .body(Body::from(serde_json::to_vec(&body).unwrap()))
                        .unwrap(),
                )
                .await
                .unwrap();
            assert_eq!(
                resp.status(),
                StatusCode::OK,
                "the project-scoped chat route must resolve `{project}` across the set"
            );
        }
    }

    #[test]
    fn unknown_workspace_name_fails_fast_listing_the_known_ones() {
        // `run_serve` validates `--workspace-name` up front via `set.select`: an
        // unknown name is a fast error naming the known workspaces, never a booted
        // server whose flat routes 404 on every request.
        let ws_api =
            rto_graph::Workspace::single("api", rto_graph::Store::open_in_memory().unwrap());
        let ws_docs =
            rto_graph::Workspace::single("docs", rto_graph::Store::open_in_memory().unwrap());
        let set = rto_graph::WorkspaceSet::from_workspaces([
            ("api".to_owned(), ws_api, true),
            ("docs".to_owned(), ws_docs, false),
        ]);
        let err = set.select(Some("nope")).err().expect("unknown must error");
        let msg = err.to_string();
        assert!(msg.contains("no workspace named `nope`"), "was: {msg}");
        assert!(msg.contains("api") && msg.contains("docs"), "was: {msg}");
        // A valid name (and the legacy `default` single-repo fold) still resolve.
        assert!(set.select(Some("api")).is_ok());
    }

    #[test]
    fn legacy_single_repo_folds_to_one_default_workspace() {
        // The single-repo fallback path: one pre-built store, wrapped as the sole
        // `default` workspace of a one-entry set (sharing the handle), exactly as
        // `run_serve` does when no `[[workspaces]]`/`[standalone]` is configured.
        let flat = std::sync::Arc::new(rto_graph::Workspace::single(
            "repo",
            rto_graph::Store::open_in_memory().unwrap(),
        ));
        let set = rto_graph::WorkspaceSet::from_single("default", flat.clone(), flat.is_multi());
        assert_eq!(set.names(), vec!["default".to_owned()]);
        // A bare selection resolves the sole workspace, and it hosts the one repo.
        assert_eq!(set.select(None).unwrap().names(), vec!["repo".to_owned()]);
    }
}

/// The `serve`/`mcp` path that flattens every configured workspace's repos into the
/// one model workspace (`resolved_repo_paths`), independent of the current
/// directory.
#[cfg(all(test, any(feature = "serve", feature = "mcp")))]
mod serve_workspace_paths_tests {
    use super::{fold_cli_roots, resolved_repo_paths};
    use rto_graph::ResolvedWorkspace;

    #[test]
    fn cli_roots_fold_into_a_default_workspace() {
        // With no configured groups, `--workspace <ROOT>` becomes a new linked
        // `default` workspace — so the CLI roots are a first-class named workspace
        // (surfaced by the graph API), not merely merged into the flat model view.
        let folded = fold_cli_roots(Vec::new(), &["/a".to_owned(), "/b".to_owned()]);
        assert_eq!(folded.len(), 1);
        assert_eq!(folded[0].name, "default");
        assert!(folded[0].linked);
        assert_eq!(folded[0].roots, vec!["/a".to_owned(), "/b".to_owned()]);

        // An existing `default` (the legacy `[workspace]`) is EXTENDED, not
        // duplicated, so CLI roots union with the configured ones.
        let existing = vec![ResolvedWorkspace {
            name: "default".to_owned(),
            roots: vec!["/cfg".to_owned()],
            repos: vec!["/cfg/extra".to_owned()],
            linked: true,
        }];
        let folded = fold_cli_roots(existing, &["/cli".to_owned()]);
        assert_eq!(folded.len(), 1, "no duplicate `default` group");
        assert_eq!(folded[0].roots, vec!["/cfg".to_owned(), "/cli".to_owned()]);
        assert_eq!(
            folded[0].repos,
            vec!["/cfg/extra".to_owned()],
            "repos untouched"
        );

        // No CLI roots ⇒ the groups are returned unchanged (named groups survive).
        let named = vec![ResolvedWorkspace {
            name: "api".to_owned(),
            roots: vec!["/api".to_owned()],
            repos: Vec::new(),
            linked: true,
        }];
        let folded = fold_cli_roots(named.clone(), &[]);
        assert_eq!(folded, named);
    }

    #[test]
    fn unions_every_group_and_cli_root_deduped_by_path() {
        // Two synthetic repos under a scanned root, plus an explicit repo — spread
        // across a linked group and a standalone singleton, with one repo named in
        // BOTH a group root and an explicit repo to prove de-duplication.
        let base = std::env::temp_dir().join(format!("rto-srv-paths-{}", std::process::id()));
        std::fs::remove_dir_all(&base).ok();
        for sub in ["scan/alpha/.git", "scan/beta/.git", "solo/gamma/.git"] {
            std::fs::create_dir_all(base.join(sub)).expect("mkrepo");
        }
        let scan = base.join("scan").to_string_lossy().into_owned();
        let alpha = base.join("scan/alpha").to_string_lossy().into_owned();
        let gamma_root = base.join("solo").to_string_lossy().into_owned();

        let resolved = vec![
            ResolvedWorkspace {
                name: "linked".to_owned(),
                roots: vec![scan.clone()],
                // `alpha` is also discovered under `scan` → must appear once.
                repos: vec![alpha.clone()],
                linked: true,
            },
            ResolvedWorkspace {
                name: "gamma".to_owned(),
                roots: Vec::new(),
                repos: vec![base.join("solo/gamma").to_string_lossy().into_owned()],
                linked: false,
            },
        ];
        // A `--workspace <ROOT>` that re-scans the same `solo` dir must not double it.
        let paths = resolved_repo_paths(&resolved, &[gamma_root]).expect("union");

        let mut got: Vec<_> = paths
            .iter()
            .map(|p| p.file_name().unwrap().to_string_lossy().into_owned())
            .collect();
        got.sort();
        assert_eq!(
            got,
            vec!["alpha".to_owned(), "beta".to_owned(), "gamma".to_owned()],
            "each repo is hosted exactly once across all groups + cli roots"
        );

        std::fs::remove_dir_all(&base).ok();
    }
}

#[cfg(test)]
mod workspace_tests {
    use rto_graph::discover_repos_under;

    #[test]
    fn discovers_the_root_and_immediate_repo_subdirs_only() {
        // A workspace root holding two repo checkouts and one plain directory.
        let base = std::env::temp_dir().join(format!("rto-disc-{}", std::process::id()));
        std::fs::remove_dir_all(&base).ok();
        for sub in ["alpha/.git", "beta/.git", "notarepo", "beta/deep/.git"] {
            std::fs::create_dir_all(base.join(sub)).expect("mkdir");
        }
        let found = discover_repos_under(&base).expect("scan");
        // The root itself is not a repo here; `alpha` and `beta` are, in sorted
        // order; `notarepo` is skipped and the scan is shallow (no `beta/deep`).
        assert_eq!(found, vec![base.join("alpha"), base.join("beta")]);

        // When the root itself is a repo, it is included first.
        std::fs::create_dir_all(base.join(".git")).expect("mkdir root .git");
        let found = discover_repos_under(&base).expect("scan");
        assert_eq!(
            found,
            vec![base.clone(), base.join("alpha"), base.join("beta")]
        );

        std::fs::remove_dir_all(&base).ok();
    }
}