mahbot 0.11.1

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

pub(crate) mod grammar;
pub(crate) mod instance;

use std::fmt::Write as _;
use std::sync::OnceLock;

use crate::db::ipc::{CallAttempt, CallOutcome, CallRequest};
use crate::util::lock::InstanceLockState;

/// The product's top-level `--help` text: every public entry point, the command-line
/// families among them. It lives beside the registry so the tie that every entry
/// point is listed runs in the library's test lane
/// (`every_entry_point_resolves_and_is_listed_in_the_top_level_usage`).
pub const TOP_LEVEL_USAGE: &str = "\
mahbot — autonomous agentic engineering system with a GUI dashboard daemon

Usage:
  mahbot                 Launch the GUI dashboard daemon
  mahbot paused          Launch the daemon with every managed workspace
                         paused (no ticket is claimed or advanced)
  mahbot audio <operation> [flags]
                         Speech on the command line: a recording into text, text
                         into a spoken WAV file
  mahbot chrome <args>   Browser automation CLI over the shared chrome core
  mahbot debug           Read-only SQL query tool against the live stores
  mahbot bench-openrouter <args>
                         Standalone OpenRouter provider benchmark
  mahbot config <operation> [flags]
                         Read and write the RUNNING product's settings, set it up
                         in one command, and manage its users, tool grants, web
                         search and custom roles; 'mahbot config reference' lists
                         every action and field
  mahbot workspace <operation> [flags]
                         Work with the RUNNING product's workspaces, their
                         tickets and board, and each workspace's own settings;
                         'mahbot workspace reference' lists every action and field
  mahbot send [flags]    Hand one message to an agent and finish — the answer
                         arrives later in your assistant's conversation, or
                         nothing does when the addressee is one-way
  mahbot document <operation> [flags]
                         Read a document with the RUNNING product's reader, or
                         produce one with its document tool
  mahbot image gen [flags]
                         Produce a picture with the RUNNING product's picture tool
  mahbot video gen [flags]
                         Produce or edit a clip with the RUNNING product's video
                         tool
  mahbot rasterize [flags]
                         Turn a file into an ordinary picture with the RUNNING
                         product's rasterizer
  mahbot photocraft <operation> [flags]
                         Edit photographs and other images with the RUNNING
                         product's PhotoCraft engine

Options:
  -h, --help             Print this help and exit
  -V, --version          Print the version and exit

Environment:
  MAHBOT_HEADLESS=1      Run the service without a window, whatever the display
                         says (a graphical host with an unusable one)";

/// The transport tag the command line's own operations are attributed to: the
/// one-way `send` reaches the history as a message the owner typed (`gui`) or
/// spoke (`voice`) does, but recorded as shell-sent. It never reaches the
/// message itself.
pub(crate) const CHANNEL: &str = "cli";

/// Whether this instance can serve a command-line operation.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum ServiceState {
    Starting,
    /// It finished starting: the whole product, so an operation may be served.
    Ready,
    /// The instance did not finish starting up: it can never serve one.
    Unavailable,
}

/// The instance's own service state, as a `watch` so a waiter wakes the moment it
/// changes. A `OnceLock` because one process is one instance and this sender
/// never drops, so a subscriber always has a live counterpart.
static SERVICE: OnceLock<tokio::sync::watch::Sender<ServiceState>> = OnceLock::new();

fn service_sender() -> &'static tokio::sync::watch::Sender<ServiceState> {
    SERVICE.get_or_init(|| tokio::sync::watch::channel(ServiceState::Starting).0)
}

pub fn mark_ready() {
    service_sender().send_replace(ServiceState::Ready);
}

pub fn mark_unavailable() {
    service_sender().send_replace(ServiceState::Unavailable);
}

/// How an operation's wait for the product ended.
pub(crate) enum ServiceGate {
    /// The whole product is up — the operation may run.
    Ready,
    /// The boot failed: operations can never be served here.
    Unavailable,
    /// The instance began shutting down: nothing ran, so the caller may retry.
    NotAccepted,
    /// Neither finished nor failed within [`SERVICE_READY_TIMEOUT`] — a wedged
    /// boot. Nothing ran, so the caller is told instead of being held forever.
    StillStarting,
}

/// How long an operation waits for the instance to finish starting before it is
/// refused: a wedged boot must not hold the caller with no answer. Once the instance
/// has taken the operation on, it is never given up on.
const SERVICE_READY_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(60);

/// Wait until this instance can serve a command-line operation.
///
/// Nothing is served before [`mark_ready`]: until then the product is not the
/// WHOLE product, and a `mahbot_config` action or a workspace registration would
/// land in a half-built instance. The caller is never simply dropped: the wait
/// resolves on `Ready`, on `Unavailable`, on
/// [`StillStarting`](ServiceGate::StillStarting) after [`SERVICE_READY_TIMEOUT`], or
/// when the shutdown token fires — where
/// [`NotAccepted`](ServiceGate::NotAccepted) carries nothing run, so the caller
/// may retry safely.
pub(crate) async fn wait_for_service() -> ServiceGate {
    let mut rx = service_sender().subscribe();
    let shutdown = crate::shutdown::shutdown_token();
    // One bound for the whole wait, not one per wake-up.
    let bound = tokio::time::sleep(SERVICE_READY_TIMEOUT);
    tokio::pin!(bound);
    loop {
        // The product has begun its exit: nothing new is taken on, whatever the
        // state says (nothing ran, so the caller may retry).
        if shutdown.is_cancelled() {
            return ServiceGate::NotAccepted;
        }
        match *rx.borrow_and_update() {
            ServiceState::Ready => return ServiceGate::Ready,
            ServiceState::Unavailable => return ServiceGate::Unavailable,
            ServiceState::Starting => {}
        }
        tokio::select! {
            changed = rx.changed() => {
                if changed.is_err() {
                    // A process-lifetime static that dropped means the process is
                    // tearing down, where nothing can be served.
                    return ServiceGate::NotAccepted;
                }
            }
            () = shutdown.cancelled() => {
                return ServiceGate::NotAccepted;
            }
            () = &mut bound => {
                return ServiceGate::StillStarting;
            }
        }
    }
}

/// The exit-code classes a command line here separates — the same numbering the
/// browser-automation command and `mahbot audio` use.
///
/// Who judges separates misuse from failure. Misuse is what a frontend settles
/// without the target: a word or flag nobody has, a flag with no value, a token
/// that is no flag, an argument that is not text — and, for a frontend that opens
/// files itself, the filesystem's verdict on the paths it was handed. Everything
/// the TARGET judges is a failed operation instead. A frontend that only CARRIES
/// the operation (this one) holds no copy of the target's rules, so it never
/// guesses a class; `mahbot audio`, which RUNS its target, may judge that target's
/// published vocabulary as misuse. Each family's help says what its classes mean.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(crate) enum Exit {
    Ok = 0,
    /// Not carried out, carried out only in part, or an outcome unknowable after
    /// the call went out (it may have happened — never the environment's class).
    Failed = 1,
    /// Nothing ran: the environment — the instance, the engine, its models, or a
    /// component the operation's input needs — could not take the operation on. The
    /// environment, not the operation.
    Environment = 2,
    /// The caller's own mistake: an invocation that cannot mean what it asks, and —
    /// for a frontend that opens the files itself — the paths it was handed.
    Usage = 3,
}

impl Exit {
    pub(crate) const fn code(self) -> i32 {
        self as i32
    }
}

/// One command-line family: the frontend onto one capability of the product, carried by
/// exactly one of its tools.
pub(crate) struct Family {
    pub(crate) word: &'static str,
    pub(crate) tool: &'static str,
    /// The protocol value this family's operation frames carry: the generation of the
    /// surface it needs. A family whose surface has not changed since a generation the
    /// channel already serves carries that generation's value and keeps working against
    /// a product one build behind; a family added since, or one whose surface gained
    /// arguments an older product would ignore, carries a newer value, so a product that
    /// does not know it refuses the call as the environment's class instead of
    /// misanswering it (see [`crate::db::ipc`]).
    pub(crate) protocol: &'static str,
    /// One line for `mahbot -h`, and the family's own help opening on it.
    pub(crate) purpose: &'static str,
    /// What follows the family's word: an operation to run, or nothing at all.
    pub(crate) surface: Surface,
}

pub(crate) enum Surface {
    /// `mahbot <word> <operation> [flags]`: one operation per sub-command, each
    /// running the family's tool — or, in one case, the product's own reader
    /// ([`DOCUMENT_READ`]).
    Operations(&'static [Operation]),
    /// The family IS its operation: `mahbot <word> [flags]`, no operation word at
    /// all, and the args carry no `action` key.
    Standalone(&'static [Flag]),
}

/// One command-line operation: the action it runs (where the tool has one) and its
/// flags. It runs the family's tool ([`Family::tool`]).
pub(crate) struct Operation {
    /// The tool's own `action` value, or `None` where the tool takes no action
    /// (the picture tool and the video tool): the operation then IS that tool.
    /// [`DOCUMENT_READ`] is the one action no tool holds.
    pub(crate) action: Option<&'static str>,
    /// One line for the family's help and the operation's own help.
    pub(crate) purpose: &'static str,
    /// The flags this operation takes, in the order its help lists them.
    pub(crate) flags: &'static [Flag],
}

/// The sub-command word of one operation, derived rather than written down so a
/// sub-command can never be spelled a way its tool or action is not: the action
/// with `_` written `-` (`fill_template` → `fill-template`), or the tool's own
/// name with the family word dropped (`image_gen` in `image` → `gen`).
fn operation_word(family: &Family, operation: &Operation) -> String {
    match operation.action {
        Some(action) => action.replace('_', "-"),
        None => family
            .tool
            .strip_prefix(family.word)
            .unwrap_or(family.tool)
            .trim_start_matches('_')
            .replace('_', "-"),
    }
}

/// The argument carrying the picture tool's generations: its flags are one
/// generation's own settings, so this command builds the single generation it
/// asks for itself — every other tool's flags ARE its arguments.
const GENERATIONS_ARG: &str = "generations";

/// Fold the picture tool's flat flags into the one generation this command asks for,
/// with the prompt left beside it and a flag left out left out of the generation
/// too, where the tool reads it as unset.
fn fold_one_generation(args: &mut serde_json::Value) {
    /// The settings one picture's generation carries — the tool schema's own
    /// entries, held to them by the tie in the tests.
    const GENERATION_SETTINGS: &[&str] = &["images", "aspect_ratio", "size"];
    let Some(map) = args.as_object_mut() else {
        return;
    };
    let mut generation = serde_json::Map::new();
    for setting in GENERATION_SETTINGS {
        if let Some(value) = map.remove(*setting) {
            generation.insert((*setting).to_string(), value);
        }
    }
    map.insert(
        GENERATIONS_ARG.to_string(),
        serde_json::Value::Array(vec![generation.into()]),
    );
}

/// Whether this family's operations produce FILES — derived from the flags the
/// registry already carries rather than stated a second time: a producing family has
/// the destination flag ([`FlagKind::Destination`]) on at least one operation, and no
/// other family carries one anywhere, which is what the registry test holds. Which
/// operation carries it is that operation's own business: the destination is the
/// FALLBACK for the place an operation writes into, so one that writes no file of its
/// own (`photocraft commands`) declares none, and so does one whose own flag
/// ([`FlagKind::Output`]) always names where its files go (`photocraft batch`) —
/// neither advertises a destination it would ignore.
#[must_use]
fn produces_files(family: &Family) -> bool {
    match family.surface {
        Surface::Operations(operations) => operations
            .iter()
            .flat_map(|operation| operation.flags)
            .any(|flag| matches!(flag.kind, FlagKind::Destination)),
        Surface::Standalone(flags) => flags
            .iter()
            .any(|flag| matches!(flag.kind, FlagKind::Destination)),
    }
}

/// The words a family answers to, as a usage line states them: the operation's
/// own sub-command word where the family's tool takes no `action`, `<operation>`
/// where an `action` picks one, `[flags]` alone where the family IS its
/// operation — derived from the registry, so no help can advertise a stale word
/// (`every_entry_point_is_listed_in_the_top_level_usage`).
#[must_use]
fn family_syntax(family: &Family) -> String {
    match family.surface {
        Surface::Standalone(_) => format!("mahbot {} [flags]", family.word),
        // A second action-less operation would derive the same word (see `operation_word`), so
        // the registry holds at most one; a family gaining a second brings its own form with it.
        Surface::Operations([operation]) if operation.action.is_none() => format!(
            "mahbot {} {} [flags]",
            family.word,
            operation_word(family, operation)
        ),
        Surface::Operations(_) => format!("mahbot {} <operation> [flags]", family.word),
    }
}

pub(crate) struct Flag {
    /// The tool's own argument name; the command-line spelling is derived from it
    /// (`ticket_id` → `--ticket-id`), so a flag can never be spelled a way the tool
    /// does not read. The exception is the destination flag
    /// ([`FlagKind::Destination`]), whose name is the command line's own.
    pub(crate) arg: &'static str,
    pub(crate) kind: FlagKind,
    /// One line for the operation's help.
    pub(crate) purpose: &'static str,
}

/// How a flag carries its value — the shape of the tool argument it fills.
///
/// Two spellings are this command line's own, read the same way by every kind
/// that carries one: `./@…` is the literal text beginning with `@` (the escape
/// exists because a text value may legitimately begin with it), and — for the
/// kinds that say so ([`Self::has_file_form`]) — `@<file>` IS what that file
/// holds. A kind whose value names a path also RESOLVES it (see [`caller_path`]):
/// a `Path` its one value, a `PathList` every entry, a `Structured` every string
/// the fields it carries name, a `Directory` its one folder — and an
/// `UncheckedPath` and an `Output` too, minus the proof that the path is there.
pub(crate) enum FlagKind {
    /// One value per occurrence: `--name bob`, read as text or — like the kinds
    /// below — taken from a FILE by writing `@<file>`.
    Value,
    /// One value per occurrence that NAMES A FILE on this machine
    /// (`--path report.pdf`), resolved before it is sent: a relative one in the
    /// directory this command was run in, and `~` against the home directory. The
    /// product has a working directory of its own, and a relative path sent on
    /// would name a different file there. It must also be there and readable —
    /// that is the caller's misuse, while a URL is left to the product.
    /// No `@<file>` form: the value already names the file.
    Path,
    /// One path per occurrence that NEED NOT BE THERE YET — a destination the
    /// operation creates (`--output new.png`), or a folder whose contents are its
    /// input. Resolved exactly as [`Path`](Self::Path) is; only the proof is
    /// absent, because a path that is not there yet is the ordinary case and
    /// whether it is usable is the tool's to judge.
    /// No `@<file>` form: the value already names the path.
    UncheckedPath,
    /// One DIRECTORY per occurrence (`--path ./proj`): resolved exactly as
    /// [`Path`](Self::Path) is, and it must be there — the folder a workspace is
    /// asked to manage is one that exists, so a typo is the caller's misuse here
    /// rather than a product-side "no such folder".
    /// No `@<file>` form: the value names the folder.
    Directory,
    /// One NUMBER per occurrence (`--duration 8`). A value that is no JSON number
    /// travels as the text it is, so the tool's own refusal — not this
    /// frontend's — is what the caller gets: whether a value is acceptable is the
    /// tool's to judge.
    Number,
    /// Repeatable, one array entry per occurrence — taken VERBATIM, so an entry
    /// that itself holds a comma is unambiguous. An EMPTY value is the EMPTY list
    /// (`--tools=`), which tools read differently from an absent key
    /// (`update_custom_role` clears the role's tools with it). An occurrence
    /// starting with `@` names a FILE holding the entries as a JSON array of
    /// strings; the `./@…` escape gives an entry that begins with `@`.
    List,
    /// [`List`](Self::List)'s file-naming form: the same array of texts, with
    /// every entry (and the file named after `@`) resolved the way
    /// [`Path`](Self::Path) resolves its one value.
    PathList,
    /// One STRUCTURED value per occurrence, for an object or an array of objects:
    /// the JSON it is written as, or `@<file>` naming a file that holds it. A
    /// value that is no JSON is sent on verbatim for the tool to judge; a file
    /// that cannot be read, or holds no JSON, is this command line's own misuse.
    ///
    /// The field names it carries are the ones a REFERENCE FILE stands under — the
    /// `image` of a block, of an edit that places one — and every string there is
    /// resolved like a [`Path`](Self::Path) value, since the product would resolve
    /// them against its own directories.
    Structured(&'static [&'static str]),
    /// A switch, for a boolean argument: the bare `--full` and `--full=true` are
    /// `true`, `--full=false` the `false` a bare switch cannot carry. Both must be
    /// spellable — an argument left out is the tool's own default, which is not
    /// `false` where the default is the provider's (a video's `--generate-audio`).
    Present,
    /// The operation's OWN output flag: one path per occurrence naming where its produced files go
    /// (`--output new.png`), resolved exactly as [`UncheckedPath`](Self::UncheckedPath) is. A call
    /// that gives it takes the place from it, so the destination ([`Destination`](Self::Destination))
    /// is only the fallback for a call that leaves it out.
    Output,
    /// The destination of the files the operation produces — the command line's
    /// OWN operand, and the single flag no tool reads: the exception the whole
    /// registry turns on (see the module docs). No `@<file>` form: it names a
    /// directory itself.
    Destination,
}

impl FlagKind {
    /// Whether this kind reads its value from the file its `@<file>` form names.
    ///
    /// The kinds whose value can be long or structured — a text, a list, a
    /// structure — have it, so a caller is never capped by the command line's own
    /// length. [`Path`](Self::Path), [`UncheckedPath`](Self::UncheckedPath),
    /// [`Output`](Self::Output) and [`Destination`](Self::Destination) do not: their
    /// value names the file (or directory) itself. [`Number`](Self::Number) and
    /// [`Present`](Self::Present) do not either: neither carries text.
    #[must_use]
    const fn has_file_form(&self) -> bool {
        matches!(
            self,
            Self::Value | Self::List | Self::PathList | Self::Structured(_)
        )
    }
}

/// The document family's `read` operation word — the `action` value the instance
/// reads as "the product's own reader"
/// ([`crate::tools::read_document::read_for_command_line`]). Deliberately no action
/// of the document tool: agents read documents through the `read` tool they have,
/// so the tool gains no action and its prompt nothing new. The registry test ties
/// every tool-backed operation to its tool's actions and pins this one separately.
pub(crate) const DOCUMENT_READ: &str = "read";

/// The command lines this file fronts: the admin Assistant's own toolset — the
/// tool each family names, and nothing else the owner holds is reachable through
/// the channel. Words are derived from here ([`family_words`],
/// [`producing_families`]), so no surface keeps a list of its own to go stale.
pub(crate) const FAMILIES: &[Family] = &[
    Family {
        word: "config",
        tool: "mahbot_config",
        // Both families whose surface this build widened carry the settings generation: a product
        // built before it knows neither the settings actions nor the arguments they carry, and
        // would answer a `set` as an unknown action — so it is refused as an unknown store
        // instead, with nothing run.
        protocol: crate::db::ipc::CALL_STORE_SETTINGS,
        purpose: "Read and write the running product's settings — provider and endpoint, models, \
                  media, web search, Telegram, audio, updates, accounts, grants, custom roles — \
                  and set it all up in one command",
        surface: Surface::Operations(&[
            Operation {
                action: Some("reference"),
                purpose: "Print every action and field of this surface, and of the workspace \
                          settings — the same text `mahbot workspace reference` prints",
                flags: &[],
            },
            Operation {
                action: Some("about"),
                purpose: "Print the product's own README — what this system is, for a machine you \
                          are new to",
                flags: &[],
            },
            Operation {
                action: Some("get"),
                purpose: "Read one setting's effective value, whole",
                flags: &[Flag {
                    arg: "setting",
                    kind: FlagKind::Value,
                    purpose: "The setting's name — `reference` lists every one; a credential \
                              answers only that it is set, with a hint",
                }],
            },
            Operation {
                action: Some("list"),
                purpose: "Summarise every setting's effective value — a long value is clipped; \
                          credentials left out",
                flags: &[],
            },
            Operation {
                action: Some("set"),
                purpose: "Change one setting; the new value is in use at once, with no restart",
                flags: &[
                    Flag {
                        arg: "setting",
                        kind: FlagKind::Value,
                        purpose: "The setting to change — `reference` lists every one",
                    },
                    Flag {
                        arg: "value",
                        kind: FlagKind::Value,
                        purpose: "Its new value; write `@file` to read a credential from a file",
                    },
                ],
            },
            Operation {
                action: Some(crate::setup::ACTION),
                purpose: "Set the whole product up in one run — the model provider, the Telegram \
                          bot and which account is the owner — changing only what is given",
                flags: &[
                    Flag {
                        arg: "provider_key",
                        kind: FlagKind::Value,
                        purpose: "The OpenRouter API key; write `@file` to read it from a file",
                    },
                    Flag {
                        arg: "provider_endpoint",
                        kind: FlagKind::Value,
                        purpose: "A custom OpenAI-compatible endpoint URL (an optional key goes \
                                  with --provider-endpoint-key)",
                    },
                    Flag {
                        arg: "provider_endpoint_key",
                        kind: FlagKind::Value,
                        purpose: "The custom endpoint's own key; write `@file` to read it from a \
                                  file",
                    },
                    Flag {
                        arg: "clear_provider_endpoint",
                        kind: FlagKind::Present,
                        purpose: "Go back to OpenRouter's own endpoint; the custom key goes with \
                                  it",
                    },
                    Flag {
                        arg: "telegram_token",
                        kind: FlagKind::Value,
                        purpose: "The Telegram bot token from BotFather; write `@file` to read it \
                                  from a file",
                    },
                    Flag {
                        arg: "owner",
                        kind: FlagKind::Value,
                        purpose: "The owner's Telegram @username or numeric id — write './@name' \
                                  for the '@' spelling, which otherwise names a file",
                    },
                    Flag {
                        arg: "unbind_owner",
                        kind: FlagKind::Present,
                        purpose: "Remove the owner's Telegram binding",
                    },
                ],
            },
            Operation {
                action: Some("setup_telegram_bot"),
                purpose: "Save the Telegram bot token from BotFather",
                flags: &[Flag {
                    arg: "token",
                    kind: FlagKind::Value,
                    purpose: "The bot token BotFather gave you",
                }],
            },
            Operation {
                action: Some("bind_telegram"),
                purpose: "Bind a Telegram account — your own, or a guest named with --user",
                flags: &[
                    Flag {
                        arg: "handle",
                        kind: FlagKind::Value,
                        purpose: "Their Telegram username or numeric id — write './@name' for the \
                                  '@' spelling, which otherwise names a file",
                    },
                    USER_FLAG,
                ],
            },
            Operation {
                action: Some("unbind_telegram"),
                purpose: "Remove an account's Telegram binding",
                flags: &[USER_FLAG],
            },
            Operation {
                action: Some("add_user"),
                purpose: "Create a guest account and, when a Telegram account is named, bind it",
                flags: &[
                    Flag {
                        arg: "name",
                        kind: FlagKind::Value,
                        purpose: "The new user's display name, which is also their personal \
                                  workspace folder",
                    },
                    Flag {
                        arg: "telegram",
                        kind: FlagKind::Value,
                        purpose: "Their Telegram username or their numeric id — omit it to create \
                                  an account with no binding yet; write './@name' for the '@' \
                                  spelling, which otherwise names a file",
                    },
                ],
            },
            Operation {
                action: Some("delete_user"),
                purpose: "Delete a guest account",
                flags: &[USER_FLAG],
            },
            Operation {
                action: Some("list_users"),
                purpose: "List the accounts and their Telegram bindings",
                flags: &[],
            },
            Operation {
                action: Some("setup_web_search"),
                purpose: "Choose the web-search provider and store its API key",
                flags: &[
                    Flag {
                        arg: "provider",
                        kind: FlagKind::Value,
                        purpose: "'deepseek' or 'exa'",
                    },
                    Flag {
                        arg: "key",
                        kind: FlagKind::Value,
                        purpose: "The API key for the chosen provider",
                    },
                ],
            },
            Operation {
                action: Some("grant_tool"),
                purpose: "Give a user one of your custom tools",
                flags: &[USER_FLAG, CUSTOM_TOOL_FLAG],
            },
            Operation {
                action: Some("revoke_tool"),
                purpose: "Take one of your custom tools back from a user",
                flags: &[USER_FLAG, CUSTOM_TOOL_FLAG],
            },
            Operation {
                action: Some("list_grants"),
                purpose: "List the custom tools granted to a user, or to every user",
                flags: &[Flag {
                    arg: "user",
                    kind: FlagKind::Value,
                    purpose: "The user's name; omit it to list every user's grants",
                }],
            },
            Operation {
                action: Some("create_custom_role"),
                purpose: "Create a custom role from a prompt",
                flags: &[
                    Flag {
                        arg: "name",
                        kind: FlagKind::Value,
                        purpose: "The role's name — ASCII letters, digits, '_' and '-' only, and \
                                  not a built-in agent namespace",
                    },
                    Flag {
                        arg: "prompt",
                        kind: FlagKind::Value,
                        purpose: "The whole definition of the role: everything it is told besides \
                                  the folder it works in",
                    },
                    Flag {
                        arg: "tools",
                        kind: FlagKind::List,
                        purpose: "A tool name, optionally `name:kind1,kind2` for one with kinds, \
                                  or `custom:<script>` for one of your `shared` folder's scripts; \
                                  repeat once per tool (omit for none)",
                    },
                    Flag {
                        arg: "behavior",
                        kind: FlagKind::Value,
                        purpose: "'continuous' (one shared branch of the role) or 'one_off' (runs \
                                  once and reports back)",
                    },
                ],
            },
            Operation {
                action: Some("update_custom_role"),
                purpose: "Change a custom role's prompt, tools or behaviour",
                flags: &[
                    Flag {
                        arg: "name",
                        kind: FlagKind::Value,
                        purpose: "The custom role to change",
                    },
                    Flag {
                        arg: "prompt",
                        kind: FlagKind::Value,
                        purpose: "The role's new definition (omit to leave it as it is)",
                    },
                    Flag {
                        arg: "tools",
                        kind: FlagKind::List,
                        purpose: "The role's new tool subset — `name`, `name:kind1,kind2` or \
                                  `custom:<script>` entries; repeat once per tool (omit to leave \
                                  it as it is)",
                    },
                    Flag {
                        arg: "behavior",
                        kind: FlagKind::Value,
                        purpose: "The role's new behaviour: 'continuous' or 'one_off' (omit to \
                                  leave it as it is)",
                    },
                ],
            },
            Operation {
                action: Some("list_custom_roles"),
                purpose: "List the custom roles",
                flags: &[],
            },
            Operation {
                action: Some("delete_custom_role"),
                purpose: "Delete a custom role",
                flags: &[Flag {
                    arg: "name",
                    kind: FlagKind::Value,
                    purpose: "The custom role to delete",
                }],
            },
        ]),
    },
    Family {
        word: "workspace",
        tool: "workspace",
        // Its surface gained the workspace's own settings and project actions — see
        // [`CALL_STORE_SETTINGS`](crate::db::ipc::CALL_STORE_SETTINGS).
        protocol: crate::db::ipc::CALL_STORE_SETTINGS,
        purpose: "Work with the running product's workspaces — add, delete or re-analyse one, \
                  its commands and rules, the active project and its maintenance — plus their \
                  tickets and board",
        surface: Surface::Operations(&[
            Operation {
                action: Some("reference"),
                purpose: "Print every action and field of this surface, and of the product's \
                          settings — the same text `mahbot config reference` prints",
                flags: &[],
            },
            Operation {
                action: Some("list"),
                purpose: "List the managed workspaces",
                flags: &[Flag {
                    arg: "workspace",
                    kind: FlagKind::Value,
                    purpose: "One managed workspace; omit it to list every one",
                }],
            },
            Operation {
                action: Some("show"),
                purpose: "Show one managed workspace: its path, status, rules and commands",
                flags: &[Flag {
                    arg: "workspace",
                    kind: FlagKind::Value,
                    purpose: "The managed workspace to show",
                }],
            },
            Operation {
                action: Some("add"),
                purpose: "Add a software project directory as a managed workspace",
                flags: &[
                    Flag {
                        arg: "name",
                        kind: FlagKind::Value,
                        purpose: "The new workspace's short unique name, used in ticket ids and \
                                  the GUI",
                    },
                    Flag {
                        arg: "path",
                        // A folder, not a reference file: resolved where this command runs and
                        // proved to be a directory there, so a mistyped path is refused in the
                        // caller's own directory.
                        kind: FlagKind::Directory,
                        purpose: "Path to the project directory to add",
                    },
                ],
            },
            Operation {
                action: Some("delete"),
                purpose: "Stop managing a workspace — its folder, repository and tickets stay on \
                          disk",
                flags: &[Flag {
                    arg: "workspace",
                    kind: FlagKind::Value,
                    purpose: "The managed workspace to delete",
                }],
            },
            // `pause` (and `resume`, which says the same) act on ONE workspace or
            // the whole fleet, told apart by ABSENCE: with no `--workspace` the
            // args carry no `workspace` key at all, and that absence IS the
            // fleet-wide form. Naming one is then the only field allowed — the tool
            // refuses a stray field so a fleet-wide write can never be widened by
            // accident, so never invent one and never send a `null`.
            Operation {
                action: Some("pause"),
                purpose: "Freeze one managed workspace, or every one when none is named",
                flags: &[Flag {
                    arg: "workspace",
                    kind: FlagKind::Value,
                    purpose: "The managed workspace to freeze; omit it to freeze EVERY \
                              managed workspace (the fleet-wide pause — a workspace that is \
                              not ready is skipped and left untouched, which makes that result \
                              a partial one)",
                }],
            },
            // See `pause`: the same fleet-wide rule, the same absent key.
            Operation {
                action: Some("resume"),
                purpose: "Resume one managed workspace, or every one when none is named",
                flags: &[Flag {
                    arg: "workspace",
                    kind: FlagKind::Value,
                    purpose: "The managed workspace to resume; omit it to resume EVERY \
                              managed workspace (the fleet-wide resume — a workspace that is \
                              not ready is skipped and left untouched, which makes that result \
                              a partial one)",
                }],
            },
            Operation {
                action: Some("maintenance"),
                purpose: "Turn a workspace's background maintainer on or off",
                flags: &[
                    Flag {
                        arg: "workspace",
                        kind: FlagKind::Value,
                        purpose: "The managed workspace whose maintainer is set",
                    },
                    Flag {
                        arg: "maintenance",
                        kind: FlagKind::Present,
                        purpose: "Run the maintainer; write `--maintenance=false` to stop it",
                    },
                ],
            },
            Operation {
                action: Some("rediscover"),
                purpose: "Re-analyse a workspace's project layout — discovery starts again, and \
                          the pipeline waits for it",
                flags: &[Flag {
                    arg: "workspace",
                    kind: FlagKind::Value,
                    purpose: "The managed workspace to re-analyse",
                }],
            },
            Operation {
                action: Some("rediscover_diagnostics"),
                purpose: "Re-detect a workspace's diagnostics commands from its project files, \
                          touching nothing else",
                flags: &[Flag {
                    arg: "workspace",
                    kind: FlagKind::Value,
                    purpose: "The managed workspace whose commands are re-detected",
                }],
            },
            Operation {
                action: Some("set_diagnostics"),
                purpose: "Write a workspace's diagnostics commands by hand",
                flags: &[
                    Flag {
                        arg: "workspace",
                        kind: FlagKind::Value,
                        purpose: "The managed workspace whose commands are written",
                    },
                    Flag {
                        arg: "format",
                        kind: FlagKind::Value,
                        purpose: "The format command; omit it to keep the stored one, write \
                                  '--format=' to clear it",
                    },
                    Flag {
                        arg: "format_check",
                        kind: FlagKind::Value,
                        purpose: "The format-check command; omit it to keep the stored one, write \
                                  '--format-check=' to clear it",
                    },
                    Flag {
                        arg: "lint",
                        kind: FlagKind::Value,
                        purpose: "The lint command; omit it to keep the stored one, write \
                                  '--lint=' to clear it",
                    },
                    Flag {
                        arg: "lint_fix",
                        kind: FlagKind::Value,
                        purpose: "The lint-fix command; omit it to keep the stored one, write \
                                  '--lint-fix=' to clear it",
                    },
                    Flag {
                        arg: "type_check",
                        kind: FlagKind::Value,
                        purpose: "The type-check command; omit it to keep the stored one, write \
                                  '--type-check=' to clear it",
                    },
                    Flag {
                        arg: "build",
                        kind: FlagKind::Value,
                        purpose: "The build command; omit it to keep the stored one, write \
                                  '--build=' to clear it",
                    },
                    Flag {
                        arg: "unit_test",
                        kind: FlagKind::Value,
                        purpose: "The unit-test command; omit it to keep the stored one, write \
                                  '--unit-test=' to clear it",
                    },
                ],
            },
            Operation {
                action: Some("set_rules"),
                purpose: "Write a workspace's project rules, which every agent there is told",
                flags: &[
                    Flag {
                        arg: "workspace",
                        kind: FlagKind::Value,
                        purpose: "The managed workspace whose rules are written",
                    },
                    Flag {
                        arg: "rules",
                        kind: FlagKind::Value,
                        purpose: "The rules text; write `@file` to read it from a file — an \
                                  empty value clears them",
                    },
                ],
            },
            Operation {
                action: Some("use"),
                purpose: "Make a workspace the active project",
                flags: &[Flag {
                    arg: "workspace",
                    kind: FlagKind::Value,
                    purpose: "The managed workspace to make active",
                }],
            },
            Operation {
                action: Some("board"),
                purpose: "List the tickets of one workspace, or of every one, by phase",
                flags: &[
                    Flag {
                        arg: "workspace",
                        kind: FlagKind::Value,
                        purpose: "One managed workspace; omit it to cover every one",
                    },
                    Flag {
                        arg: "phase",
                        kind: FlagKind::Value,
                        purpose: "Narrow the listing to one ticket phase (e.g. 'queued', \
                                  'in_development', 'done'); omit it for every non-archived ticket",
                    },
                ],
            },
            Operation {
                action: Some("ticket"),
                purpose: "Show one ticket",
                flags: &[
                    Flag {
                        arg: "ticket_id",
                        kind: FlagKind::Value,
                        purpose: "The ticket's full id — '<workspace>-<number>', which already \
                                  carries its workspace (a bare number is refused)",
                    },
                    Flag {
                        arg: "full",
                        kind: FlagKind::Present,
                        purpose: "The ticket whole and unclipped — omitted, the tool's own \
                                  default is the clipped form",
                    },
                ],
            },
            Operation {
                action: Some("comment"),
                purpose: "Leave a clarification note on a ticket",
                flags: &[
                    Flag {
                        arg: "ticket_id",
                        kind: FlagKind::Value,
                        purpose: "The ticket's full id — '<workspace>-<number>'",
                    },
                    Flag {
                        arg: "content",
                        kind: FlagKind::Value,
                        purpose: "The clarification note to leave on the ticket",
                    },
                ],
            },
        ]),
    },
    Family {
        word: "send",
        tool: "send",
        // This build's own family: a product built before it answers the call as a
        // failed operation, so it carries the current value and is refused as the
        // environment's class instead.
        protocol: crate::db::ipc::CALL_STORE,
        purpose: "Hand one message to an agent and finish — an answer arrives later in your \
                  assistant's conversation, and nothing does for the one-way 'guest' address",
        surface: Surface::Standalone(&[
            Flag {
                arg: "message",
                kind: FlagKind::Value,
                purpose: "The work to hand over; make it self-contained — the addressee cannot \
                          see your conversation (required)",
            },
            // The address vocabulary's own words, which `tools::send` checks name
            // every address and every argument an address requires.
            Flag {
                arg: "addressee",
                kind: FlagKind::Value,
                purpose: crate::tools::send::ADDRESSEE_FLAG_HELP,
            },
            Flag {
                arg: "place",
                kind: FlagKind::Value,
                purpose: "The folder the addressee works in: for 'manager', the managed \
                          workspace to message, by its managed name or its own folder; for \
                          'role', a managed workspace, a folder path, or 'personal:<user>'; a \
                          worker or a worker branch works in a directory outside the managed \
                          workspaces (one inside is refused), and in your own workspace when it \
                          names none",
            },
            Flag {
                arg: "branch",
                kind: FlagKind::Value,
                purpose: "The branch to continue or create — a worker branch's, or a custom \
                          role's own named branch (ASCII letters, digits, '_' and '-', at most \
                          32 chars)",
            },
            Flag {
                arg: "name",
                kind: FlagKind::Value,
                purpose: "The name the chosen address takes: for 'role', the custom role to \
                          start (it must exist); for 'guest', the account name of the guest whose \
                          own assistant receives the message",
            },
        ]),
    },
    // These families front the tools every Assistant holds regardless of account (the
    // media models resolve per-user), so the command line reaches what the owner's own
    // assistant can already do. What it adds is the DESTINATION ([`FlagKind::Destination`]).
    Family {
        word: "document",
        tool: "document",
        // This build's own families: a product built before them serves no such
        // tool, so the call comes back as the environment's class — nothing ran —
        // rather than as a failed operation.
        protocol: crate::db::ipc::CALL_STORE,
        purpose: "Read a document with the product's own reader, or produce one with its document \
                  tool — write, fill a template, edit an Office file, and every PDF operation",
        surface: Surface::Operations(&[
            Operation {
                action: Some(DOCUMENT_READ),
                purpose: "Read a document with the running product's own reader: its full text and \
                          every image it produces, in a folder of their own",
                flags: &[DOCUMENT_PATH_FLAG, DOCUMENT_FILE_NAME_FLAG, OUTPUT_DIR_FLAG],
            },
            Operation {
                action: Some("create"),
                purpose: "Write a new file: docx/pptx/pdf blocks, or xlsx sheets",
                flags: &[
                    DOCUMENT_FORMAT_FLAG,
                    DOCUMENT_CONTENT_FLAG,
                    DOCUMENT_SHEETS_FLAG,
                    DOCUMENT_SLIDE_SIZE_FLAG,
                    DOCUMENT_HEADER_FLAG,
                    DOCUMENT_FOOTER_FLAG,
                    DOCUMENT_METADATA_FLAG,
                    DOCUMENT_FILE_NAME_FLAG,
                    OUTPUT_DIR_FLAG,
                ],
            },
            Operation {
                action: Some("fill_template"),
                purpose: "Fill a copy of your own .docx/.pptx/.xlsx sample's placeholders",
                flags: &[
                    DOCUMENT_PATH_FLAG,
                    DOCUMENT_VALUES_FLAG,
                    DOCUMENT_FILE_NAME_FLAG,
                    OUTPUT_DIR_FLAG,
                ],
            },
            Operation {
                action: Some("docx_edit"),
                purpose: "Edit a .docx/.docm",
                flags: &[
                    DOCUMENT_PATH_FLAG,
                    IMAGE_EDITS_FLAG,
                    DOCUMENT_FILE_NAME_FLAG,
                    OUTPUT_DIR_FLAG,
                ],
            },
            Operation {
                action: Some("xlsx_edit"),
                purpose: "Edit an .xlsx/.xlsm",
                flags: &[
                    DOCUMENT_PATH_FLAG,
                    IMAGE_EDITS_FLAG,
                    DOCUMENT_FILE_NAME_FLAG,
                    OUTPUT_DIR_FLAG,
                ],
            },
            Operation {
                action: Some("pptx_edit"),
                purpose: "Edit a .pptx/.pptm",
                flags: &[
                    DOCUMENT_PATH_FLAG,
                    IMAGE_EDITS_FLAG,
                    DOCUMENT_FILE_NAME_FLAG,
                    OUTPUT_DIR_FLAG,
                ],
            },
            Operation {
                action: Some("pdf_merge"),
                purpose: "Merge PDFs into one new file",
                flags: &[
                    DOCUMENT_PATHS_FLAG,
                    DOCUMENT_METADATA_FLAG,
                    DOCUMENT_FILE_NAME_FLAG,
                    OUTPUT_DIR_FLAG,
                ],
            },
            Operation {
                action: Some("pdf_split"),
                purpose: "Split a PDF, one produced file per page entry",
                flags: &[
                    DOCUMENT_PATH_FLAG,
                    DOCUMENT_PAGES_FLAG,
                    DOCUMENT_METADATA_FLAG,
                    DOCUMENT_FILE_NAME_FLAG,
                    OUTPUT_DIR_FLAG,
                ],
            },
            Operation {
                action: Some("pdf_rotate"),
                purpose: "Add a rotation to a PDF's pages",
                flags: &[
                    DOCUMENT_PATH_FLAG,
                    DOCUMENT_DEGREES_FLAG,
                    DOCUMENT_PAGES_FLAG,
                    DOCUMENT_METADATA_FLAG,
                    DOCUMENT_FILE_NAME_FLAG,
                    OUTPUT_DIR_FLAG,
                ],
            },
            Operation {
                action: Some("pdf_crop"),
                purpose: "Crop a PDF page's visible area",
                flags: &[
                    DOCUMENT_PATH_FLAG,
                    DOCUMENT_AREA_FLAG,
                    DOCUMENT_PAGES_FLAG,
                    DOCUMENT_METADATA_FLAG,
                    DOCUMENT_FILE_NAME_FLAG,
                    OUTPUT_DIR_FLAG,
                ],
            },
            Operation {
                action: Some("pdf_resize"),
                purpose: "Resize a PDF page, scaling its content to fit",
                flags: &[
                    DOCUMENT_PATH_FLAG,
                    DOCUMENT_WIDTH_FLAG,
                    DOCUMENT_HEIGHT_FLAG,
                    DOCUMENT_PAGES_FLAG,
                    DOCUMENT_METADATA_FLAG,
                    DOCUMENT_FILE_NAME_FLAG,
                    OUTPUT_DIR_FLAG,
                ],
            },
            Operation {
                action: Some("pdf_text"),
                purpose: "Draw text on a PDF's pages, as page content rather than an annotation",
                flags: &[
                    DOCUMENT_PATH_FLAG,
                    DOCUMENT_TEXT_FLAG,
                    DOCUMENT_PAGES_FLAG,
                    DOCUMENT_X_FLAG,
                    DOCUMENT_Y_FLAG,
                    DOCUMENT_SIZE_FLAG,
                    DOCUMENT_COLOR_FLAG,
                    DOCUMENT_STAMP_FLAG,
                    DOCUMENT_OPACITY_FLAG,
                    DOCUMENT_ROTATE_FLAG,
                    DOCUMENT_METADATA_FLAG,
                    DOCUMENT_FILE_NAME_FLAG,
                    OUTPUT_DIR_FLAG,
                ],
            },
            Operation {
                action: Some("pdf_image"),
                purpose: "Place a PNG or JPEG on a PDF's pages, as page content rather than an \
                          annotation",
                flags: &[
                    DOCUMENT_PATH_FLAG,
                    DOCUMENT_IMAGE_FLAG,
                    DOCUMENT_PAGES_FLAG,
                    DOCUMENT_X_FLAG,
                    DOCUMENT_Y_FLAG,
                    DOCUMENT_WIDTH_FLAG,
                    DOCUMENT_HEIGHT_FLAG,
                    DOCUMENT_METADATA_FLAG,
                    DOCUMENT_FILE_NAME_FLAG,
                    OUTPUT_DIR_FLAG,
                ],
            },
            Operation {
                action: Some("pdf_form_fill"),
                purpose: "Fill a PDF's form fields into a copy",
                flags: &[
                    DOCUMENT_PATH_FLAG,
                    DOCUMENT_VALUES_FLAG,
                    DOCUMENT_FLATTEN_FLAG,
                    DOCUMENT_METADATA_FLAG,
                    DOCUMENT_FILE_NAME_FLAG,
                    OUTPUT_DIR_FLAG,
                ],
            },
        ]),
    },
    Family {
        word: "image",
        tool: "image_gen",
        protocol: crate::db::ipc::CALL_STORE,
        purpose: "Produce a picture with the running product's own picture tool",
        surface: Surface::Operations(&[Operation {
            action: None,
            purpose: "Produce a picture from a description, or from reference pictures",
            flags: &[
                IMAGE_PROMPT_FLAG,
                IMAGE_IMAGES_FLAG,
                IMAGE_ASPECT_RATIO_FLAG,
                IMAGE_SIZE_FLAG,
                OUTPUT_DIR_FLAG,
            ],
        }]),
    },
    Family {
        word: "video",
        tool: "video_gen",
        // The video family's surface gained the reference, frame-anchor and reference-image
        // arguments. A product one build behind accepts the frame and ignores them, billing a
        // fresh clip where an edit was asked for; its own generation makes that a refusal (the
        // environment's class — nothing ran) instead of a wrong, paid operation.
        protocol: crate::db::ipc::CALL_STORE_VIDEO,
        purpose: "Produce a clip from a description, or from a reference — a clip to edit, a \
                  picture to start from, or its first and last frames",
        surface: Surface::Operations(&[Operation {
            action: None,
            purpose: "Produce a new clip, or edit a clip the caller references",
            flags: &[
                VIDEO_PROMPT_FLAG,
                VIDEO_URL_FLAG,
                VIDEO_IMAGES_FLAG,
                VIDEO_DURATION_FLAG,
                VIDEO_RESOLUTION_FLAG,
                VIDEO_ASPECT_RATIO_FLAG,
                VIDEO_SIZE_FLAG,
                VIDEO_GENERATE_AUDIO_FLAG,
                VIDEO_SEED_FLAG,
                VIDEO_FIRST_FRAME_FLAG,
                VIDEO_LAST_FRAME_FLAG,
                OUTPUT_DIR_FLAG,
            ],
        }]),
    },
    Family {
        word: "rasterize",
        tool: "rasterize",
        protocol: crate::db::ipc::CALL_STORE,
        purpose: "Turn a file into an ordinary picture with the running product's own rasterizer",
        surface: Surface::Standalone(&[RASTER_PATH_FLAG, RASTER_PAGE_FLAG, OUTPUT_DIR_FLAG]),
    },
    Family {
        word: "photocraft",
        tool: "photocraft",
        // A family this build added: a product built before it does not know this value, so the
        // frame is refused as an unknown store — nothing ran — rather than answered as a failed
        // operation by a build that serves no such tool.
        protocol: crate::db::ipc::CALL_STORE_PHOTO,
        purpose: "Edit an existing image with the running product's own PhotoCraft engine",
        surface: Surface::Operations(&[
            Operation {
                action: Some("commands"),
                purpose: "List the vendor commands a chain can name, optionally narrowed",
                flags: &[PHOTOCRAFT_FILTER_FLAG],
            },
            Operation {
                action: Some("inspect"),
                purpose: "Report a document's size, colour mode, depth, layers and the format its \
                          name gives",
                flags: &[PHOTOCRAFT_INPUT_FLAG],
            },
            Operation {
                action: Some("run"),
                purpose: "Run a chain of vendor commands over one document — or over a new canvas \
                          named by --canvas — into a new file",
                flags: &[
                    PHOTOCRAFT_INPUT_FLAG,
                    PHOTOCRAFT_CANVAS_FLAG,
                    PHOTOCRAFT_OUTPUT_FLAG,
                    PHOTOCRAFT_CHAIN_FLAG,
                    OUTPUT_DIR_FLAG,
                ],
            },
            Operation {
                action: Some("batch"),
                purpose: "Run one chain over every document in a folder, writing the results into \
                          the folder --output names",
                flags: &[
                    PHOTOCRAFT_INPUT_FLAG,
                    PHOTOCRAFT_OUTPUT_FLAG,
                    PHOTOCRAFT_CHAIN_FLAG,
                    PHOTOCRAFT_FORMAT_FLAG,
                    PHOTOCRAFT_QUALITY_FLAG,
                    PHOTOCRAFT_TIFF_LAYERS_FLAG,
                ],
            },
        ]),
    },
];

const RASTER_PATH_FLAG: Flag = Flag {
    arg: "path",
    kind: FlagKind::Path,
    purpose: "The file to render — an SVG, one page of a PDF, or an HTML file inside your \
              personal workspace — or an http(s) address; resolved where this command runs, and \
              read with the owner's own authority",
};

const RASTER_PAGE_FLAG: Flag = Flag {
    arg: "page",
    kind: FlagKind::Number,
    purpose: "The 1-based page to render, for a PDF of several pages",
};

/// The destination every producing operation carries: the command line's OWN
/// operand, the one flag no tool reads (see [`FlagKind::Destination`]).
const OUTPUT_DIR_FLAG: Flag = Flag {
    arg: "output_dir",
    kind: FlagKind::Destination,
    purpose: "The directory the operation writes into — the produced file(s), or the one folder \
              they are all in; it must already exist, and it is the directory this command is run \
              in when it is left out. An operation whose own flag names the output takes it from \
              there instead",
};

/// The base name of what it produces — every document operation carries it.
const DOCUMENT_FILE_NAME_FLAG: Flag = Flag {
    arg: "file_name",
    kind: FlagKind::Value,
    purpose: "The base name of what is produced, without an extension where one is appended; a \
              free name is used, so nothing already there is overwritten",
};

const DOCUMENT_FORMAT_FLAG: Flag = Flag {
    arg: "format",
    kind: FlagKind::Value,
    purpose: "The format to write: docx, pptx, xlsx or pdf",
};

/// `create`'s slide size (a `pdf_text`'s `size` is a font size, its own flag).
const DOCUMENT_SLIDE_SIZE_FLAG: Flag = Flag {
    arg: "size",
    kind: FlagKind::Value,
    purpose: "A pptx slide size: widescreen, standard or portrait; unnamed is the tool's own default deck",
};

/// The document tool's `content` argument — `create`'s blocks, for every format but xlsx.
const DOCUMENT_CONTENT_FLAG: Flag = Flag {
    arg: "content",
    kind: FlagKind::Structured(&["image"]),
    purpose: "The blocks to lay down, as a JSON array — one object per block, with the \
              'text'/'table'/'image'/'...' kind it names beside its own fields",
};

const DOCUMENT_HEADER_FLAG: Flag = Flag {
    arg: "header",
    kind: FlagKind::Value,
    purpose: "A created .docx's running header, one paragraph per line; {page} is the page \
              number and {pages} the document's page count",
};

const DOCUMENT_FOOTER_FLAG: Flag = Flag {
    arg: "footer",
    kind: FlagKind::Value,
    purpose: "A created .docx's running footer, one paragraph per line; {page} is the page \
              number and {pages} the document's page count",
};

const DOCUMENT_SHEETS_FLAG: Flag = Flag {
    arg: "sheets",
    kind: FlagKind::Structured(&[]),
    purpose: "The worksheets to write, as a JSON array — one object per sheet with its 'name', \
              its 'rows' and its own fields",
};

/// The document tool's `metadata` argument — every operation that writes a PDF.
const DOCUMENT_METADATA_FLAG: Flag = Flag {
    arg: "metadata",
    kind: FlagKind::Structured(&[]),
    purpose: "A PDF's own description, as a JSON object keyed {{pdf_metadata_fields}}; a named \
              field is set (a date is {{pdf_date_format}}), an empty string clears one, a field \
              you do not name is left as the file has it, and an existing modified date advances \
              to the write",
};

/// The one input most operations act on — and the file the reader reads.
const DOCUMENT_PATH_FLAG: Flag = Flag {
    arg: "path",
    kind: FlagKind::Path,
    purpose: "The input file to work on",
};

const DOCUMENT_PATHS_FLAG: Flag = Flag {
    arg: "paths",
    kind: FlagKind::PathList,
    purpose: "One input PDF, in the order it must be merged; repeat once per file, or name a \
              file holding them as a JSON array with '@<file>'",
};

const DOCUMENT_PAGES_FLAG: Flag = Flag {
    arg: "pages",
    kind: FlagKind::List,
    purpose: "One page entry: \"all\", a page, a range, or a comma list like \"1-3,5\" (\"all\" \
              stands alone); repeat once per entry, or name a file holding them as a JSON array \
              with '@<file>'; left out, every page",
};

/// The document tool's `edits` argument, whose `add_image` names a reference
/// file — so the list resolves that `image` where the command runs.
const IMAGE_EDITS_FLAG: Flag = Flag {
    arg: "edits",
    kind: FlagKind::Structured(&["image"]),
    purpose: EDITS_PURPOSE,
};

/// What the `edits` argument is, as every operation that takes it states it.
const EDITS_PURPOSE: &str = "The edits to apply, as a JSON array — one object per edit, naming the \
                              operation it is ('format_text', 'set_cell', 'add_slide', …) beside \
                              its own fields";

const DOCUMENT_VALUES_FLAG: Flag = Flag {
    arg: "values",
    kind: FlagKind::Structured(&[]),
    purpose: "The values to write, as a JSON object keyed by placeholder name (or form field \
              name)",
};

const DOCUMENT_DEGREES_FLAG: Flag = Flag {
    arg: "degrees",
    kind: FlagKind::Number,
    purpose: "The rotation to add, in degrees (a multiple of the tool's own step)",
};

const DOCUMENT_AREA_FLAG: Flag = Flag {
    arg: "area",
    kind: FlagKind::Structured(&[]),
    purpose: "The area to keep, as a JSON object of x, y, width and height — fractions of the \
              page's visible area, from the displayed top-left",
};

const DOCUMENT_TEXT_FLAG: Flag = Flag {
    arg: "text",
    kind: FlagKind::Value,
    purpose: "The text to draw",
};

const DOCUMENT_IMAGE_FLAG: Flag = Flag {
    arg: "image",
    kind: FlagKind::Path,
    purpose: "The PNG or JPEG to place",
};

const DOCUMENT_X_FLAG: Flag = Flag {
    arg: "x",
    kind: FlagKind::Number,
    purpose: "Across the page, in points",
};

const DOCUMENT_Y_FLAG: Flag = Flag {
    arg: "y",
    kind: FlagKind::Number,
    purpose: "Down the page, in points",
};

const DOCUMENT_SIZE_FLAG: Flag = Flag {
    arg: "size",
    kind: FlagKind::Number,
    purpose: "The font size, in points",
};

const DOCUMENT_COLOR_FLAG: Flag = Flag {
    arg: "color",
    kind: FlagKind::Value,
    purpose: "The text colour, as hex digits",
};

const DOCUMENT_STAMP_FLAG: Flag = Flag {
    arg: "stamp",
    kind: FlagKind::Present,
    purpose: "Draw a box around the text",
};

const DOCUMENT_OPACITY_FLAG: Flag = Flag {
    arg: "opacity",
    kind: FlagKind::Number,
    purpose: "Opacity from just above zero to one; unnamed is fully opaque",
};

const DOCUMENT_ROTATE_FLAG: Flag = Flag {
    arg: "rotate",
    kind: FlagKind::Number,
    purpose: "The text's own rotation, in degrees",
};

/// `pdf_image`'s placed width, or `pdf_resize`'s new page width.
const DOCUMENT_WIDTH_FLAG: Flag = Flag {
    arg: "width",
    kind: FlagKind::Number,
    purpose: "The width, in points: a picture's placed width, or the page width a resize makes",
};

/// `pdf_image`'s placed height, or `pdf_resize`'s new page height.
const DOCUMENT_HEIGHT_FLAG: Flag = Flag {
    arg: "height",
    kind: FlagKind::Number,
    purpose: "The height, in points: a picture's placed height, or the page height a resize makes",
};

const DOCUMENT_FLATTEN_FLAG: Flag = Flag {
    arg: "flatten",
    kind: FlagKind::Present,
    purpose: "Bake the fields into the page content and remove them",
};

const IMAGE_PROMPT_FLAG: Flag = Flag {
    arg: "prompt",
    kind: FlagKind::Value,
    purpose: "The text description of the picture to produce (required)",
};

/// The one generation's reference pictures: given any, it is picture-to-picture.
const IMAGE_IMAGES_FLAG: Flag = Flag {
    arg: "images",
    kind: FlagKind::PathList,
    purpose: "One reference picture, by path; repeat once per picture, or name a file holding \
              them as a JSON array with '@<file>' — given any, the request is \
              picture-to-picture rather than text-to-picture",
};

const IMAGE_ASPECT_RATIO_FLAG: Flag = Flag {
    arg: "aspect_ratio",
    kind: FlagKind::Value,
    purpose: "The aspect ratio, like '16:9', '1:1' or '4:3'",
};

const IMAGE_SIZE_FLAG: Flag = Flag {
    arg: "size",
    kind: FlagKind::Value,
    purpose: "The picture's size — a tier like '1K'/'2K' or explicit pixels like '1024x1024'; \
              a model that cannot express the value is not sent the request",
};

const VIDEO_PROMPT_FLAG: Flag = Flag {
    arg: "prompt",
    kind: FlagKind::Value,
    purpose: "The text description of the clip to produce, or of the edit to apply (required)",
};

const VIDEO_IMAGES_FLAG: Flag = Flag {
    arg: "images",
    kind: FlagKind::PathList,
    purpose: "The path of ONE local picture to start a new clip from — or, with a clip to edit, \
              of a picture guiding the edit: repeat once per picture, up to nine, or name a file \
              holding them as a JSON array with '@<file>'. A new clip's start picture is a local \
              file only; an edit's guiding pictures may also be public https URLs",
};

const VIDEO_DURATION_FLAG: Flag = Flag {
    arg: "duration",
    kind: FlagKind::Number,
    purpose: "The clip's length in seconds — a new clip's, or an edit's; the values the \
              account's own model takes are the ones it takes",
};

const VIDEO_RESOLUTION_FLAG: Flag = Flag {
    arg: "resolution",
    kind: FlagKind::Value,
    purpose: "A new clip's resolution, as the model states it — refused with a clip to edit or \
              frame anchors",
};

const VIDEO_ASPECT_RATIO_FLAG: Flag = Flag {
    arg: "aspect_ratio",
    kind: FlagKind::Value,
    purpose: "A new clip's aspect ratio, as the model states it — refused with a clip to edit \
              or frame anchors",
};

const VIDEO_SIZE_FLAG: Flag = Flag {
    arg: "size",
    kind: FlagKind::Value,
    purpose: "A new clip's exact size, as WxH (like '1280x720') — refused with a clip to edit \
              or frame anchors",
};

const VIDEO_GENERATE_AUDIO_FLAG: Flag = Flag {
    arg: "generate_audio",
    kind: FlagKind::Present,
    purpose: "Ask a new clip for an audio track, where the model offers one — omitted, the \
              model's own default applies and `=false` asks for a silent clip; refused with a \
              clip to edit or frame anchors",
};

const VIDEO_SEED_FLAG: Flag = Flag {
    arg: "seed",
    kind: FlagKind::Number,
    purpose: "A new clip's seed for a repeatable generation — refused with a clip to edit or \
              frame anchors",
};

/// The video tool's `video_url` argument: the clip to edit, and the edit
/// form's own input.
const VIDEO_URL_FLAG: Flag = Flag {
    arg: "video_url",
    kind: FlagKind::Path,
    purpose: "The clip to edit: a local path or a public https URL — given it the call edits \
              that clip; omitted, a new clip is generated; mutually exclusive with the first \
              and last frames",
};

const VIDEO_FIRST_FRAME_FLAG: Flag = Flag {
    arg: "first_frame",
    kind: FlagKind::Path,
    purpose: "The picture to use as the exact first frame, by local path or public https URL — \
              the frame-anchor form, which excludes a clip and reference pictures",
};

const VIDEO_LAST_FRAME_FLAG: Flag = Flag {
    arg: "last_frame",
    kind: FlagKind::Path,
    purpose: "The picture to use as the exact last frame, by local path or public https URL — \
              the frame-anchor form, which excludes a clip and reference pictures",
};

/// The one input most operations act on — a document, or the folder a batch processes.
const PHOTOCRAFT_INPUT_FLAG: Flag = Flag {
    arg: "input",
    kind: FlagKind::UncheckedPath,
    purpose: "The document to work on, or with a batch the folder to process",
};

/// Where a run writes its file, or the folder a batch writes into — the operation's own output, so a
/// call that gives it takes the place from it and the destination is only the fallback.
const PHOTOCRAFT_OUTPUT_FLAG: Flag = Flag {
    arg: "output",
    kind: FlagKind::Output,
    purpose: "The file to write, which must not already exist, or with a batch the folder to \
              write into",
};

/// The vendor command chain — one object per step, its id beside its params.
const PHOTOCRAFT_CHAIN_FLAG: Flag = Flag {
    arg: "chain",
    kind: FlagKind::Structured(&[]),
    purpose: "The commands to run, as a JSON array — one object per step with its 'command' id \
              ('filter.sharpen.smartSharpen', 'layer.newAdjustmentLayer.curves') and its \
              'params'; the 'commands' operation lists the registry, and '@<file>' reads the \
              array from a file",
};

/// The new document a `run` starts from instead of opening one.
const PHOTOCRAFT_CANVAS_FLAG: Flag = Flag {
    arg: "canvas",
    kind: FlagKind::Structured(&[]),
    purpose: "Start from a new document with these JSON parameters instead of opening --input, like \
              '{\"width\": 800, \"height\": 600}'; a fresh output for one is PNG",
};

/// The `commands` operation's narrowing text.
const PHOTOCRAFT_FILTER_FLAG: Flag = Flag {
    arg: "filter",
    kind: FlagKind::Value,
    purpose: "Text to narrow the command registry by; a narrowed answer adds each match's parameter \
              documentation",
};

/// A batch's output extension.
const PHOTOCRAFT_FORMAT_FLAG: Flag = Flag {
    arg: "format",
    kind: FlagKind::Value,
    purpose: "The extension to write, like 'jpg' or 'png'; with no --chain it is what a folder-wide \
              conversion writes",
};

/// A batch's encoder quality.
const PHOTOCRAFT_QUALITY_FLAG: Flag = Flag {
    arg: "quality",
    kind: FlagKind::Number,
    purpose: "The encoder quality, 1 to 100",
};

/// A batch's layered TIFF output.
const PHOTOCRAFT_TIFF_LAYERS_FLAG: Flag = Flag {
    arg: "tiff_layers",
    kind: FlagKind::Present,
    purpose: "Keep layers in TIFF output — a `format` of tif or tiff keeps them anyway",
};

/// The `user` argument of the account actions, shared by `bind-telegram`, `unbind-telegram`,
/// `delete-user`, `grant-tool` and `revoke-tool` so the five cannot describe it differently.
const USER_FLAG: Flag = Flag {
    arg: "user",
    kind: FlagKind::Value,
    purpose: "The user's name",
};

/// The `tool` argument of the grant actions — see [`USER_FLAG`].
const CUSTOM_TOOL_FLAG: Flag = Flag {
    arg: "tool",
    kind: FlagKind::Value,
    purpose: "The custom tool's name — a script in the 'shared' folder of your personal workspace",
};

/// One of the command lines this module fronts, resolved from its word by
/// [`entry_point`]. Opaque on purpose: the gate and the dispatch cannot disagree.
pub struct Cli(&'static Family);

/// Resolve a command-line word to its family: the registry lookup under
/// [`entry_point`].
#[must_use]
fn family(word: &str) -> Option<Cli> {
    FAMILIES.iter().find(|family| family.word == word).map(Cli)
}

/// The word the login registration passes, so a start the system made at login can
/// tell itself apart from a hand launch. Hidden like `__grep-engine`.
pub(crate) const LOGIN_START_ARG: &str = "__login-start";

/// One entry point a launch's first word can name: the binary's whole command table,
/// the families beside the fixed words. The ladder dispatches on this answer alone,
/// so a word with no variant here is refused as the caller's own misuse.
pub enum EntryPoint {
    /// `mahbot` with no first word: the dashboard daemon.
    Daemon,
    /// `mahbot paused`: the daemon, with every managed workspace paused before
    /// the poll loop starts.
    Paused,
    /// `mahbot __login-start`: the daemon as the login registration starts it — not a
    /// second launch, its window hidden until the tray brings it up (and shown at once
    /// when there is no tray icon to bring it back).
    LoginStart,
    /// `-h`/`--help`.
    Help,
    /// `-V`/`--version`.
    Version,
    /// `mahbot debug` — the read-only query tool ([`crate::db::debug`]).
    Debug,
    /// `mahbot __grep-engine` — the shell's own grep serving.
    GrepEngine,
    /// `mahbot __env-dump` — the shell-environment reader's child dumper.
    EnvDump,
    /// `mahbot bench-openrouter` — the standalone provider benchmark.
    BenchOpenRouter,
    /// `mahbot audio` — the speech command.
    Audio,
    /// `mahbot chrome` — the browser-automation command.
    Chrome,
    /// One of the command-line families ([`FAMILIES`]).
    Family(Cli),
}

/// Resolve a launch's first word — `None` when it had none — to the entry point it
/// names, or `None` when this build has no such word. The words are compiled in, so
/// an instance takes no part in the answer.
#[must_use]
pub fn entry_point(word: Option<&str>) -> Option<EntryPoint> {
    Some(match word {
        None => EntryPoint::Daemon,
        Some("paused") => EntryPoint::Paused,
        Some(LOGIN_START_ARG) => EntryPoint::LoginStart,
        Some("-h" | "--help") => EntryPoint::Help,
        Some("-V" | "--version") => EntryPoint::Version,
        Some("debug") => EntryPoint::Debug,
        Some("__grep-engine") => EntryPoint::GrepEngine,
        Some("__env-dump") => EntryPoint::EnvDump,
        Some("bench-openrouter") => EntryPoint::BenchOpenRouter,
        Some("audio") => EntryPoint::Audio,
        Some("chrome") => EntryPoint::Chrome,
        Some(word) => EntryPoint::Family(family(word)?),
    })
}

/// Whether this command line fronts `tool` by name. The instance serves an
/// operation only for a tool a family fronts, so the surface reachable through
/// the channel is exactly these frontends — never the owner's whole toolset.
pub(crate) fn fronts_tool(tool: &str) -> bool {
    family_tools().any(|fronted| fronted == tool)
}

/// Every tool the families front, in registry order.
fn family_tools() -> impl Iterator<Item = &'static str> {
    FAMILIES.iter().map(|family| family.tool)
}

pub(crate) fn family_words() -> impl Iterator<Item = &'static str> {
    FAMILIES.iter().map(|family| family.word)
}

/// The family words that make files ([`produces_files`]), as the read-only surfaces
/// name them: backticked, joined by a slash. Derived here alone, so a family added
/// to the registry is named — and refused — by every one of them without an edit.
pub(crate) fn producing_families() -> String {
    FAMILIES
        .iter()
        .filter(|family| produces_files(family))
        .map(|family| format!("`{}`", family.word))
        .collect::<Vec<_>>()
        .join("/")
}

/// What an operation's flag tail turned out to be.
enum Tail {
    /// The caller asked for the operation's own help — a `-h`/`--help` where a
    /// flag could stand.
    Help,
    /// The call to send.
    Call(Parsed),
}

/// One parsed command line: what is sent with the call.
struct Parsed {
    /// The tool's args object: the `action` where the tool takes one, one whose
    /// tool takes none has no `action` key at all, plus exactly the flags given.
    /// An absent flag leaves its key ABSENT, never null — the tools tell the two
    /// apart, and `pause`/`resume` read the absent `workspace` as the fleet-wide form.
    args: serde_json::Value,
    /// The directory the produced files must go into, exactly as the caller
    /// spelled it — `None` when the flag was left out. The DESTINATION is not a
    /// tool argument (see [`FlagKind::Destination`]): it travels beside them, and
    /// is resolved before anything is sent ([`resolve_output_dir`]).
    output_dir: Option<String>,
}

fn flag_spelling(arg: &str) -> String {
    arg.replace('_', "-")
}

/// Parse one operation's flag tail — the tokens after the operation word.
///
/// The grammar is [`grammar`]; what is this frontend's own is the handling under
/// it, with a `List` accumulating an entry per occurrence. Every reason names a
/// flag and never a VALUE — a mistyped secret must not travel back out — and a
/// token that is no flag is not echoed either. What this frontend judges by itself
/// is [`Exit::Usage`]; a value the tool refuses travels as written and is a failed
/// operation, which is why a `Number` or a `Structured` value that is neither
/// travels as the text it is.
///
/// `action` is the tool's own action, and `None` where the tool takes none.
fn parse_flags(
    action: Option<&'static str>,
    operation_word: &str,
    flags: &'static [Flag],
    tokens: &[String],
) -> Result<Tail, String> {
    let mut args = serde_json::Map::new();
    if let Some(action) = action {
        args.insert(
            "action".to_string(),
            serde_json::Value::String(action.to_string()),
        );
    }
    let mut output_dir: Option<String> = None;
    // The flags already given, so a repeat is refused rather than silently kept,
    // and the `List` entries, which become the array at the end.
    let mut given: Vec<&'static str> = Vec::new();
    let mut lists: Vec<(&'static str, Vec<serde_json::Value>)> = Vec::new();
    let spellings: Vec<String> = flags.iter().map(|flag| flag_spelling(flag.arg)).collect();

    let mut rest = tokens.iter();
    while let Some(token) = rest.next() {
        let (name, inline) = match grammar::read_token(token)? {
            grammar::Token::Help => return Ok(Tail::Help),
            grammar::Token::Flag { name, inline } => (name, inline),
        };
        let Some(index) = spellings.iter().position(|spelling| spelling == name) else {
            return Err(grammar::unknown_flag(name, operation_word));
        };
        let flag = &flags[index];

        if !matches!(flag.kind, FlagKind::List | FlagKind::PathList) {
            if given.contains(&flag.arg) {
                return Err(grammar::repeated_flag(name));
            }
            given.push(flag.arg);
        }

        match flag.kind {
            FlagKind::Present => {
                let value = match inline {
                    Some(text) => text.parse::<bool>().map_err(|_| bool_switch_misuse(name))?,
                    None => true,
                };
                args.insert(flag.arg.to_string(), serde_json::Value::Bool(value));
            }
            FlagKind::Value
            | FlagKind::Path
            | FlagKind::UncheckedPath
            | FlagKind::Directory
            | FlagKind::Output
            | FlagKind::Number
            | FlagKind::List
            | FlagKind::PathList
            | FlagKind::Structured(_)
            | FlagKind::Destination => {
                let value = match inline {
                    Some(value) => value.to_string(),
                    None => rest
                        .next()
                        .cloned()
                        .ok_or_else(|| grammar::flag_value_missing(name))?,
                };
                take_value(flag, &value, &mut args, &mut lists, &mut output_dir)?;
            }
        }
    }

    for (arg, entries) in lists {
        args.insert(arg.to_string(), serde_json::Value::Array(entries));
    }
    Ok(Tail::Call(Parsed {
        args: serde_json::Value::Object(args),
        output_dir,
    }))
}

/// Put one value-carrying flag's value where it belongs: into the args object for
/// every kind a tool reads, and aside for the destination, which no tool reads.
///
/// The `@` file form and the `./@…` escape are read off the value once, here, for
/// every kind; reading a FILE is only the kinds that have that form
/// ([`FlagKind::has_file_form`]). A flag whose value names a path itself is never
/// read from a file: it names the file.
fn take_value(
    flag: &Flag,
    value: &str,
    args: &mut serde_json::Map<String, serde_json::Value>,
    lists: &mut Vec<(&'static str, Vec<serde_json::Value>)>,
    output_dir: &mut Option<String>,
) -> Result<(), String> {
    let arg = flag.arg.to_string();
    let escaped = value.strip_prefix("./@").map(|rest| format!("@{rest}"));
    let value: &str = escaped.as_deref().unwrap_or(value);
    let file: Option<&str> = if escaped.is_none() && flag.kind.has_file_form() {
        value.strip_prefix('@')
    } else {
        None
    };
    match flag.kind {
        FlagKind::Destination => *output_dir = Some(value.to_string()),
        FlagKind::Value => {
            let held = match file {
                Some(file) => text_from_file(flag, file)?,
                None => value.to_string(),
            };
            args.insert(arg, serde_json::Value::String(held));
        }
        FlagKind::Path => {
            args.insert(arg, serde_json::Value::String(caller_path(flag, value)?));
        }
        FlagKind::UncheckedPath | FlagKind::Output => {
            args.insert(arg, serde_json::Value::String(resolved_path(value)));
        }
        FlagKind::Directory => {
            args.insert(
                arg,
                serde_json::Value::String(caller_directory(flag, value)?),
            );
        }
        FlagKind::Number => {
            args.insert(arg, number_or_text(value));
        }
        FlagKind::Structured(fields) => {
            let mut structured = match file {
                Some(file) => json_from_file(flag, file)?,
                None => serde_json::from_str(value)
                    .unwrap_or_else(|_| serde_json::Value::String(value.to_string())),
            };
            resolve_embedded_paths(flag, fields, &mut structured)?;
            args.insert(arg, structured);
        }
        FlagKind::List | FlagKind::PathList => {
            // One array entry per occurrence, verbatim: never split on its commas,
            // so `name:kind1,kind2` stays one tool specification. An EMPTY value
            // empties the list as of that point ([`FlagKind::List`]); a path list
            // resolves every entry the way a single path is resolved.
            let named = matches!(flag.kind, FlagKind::PathList);
            let entries = if let Some(index) = lists.iter().position(|(held, _)| *held == flag.arg)
            {
                &mut lists[index].1
            } else {
                lists.push((flag.arg, Vec::new()));
                let index = lists.len() - 1;
                &mut lists[index].1
            };
            // A path list resolves every entry the way a single path is resolved.
            let mut entry = |value: &str| -> Result<(), String> {
                let held = if named {
                    caller_path(flag, value)?
                } else {
                    value.to_string()
                };
                entries.push(serde_json::Value::String(held));
                Ok(())
            };
            match file {
                Some(file) => {
                    for held in list_entries_from_file(flag, file)? {
                        entry(held.as_str().expect("a list entry is a string"))?;
                    }
                }
                None if value.is_empty() => entries.clear(),
                None => entry(value)?,
            }
        }
        FlagKind::Present => unreachable!("a switch carries no value"),
    }
    Ok(())
}

/// The JSON a `Number` flag carries: the number it is, else the text — whether the
/// tool takes it is the tool's to judge.
fn number_or_text(value: &str) -> serde_json::Value {
    serde_json::from_str::<serde_json::Value>(value)
        .ok()
        .filter(serde_json::Value::is_number)
        .unwrap_or_else(|| serde_json::Value::String(value.to_string()))
}

/// A switch given a value that is no boolean: the form is spelled out, so the
/// caller is told what to write and not only what was wrong.
fn bool_switch_misuse(name: &str) -> String {
    format!("flag '--{name}' is a switch: write it bare for true, or '--{name}=false' for false")
}

/// Whether a value is no path of this command's to resolve: empty, or an http(s) address. It travels
/// as written, and the tool says why it cannot use it.
fn names_no_path(value: &str) -> bool {
    value.is_empty() || crate::util::is_http_url(value)
}

/// A path a flag names, resolved the way every path this command line sends is: `~` expands against
/// the home directory and a relative path resolves in the directory this command was run in — the
/// product's working directory is another one, so a path sent on as written would name a different
/// file. A value that names no path of this command's to resolve travels as written.
fn resolved_path(value: &str) -> String {
    if names_no_path(value) {
        return value.to_string();
    }
    resolve_against_cwd(value)
}

/// [`resolved_path`]'s one resolution rule, for a value already known to name a path.
fn resolve_against_cwd(value: &str) -> String {
    let expanded = crate::util::expand_tilde(value);
    if expanded.is_absolute() {
        expanded.to_string_lossy().into_owned()
    } else {
        // No working directory to resolve against: the value travels as the
        // caller wrote it, and the product says why it cannot open it.
        std::env::current_dir().map_or_else(
            |_| value.to_string(),
            |here| here.join(expanded).to_string_lossy().into_owned(),
        )
    }
}

/// A REFERENCE path a flag names, as the caller meant it and checked: resolved
/// like every path ([`resolve_against_cwd`]), and the reference material must be THERE,
/// readable and a REGULAR file. The product reads it with no timeout, so a pipe
/// with no writer or an endless device would hold the daemon forever. Missing or
/// unreadable is misuse, judged from metadata alone before anything is sent, so
/// the refusal cannot block; a URL is left to the product.
fn caller_path(flag: &Flag, value: &str) -> Result<String, String> {
    if names_no_path(value) {
        return Ok(value.to_string());
    }
    let path = resolve_against_cwd(value);
    let spelling = flag_spelling(flag.arg);
    let unreadable = |spelling: &str| {
        format!("flag '--{spelling}' names a reference file that is not there or cannot be read")
    };
    let Ok(meta) = std::fs::metadata(&path) else {
        return Err(unreadable(&spelling));
    };
    if !meta.is_file() {
        return Err(format!(
            "flag '--{spelling}' names something that is not a regular file; a reference file must \
             be one"
        ));
    }
    if std::fs::File::open(&path).is_err() {
        return Err(unreadable(&spelling));
    }
    Ok(path)
}

/// A DIRECTORY a flag names, as the caller meant it and checked: resolved like every path
/// ([`resolve_against_cwd`]), and it must be there and be a directory — a folder the caller
/// mistyped is their misuse, judged from metadata alone before anything is sent.
fn caller_directory(flag: &Flag, value: &str) -> Result<String, String> {
    if names_no_path(value) {
        return Ok(value.to_string());
    }
    let path = resolve_against_cwd(value);
    let spelling = flag_spelling(flag.arg);
    match std::fs::metadata(&path) {
        Ok(meta) if meta.is_dir() => Ok(path),
        Ok(_) => Err(format!(
            "flag '--{spelling}' names something that is not a directory"
        )),
        Err(_) => Err(format!(
            "flag '--{spelling}' names a directory that is not there"
        )),
    }
}

/// Resolve every reference file a structured value names under one of `fields` (a
/// document's image block, an edit that places a picture), which the product would
/// otherwise resolve against its OWN directories (a workspace's `generated/`, a
/// personal workspace's `uploads/`). Each string there, and each string of an array
/// there, is resolved like a `--path` value ([`caller_path`]); a member of another
/// shape is left to the tool.
fn resolve_embedded_paths(
    flag: &Flag,
    fields: &'static [&'static str],
    value: &mut serde_json::Value,
) -> Result<(), String> {
    match value {
        serde_json::Value::Object(members) => {
            for (key, member) in members.iter_mut() {
                if fields.contains(&key.as_str()) {
                    resolve_embedded_path(flag, member)?;
                } else {
                    resolve_embedded_paths(flag, fields, member)?;
                }
            }
        }
        serde_json::Value::Array(items) => {
            for item in items {
                resolve_embedded_paths(flag, fields, item)?;
            }
        }
        _ => {}
    }
    Ok(())
}

/// One member a structured value names a reference file under: the string it is,
/// or every string of the array it is.
fn resolve_embedded_path(flag: &Flag, member: &mut serde_json::Value) -> Result<(), String> {
    match member {
        serde_json::Value::String(text) => *text = caller_path(flag, text)?,
        serde_json::Value::Array(items) => {
            for item in items {
                if let serde_json::Value::String(text) = item {
                    *text = caller_path(flag, text)?;
                }
            }
        }
        _ => {}
    }
    Ok(())
}

/// Upper bound on the file a flag's `@<file>` form may read: a value travels as one
/// argument, so a file far past any command line is a mistaken path rather than a
/// value — and the bound keeps an endless file from becoming an out-of-memory.
const MAX_VALUE_FILE_BYTES: u64 = 8 * 1024 * 1024;

/// The text of the file a flag's `@<file>` form names — the ONE read every value
/// form shares, so no two of them can guard differently.
///
/// The file must be a REGULAR file of a bounded size: the parse has no timeout, so
/// a pipe (`--prompt @<fifo>`) would hold the command forever and an endless device
/// (`--prompt @/dev/zero`) would read until memory ran out. That is the caller's
/// own misuse, and the reason names the FLAG and never the path.
fn value_file_text(flag: &Flag, file: &str, what: &str) -> Result<String, String> {
    let spelling = flag_spelling(flag.arg);
    let unusable = |why: &str| {
        format!(
            "flag '--{spelling}' names a file that {why}; '@<file>' must name a file holding {what}"
        )
    };
    let path = crate::util::expand_tilde(file);
    let Ok(meta) = std::fs::metadata(&path) else {
        return Err(unusable("could not be read"));
    };
    if !meta.is_file() {
        return Err(unusable("is not a regular file"));
    }
    if meta.len() > MAX_VALUE_FILE_BYTES {
        return Err(unusable(&format!(
            "is over {} MB",
            MAX_VALUE_FILE_BYTES / (1024 * 1024)
        )));
    }
    std::fs::read_to_string(&path).map_err(|_| unusable("could not be read"))
}

/// The text the file a value flag's `@<file>` form names holds, without one
/// trailing line break — a file's last newline is the file's, not the value's. A
/// file it cannot use is misuse, and the reason names the FLAG, never the path.
fn text_from_file(flag: &Flag, file: &str) -> Result<String, String> {
    let text = value_file_text(flag, file, "the value")?;
    Ok(text
        .strip_suffix('\n')
        .map_or(text.as_str(), |rest| {
            rest.strip_suffix('\r').unwrap_or(rest)
        })
        .to_string())
}

/// Read the file a `Structured` flag's `@<file>` form names and take the JSON it
/// holds; a file it cannot use is misuse, the reason naming the FLAG, not the path.
fn json_from_file(flag: &Flag, file: &str) -> Result<serde_json::Value, String> {
    let spelling = flag_spelling(flag.arg);
    let text = value_file_text(flag, file, "the value")?;
    serde_json::from_str(&text).map_err(|_| {
        format!(
            "flag '--{spelling}' names a file that does not hold the value; '@<file>' must \
             name a file holding it as JSON"
        )
    })
}

/// Read the file a `List` flag's `@<file>` form names and take the entries it
/// holds — a JSON array of strings, and nothing else.
fn list_entries_from_file(flag: &Flag, file: &str) -> Result<Vec<serde_json::Value>, String> {
    let spelling = flag_spelling(flag.arg);
    let text = value_file_text(flag, file, "the entries as a JSON array")?;
    match serde_json::from_str::<serde_json::Value>(&text) {
        Ok(serde_json::Value::Array(entries))
            if entries.iter().all(serde_json::Value::is_string) =>
        {
            Ok(entries)
        }
        _ => Err(format!(
            "flag '--{spelling}' names a file that does not hold the entries; '@<file>' must name \
             a file holding them as a JSON array of strings"
        )),
    }
}

/// The exit classes and the one sentence that makes them the contract — shared by
/// every help, so no two can word it differently.
const EXIT_CLASS_HELP: &str = "\nExit codes:\n  0  the operation was carried out\n  1  the \
     operation failed — the product refused it, carried it out only in part, or the exchange was \
     severed after the call went out (an operation that may be under way is never the \
     environment's class)\n  2  the environment — nothing ran: the product is not up, its \
     channel was not reachable, or it could not take the operation on\n  3  this command was \
     misused\nA script reads the exit code, not the text: a refusal still prints the product's \
     own answer on stdout, so only the code says whether the operation happened.\n";

/// What one of these command lines IS — shared by every help, so a caller entering
/// through an operation's help learns the same contract as one reading the family's. `excepted`
/// qualifies the sentence that asks for the instance, and is empty where every operation crosses to
/// it: a family that prints a text itself states the exception there, not in a line below it.
fn running_contract_help(excepted: &str) -> String {
    format!(
        "\nA frontend onto the RUNNING product, acting with the \
         owner's authority and with no agent session behind it: the operation is carried into the \
         instance that is already up and the product itself runs it there — the same validation, and \
         the same immediate effect (a value it writes is in use at once, with no restart). The product \
         must be running{excepted}: there is no way to run these operations against its stores directly.\n"
    )
}

/// What a static-text operation's help says instead of the running contract: this command answers
/// it itself ([`StaticText`]), so nothing about it depends on the product being up.
const LOCAL_TEXT_CONTRACT_HELP: &str = "\nA text this command carries itself, printed word for \
     word: it needs no running instance, no lock and no source tree, and the tool of the same \
     surface returns the same text.\n";

/// Where the two streams go — shared by every help, like the contract blocks.
const OUTPUT_HELP: &str = "\nOutput:\n  stdout  the product's answer, word for word\n  stderr  \
     this command's own diagnostics\n";

/// How a value may be given from a file — shared by every help, because the form
/// belongs to this command line rather than to any family's flags.
const VALUE_FILE_HELP: &str = "\nValues:\n  A text value, a list or a structure may also be given \
     from a FILE by writing `@<file>`: a text value is the file's whole text (without one trailing \
     line break), while a list and a structure must hold JSON there. Write `./@…` for a value that \
     itself begins with `@` — the `./` is dropped and no file is read. A flag whose value names a \
     file or a directory itself — any path flag, `--path` and `--output-dir` among them — takes no \
     file form.\n";

/// What a producing family's help adds to the tool's own flags: where produced
/// files go, and how the caller's paths are read — shared by every help of such a
/// family. The destination row is rendered from the registry
/// ([`OUTPUT_DIR_FLAG`]), so its spelling and description are stated once, and
/// the "Paths" paragraph belongs here because the resolution is this frontend's.
fn producing_help() -> String {
    let mut out = String::from("\nWhere produced files go:\n");
    out.push_str(&flag_rows(std::iter::once(&OUTPUT_DIR_FLAG)));
    out.push_str(
        "\nThe names are this command's own: a free one is chosen so nothing already there is \
         overwritten, and an operation producing several files puts all of them there — unless a \
         flag of the operation names the output itself, whose own description states the rule. The \
         destination is refused when it is the product's own data directory or one of its temporary \
         areas, because the product's own cleanup would take a file left there.\n\nPaths:\n  Every \
         path this command takes as a flag — the destination, a reference file, and every path a \
         value carries, a structured value's own included — is resolved where this command runs: a \
         relative one in the directory it was run in, and `~` against your home directory. A path \
         that names a reference file must be there and readable.\n",
    );
    out
}

/// `mahbot <word> -h`: what this family's command line is and what a caller reads. A family that
/// publishes a `reference` closes on where its whole surface is written down. The texts it prints
/// itself ([`StaticText`]) are excepted in the sentence that asks for the instance, so no line of
/// this help claims one they do not need.
fn family_help(family: &Family) -> String {
    let mut out = String::new();
    let _ = writeln!(out, "mahbot {} — {}", family.word, family.purpose);
    match family.surface {
        Surface::Operations(operations) => {
            // Named from the operation list alone: the help must not load either text to say
            // which operations skip the instance.
            let static_texts: Vec<String> = operations
                .iter()
                .filter_map(static_text)
                .map(|text| format!("`{}`", text.action()))
                .collect();
            let excepted = match static_texts.as_slice() {
                [] => String::new(),
                [only] => format!(
                    " for everything but {only}, which it prints itself and answers with no instance"
                ),
                many => format!(
                    " for everything but the texts it prints itself, {}, which it answers with no \
                     instance",
                    many.join(" and ")
                ),
            };
            out.push_str(&running_contract_help(&excepted));
            let _ = write!(
                out,
                "\nEvery operation below that crosses to the product is carried out there, by the \
                 same code the owner's assistant runs — so this command line brings no behaviour of \
                 its own."
            );
            let _ = write!(out, "\nUsage: {}\n", family_syntax(family));
            out.push_str("\nOperations:\n");
            let width = operations
                .iter()
                .map(|operation| operation_word(family, operation).len())
                .max()
                .unwrap_or_default();
            for operation in operations {
                let _ = writeln!(
                    out,
                    "  {:<width$}  {}",
                    operation_word(family, operation),
                    operation.purpose
                );
            }
            if produces_files(family) {
                out.push_str(&producing_help());
            }
            out.push_str(if produces_files(family) {
                "\nFlags:\n  The destination above is the fallback for an operation that does not \
                 name its own output; every other flag belongs to the operation whose argument it \
                 names.\n\n  -h, --help  Print this help and exit\n"
            } else {
                "\nFlags:\n  None are common to every operation: a flag belongs to the operation \
                 whose argument it names.\n\n  -h, --help  Print this help and exit\n"
            });
        }
        // The family word IS the operation: no operation list below.
        Surface::Standalone(flags) => {
            out.push_str(&running_contract_help(""));
            let _ = write!(out, "\nUsage: {}\n", family_syntax(family));
            if produces_files(family) {
                out.push_str(&producing_help());
            }
            out.push_str("\nFlags:\n");
            out.push_str(&flag_table(flags));
            out.push_str("\n  -h, --help  Print this help and exit\n");
        }
    }
    out.push_str(EXIT_CLASS_HELP);
    out.push_str(OUTPUT_HELP);
    out.push_str(VALUE_FILE_HELP);
    // Where the whole surface is written down: the asset a `reference` operation prints, here and
    // with no instance behind it. The hint names `reference` because that is the operation it
    // means — another locally printed text is not one.
    if publishes_reference(family) {
        let _ = writeln!(
            out,
            "\nEvery action and field in full: run 'mahbot {} reference'.",
            family.word
        );
    }
    out
}

/// Whether `family` has a `reference` operation — the text its help closes by naming.
fn publishes_reference(family: &Family) -> bool {
    matches!(
        family.surface,
        Surface::Operations(operations)
            if operations
                .iter()
                .any(|operation| operation.action == Some(REFERENCE))
    )
}

/// A flag's purpose with the shared vocabulary filled in, from the rules themselves,
/// so the help cannot drift from the schema and the reading.
fn flag_purpose(flag: &Flag) -> String {
    flag.purpose
        .replace(
            "{{pdf_metadata_fields}}",
            &crate::docgen::pdf_metadata_fields_spelled(),
        )
        .replace("{{pdf_date_format}}", crate::docgen::pdf_date_format())
}

/// The flag table of a help: one width-aligned row per flag.
fn flag_rows<'a>(flags: impl IntoIterator<Item = &'a Flag>) -> String {
    let rows: Vec<(String, String)> = flags
        .into_iter()
        .map(|flag| {
            let mut spelling = format!("--{}", flag_spelling(flag.arg));
            match flag.kind {
                FlagKind::Value => spelling.push_str(" <value>"),
                FlagKind::Path
                | FlagKind::UncheckedPath
                | FlagKind::Directory
                | FlagKind::Output => {
                    spelling.push_str(" <path>");
                }
                FlagKind::Number => spelling.push_str(" <number>"),
                FlagKind::List => spelling.push_str(" <value> (repeatable; empty clears the list)"),
                FlagKind::PathList => {
                    spelling.push_str(" <path> (repeatable; empty clears the list)");
                }
                FlagKind::Structured(_) => spelling.push_str(" <json>"),
                FlagKind::Present => spelling.push_str("[=<true|false>]"),
                FlagKind::Destination => spelling.push_str(" <dir>"),
            }
            (spelling, flag_purpose(flag))
        })
        .collect();
    let width = rows
        .iter()
        .map(|(spelling, _)| spelling.len())
        .max()
        .unwrap_or_default();
    let mut out = String::new();
    for (spelling, description) in rows {
        let _ = writeln!(out, "  {spelling:<width$}  {description}");
    }
    out
}

/// A help's flag table: the destination is stated separately, being the command
/// line's own operand, and a table with nothing else in it says so.
fn flag_table(flags: &[Flag]) -> String {
    let flags: Vec<&Flag> = flags
        .iter()
        .filter(|flag| !matches!(flag.kind, FlagKind::Destination))
        .collect();
    if flags.is_empty() {
        return "  none\n".to_string();
    }
    flag_rows(flags)
}

/// `mahbot <word> <operation> -h`: what one operation does and the flags it takes — plus the
/// contract that operation really has, since a caller may enter here: the running product for
/// one carried to it, this command's own answer for a static text.
fn operation_help(family: &Family, operation: &Operation) -> String {
    let word = operation_word(family, operation);
    let mut out = String::new();
    let _ = writeln!(
        out,
        "mahbot {} {} — {}",
        family.word, word, operation.purpose
    );
    let _ = write!(out, "\nUsage: mahbot {} {} [flags]\n", family.word, word);
    if operation
        .flags
        .iter()
        .any(|flag| matches!(flag.kind, FlagKind::Destination))
    {
        out.push_str(&producing_help());
    }
    out.push_str("\nFlags:\n");
    out.push_str(&flag_table(operation.flags));
    // A static text is answered here, so the running contract would promise an instance this
    // operation never asks for.
    let contract = if static_text(operation).is_some() {
        LOCAL_TEXT_CONTRACT_HELP.to_string()
    } else {
        running_contract_help("")
    };
    out.push_str(&contract);
    out.push_str(EXIT_CLASS_HELP);
    out.push_str(OUTPUT_HELP);
    out.push_str(VALUE_FILE_HELP);
    out
}

/// The action whose answer is static text this command prints itself, the way it prints its own
/// help: the one embedded reference asset ([`crate::settings::reference`]), which names every
/// action and field of both settings surfaces.
const REFERENCE: &str = "reference";

/// The action that answers with the product's own README ([`crate::settings::about`]): what the
/// system is, for an assistant that has just met it on another machine.
const ABOUT: &str = "about";

/// The texts this command answers itself, the way it prints its own help.
#[derive(Clone, Copy)]
enum StaticText {
    Reference,
    About,
}

impl StaticText {
    /// The action that publishes this text.
    const fn action(self) -> &'static str {
        match self {
            Self::Reference => REFERENCE,
            Self::About => ABOUT,
        }
    }

    /// The text itself. Both are static, so printing them here is what makes the terminal's bytes
    /// and the tool's the same, and what lets them answer with the product stopped or absent.
    fn text(self) -> &'static str {
        match self {
            Self::Reference => crate::settings::reference(),
            Self::About => crate::settings::about(),
        }
    }
}

/// The static text `operation` answers with — `None` for every operation carried to the running
/// product. The operation itself decides: an answer must not depend on a word elsewhere, or a
/// renamed family would route a text through the instance and fail for want of one.
fn static_text(operation: &Operation) -> Option<StaticText> {
    match operation.action? {
        REFERENCE => Some(StaticText::Reference),
        ABOUT => Some(StaticText::About),
        _ => None,
    }
}

/// What a static text is printed as: its own bytes without the one trailing line break, which
/// [`crate::util::print_stdout`] puts back — so stdout carries the shipped text verbatim.
fn printed_line(text: &str) -> &str {
    text.strip_suffix('\n').unwrap_or(text)
}

/// Run one family's command line, returning the process exit code.
///
/// The product's answer goes to STDOUT exactly as it worded it; everything this
/// command says on its own goes to STDERR, help to stdout, and the exit code is
/// what a script reads ([`Exit`]). An operation's destination is resolved HERE —
/// and only when that operation writes into it — before the environment is probed:
/// it is misuse this command judges by itself, so nothing is sent.
pub async fn run(cli: Cli, args: &[String]) -> i32 {
    let family = cli.0;
    let (mut parsed, flags) = match family.surface {
        Surface::Operations(operations) => {
            let Some(named) = args.first().map(String::as_str) else {
                return misuse(family, "no operation was given");
            };
            if grammar::is_help(named) {
                crate::util::print_stdout(&family_help(family));
                return Exit::Ok.code();
            }
            let Some(operation) = operations
                .iter()
                .find(|operation| operation_word(family, operation) == named)
            else {
                return misuse(family, &format!("unknown operation '{named}'"));
            };
            match parse_flags(operation.action, named, operation.flags, &args[1..]) {
                Ok(Tail::Call(parsed)) => {
                    // Static text — the reference or the README — is answered HERE, the way `-h`
                    // is: no storage root, no lock and no call, and both routes print the same
                    // bytes. The printer's own line break is the one the text already ends with, so
                    // it is neither doubled nor run into the next prompt.
                    if let Some(text) = static_text(operation) {
                        crate::util::print_stdout(printed_line(text.text()));
                        return Exit::Ok.code();
                    }
                    (parsed, operation.flags)
                }
                // A `-h` where a flag could stand is this operation's help — the rule
                // the browser-automation command follows too, turning a would-be usage
                // error into help. Where a VALUE stands it is that value instead (see
                // `parse_flags`): a script must never read success for a run that did not happen.
                Ok(Tail::Help) => {
                    crate::util::print_stdout(&operation_help(family, operation));
                    return Exit::Ok.code();
                }
                Err(reason) => return misuse(family, &reason),
            }
        }
        // The family word IS the operation and the tool takes no `action`, so the
        // first token is already a flag: a bare `mahbot send` sends nothing and the
        // product refuses it as the missing message — a failed operation, since this
        // frontend never judges what the tool requires.
        Surface::Standalone(flags) => match parse_flags(None, family.word, flags, args) {
            Ok(Tail::Call(parsed)) => (parsed, flags),
            Ok(Tail::Help) => {
                crate::util::print_stdout(&family_help(family));
                return Exit::Ok.code();
            }
            Err(reason) => return misuse(family, &reason),
        },
    };
    let tool = family.tool;

    // The picture tool's flags are one generation's settings, and this asks for one
    // picture: it builds that generation itself.
    if tool == "image_gen" {
        fold_one_generation(&mut parsed.args);
    }

    // The destination, like the words: an operation that writes into it takes it from
    // there, and a place it cannot write into is misuse, judged before the probe.
    let output_dir = match destination(flags, &parsed) {
        Ok(dir) => dir,
        Err(reason) => return misuse(family, &reason),
    };

    // These commands act ON the running product and cannot run otherwise, so the
    // storage root and the instance lock are settled before anything is sent.
    let root = match running_root(family).await {
        Ok(root) => root,
        Err(code) => return code,
    };

    let call = CallRequest {
        tool: tool.to_string(),
        args: parsed.args,
        output_dir,
    };
    let decision = verdict(
        family.word,
        crate::db::ipc::ipc_call_with_wait(&root, &call, family.protocol).await,
    );
    if let Some(answer) = decision.answer {
        crate::util::print_stdout(&answer);
    }
    if let Some(diagnostic) = decision.diagnostic {
        crate::util::print_stderr(&diagnostic);
    }
    decision.code.code()
}

/// The running product's storage root, or the class to exit with when there is
/// none to send to.
///
/// The probe is the same fail-closed one `mahbot debug` routes on: an `Unknown`
/// lock is never read as "no instance is running". A FREE lock is not "nothing is
/// running" either — a product restarting or updating itself releases it for the
/// seconds the replacement needs — so it is ridden out over the window the channel
/// itself uses (`MAHBOT_IPC_BOUND_TIMEOUT_SECS`), and only a window that stays
/// free is reported as nothing running.
async fn running_root(family: &Family) -> Result<std::path::PathBuf, i32> {
    let root = match crate::config::default_config_dir() {
        Ok(root) => root,
        Err(e) => {
            crate::util::print_stderr(&format!(
                "mahbot {}: cannot resolve the storage root: {e:#}",
                family.word
            ));
            return Err(Exit::Environment.code());
        }
    };
    let deadline = std::time::Instant::now() + crate::db::ipc::ipc_bound_timeout();
    let mut attempt = 0usize;
    loop {
        match crate::util::lock::instance_lock_state_settled(&root) {
            InstanceLockState::Held => return Ok(root),
            InstanceLockState::Free if std::time::Instant::now() >= deadline => {
                crate::util::print_stderr(&format!(
                    "mahbot {}: no instance is running against {} — these commands act on the \
                     running product: start mahbot and try again",
                    family.word,
                    root.display()
                ));
                return Err(Exit::Environment.code());
            }
            InstanceLockState::Unknown(e) if std::time::Instant::now() >= deadline => {
                crate::util::print_stderr(&format!(
                    "mahbot {}: cannot tell whether a mahbot instance holds {} ({e}) — an \
                     operation is only ever sent to a running product, so none was sent",
                    family.word,
                    root.display()
                ));
                return Err(Exit::Environment.code());
            }
            // Between boots, or a probe that could not settle: wait and look again.
            InstanceLockState::Free | InstanceLockState::Unknown(_) => {}
        }
        tokio::time::sleep(crate::db::ipc::retry_backoff(attempt)).await;
        attempt += 1;
    }
}

/// Report a misuse on STDERR and hand back its class: the reason, then the line
/// that says how to see the right form. Nothing was sent and nothing judged.
fn misuse(family: &Family, reason: &str) -> i32 {
    crate::util::print_stderr(&format!("mahbot {}: {reason}", family.word));
    crate::util::print_stderr(&format!("run 'mahbot {} -h' for usage.", family.word));
    Exit::Usage.code()
}

/// The directory this call's produced files go into, or `None` when it needs none. The destination is
/// the FALLBACK for the place an operation writes into: it is resolved only for an operation that
/// carries it ([`FlagKind::Destination`]), and only when the call left that operation's own output
/// flag ([`FlagKind::Output`]) out — a call that named its output takes the place from there. So
/// nothing is resolved, and nothing can be refused, for a directory that would never be used.
fn destination(flags: &[Flag], parsed: &Parsed) -> Result<Option<String>, String> {
    let names_its_own = flags
        .iter()
        .any(|flag| matches!(flag.kind, FlagKind::Output) && parsed.args.get(flag.arg).is_some());
    let writes_into_it = flags
        .iter()
        .any(|flag| matches!(flag.kind, FlagKind::Destination));
    if !writes_into_it || names_its_own {
        return Ok(None);
    }
    resolve_output_dir(parsed.output_dir.as_deref()).map(Some)
}

/// Resolve a producing command's destination — the `--output-dir` value, or the
/// directory this command was run in — into the absolute directory the produced
/// files go into, or the reason it cannot be used. Shared with the `mahbot chrome` screenshot.
///
/// It is resolved where this command runs, never against the product's working
/// directory; it must already exist (no directory is created for the caller) and
/// must not be a place the product keeps for itself, where a produced file would
/// not stay ([`cleanup_governed`]). Every failure is the caller's misuse, judged
/// before anything is sent. The one gap: a daemon whose temp environment differs
/// from this process's may scan a root this process cannot name
/// ([`crate::temp::cleanup_scan_roots_unpinned`]).
pub(crate) fn resolve_output_dir(named: Option<&str>) -> Result<String, String> {
    let (raw, what) = match named {
        Some(value) => (
            crate::util::expand_tilde(value),
            format!("the destination '{value}'"),
        ),
        None => (
            std::env::current_dir().map_err(|e| {
                format!(
                    "the directory this command was run in cannot be used as the destination: {e}"
                )
            })?,
            "the directory this command was run in".to_string(),
        ),
    };
    let resolved =
        std::fs::canonicalize(&raw).map_err(|e| format!("{what} cannot be used: {e}"))?;
    if !resolved.is_dir() {
        return Err(format!(
            "{what} is not a directory — the destination is the directory the produced files go \
             into"
        ));
    }
    if let Some(place) = cleanup_governed(&resolved) {
        return Err(format!(
            "{what} is {place} — a produced file must go to a directory of your own"
        ));
    }
    // A destination the caller cannot write into is the caller's own to fix, judged
    // here so the exit code says "your invocation" and nothing is sent. `access(2)`
    // answers it on unix without writing into the caller's directory; off unix the
    // product's own refusal is the answer.
    #[cfg(unix)]
    if !crate::util::dir_is_writable(&resolved) {
        return Err(format!("{what} cannot be written into"));
    }
    // The plain spelling, so the value that travels is the one the caller wrote.
    Ok(crate::util::strip_verbatim_prefix(&resolved)
        .to_string_lossy()
        .into_owned())
}

/// The place the product keeps for itself that `dir` lies in, or `None` when the
/// directory is the caller's own to use.
///
/// The roots come from [`crate::temp`] — the module that owns where the product's
/// cleaner may act, so the two cannot disagree — plus its data directory, whose
/// stores, personal-workspace `generated`/`uploads` (swept by its media sweep once a
/// day old) and document-kit scratch are its own. The test is on the RESOLVED path,
/// so a link into one of them is refused all the same ([`crate::util::is_within`]),
/// and a machine's temp area is refused as a whole.
fn cleanup_governed(dir: &std::path::Path) -> Option<&'static str> {
    const DATA_DIR: &str = "the product's own data directory, where it keeps its own files";
    const TEMP: &str = "the product's own temporary area, which its cleanup keeps empty";
    if let Ok(root) = crate::config::default_config_dir() {
        let root = std::fs::canonicalize(&root).unwrap_or(root);
        if crate::util::is_within(dir, &root) {
            return Some(DATA_DIR);
        }
    }
    if crate::temp::cleanup_scan_roots_unpinned()
        .iter()
        .any(|root| crate::util::is_within(dir, root))
    {
        return Some(TEMP);
    }
    None
}

/// What an argument the process cannot read as text is told — the same sentence
/// everywhere, never naming it: the bytes may be a value the caller meant as a secret.
const NON_TEXT_ARGUMENT: &str = "an argument that is not valid text was given — no entry point \
                                 and no value can be read from it, and it is not printed here; \
                                 check what you passed";

/// Refuse an argument the runner cannot read as text, returning this command line's
/// misuse class — needed before the entry point can even be told, since a non-text
/// `argv[1]` names none of them, and the panic the text-only reader raises would
/// break the classes a script reads and print the caller's own bytes.
#[must_use]
pub fn refuse_non_text_argument() -> i32 {
    crate::util::print_stderr(&format!("mahbot: {NON_TEXT_ARGUMENT}"));
    Exit::Usage.code()
}

/// What a first word no entry point has is told. It is never echoed
/// ([`grammar::read_token`]): a first word is as likely a stray secret as a typo.
const UNKNOWN_ENTRY_POINT: &str = "the first word names no entry point of this build — nothing \
                                   was started; run 'mahbot -h' for the commands this build has";

/// Refuse a first word this build has no entry point for, returning this command
/// line's misuse class. It must not fall through to the daemon, where it would start
/// one or report the instance lock instead of the caller's own mistake.
#[must_use]
pub fn refuse_unknown_entry_point() -> i32 {
    crate::util::print_stderr(&format!("mahbot: {UNKNOWN_ENTRY_POINT}"));
    Exit::Usage.code()
}

struct Verdict {
    /// The product's own answer, printed to stdout verbatim — present whenever it answered
    /// the operation itself, a refusal included.
    answer: Option<String>,
    /// This command's own diagnostic, printed to stderr.
    diagnostic: Option<String>,
    code: Exit,
}

/// Classify one attempt at an operation. A pure function of the attempt, so the
/// decision can be read — and tested — with no socket near it.
///
/// An answer the product gave goes to stdout whatever its outcome: the exit code,
/// not the text, says whether the operation happened, and a partial run adds one
/// short diagnostic, so the caller need not read the product's wording for a
/// verdict. An operation never taken on has no answer: the product's wording (or
/// this command's) goes to stderr and the class is the environment's. An exchange
/// severed after the frame went out is NOT the environment's — it may have
/// happened — so it is a failed operation, and the diagnostic states once that the
/// outcome is unknown and that it was deliberately not sent again.
fn verdict(word: &str, attempt: CallAttempt) -> Verdict {
    match attempt {
        CallAttempt::Answered(reply) => match reply.outcome {
            CallOutcome::Done => Verdict {
                answer: Some(reply.answer),
                diagnostic: None,
                code: Exit::Ok,
            },
            CallOutcome::Partial => Verdict {
                answer: Some(reply.answer),
                diagnostic: Some(format!(
                    "mahbot {word}: the product reports the operation was carried out only in \
                     part — its answer above names the part that did not succeed"
                )),
                code: Exit::Failed,
            },
            CallOutcome::Refused => Verdict {
                answer: Some(reply.answer),
                diagnostic: None,
                code: Exit::Failed,
            },
            // A product that did not take the operation on: `Unavailable` reaches the
            // caller as the instance answered it (an unrestricted socket, a failed or
            // unfinished boot, whose sentence says whether a retry may help), and
            // `NotAccepted` is folded into `NotServed` by the wire client. Nothing was
            // answered about the operation itself, so the instance's sentence becomes
            // this command's diagnostic, prefixed like the rest.
            CallOutcome::NotAccepted | CallOutcome::Unavailable => Verdict {
                answer: None,
                diagnostic: Some(format!("mahbot {word}: {}", reply.answer)),
                code: Exit::Environment,
            },
        },
        // Never reached the product: nothing ran, and this command's wording says what
        // to do next.
        CallAttempt::NotServed(reason) => Verdict {
            answer: None,
            diagnostic: Some(format!("mahbot {word}: {reason}")),
            code: Exit::Environment,
        },
        CallAttempt::TooOld => Verdict {
            answer: None,
            diagnostic: Some(format!(
                "mahbot {word}: the running product is older than this command line and cannot \
                 serve its operations — restart it from this build and try again"
            )),
            code: Exit::Environment,
        },
        // Nothing readable came back after the frame went out: the operation may have
        // been carried out, so this is a failed operation, never the environment's —
        // stated ONCE, with the cause in parentheses and no claim about the class.
        CallAttempt::Severed(e) => Verdict {
            answer: None,
            diagnostic: Some(format!(
                "mahbot {word}: the outcome of the operation could not be confirmed, so it may \
                 have been carried out, and it was deliberately NOT sent again ({e:#})"
            )),
            code: Exit::Failed,
        },
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::chrome::contract::OutKind;
    use crate::db::ipc::CallReply;

    /// Every entry point this build has is discoverable from `mahbot -h` — the
    /// families in the derived form ([`family_syntax`]), the rest by their own word —
    /// so none is reachable only by someone who already knew it, `mahbot audio`
    /// above all on a platform where it can only refuse. Resolution is pinned word
    /// by word, so a misrouting is caught here rather than by a run, and both
    /// directions are held: a word with no entry point resolves to nothing and never
    /// falls back to the daemon, which is the one wordless entry.
    #[test]
    fn every_entry_point_resolves_and_is_listed_in_the_top_level_usage() {
        assert!(matches!(entry_point(Some("-h")), Some(EntryPoint::Help)));
        assert!(matches!(
            entry_point(Some("--help")),
            Some(EntryPoint::Help)
        ));
        assert!(matches!(entry_point(Some("-V")), Some(EntryPoint::Version)));
        assert!(matches!(
            entry_point(Some("--version")),
            Some(EntryPoint::Version)
        ));
        assert!(matches!(
            entry_point(Some("paused")),
            Some(EntryPoint::Paused)
        ));
        assert!(matches!(
            entry_point(Some("debug")),
            Some(EntryPoint::Debug)
        ));
        assert!(matches!(
            entry_point(Some("__grep-engine")),
            Some(EntryPoint::GrepEngine)
        ));
        assert!(matches!(
            entry_point(Some("__env-dump")),
            Some(EntryPoint::EnvDump)
        ));
        assert!(matches!(
            entry_point(Some(LOGIN_START_ARG)),
            Some(EntryPoint::LoginStart)
        ));
        assert!(matches!(
            entry_point(Some("bench-openrouter")),
            Some(EntryPoint::BenchOpenRouter)
        ));
        assert!(matches!(
            entry_point(Some("audio")),
            Some(EntryPoint::Audio)
        ));
        assert!(matches!(
            entry_point(Some("chrome")),
            Some(EntryPoint::Chrome)
        ));
        for word in ["paused", "audio", "chrome", "debug", "bench-openrouter"] {
            let entry = format!("  mahbot {word} ");
            assert!(
                TOP_LEVEL_USAGE.lines().any(|line| line.starts_with(&entry)),
                "'mahbot {word}' has no entry in the top-level usage"
            );
        }
        for family in FAMILIES {
            assert!(
                matches!(entry_point(Some(family.word)), Some(EntryPoint::Family(_))),
                "'{}' must resolve to its family",
                family.word
            );
            let entry = format!("  {}", family_syntax(family));
            assert!(
                TOP_LEVEL_USAGE.lines().any(|line| line.starts_with(&entry)),
                "'{entry}' has no entry in the top-level usage"
            );
        }
        assert!(matches!(entry_point(None), Some(EntryPoint::Daemon)));
        assert!(entry_point(Some("frobnicate")).is_none());
    }

    /// The admin Assistant's own toolset — the toolset the command line fronts.
    fn admin_toolset() -> Vec<Box<dyn crate::Tool>> {
        crate::Role::Assistant.tools(
            &crate::workspace::test_ws("test"),
            true,
            std::sync::Arc::new(crate::tools::chrome::ChromeRunSessions::default()),
        )
    }

    fn tool_schema(tool: &str) -> serde_json::Value {
        let tools = admin_toolset();
        crate::tools::find_tool(&tools, tool)
            .unwrap_or_else(|| panic!("the admin Assistant must hold '{tool}'"))
            .parameters_schema()
    }

    /// The action words a tool's schema publishes: its `action` enum, or its `oneOf` keys.
    fn tool_actions(schema: &serde_json::Value) -> Vec<&str> {
        let action = &schema["properties"]["action"];
        if let Some(actions) = action["enum"].as_array() {
            return actions
                .iter()
                .map(|action| action.as_str().expect("action words are strings"))
                .collect();
        }
        action["oneOf"]
            .as_array()
            .unwrap_or_else(|| panic!("the tool states its actions as an enum or a oneOf"))
            .iter()
            .flat_map(|entry| {
                entry["properties"]
                    .as_object()
                    .expect("an action entry names the action")
                    .keys()
                    .map(String::as_str)
            })
            .collect()
    }

    /// Whether a tool's actions declare their OWN arguments (`oneOf`) rather than
    /// sharing one set beside the action (`enum`): only the former sweeps per
    /// operation, the latter stating its arguments once for every action.
    fn declares_per_action_arguments(tool: &str) -> bool {
        tool_schema(tool)["properties"]["action"]
            .get("enum")
            .is_none()
    }

    /// The arguments one command line can fill: the tool's whole top-level set, or —
    /// where actions declare their own — the action's entry plus those beside it.
    fn argument_schema(
        family: &Family,
        operation: &Operation,
    ) -> serde_json::Map<String, serde_json::Value> {
        // The reader is no tool action: its arguments are the two inputs the reading takes.
        if operation.action == Some(DOCUMENT_READ) {
            return ["path", "file_name"]
                .into_iter()
                .map(|name| (name.to_string(), serde_json::json!({ "type": "string" })))
                .collect();
        }
        let schema = tool_schema(family.tool);
        let top = schema["properties"]
            .as_object()
            .expect("the tool's properties")
            .clone();
        let Some(action) = operation.action else {
            return top;
        };
        // An enum-shaped action states only WHICH action runs: its arguments
        // stand beside it at the tool's top level.
        if !declares_per_action_arguments(family.tool) {
            return top.into_iter().filter(|(key, _)| key != "action").collect();
        }
        let entries = schema["properties"]["action"]["oneOf"]
            .as_array()
            .expect("the tool's action entries");
        let entry = entries
            .iter()
            .find_map(|entry| entry["properties"].get(action))
            .unwrap_or_else(|| {
                panic!(
                    "'{}' has no schema entry for action '{action}'",
                    family.tool
                )
            });
        let declared = entry["properties"]
            .as_object()
            .unwrap_or_else(|| panic!("'{action}' must declare its properties"));
        // A root argument an action opts into belongs to that action: keeping the root
        // copy would demand a form for it where the action refuses it.
        let per_action: Vec<&str> = entries
            .iter()
            .flat_map(|entry| entry["properties"].as_object().into_iter())
            .flat_map(|actions| actions.values())
            .flat_map(|action| action["properties"].as_object().into_iter())
            .flat_map(|properties| properties.keys().map(String::as_str))
            .collect();
        let mut args: serde_json::Map<String, serde_json::Value> = top
            .into_iter()
            .filter(|(key, _)| key != "action" && !per_action.contains(&key.as_str()))
            .collect();
        args.extend(declared.clone());
        args
    }

    /// The words appearing more than once in `words` — a registry bug equality hides.
    fn duplicates<'a>(words: impl IntoIterator<Item = &'a str>) -> Vec<&'a str> {
        let mut seen: Vec<&'a str> = Vec::new();
        let mut repeated: Vec<&'a str> = Vec::new();
        for word in words {
            if seen.contains(&word) {
                if !repeated.contains(&word) {
                    repeated.push(word);
                }
            } else {
                seen.push(word);
            }
        }
        repeated
    }

    /// The registry a test parses against: `mahbot <family> <operation>`.
    fn operation(family_word: &str, operation_word: &str) -> &'static Operation {
        let family = family_of(family_word);
        match family.surface {
            Surface::Operations(operations) => operations
                .iter()
                .find(|entry| super::operation_word(family, entry) == operation_word)
                .unwrap_or_else(|| {
                    panic!("no 'mahbot {family_word} {operation_word}' command line")
                }),
            Surface::Standalone(_) => panic!("'mahbot {family_word}' has no operation word"),
        }
    }

    fn family_of(family_word: &str) -> &'static Family {
        family(family_word).map_or_else(
            || panic!("'mahbot {family_word}' is no family"),
            |cli| cli.0,
        )
    }

    fn parse(family_word: &str, operation_word: &str, tokens: &[&str]) -> Result<Tail, String> {
        let operation = operation(family_word, operation_word);
        parse_flags(
            operation.action,
            operation_word,
            operation.flags,
            &tokens.iter().map(ToString::to_string).collect::<Vec<_>>(),
        )
    }

    /// Parse a standalone family's flag tail: no operation word, so it is all flags.
    fn parse_standalone(family_word: &str, tokens: &[&str]) -> Result<Tail, String> {
        let cli =
            family(family_word).unwrap_or_else(|| panic!("'mahbot {family_word}' is no family"));
        let Surface::Standalone(flags) = cli.0.surface else {
            panic!("'mahbot {family_word}' is not a standalone family");
        };
        parse_flags(
            None,
            cli.0.word,
            flags,
            &tokens.iter().map(ToString::to_string).collect::<Vec<_>>(),
        )
    }

    fn parsed(family: &str, operation_word: &str, tokens: &[&str]) -> Parsed {
        match parse(family, operation_word, tokens) {
            Ok(Tail::Call(parsed)) => parsed,
            Ok(Tail::Help) => panic!("'{family} {operation_word}' must not ask for help"),
            Err(e) => panic!("'{family} {operation_word}' must parse: {e}"),
        }
    }

    fn parsed_standalone(family_word: &str, tokens: &[&str]) -> Parsed {
        match parse_standalone(family_word, tokens) {
            Ok(Tail::Call(parsed)) => parsed,
            Ok(Tail::Help) => panic!("'mahbot {family_word}' must not ask for help"),
            Err(e) => panic!("'mahbot {family_word}' must parse: {e}"),
        }
    }

    /// The words are derived and unique: two operations could derive the same word
    /// (an action kebab-cased, a tool's own name with the family word dropped) and
    /// the first would shadow the second in `run`'s lookup. A standalone family has
    /// no operation word at all, and its tool takes no `action`.
    #[test]
    fn every_family_derives_unique_operation_words() {
        for family in FAMILIES {
            let Surface::Operations(operations) = family.surface else {
                assert!(
                    tool_schema(family.tool)["properties"]
                        .get("action")
                        .is_none(),
                    "'{}' publishes no operation, but its tool takes an `action`",
                    family.tool
                );
                continue;
            };
            let words: Vec<String> = operations
                .iter()
                .map(|operation| operation_word(family, operation))
                .collect();
            assert!(
                words.iter().all(|word| !word.is_empty()),
                "'mahbot {}' derives an empty operation word",
                family.word
            );
            assert!(
                duplicates(words.iter().map(String::as_str)).is_empty(),
                "'mahbot {}' derives the same operation word twice, so one would shadow the other",
                family.word
            );
        }
    }

    /// The command line and the tools must agree on what exists, in both directions:
    /// an operation the tool cannot run, an action the command line cannot reach, a
    /// duplicate on either side. A tool taking no `action` has none in the registry
    /// either; the one operation no tool action backs is pinned separately
    /// ([`the_reader_is_the_one_operation_no_tool_backs`]).
    #[test]
    fn operations_match_the_tools_own_actions() {
        for family in FAMILIES {
            let Surface::Operations(operations) = family.surface else {
                continue;
            };
            let tool = family.tool;
            let ours: Vec<Option<&str>> = operations
                .iter()
                // The reader is no tool action: it is pinned in its own test.
                .filter(|operation| operation.action != Some(DOCUMENT_READ))
                .map(|operation| operation.action)
                .collect();
            assert!(
                !ours.is_empty(),
                "'{tool}' is fronted by 'mahbot {}' but no operation runs it",
                family.word
            );
            let schema = tool_schema(tool);
            let taken: Vec<&str> = ours.iter().flatten().copied().collect();
            if taken.is_empty() {
                assert!(
                    schema["properties"].get("action").is_none(),
                    "'{tool}' takes an `action`, so its operations must name one"
                );
                continue;
            }
            assert_eq!(
                taken.len(),
                ours.len(),
                "one of '{tool}'s command lines names an action where another does not"
            );
            let theirs: Vec<&str> = tool_actions(&schema);
            assert!(
                duplicates(taken.iter().copied()).is_empty(),
                "the '{}' command line repeats an action of '{tool}'",
                family.word
            );
            assert!(
                duplicates(theirs.iter().copied()).is_empty(),
                "'{tool}' repeats an action"
            );
            // The command line's surface is the tool's own, action for action — no exception
            // left but the reader, which is filtered out above and pinned in its own test.
            let mut theirs: Vec<String> = theirs.into_iter().map(str::to_string).collect();
            let mut ours: Vec<String> = taken.into_iter().map(str::to_string).collect();
            ours.sort_unstable();
            theirs.sort_unstable();
            assert_eq!(
                ours, theirs,
                "'mahbot {}' must expose exactly the actions of its tool '{tool}'",
                family.word
            );
        }
    }

    /// The reader is the one operation no tool action backs: exactly one operation
    /// names it, the document family's, and the tool publishes no such action.
    #[test]
    fn the_reader_is_the_one_operation_no_tool_backs() {
        let mut readers = Vec::new();
        for family in FAMILIES {
            let Surface::Operations(operations) = family.surface else {
                continue;
            };
            for operation in operations {
                if operation.action == Some(DOCUMENT_READ) {
                    readers.push((family, operation));
                }
            }
        }
        assert_eq!(
            readers.len(),
            1,
            "exactly one operation must name the reader's action"
        );
        let (family, _) = readers[0];
        assert_eq!(
            family.word, "document",
            "the reader belongs to the document family"
        );
        assert_eq!(
            family.tool, "document",
            "the reader is served by the document tool"
        );
        assert!(
            !tool_actions(&tool_schema("document")).contains(&DOCUMENT_READ),
            "the reader must not be an action of the document tool"
        );
    }

    /// A static operation is answered by this command itself — the embedded asset or the README,
    /// printed the way `-h` is printed, so both routes serve the bytes the product ships. Every
    /// other operation is carried to the running product.
    #[test]
    fn static_operations_print_the_embedded_text_locally() {
        // The README is the config family's alone; the reference is both families'. The shipped
        // file is the authority: comparing against the loader that reads it would prove only that
        // the loader is called twice.
        for (word, action, file) in [
            ("config", "reference", "src/prompt/config_reference.md"),
            ("workspace", "reference", "src/prompt/config_reference.md"),
            ("config", "about", "README.md"),
        ] {
            let static_operation = operation(word, action);
            let Some(text) = static_text(static_operation).map(StaticText::text) else {
                panic!("'mahbot {word} {action}' must be answered by this command");
            };
            let shipped = std::fs::read_to_string(format!("{}/{file}", env!("CARGO_MANIFEST_DIR")))
                .unwrap_or_else(|e| panic!("the shipped {file}: {e}"));
            // What the printer is handed, so its own line break does not enter the comparison.
            assert_eq!(
                printed_line(text),
                printed_line(&shipped),
                "'mahbot {word} {action}' prints the shipped text, whole"
            );
            assert!(
                static_operation.flags.is_empty(),
                "'mahbot {word} {action}' takes no flag: the text is the whole answer"
            );
        }
    }

    /// A tool that takes no action is named by its operations from its OWN name
    /// — the family word dropped and the rest kebab-cased — so a sub-command
    /// cannot be spelled a way its tool is not.
    #[test]
    fn action_less_operations_are_named_from_their_tools() {
        for family in FAMILIES {
            let Surface::Operations(operations) = family.surface else {
                continue;
            };
            for operation in operations.iter().filter(|o| o.action.is_none()) {
                let word = operation_word(family, operation);
                let held = word.replace('-', "_");
                assert!(
                    !held.is_empty(),
                    "'mahbot {} {word}' derives no word",
                    family.word
                );
                assert_eq!(
                    family.tool,
                    format!("{}_{held}", family.word),
                    "'mahbot {} {word}' must be its tool '{}' with the family word dropped",
                    family.word,
                    family.tool
                );
            }
        }
    }

    /// One command line of a family, as the tie sweeps it: name, tool, arguments, flags.
    struct CommandLine {
        called: String,
        tool: &'static str,
        arguments: serde_json::Map<String, serde_json::Value>,
        flags: &'static [Flag],
    }

    impl CommandLine {
        /// The schema a flag fills: one of the tool's own, or a generation setting.
        fn property(&self, arg: &str) -> Option<&serde_json::Value> {
            self.arguments.get(arg).or_else(|| {
                self.arguments
                    .get(self.generation()?)?
                    .get("items")?
                    .get("properties")?
                    .get(arg)
            })
        }

        /// The argument holding the picture command's one generation, if this is it.
        fn generation(&self) -> Option<&'static str> {
            (self.tool == "image_gen").then_some(super::GENERATIONS_ARG)
        }

        /// The one generation's declared settings, when the command line builds one.
        fn generation_settings(&self) -> Option<&serde_json::Map<String, serde_json::Value>> {
            self.arguments
                .get(self.generation()?)?
                .get("items")?
                .get("properties")?
                .as_object()
        }
    }

    fn fillable_types(kind: &FlagKind) -> &'static [&'static str] {
        match kind {
            // One string, so it fills a string argument — a path being one it resolves.
            FlagKind::Value
            | FlagKind::Path
            | FlagKind::UncheckedPath
            | FlagKind::Directory
            | FlagKind::Output => &["string"],
            FlagKind::Number => &["integer", "number"],
            // Entries, as an array — each one a path for a path list.
            FlagKind::List | FlagKind::PathList => &["array"],
            // The JSON it is — and, as the text it falls back to, a string.
            FlagKind::Structured(_) => &["array", "object", "string"],
            FlagKind::Present => &["boolean"],
            // The destination is the command line's own; it fills no argument.
            FlagKind::Destination => &[],
        }
    }

    /// A flag kind's own name, for the message a failed tie prints.
    fn flag_kind_name(kind: &FlagKind) -> &'static str {
        match kind {
            FlagKind::Value => "Value",
            FlagKind::Path => "Path",
            FlagKind::UncheckedPath => "UncheckedPath",
            FlagKind::Directory => "Directory",
            FlagKind::Output => "Output",
            FlagKind::Number => "Number",
            FlagKind::List => "List",
            FlagKind::PathList => "PathList",
            FlagKind::Structured(_) => "Structured",
            FlagKind::Present => "Present",
            FlagKind::Destination => "Destination",
        }
    }

    fn argument_types(property: &serde_json::Value) -> Vec<&str> {
        match &property["type"] {
            serde_json::Value::String(kind) => vec![kind.as_str()],
            serde_json::Value::Array(kinds) => kinds
                .iter()
                .map(|kind| kind.as_str().expect("a type word is a string"))
                .collect(),
            _ => Vec::new(),
        }
    }

    /// Every property name a schema subtree declares, at any depth: the fields a
    /// structured value can carry, held against the tool's schema, not a second list.
    fn property_names(schema: &serde_json::Value) -> Vec<String> {
        let mut names = Vec::new();
        match schema {
            serde_json::Value::Object(members) => {
                if let Some(serde_json::Value::Object(properties)) = members.get("properties") {
                    names.extend(properties.keys().cloned());
                }
                for member in members.values() {
                    names.extend(property_names(member));
                }
            }
            serde_json::Value::Array(items) => {
                for item in items {
                    names.extend(property_names(item));
                }
            }
            _ => {}
        }
        names
    }
    /// The property names a schema subtree declares whose own schema IS one of the
    /// tool's picture arguments: such a field names a FILE, so the field tie's other
    /// direction learns which fields the resolution owes. The picture's schema
    /// differs by target, so the whole family is read.
    fn file_naming_fields(
        schema: &serde_json::Value,
        pictures: &[serde_json::Value],
    ) -> Vec<String> {
        let mut names = Vec::new();
        match schema {
            serde_json::Value::Object(members) => {
                if let Some(serde_json::Value::Object(properties)) = members.get("properties") {
                    for (name, property) in properties {
                        if pictures.contains(property) {
                            names.push(name.clone());
                        }
                    }
                }
                for member in members.values() {
                    names.extend(file_naming_fields(member, pictures));
                }
            }
            serde_json::Value::Array(items) => {
                for item in items {
                    names.extend(file_naming_fields(item, pictures));
                }
            }
            _ => {}
        }
        names
    }

    /// The command lines of one family, as the ties sweep them: name, tool, arguments, flags.
    fn command_lines(family: &'static Family) -> Vec<CommandLine> {
        match family.surface {
            Surface::Operations(operations) => operations
                .iter()
                .map(|operation| CommandLine {
                    called: format!("{} {}", family.word, operation_word(family, operation)),
                    tool: family.tool,
                    arguments: argument_schema(family, operation),
                    flags: operation.flags,
                })
                .collect(),
            Surface::Standalone(flags) => {
                let tool = family.tool;
                vec![CommandLine {
                    called: family.word.to_string(),
                    tool,
                    arguments: tool_schema(tool)["properties"]
                        .as_object()
                        .expect("the tool's properties")
                        .clone(),
                    flags,
                }]
            }
        }
    }

    /// No operation repeats a flag. Swept over the registry itself rather than through the tie
    /// below, so every operation is held to it — the tie judges a flag against the tool's own
    /// arguments, which an operation need not have.
    #[test]
    fn no_operation_repeats_a_flag() {
        for family in FAMILIES {
            let Surface::Operations(operations) = family.surface else {
                continue;
            };
            for operation in operations {
                assert!(
                    duplicates(operation.flags.iter().map(|flag| flag.arg)).is_empty(),
                    "'mahbot {} {}' repeats a flag",
                    family.word,
                    operation_word(family, operation)
                );
            }
        }
    }

    /// Every flag must be an argument the tool actually reads, and able to fill that
    /// argument's type — swept per OPERATION, so a flag is judged against its own
    /// operation. The ONE exception is the destination ([`FlagKind::Destination`]),
    /// the command line's own operand: the one flag not looked up among the tool's
    /// arguments, carried by the operations whose own output flag is optional.
    #[test]
    fn flags_stay_tied_to_the_tools_own_arguments() {
        let mut file_fields = 0usize;
        for family in FAMILIES {
            let lines = command_lines(family);
            for line in &lines {
                for flag in line.flags {
                    if matches!(flag.kind, FlagKind::Destination) {
                        continue;
                    }
                    let property = line.property(flag.arg).unwrap_or_else(|| {
                        panic!(
                            "'{}' is not an argument of 'mahbot {}'",
                            flag.arg, line.called
                        )
                    });
                    let kinds = argument_types(property);
                    assert!(
                        fillable_types(&flag.kind)
                            .iter()
                            .any(|fill| kinds.contains(fill)),
                        "the {} flag '{}' cannot fill a {kinds:?} argument of 'mahbot {}'",
                        flag_kind_name(&flag.kind),
                        flag.arg,
                        line.called,
                    );
                    // A structured value's path-bearing fields are swept in BOTH
                    // directions: a field the tool does not have would be a resolution
                    // this frontend invented, and a field the tool builds as one that
                    // NAMES A FILE (its own `image` argument) must be declared here, so
                    // a field added later cannot silently stop being resolved.
                    if let FlagKind::Structured(fields) = &flag.kind {
                        let declared = property_names(property);
                        for field in *fields {
                            assert!(
                                declared.iter().any(|name| name == field),
                                "'{field}' is no field of the '{}' argument of 'mahbot {}'",
                                flag.arg,
                                line.called,
                            );
                        }
                        let naming_a_file =
                            file_naming_fields(property, &crate::tools::document::image_args());
                        file_fields += naming_a_file.len();
                        for field in naming_a_file {
                            assert!(
                                fields.contains(&field.as_str()),
                                "'{field}' of the '{}' argument of 'mahbot {}' names a file, so \
                                 the command line must resolve it — declare it on the flag",
                                flag.arg,
                                line.called,
                            );
                        }
                    }
                }
                // The picture tool's flags fill the one generation its command builds.
                if let Some(declared) = line.generation_settings() {
                    let mut declared: Vec<&str> = declared.keys().map(String::as_str).collect();
                    let mut folded: Vec<&str> = line
                        .flags
                        .iter()
                        .filter(|flag| !matches!(flag.kind, FlagKind::Destination))
                        .map(|flag| flag.arg)
                        .filter(|arg| !line.arguments.contains_key(*arg))
                        .collect();
                    declared.sort_unstable();
                    folded.sort_unstable();
                    assert_eq!(
                        declared, folded,
                        "'mahbot {}' folds its per-generation flags into one generation",
                        line.called
                    );
                }
            }
            // The destination is the fallback for an operation that does not name its own output: a
            // producing family carries at least one, and no operation carries more than one.
            for line in &lines {
                let carried = line
                    .flags
                    .iter()
                    .filter(|flag| matches!(flag.kind, FlagKind::Destination))
                    .count();
                assert!(
                    carried <= 1,
                    "'mahbot {}' carries {carried} destination flags where at most one names the \
                     directory the operation writes into",
                    line.called
                );
            }
            if produces_files(family) {
                assert!(
                    lines.iter().any(|line| line
                        .flags
                        .iter()
                        .any(|flag| matches!(flag.kind, FlagKind::Destination))),
                    "'mahbot {}' produces files, so one of its operations carries the destination",
                    family.word
                );
            }
        }
        // The reverse direction has to have found every one of them, or it would hold
        // vacuously: the document tool's picture stands in a `create` block and in three
        // placing edits — four fields the command line owes a resolution.
        assert!(
            file_fields >= 4,
            "the picture fields naming a file were not all found ({file_fields}) — the tie would \
             be vacuous"
        );
    }

    /// Every argument a tool reads — bar the action — must have a command-line form, so
    /// a new argument cannot arrive with no way to set it. Swept per OPERATION where
    /// actions declare their OWN arguments ([`declares_per_action_arguments`]): a flag
    /// one operation omits is a real hole a union would hide, while where the actions
    /// share one set the union is the right rule.
    #[test]
    fn every_tool_argument_has_a_command_line_form() {
        for family in FAMILIES {
            let lines = command_lines(family);
            let tool = family.tool;
            let strict = declares_per_action_arguments(tool);
            let mut reachable: Vec<&str> = Vec::new();
            let mut declared: Vec<&str> = Vec::new();
            for line in &lines {
                // Its generation argument is this frontend's OWN shape, never a flag.
                let line_reachable: Vec<&str> = line
                    .flags
                    .iter()
                    .filter(|flag| !matches!(flag.kind, FlagKind::Destination))
                    .map(|flag| flag.arg)
                    .chain(line.generation())
                    .collect();
                let line_declared: Vec<&str> = line
                    .arguments
                    .keys()
                    .map(String::as_str)
                    .filter(|key| *key != "action")
                    .chain(line.generation())
                    .collect();
                if strict {
                    for argument in &line_declared {
                        assert!(
                            line_reachable.contains(argument),
                            "'{argument}' of '{tool}' has no command-line form on 'mahbot {}'",
                            line.called
                        );
                    }
                }
                reachable.extend(line_reachable);
                declared.extend(line_declared);
            }
            if !strict {
                for argument in &declared {
                    assert!(
                        reachable.contains(argument),
                        "'{argument}' of '{tool}' has no command-line form on 'mahbot {}'",
                        family.word
                    );
                }
            }
        }
    }

    /// Every family declares a protocol value the listener serves — plain strings in two
    /// modules, so nothing else can see a family sent under an unknown value, whose every
    /// call would come back as an unknown store (see [`crate::db::ipc`]).
    #[test]
    fn every_family_carries_a_protocol_value_the_listener_serves() {
        for cli in FAMILIES {
            assert!(
                crate::db::ipc::CALL_STORES.contains(&cli.protocol),
                "'mahbot {}' carries '{}', which the listener does not serve",
                cli.word,
                cli.protocol
            );
        }
        // Only a family whose surface this build added or changed carries a newer value: one the
        // channel has already served keeps the older value, so a product one build behind still
        // serves it. The lists are the checkpoint for that decision.
        let current: Vec<&str> = FAMILIES
            .iter()
            .filter(|cli| cli.protocol == crate::db::ipc::CALL_STORE)
            .map(|cli| cli.word)
            .collect();
        assert_eq!(
            current,
            vec!["send", "document", "image", "rasterize"],
            "the families the channel's second generation added"
        );
        let changed: Vec<&str> = FAMILIES
            .iter()
            .filter(|cli| cli.protocol == crate::db::ipc::CALL_STORE_VIDEO)
            .map(|cli| cli.word)
            .collect();
        assert_eq!(
            changed,
            vec!["video"],
            "the family whose surface changed after the channel had served it"
        );
        let added: Vec<&str> = FAMILIES
            .iter()
            .filter(|cli| cli.protocol == crate::db::ipc::CALL_STORE_PHOTO)
            .map(|cli| cli.word)
            .collect();
        assert_eq!(
            added,
            vec!["photocraft"],
            "the family added after the channel had served its second generation"
        );
        let settings: Vec<&str> = FAMILIES
            .iter()
            .filter(|cli| cli.protocol == crate::db::ipc::CALL_STORE_SETTINGS)
            .map(|cli| cli.word)
            .collect();
        assert_eq!(
            settings,
            vec!["config", "workspace"],
            "the two families whose surface this build widened — a product built before them \
             would answer a `set` as an unknown action and drop a `set_diagnostics` field"
        );
        // The base generation is served but carried by no family any more: a frontend one build
        // behind still sends it, so the listener must keep answering it.
        assert!(
            FAMILIES
                .iter()
                .all(|cli| cli.protocol != crate::db::ipc::CALL_STORE_BASE),
            "the base generation is served for older frontends only"
        );
    }

    /// The instance serves a tool by NAME only when a family publishes it, so the
    /// owner's other tools are unreachable through the channel however privileged the
    /// socket is. The tools named below are the checkpoint for that.
    #[test]
    fn tools_no_family_publishes_are_not_served_by_name() {
        for tool in ["shell", "edit", "analyze", "say", "report_gap", "show_tab"] {
            assert!(
                !fronts_tool(tool),
                "'{tool}' is published by no family, so the channel must not serve it by name"
            );
        }
    }

    /// A help states the contract its operation really has and the exit classes: the running
    /// product for one carried to it, this command's own answer for a static text.
    fn assert_help_contract(help: &str, is_static: bool) {
        assert!(
            !help.contains("{{"),
            "a help placeholder was not expanded:\n{help}"
        );
        for required in [
            "Exit codes:",
            "0  the operation was carried out",
            "3  this command was misused",
            "Output:",
        ] {
            assert!(
                help.contains(required),
                "'{required}' is missing from:\n{help}"
            );
        }
        // A static text is printed here and must not claim a running product.
        if is_static {
            assert!(
                help.contains("needs no running instance"),
                "a static text's help must say it needs no instance:\n{help}"
            );
            assert!(
                !help.contains("must be running"),
                "a static text's help must not claim a running product:\n{help}"
            );
        } else {
            for required in ["must be running", "owner's authority"] {
                assert!(
                    help.contains(required),
                    "'{required}' is missing from:\n{help}"
                );
            }
        }
    }

    /// Both helps carry the whole contract — a running product, these commands acting with
    /// the owner's authority, the exit classes — so a caller entering through an
    /// operation's help learns no less. A static text is the exception on both: its own help
    /// states that this command answers it, and the family help excepts it where it states
    /// the contract, so neither claims an instance the text does not need. A standalone
    /// family has no operation help, so its family help carries the usage line and every
    /// flag row. The family help also closes by naming the detailed help where the family
    /// publishes a `reference`, and says nothing of one where it does not.
    #[test]
    fn every_help_states_the_contract_it_really_has_and_the_exit_classes() {
        for family in FAMILIES {
            let helps = match family.surface {
                Surface::Operations(operations) => std::iter::once((false, family_help(family)))
                    .chain(operations.iter().map(|operation| {
                        (
                            static_text(operation).is_some(),
                            operation_help(family, operation),
                        )
                    }))
                    .collect(),
                Surface::Standalone(flags) => {
                    let help = family_help(family);
                    let usage = format!("Usage: mahbot {} [flags]", family.word);
                    assert!(help.contains(&usage), "'{usage}' is missing from:\n{help}");
                    for flag in flags {
                        let spelling = format!("--{}", flag_spelling(flag.arg));
                        assert!(
                            help.contains(&spelling),
                            "'{spelling}' has no row in:\n{help}"
                        );
                    }
                    vec![(false, help)]
                }
            };
            for (is_static, help) in &helps {
                assert_help_contract(help, *is_static);
            }
            // The family help states the exception in the sentence that claims the instance: a
            // claim with a static text in the list, contradicted a paragraph later, is false.
            if let Surface::Operations(operations) = family.surface {
                let has_static = operations
                    .iter()
                    .any(|operation| static_text(operation).is_some());
                let claim = helps[0]
                    .1
                    .split("\n\n")
                    .find(|paragraph| paragraph.contains("must be running"))
                    .unwrap_or_default();
                assert_eq!(
                    claim.contains("answers with no instance"),
                    has_static,
                    "'mahbot {}': the texts it prints itself must be excepted where the contract is \
                     stated, not a paragraph later:\n{}",
                    family.word,
                    helps[0].1
                );
            }
            let helps: Vec<&String> = helps.iter().map(|(_, help)| help).collect();
            // The family help closes by naming the detailed help where the family publishes one:
            // the same asset its `reference` operation prints, so a caller reading the operation
            // list learns where every action and field is written down.
            let closing = format!(
                "Every action and field in full: run 'mahbot {} reference'.",
                family.word
            );
            if publishes_reference(family) {
                assert!(
                    helps[0].lines().last() == Some(closing.as_str()),
                    "'mahbot {}' must close its help with '{closing}', got:\n{}",
                    family.word,
                    helps[0]
                );
            } else {
                assert!(
                    !helps[0].contains(&closing),
                    "'mahbot {}' publishes no reference, so its help must not name one:\n{}",
                    family.word,
                    helps[0]
                );
            }
            // A producing family states the destination wherever it applies: the family help always,
            // and an operation's own help exactly when that operation carries one — an operation
            // whose own flag always names where its files go must not advertise a destination it
            // would ignore.
            if produces_files(family) {
                assert!(
                    helps[0].contains("--output-dir <dir>"),
                    "'mahbot {}' produces files without stating the destination in its help",
                    family.word
                );
                if let Surface::Operations(operations) = family.surface {
                    for (operation, help) in operations.iter().zip(&helps[1..]) {
                        let carries = operation
                            .flags
                            .iter()
                            .any(|flag| matches!(flag.kind, FlagKind::Destination));
                        assert_eq!(
                            help.contains("--output-dir <dir>"),
                            carries,
                            "'mahbot {} {}': the destination row must appear exactly when the \
                             operation carries it",
                            family.word,
                            operation_word(family, operation)
                        );
                    }
                }
            }
        }
    }

    /// Every flag kind the grammar admits, typed as the tool's schema declares it and
    /// carried verbatim. An ABSENT flag leaves no key; a value the tool will refuse
    /// travels as written, except a non-boolean switch, which is this command's misuse.
    #[test]
    #[expect(clippy::too_many_lines)] // one section per flag kind, in flag order
    fn parsing_carries_each_value_in_the_type_its_flag_declares() {
        let p = parsed(
            "config",
            "create-custom-role",
            &[
                "--name",
                "triager",
                "--prompt",
                "the whole definition",
                "--tools",
                "analyze:quick,deep",
                "--tools",
                "send",
                "--behavior",
                "one_off",
            ],
        );
        assert_eq!(
            p.args["tools"],
            serde_json::json!(["analyze:quick,deep", "send"])
        );
        assert_eq!(p.args["behavior"], "one_off");
        assert_eq!(p.args["prompt"], "the whole definition");

        // An empty value on a list flag is the EMPTY list; occurrences after it add to it,
        // and an absent flag is still an absence.
        let cleared = parsed(
            "config",
            "update-custom-role",
            &["--name", "triager", "--tools="],
        );
        assert_eq!(cleared.args["tools"], serde_json::json!([]));
        let after = parsed(
            "config",
            "update-custom-role",
            &["--name", "triager", "--tools=", "--tools", "send"],
        );
        assert_eq!(after.args["tools"], serde_json::json!(["send"]));
        let untouched = parsed("config", "update-custom-role", &["--name", "triager"]);
        assert!(untouched.args.get("tools").is_none(), "{}", untouched.args);

        let full = parsed("workspace", "ticket", &["--ticket-id", "proj-7", "--full"]);
        assert_eq!(
            full.args,
            serde_json::json!({"action": "ticket", "ticket_id": "proj-7", "full": true})
        );
        let explicit = parsed(
            "workspace",
            "ticket",
            &["--ticket-id", "proj-7", "--full=true"],
        );
        assert_eq!(explicit.args["full"], serde_json::json!(true));
        let silenced = parsed(
            "video",
            "gen",
            &["--prompt", "a cat", "--generate-audio=false"],
        );
        assert_eq!(
            silenced.args["generate_audio"],
            serde_json::json!(false),
            "a script must be able to ask for the silent clip the tool accepts"
        );
        let loud = parsed("video", "gen", &["--prompt", "a cat", "--generate-audio"]);
        assert_eq!(loud.args["generate_audio"], serde_json::json!(true));
        let silent = parsed("video", "gen", &["--prompt", "a cat"]);
        assert!(
            silent.args.get("generate_audio").is_none(),
            "an absent switch leaves the provider's own default: {}",
            silent.args
        );
        let clipped = parsed("workspace", "ticket", &["--ticket-id", "proj-7"]);
        assert!(
            clipped.args.get("full").is_none(),
            "an absent switch must leave no key: {}",
            clipped.args
        );
        let fleet = parsed("workspace", "pause", &[]);
        assert_eq!(fleet.args, serde_json::json!({"action": "pause"}));
        assert!(
            fleet.args.get("workspace").is_none(),
            "a fleet-wide pause must send no `workspace` key at all: {}",
            fleet.args
        );

        // A non-boolean switch value is misuse, and the reason spells the form.
        let reason = parse(
            "video",
            "gen",
            &["--prompt", "a cat", "--generate-audio=maybe"],
        )
        .err()
        .expect("a switch given a non-boolean is misuse");
        assert!(reason.contains("--generate-audio"), "{reason}");
        assert!(
            reason.contains("=false"),
            "the form is spelled out: {reason}"
        );
        assert!(
            !reason.contains("maybe"),
            "a reason must never carry a value: {reason}"
        );

        let p = parsed(
            "document",
            "pdf-rotate",
            &["--path", "Cargo.toml", "--degrees", "90"],
        );
        assert_eq!(p.args["degrees"], serde_json::json!(90));
        assert!(
            p.args["degrees"].is_number(),
            "a number must travel as one: {}",
            p.args
        );
        let p = parsed("video", "gen", &["--prompt", "a cat", "--seed", "7"]);
        assert_eq!(p.args["seed"], serde_json::json!(7));
        let p = parsed(
            "document",
            "pdf-rotate",
            &["--path", "Cargo.toml", "--degrees", "sideways"],
        );
        assert_eq!(p.args["degrees"], serde_json::json!("sideways"));

        // A structured value travels as its JSON, and one that is no JSON as text.
        let p = parsed(
            "document",
            "create",
            &[
                "--format",
                "pdf",
                "--content",
                r#"[{"type": "paragraph", "text": "hi"}]"#,
            ],
        );
        assert_eq!(p.args["content"][0]["type"], "paragraph");
        let p = parsed(
            "document",
            "fill-template",
            &["--path", "Cargo.toml", "--values", r#"{"name": "Ada"}"#],
        );
        assert_eq!(p.args["values"]["name"], "Ada");
        let p = parsed(
            "document",
            "create",
            &["--format", "pdf", "--content", "not json"],
        );
        assert_eq!(p.args["content"], serde_json::json!("not json"));
    }

    /// Which token is a value is decided by where it stands: after a flag the next
    /// token IS the value, a leading dash and all (a script must never read success
    /// for an operation that did not run), while where a FLAG could stand `-h` asks
    /// for the help.
    #[test]
    fn parsing_decides_values_by_position() {
        let p = parsed("config", "setup-telegram-bot", &["--token", "NNN:AAA"]);
        assert_eq!(p.args["token"], "NNN:AAA");

        // A dash-led value is a value.
        let p = parsed("config", "setup-telegram-bot", &["--token", "-h"]);
        assert_eq!(p.args["token"], "-h");
        let p = parsed("workspace", "board", &["--phase", "--help"]);
        assert_eq!(p.args["phase"], "--help");

        // Where a flag could stand, the help word asks for the help.
        assert!(
            matches!(parse("workspace", "list", &["-h"]), Ok(Tail::Help)),
            "a bare -h where a flag could stand asks for the help"
        );
        assert!(
            matches!(
                parse("workspace", "board", &["--workspace", "w", "--help"]),
                Ok(Tail::Help)
            ),
            "so does one after a flag that already has its value"
        );
    }

    /// Anything this frontend can judge by itself is misuse, its reason naming the flag.
    #[test]
    fn parsing_refuses_misuse_without_echoing_a_value() {
        /// One misuse case: the tokens, the flag its reason names, and the values never echoed.
        struct Case {
            family: &'static str,
            operation: &'static str,
            tokens: &'static [&'static str],
            names: &'static str,
            values: &'static [&'static str],
        }
        let cases = [
            Case {
                family: "workspace",
                operation: "list",
                tokens: &["--nope", "VAL1"],
                names: "--nope",
                values: &["VAL1"],
            },
            Case {
                family: "workspace",
                operation: "list",
                tokens: &["--workspace"],
                names: "--workspace",
                values: &[],
            },
            Case {
                family: "workspace",
                operation: "list",
                tokens: &["VAL3"],
                names: "unexpected argument",
                values: &["VAL3"],
            },
            Case {
                family: "workspace",
                operation: "ticket",
                tokens: &["--ticket-id", "proj-7", "--full=VAL4"],
                names: "--full",
                values: &["VAL4"],
            },
            Case {
                family: "config",
                operation: "grant-tool",
                tokens: &["--user", "VAL5", "--user", "VAL6"],
                names: "--user",
                values: &["VAL5", "VAL6"],
            },
        ];
        for Case {
            family,
            operation: operation_word,
            tokens,
            names,
            values,
        } in cases
        {
            let reason = parse(family, operation_word, tokens)
                .err()
                .unwrap_or_else(|| panic!("'{family} {operation_word}' {tokens:?} must be misuse"));
            assert!(
                reason.contains(names),
                "'{family} {operation_word}' must name '{names}', got: {reason}"
            );
            for value in values {
                assert!(
                    !reason.contains(value),
                    "a usage error must never carry '{value}': {reason}"
                );
            }
        }

        // A secret that was given stays out of the next mistake's reason.
        let reason = parse(
            "config",
            "setup-telegram-bot",
            &["--token", "SEKRIT", "--nope"],
        )
        .err()
        .expect("a stray flag is misuse");
        assert!(
            !reason.contains("SEKRIT"),
            "a usage error must never carry a value: {reason}"
        );
        // Neither is a secret mistyped as a positional: the token is not echoed.
        let reason = parse("config", "setup-telegram-bot", &["SEKRIT"])
            .err()
            .expect("a stray token is misuse");
        assert!(
            !reason.contains("SEKRIT"),
            "a usage error must never carry a token: {reason}"
        );
    }

    /// A value too long for one command line may be given by naming a file: a `List`'s
    /// `@<file>` adds the entries it holds, a structured one's takes its JSON, a text
    /// one's is its text without one trailing line break. `./@…` escapes a value that
    /// begins with `@`, and a flag whose value names a path itself has no file form.
    /// A file it cannot use is misuse, the reason naming the FLAG, never the path; a
    /// value given from a file is the FILE's content.
    #[test]
    fn parsing_reads_a_value_from_a_file_the_caller_names() {
        let dir = crate::util::test::test_root().join("cli-file-values");
        std::fs::create_dir_all(&dir).expect("a place for the value files");

        let list = dir.join("entries.json");
        std::fs::write(&list, r#"["Cargo.toml", "Cargo.lock"]"#).expect("write the entries");
        let from_file = format!("@{}", list.display());
        let p = parsed(
            "document",
            "pdf-merge",
            &["--paths", &from_file, "--paths", "README.md"],
        );
        let here = std::env::current_dir().expect("a working directory");
        let resolved = |name: &str| here.join(name).to_string_lossy().into_owned();
        assert_eq!(
            p.args["paths"],
            serde_json::json!([
                // The entries a file holds are paths, each resolved where this command runs.
                resolved("Cargo.toml"),
                resolved("Cargo.lock"),
                resolved("README.md"),
            ])
        );

        let value = dir.join("values.json");
        std::fs::write(&value, r#"{"name": "Ada"}"#).expect("write the value");
        let from_file = format!("@{}", value.display());
        let p = parsed(
            "document",
            "fill-template",
            &["--path", "Cargo.toml", "--values", &from_file],
        );
        assert_eq!(p.args["values"]["name"], "Ada");

        // A file holding the wrong thing is misuse, the reason never echoing the path.
        let wrong = dir.join("wrong.json");
        std::fs::write(&wrong, r#"{"a": 1}"#).expect("write the wrong shape");
        let from_file = format!("@{}", wrong.display());
        let reason = parse("document", "pdf-merge", &["--paths", &from_file])
            .err()
            .expect("a file that does not hold the entries is misuse");
        assert!(reason.contains("--paths"), "{reason}");
        assert!(
            !reason.contains(wrong.to_string_lossy().as_ref()),
            "a reason must never carry a path value: {reason}"
        );

        let text = crate::util::test::test_root().join("cli-text-values");
        std::fs::create_dir_all(&text).expect("a place for the value files");

        let brief = text.join("brief.txt");
        std::fs::write(&brief, "a cat asleep on a keyboard\n").expect("write the brief");
        let from_file = format!("@{}", brief.display());
        let p = parsed("image", "gen", &["--prompt", &from_file]);
        assert_eq!(p.args["prompt"], "a cat asleep on a keyboard");

        // A value beginning with `@` is written `./@…`: no file is read, existing or not.
        std::fs::write(text.join("alice"), "not the prompt").expect("write a decoy file");
        let decoy = format!("./@{}", text.join("alice").display());
        let p = parsed("image", "gen", &["--prompt", &decoy]);
        assert_eq!(
            p.args["prompt"],
            format!("@{}", text.join("alice").display())
        );

        // A file that is not there is misuse, the reason naming the flag, never the path.
        let missing = format!("@{}", text.join("nothing-here.txt").display());
        let reason = parse("image", "gen", &["--prompt", &missing])
            .err()
            .expect("a file that cannot be read is misuse");
        assert!(reason.contains("--prompt"), "{reason}");
        assert!(
            !reason.contains("nothing-here"),
            "a reason must never carry a path value: {reason}"
        );

        // A value given from a file is the FILE's content, never the spelling that named it.
        let key = text.join("provider-key.txt");
        std::fs::write(&key, "sk-secret-from-a-file\n").expect("write the key");
        let from_file = format!("@{}", key.display());
        let p = parsed(
            "config",
            "setup-web-search",
            &["--provider", "exa", "--key", &from_file],
        );
        assert_eq!(p.args["key"], "sk-secret-from-a-file");

        // A flag whose value names a path itself takes no file form.
        let named = text.join("@report.pdf");
        std::fs::write(&named, "not a pdf").expect("write a file whose name begins with @");
        let p = parsed(
            "document",
            "pdf-rotate",
            &["--path", &named.to_string_lossy(), "--degrees", "90"],
        );
        assert_eq!(p.args["path"], named.to_string_lossy().as_ref());
        let p = parsed(
            "document",
            "create",
            &["--format", "pdf", "--output-dir", "@mine"],
        );
        assert_eq!(p.output_dir.as_deref(), Some("@mine"));

        // A missing file, last of all, is misuse naming the flag.
        let missing = format!("@{}", dir.join("nothing-here.json").display());
        let reason = parse("document", "pdf-merge", &["--paths", &missing])
            .err()
            .expect("a file that cannot be read is misuse");
        assert!(reason.contains("--paths"), "{reason}");
    }

    /// A flag that names a FILE carries the path the CALLER meant: `~` expanded against
    /// the home directory, a relative path resolved in this command's directory — the
    /// product's own working directory would name a different file. A value that names
    /// no file, an absolute path and a public URL are left as written.
    #[test]
    fn parsing_resolves_a_path_where_the_command_runs() {
        let here = std::env::current_dir().expect("a working directory");
        let relative = |name: &str| here.join(name).to_string_lossy().into_owned();
        let absolute = relative("Cargo.toml");

        let p = parsed(
            "document",
            "pdf-rotate",
            &["--path", "Cargo.toml", "--degrees", "90"],
        );
        assert_eq!(p.args["path"], serde_json::json!(absolute));

        let p = parsed(
            "document",
            "pdf-merge",
            &["--paths", "Cargo.toml", "--paths", &absolute],
        );
        assert_eq!(p.args["paths"][0], absolute);
        assert_eq!(
            p.args["paths"][1], absolute,
            "an absolute path stays as it is"
        );

        // A flag whose value may be a URL leaves a URL alone.
        let p = parsed(
            "video",
            "gen",
            &[
                "--prompt",
                "restyle it",
                "--video-url",
                "https://example.test/clip.mp4",
                "--images",
                "Cargo.toml",
            ],
        );
        assert_eq!(p.args["video_url"], "https://example.test/clip.mp4");
        assert_eq!(p.args["images"][0], relative("Cargo.toml"));

        // `~` is the home directory: a bare `~` is one, a reference file must be a file.
        if let Ok(home) = std::env::var("HOME") {
            let resolved = resolve_output_dir(Some("~")).expect("the home directory is usable");
            assert_eq!(
                resolved.trim_end_matches('/'),
                crate::util::strip_verbatim_prefix(
                    &std::fs::canonicalize(&home).expect("the home directory resolves")
                )
                .to_string_lossy()
                .trim_end_matches('/'),
                "a bare ~ is the home directory"
            );
        }

        // A name is not a path, and a plain value is not one either.
        let p = parsed(
            "document",
            "create",
            &["--format", "docx", "--file-name", "report"],
        );
        assert_eq!(p.args["file_name"], "report");
        let p = parsed("image", "gen", &["--prompt", "a cat by a window"]);
        assert_eq!(p.args["prompt"], "a cat by a window");
    }

    /// A path that need not exist yet — the photocraft family's, whose `run` output and `batch`
    /// folders are destinations rather than references — resolves exactly where the command runs,
    /// and demands nothing of the filesystem: the tool judges what it was handed.
    #[test]
    fn a_destination_path_need_not_exist_and_resolves_where_the_command_runs() {
        let here = std::env::current_dir().expect("a working directory");
        let relative = |name: &str| here.join(name).to_string_lossy().into_owned();

        let p = parsed(
            "photocraft",
            "run",
            &["--input", "Cargo.toml", "--output", "out.png"],
        );
        assert_eq!(p.args["output"], relative("out.png"));
        // The input of a batch is a folder, so it takes the same unchecked resolution.
        let p = parsed(
            "photocraft",
            "batch",
            &["--input", "photos", "--output", "out", "--format", "png"],
        );
        assert_eq!(p.args["input"], relative("photos"));
        assert_eq!(p.args["output"], relative("out"));
        // An http(s) address is no path to resolve, in either kind.
        let p = parsed(
            "photocraft",
            "inspect",
            &["--input", "https://example.com/a.png"],
        );
        assert_eq!(p.args["input"], "https://example.com/a.png");
        // An absolute path and `~` are resolved the same way here as everywhere.
        let absolute = relative("plate.psd");
        let p = parsed("photocraft", "inspect", &["--input", &absolute]);
        assert_eq!(p.args["input"], absolute);
        if let Ok(home) = std::env::var("HOME") {
            let p = parsed("photocraft", "run", &["--output", "~/out.png"]);
            assert_eq!(
                p.args["output"],
                std::path::Path::new(&home)
                    .join("out.png")
                    .to_string_lossy()
                    .into_owned()
            );
        }
    }

    /// The destination is the fallback for the place an operation writes into, and it is resolved only
    /// where it would be used: an operation that writes no file of its own carries none, one whose own
    /// output flag always names where its files go carries none, and one whose own flag is optional
    /// takes the place from it when it is given — so a directory this command could not write into is
    /// no refusal for any of them.
    #[test]
    fn a_destination_is_resolved_only_for_the_operation_that_writes_into_it() {
        let flags = |word: &str| -> &'static [Flag] {
            let cli = super::family("photocraft").expect("the photocraft family");
            let family = cli.0;
            let Surface::Operations(operations) = family.surface else {
                panic!("photocraft lists its operations");
            };
            operations
                .iter()
                .find(|operation| super::operation_word(family, operation) == word)
                .expect("the operation")
                .flags
        };
        // Neither of these writes a file, so no destination is resolved for them.
        let p = parsed("photocraft", "commands", &[]);
        assert!(
            destination(flags("commands"), &p)
                .expect("nothing is judged")
                .is_none()
        );
        let p = parsed("photocraft", "inspect", &["--input", "Cargo.toml"]);
        assert!(
            destination(flags("inspect"), &p)
                .expect("nothing is judged")
                .is_none()
        );
        // A batch's own flag always names the folder it writes into, so it carries no destination.
        let p = parsed(
            "photocraft",
            "batch",
            &["--input", "src", "--output", "out", "--format", "png"],
        );
        assert!(
            destination(flags("batch"), &p)
                .expect("nothing is judged")
                .is_none()
        );
        // `run` names its file itself when it is given one: the destination would never be used.
        let p = parsed(
            "photocraft",
            "run",
            &["--input", "Cargo.toml", "--output", "out.png"],
        );
        assert!(
            destination(flags("run"), &p)
                .expect("nothing is judged")
                .is_none()
        );
        // Without it, a fresh file lands in the destination, which is where this command runs.
        let p = parsed("photocraft", "run", &["--input", "Cargo.toml"]);
        assert!(
            destination(flags("run"), &p)
                .expect("the working directory is the destination")
                .is_some(),
            "a fresh output needs a directory"
        );
        // A place the product keeps for itself is refused only where it would be used: with the
        // output named by the operation's own flag, the same place is never resolved.
        let governed = std::env::temp_dir();
        if governed.is_dir() {
            let named = governed.to_string_lossy().into_owned();
            let p = parsed(
                "photocraft",
                "run",
                &[
                    "--input",
                    "Cargo.toml",
                    "--output",
                    "out.png",
                    "--output-dir",
                    &named,
                ],
            );
            assert!(
                destination(flags("run"), &p)
                    .expect("nothing is judged")
                    .is_none()
            );
            let p = parsed(
                "photocraft",
                "run",
                &["--input", "Cargo.toml", "--output-dir", &named],
            );
            let reason = destination(flags("run"), &p).expect_err("a governed place is refused");
            assert!(reason.contains("temporary area"), "{reason}");
        }
    }

    /// The picture family's flat flags become the one generation it asks for: the
    /// settings go inside the generation, the prompt beside the list, and a flag left
    /// out is left out of the generation rather than sent flat for the tool to ignore.
    #[test]
    fn the_picture_family_folds_its_flags_into_one_generation() {
        let mut args = serde_json::json!({
            "prompt": "retouch the defects",
            "images": ["reference.png"],
            "size": "1K",
        });
        super::fold_one_generation(&mut args);
        assert_eq!(args["prompt"], "retouch the defects");
        assert!(
            args.get("images").is_none() && args.get("size").is_none(),
            "no setting stays a flat argument the tool would ignore: {args}"
        );
        let generations = args[crate::cli::GENERATIONS_ARG]
            .as_array()
            .expect("the batch form");
        assert_eq!(generations.len(), 1, "one picture is a batch of one");
        assert_eq!(generations[0]["images"][0], "reference.png");
        assert_eq!(generations[0]["size"], "1K");
        assert!(
            generations[0].get("aspect_ratio").is_none(),
            "a flag left out is unset in the generation: {}",
            generations[0]
        );

        // A call carrying no setting is still one generation: all optional, none invented.
        let mut bare = serde_json::json!({ "prompt": "a cat" });
        super::fold_one_generation(&mut bare);
        assert_eq!(bare["generations"][0], serde_json::json!({}), "{bare}");
    }

    /// A path a STRUCTURED value carries resolves exactly like a `--path` value, since
    /// the product resolves an embedded image against its own directories — and a field
    /// that names no file is the caller's own text.
    #[test]
    fn parsing_resolves_a_path_inside_a_structured_value() {
        let here = std::env::current_dir().expect("a working directory");
        let joined = here.join("Cargo.toml").to_string_lossy().into_owned();

        // The image a create's own block embeds, and the one an edit places.
        let p = parsed(
            "document",
            "create",
            &[
                "--format",
                "docx",
                "--content",
                r#"[{"type": "paragraph", "text": "hi"}, {"type": "image", "image": "Cargo.toml"}]"#,
            ],
        );
        assert_eq!(p.args["content"][0].get("image"), None);
        assert_eq!(p.args["content"][1]["image"], serde_json::json!(joined));

        let p = parsed(
            "document",
            "pptx-edit",
            &[
                "--path",
                "Cargo.toml",
                "--edits",
                r#"[{"op": "add_image", "slide": 1, "image": "Cargo.toml"}]"#,
            ],
        );
        assert_eq!(p.args["edits"][0]["image"], serde_json::json!(joined));

        let p = parsed(
            "document",
            "docx-edit",
            &[
                "--path",
                "Cargo.toml",
                "--edits",
                r#"[{"op": "add_image", "after": "x", "image": "Cargo.toml"}]"#,
            ],
        );
        assert_eq!(p.args["edits"][0]["image"], serde_json::json!(joined));

        // A URL is left to the product, which is the one that can fetch it.
        let p = parsed(
            "document",
            "create",
            &[
                "--format",
                "docx",
                "--content",
                r#"[{"type": "image", "image": "https://example.test/picture.png"}]"#,
            ],
        );
        assert_eq!(
            p.args["content"][0]["image"],
            "https://example.test/picture.png"
        );

        // A field no file stands under is a plain value: a path-like cell is caller text.
        let p = parsed(
            "document",
            "create",
            &[
                "--format",
                "xlsx",
                "--sheets",
                r#"[{"name": "S", "rows": [["generated/logo.png"]]}]"#,
            ],
        );
        assert_eq!(p.args["sheets"][0]["rows"][0][0], "generated/logo.png");

        // A reference file inside a value that is missing is misuse, naming the flag.
        let reason = parse(
            "document",
            "create",
            &[
                "--format",
                "docx",
                "--content",
                r#"[{"type": "image", "image": "no-such-picture-here.png"}]"#,
            ],
        )
        .err()
        .expect("a missing reference file inside a value is misuse");
        assert!(reason.contains("--content"), "{reason}");
        assert!(!reason.contains("no-such-picture-here"), "{reason}");
    }

    /// A file the caller names — a reference path, a path inside a structured value, a file
    /// a value is read from — must be a REGULAR file it can read: a pipe would hold the
    /// command forever (neither the parse nor the product has a timeout), an endless device
    /// would exhaust memory, and a value file far past any command line is a mistaken path.
    /// All of it is judged before anything is sent, naming the FLAG and never the path.
    #[test]
    #[expect(clippy::too_many_lines)] // one section per way a named file can be unusable
    fn the_file_the_caller_names_must_be_a_regular_file_it_can_read() {
        let reason = parse(
            "document",
            "pdf-rotate",
            &["--path", "./no-such-file-here.pdf"],
        )
        .err()
        .expect("a missing reference file is misuse");
        assert!(reason.contains("--path"), "{reason}");
        assert!(
            !reason.contains("no-such-file-here"),
            "a reason must never carry a path value: {reason}"
        );

        let reason = parse(
            "document",
            "pdf-merge",
            &[
                "--paths",
                "Cargo.toml",
                "--paths",
                "./no-such-file-here.pdf",
            ],
        )
        .err()
        .expect("one missing entry of a path list is misuse");
        assert!(reason.contains("--paths"), "{reason}");

        // A URL is not a path at all.
        let p = parsed(
            "video",
            "gen",
            &[
                "--prompt",
                "restyle",
                "--video-url",
                "https://example.test/x.mp4",
            ],
        );
        assert_eq!(p.args["video_url"], "https://example.test/x.mp4");

        // Something that exists but is no regular file is misuse: only metadata is read.
        let dir = crate::util::test::test_root().join("cli-reference-not-a-file");
        std::fs::create_dir_all(&dir).expect("a directory that is no reference file");
        let reason = parse(
            "document",
            "pdf-rotate",
            &["--path", &dir.to_string_lossy()],
        )
        .err()
        .expect("a directory is not a reference file");
        assert!(reason.contains("--path"), "{reason}");
        assert!(reason.contains("regular file"), "{reason}");
        assert!(
            !reason.contains("cli-reference-not-a-file"),
            "a reason must never carry a path value: {reason}"
        );

        // The same rule for a file a VALUE is read from, with a bound on its size since a
        // value travels as one argument.
        let values = crate::util::test::test_root().join("cli-value-file-guards");
        std::fs::create_dir_all(&values).expect("a place for the guard fixtures");
        let reason = parse(
            "image",
            "gen",
            &["--prompt", &format!("@{}", values.display())],
        )
        .err()
        .expect("a directory is misuse");
        assert!(reason.contains("--prompt"), "{reason}");
        assert!(reason.contains("regular file"), "{reason}");

        let huge = values.join("huge.txt");
        std::fs::File::create(&huge)
            .and_then(|file| file.set_len(MAX_VALUE_FILE_BYTES + 1))
            .expect("a sparse file past the bound");
        let reason = parse(
            "image",
            "gen",
            &["--prompt", &format!("@{}", huge.display())],
        )
        .err()
        .expect("a value file past the bound is misuse");
        assert!(reason.contains("over 8 MB"), "{reason}");

        #[cfg(unix)]
        {
            // A pipe would block the read until something writes it.
            let fifo = dir.join("clip.mp4");
            let _ = std::fs::remove_file(&fifo);
            let path = std::ffi::CString::new(fifo.to_string_lossy().as_bytes())
                .expect("a path without a NUL");
            // SAFETY: `mkfifo` takes a NUL-terminated path and a mode.
            if unsafe { libc::mkfifo(path.as_ptr(), 0o600) } == 0 {
                let reason = parse("video", "gen", &["--video-url", &fifo.to_string_lossy()])
                    .err()
                    .expect("a pipe is not a reference file");
                assert!(reason.contains("regular file"), "{reason}");
                // The structured fields a value carries are held to it too.
                let content = format!(
                    r#"[{{"type": "image", "image": "{}"}}]"#,
                    fifo.to_string_lossy()
                );
                let reason = parse(
                    "document",
                    "create",
                    &["--format", "docx", "--content", &content],
                )
                .err()
                .expect("a pipe inside a value is no reference file either");
                assert!(reason.contains("--content"), "{reason}");
                assert!(reason.contains("regular file"), "{reason}");

                // A pipe a VALUE would be read from is refused the same way.
                let value_fifo = values.join("value.fifo");
                let _ = std::fs::remove_file(&value_fifo);
                let path = std::ffi::CString::new(value_fifo.to_string_lossy().as_bytes())
                    .expect("a path without a NUL");
                // SAFETY: `mkfifo` takes a NUL-terminated path and a mode.
                if unsafe { libc::mkfifo(path.as_ptr(), 0o600) } == 0 {
                    let reason = parse(
                        "image",
                        "gen",
                        &["--prompt", &format!("@{}", value_fifo.display())],
                    )
                    .err()
                    .expect("a pipe is misuse");
                    assert!(reason.contains("regular file"), "{reason}");
                }
            }
            // An endless device would read until memory runs out.
            let reason = parse("image", "gen", &["--prompt", "@/dev/zero"])
                .err()
                .expect("a device is misuse");
            assert!(reason.contains("regular file"), "{reason}");
        }
    }

    /// The destination is resolved on this machine, in the directory this command was run
    /// in: a missing one, or one that is no directory, is misuse, and one the product
    /// keeps for itself is refused however it is spelled.
    #[test]
    fn the_destination_is_resolved_and_the_products_own_places_are_refused() {
        // The default destination is the directory this command was run in. A tree under a
        // governed root is refused like any other place — the rule is about the PLACE — so
        // the default and the same directory named explicitly agree.
        let cwd = std::env::current_dir().expect("a working directory");
        let cwd_string = cwd.to_string_lossy().into_owned();
        let named = resolve_output_dir(Some(&cwd_string)).ok();
        assert_eq!(resolve_output_dir(None).ok(), named);
        if let Some(resolved) = named {
            assert_eq!(
                resolved,
                crate::util::strip_verbatim_prefix(
                    &std::fs::canonicalize(&cwd).expect("the working directory canonicalizes")
                )
                .to_string_lossy()
                .into_owned()
            );
        }

        // A destination that is not there is misuse, never created.
        let absent = crate::util::test::test_root().join("no-such-destination");
        let reason = resolve_output_dir(Some(&absent.to_string_lossy()))
            .expect_err("a missing destination is misuse");
        assert!(reason.contains("cannot be used"), "{reason}");
        assert!(!absent.exists(), "the command must create no directory");

        // A destination that is a file is misuse: it is not a directory.
        let file = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("Cargo.toml");
        let reason = resolve_output_dir(Some(&file.to_string_lossy()))
            .expect_err("a file is not a destination");
        assert!(reason.contains("is not a directory"), "{reason}");

        // The product's own temporary area, however it is spelled — a link into it is
        // refused too. The check is on the RESOLVED path, so a machine without the area
        // has nothing to refuse.
        let temp = std::env::temp_dir();
        if temp.is_dir() {
            let reason = resolve_output_dir(Some(&temp.to_string_lossy()))
                .expect_err("the product's temporary area is refused");
            assert!(reason.contains("temporary area"), "{reason}");
            #[cfg(unix)]
            {
                let link = crate::util::test::test_root().join("cli-destination-link");
                let _ = std::fs::remove_file(&link);
                if std::os::unix::fs::symlink(&temp, &link).is_ok() {
                    let reason = resolve_output_dir(Some(&link.to_string_lossy()))
                        .expect_err("a path resolving into it is refused too");
                    assert!(reason.contains("temporary area"), "{reason}");
                }
            }
        }

        // The product's own data directory, and everything under it. The rule is asserted
        // without the filesystem: a machine without the directory has nothing resolvable
        // inside it, not a usable destination.
        let data = crate::config::default_config_dir().expect("the storage root resolves");
        let inside = data.join("somewhere");
        assert!(
            cleanup_governed(&inside).is_some(),
            "the product's own data directory is refused"
        );
        if data.is_dir() {
            let reason = resolve_output_dir(Some(&data.to_string_lossy()))
                .expect_err("the product's data directory is refused");
            assert!(reason.contains("data directory"), "{reason}");
        }
    }

    /// A family whose tool takes no `action`: the family word IS the operation.
    #[test]
    fn a_family_with_no_actions_is_its_own_operation() {
        let sent = parsed_standalone(
            "send",
            &[
                "--message",
                "do the thing",
                "--addressee",
                "manager",
                "--place",
                "proj",
            ],
        );
        assert_eq!(
            sent.args,
            serde_json::json!({
                "message": "do the thing",
                "addressee": "manager",
                "place": "proj",
            })
        );
        assert!(
            sent.args.get("branch").is_none(),
            "an absent flag leaves no key: {}",
            sent.args
        );

        // The required flags are the tool's judgement: a bare family word sends no key.
        assert_eq!(parsed_standalone("send", &[]).args, serde_json::json!({}));
    }

    /// The exit classes are the browser-automation command's own numbering, class for
    /// class, and asserted against that table rather than restated, so the two cannot
    /// drift into a second table for a script to learn.
    #[test]
    fn exit_classes_match_the_browser_automation_command() {
        /// The class each of the other command's kinds belongs to, matched exhaustively.
        fn class_of(kind: OutKind) -> Exit {
            match kind {
                OutKind::Ok | OutKind::Empty => Exit::Ok,
                OutKind::Timeout
                | OutKind::Network
                | OutKind::Redesign
                | OutKind::NotFound
                | OutKind::Error => Exit::Failed,
                OutKind::Environment | OutKind::Conflict => Exit::Environment,
                OutKind::Usage => Exit::Usage,
            }
        }

        for kind in [
            OutKind::Ok,
            OutKind::Empty,
            OutKind::Timeout,
            OutKind::Network,
            OutKind::Redesign,
            OutKind::NotFound,
            OutKind::Error,
            OutKind::Environment,
            OutKind::Usage,
            OutKind::Conflict,
        ] {
            assert_eq!(
                kind.exit_code(),
                class_of(kind).code(),
                "OutKind::{} must keep its class",
                kind.as_str()
            );
        }
    }

    /// What one attempt becomes: where each part goes and the class a script reads.
    #[test]
    fn attempt_decisions_map_to_the_documented_streams_and_exit_codes() {
        let done = verdict(
            "config",
            CallAttempt::Answered(CallReply::done("token saved")),
        );
        assert_eq!(done.answer.as_deref(), Some("token saved"));
        assert_eq!(done.diagnostic, None);
        assert_eq!(done.code, Exit::Ok);

        let refused = verdict(
            "config",
            CallAttempt::Answered(CallReply::refused("no such user 'bob'")),
        );
        assert_eq!(refused.answer.as_deref(), Some("no such user 'bob'"));
        assert_eq!(refused.diagnostic, None, "a refusal needs no note of ours");
        assert_eq!(refused.code, Exit::Failed);

        let partial = verdict(
            "workspace",
            CallAttempt::Answered(CallReply::partial("froze 2 of 3")),
        );
        assert_eq!(partial.answer.as_deref(), Some("froze 2 of 3"));
        assert!(
            partial.diagnostic.is_some(),
            "a partly carried-out operation needs its own note"
        );
        assert_eq!(partial.code, Exit::Failed);

        // The two the wire client should never hand over: not taken on, sentence to stderr.
        for reply in [
            CallReply::not_accepted("still starting"),
            CallReply::unavailable("cannot serve operations"),
        ] {
            let wording = reply.answer.clone();
            let decision = verdict("workspace", CallAttempt::Answered(reply));
            assert_eq!(decision.answer, None);
            assert_eq!(
                decision.diagnostic.as_deref(),
                Some(format!("mahbot workspace: {wording}").as_str())
            );
            assert_eq!(decision.code, Exit::Environment);
        }

        let not_served = verdict(
            "workspace",
            CallAttempt::NotServed("no endpoint".to_string()),
        );
        assert_eq!(not_served.answer, None);
        assert_eq!(
            not_served.diagnostic.as_deref(),
            Some("mahbot workspace: no endpoint"),
            "a diagnostic of ours names this command"
        );
        assert_eq!(not_served.code, Exit::Environment);

        let too_old = verdict("workspace", CallAttempt::TooOld);
        assert_eq!(too_old.answer, None);
        assert!(
            too_old
                .diagnostic
                .as_deref()
                .is_some_and(|line| line.contains("older") && line.contains("restart")),
            "a too-old product must say what to do: {:?}",
            too_old.diagnostic
        );
        assert_eq!(too_old.code, Exit::Environment);

        let severed = verdict(
            "workspace",
            CallAttempt::Severed(anyhow::anyhow!("the answer could not be read")),
        );
        assert_eq!(severed.answer, None);
        let line = severed.diagnostic.as_deref().expect("a diagnostic");
        assert!(
            line.contains("could not be confirmed") && line.contains("NOT sent again"),
            "an unconfirmed outcome must say plainly what is unknown: {line}"
        );
        assert_eq!(
            line.matches("sent again").count(),
            1,
            "the conclusion is stated once, with the cause beside it: {line}"
        );
        assert_eq!(severed.code, Exit::Failed);
    }

    /// Misuse is exit 3, decided before the environment is touched: no instance here.
    #[tokio::test]
    async fn misuse_is_exit_3_before_the_environment_is_probed() {
        let invocations: [&[&str]; 12] = [
            &["config"],
            &["config", "no-such-operation"],
            &["workspace", "list", "--nope", "x"],
            &["workspace", "list", "--workspace"],
            &["workspace", "list", "proj"],
            &["send", "--nope"],
            &["document"],
            &["document", "no-such-operation"],
            &["image", "gen", "--nope"],
            &["video", "gen", "--prompt"],
            // The destination is judged here too: a place that is not there is misuse.
            &[
                "image",
                "gen",
                "--prompt",
                "x",
                "--output-dir",
                "/no/such/place",
            ],
            // A family that produces nothing does not take the destination.
            &["workspace", "list", "--output-dir", "/tmp"],
        ];
        for invocation in invocations {
            let args = invocation
                .iter()
                .map(ToString::to_string)
                .collect::<Vec<_>>();
            let cli =
                family(&args[0]).unwrap_or_else(|| panic!("'{}' must be a family word", args[0]));
            let code = run(cli, &args[1..]).await;
            assert_eq!(code, Exit::Usage.code(), "{invocation:?}");
        }
    }
}