knowyourbusiness 0.3.4

Git-backed, searchable knowledge base and incident tracker for AI agent fleets
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
/*
 * KYB (Know Your Business) — git-backed knowledge base for AI agent fleets
 * Copyright (c) 2026 Alexander Panasenko
 *
 * Contact: alex@prod.codes
 * Author: https://prod.codes/about/
 * Project: https://github.com/alex09x/kyb
 * SPDX-License-Identifier: MIT
 */

mod audit;
mod auth;
mod brief;
mod brief_api;
mod config;
mod confident;
mod confident_api;
mod confident_index;
mod deadline;
mod deadline_api;
mod embed;
mod export;
mod index;
mod links;
mod mcp;
mod model;
mod store;
mod web;
#[cfg(test)]
mod tag_regressions;

use anyhow::Result;
use axum::extract::rejection::QueryRejection;
use axum::extract::{FromRequestParts, Path, Query, State};
use axum::response::{IntoResponse, Response};
use axum::http::StatusCode;
use axum::middleware;
use axum::routing::{get, post};
use axum::{Json, Router};
use serde::Deserialize;
use serde_json::{json, Value};
use std::collections::HashSet;
use std::net::SocketAddr;
use std::sync::Arc;
use tantivy::IndexWriter;
use tokio::sync::Mutex;

pub struct AppState {
    store: store::Store,
    index: index::SearchIndex,
    audit: audit::Audit,
    /// Vectors + model; None when no model is installed (lexical-only mode).
    semantic: Option<embed::Semantic>,
    /// One lock for ALL writes: Tantivy allows a single IndexWriter and git
    /// commits are strictly sequential anyway. Search takes no locks.
    writer: Mutex<IndexWriter>,
    pub(crate) audit_path: std::path::PathBuf,
    /// An entry's history is a walk over every commit in the repository; with
    /// thousands of them that is close to a second per request, and the UI asks
    /// for it on every card. One index of every key's versions, built by one walk
    /// at start and extended by the commits since whenever HEAD has moved.
    history_index: std::sync::Mutex<Option<Arc<store::HistoryIndex>>>,
    /// Bumped by every write. The link index remembers the generation it was
    /// built at and is rebuilt once that no longer matches; a build that began
    /// before a write therefore never installs its pre-write answer. (The
    /// history index does not use it: a commit moves HEAD, and that is its test.)
    history_gen: std::sync::atomic::AtomicU64,
    /// Relations between entries, derived from the repository. Kept until the
    /// next write (the generation it was built at no longer matches).
    links_cache: std::sync::Mutex<Option<LinksCache>>,
    /// Keys archived since the link index last took note. A key can be filed and
    /// closed between two builds, so comparing trees alone would miss it.
    /// Each note carries its own number, so a build removes exactly the notes it
    /// read and never a later one that happens to name the same key.
    archived_since: std::sync::Mutex<Vec<(u64, String)>>,
    note_seq: std::sync::atomic::AtomicU64,
    pub(crate) auth: auth::Auth,
    /// Decision records (confident.rs), all in memory with their vectors.
    confident: confident_index::Index,
    /// Workspace name fragments that record no decisions (KYB_CONFIDENT_DENY).
    confident_deny: Vec<String>,
}

/// The link index with what it takes to rebuild it without re-reading history.
struct LinksCache {
    gen: u64,
    index: Arc<links::LinkIndex>,
    archived: Arc<std::collections::HashMap<String, model::Entry>>,
}

impl AppState {
    /// A closed incident or task left the tree: remembered for the next link-index build.
    fn note_archived(&self, key: &str) {
        let n = self.note_seq.fetch_add(1, std::sync::atomic::Ordering::AcqRel);
        self.archived_since.lock().unwrap().push((n, key.to_string()));
    }

    /// Remove exactly the notes a build read - by number, so a note for the same
    /// key pushed after the build read its snapshot is left for the next build.
    fn settle_notes(&self, read: &[(u64, String)]) {
        let mut since = self.archived_since.lock().unwrap();
        since.retain(|(n, _)| !read.iter().any(|(r, _)| r == n));
    }

    /// The link index for the current state of the repository.
    ///
    /// The tree is cheap to read; the archive is not - finding the last version
    /// of every closed incident and task walks the whole history. That walk
    /// happens once per process. After it, a rebuild only looks at the keys the
    /// server archived since the previous build: each one's last version is a
    /// short walk back from HEAD, and a key that came back into the tree leaves
    /// the archive. (Retracted knowledge is never in the archive: only closing an
    /// incident or task archives.)
    fn links(&self) -> Result<Arc<links::LinkIndex>> {
        use std::sync::atomic::Ordering;
        let gen = self.history_gen.load(Ordering::Acquire);
        let prev = {
            let held = self.links_cache.lock().unwrap();
            match held.as_ref() {
                Some(c) if c.gen == gen => return Ok(c.index.clone()),
                Some(c) => Some(((), c.archived.clone())),
                None => None,
            }
        };
        // noted before the tree is read: an archive that lands after this is a later build's
        let noted: Vec<(u64, String)> = self.archived_since.lock().unwrap().clone();
        let head = self.store.list_head()?;
        let head_kinds: HashSet<String> = head.iter().map(|e| e.key.clone()).collect();
        let archived: Arc<std::collections::HashMap<String, model::Entry>> = match prev {
            None => Arc::new(self.store.archived_latest()?.into_iter().map(|e| (e.key.clone(), e)).collect()),
            Some((_, archived)) => {
                let mut next = (*archived).clone();
                next.retain(|k, _| !head_kinds.contains(k));
                for key in noted.iter().map(|(_, k)| k).filter(|k| !head_kinds.contains(*k)) {
                    if let Some(last) = self.store.latest_version(key)? {
                        next.insert(key.clone(), last);
                    }
                }
                Arc::new(next)
            }
        };
        let archived_list: Vec<model::Entry> = archived.values().cloned().collect();
        let index = Arc::new(links::LinkIndex::build(&head, &archived_list));
        // a write that landed while we were reading makes this answer stale: serve it once, do not keep it
        if self.history_gen.load(Ordering::Acquire) == gen {
            *self.links_cache.lock().unwrap() = Some(LinksCache { gen, index: index.clone(), archived });
            // Every note this build read is settled: a note is pushed only after its
            // archive commit, so a key that is nonetheless in the tree was filed again
            // since, and the live entry supersedes the archived one. Notes pushed while
            // we were building stay for the next build.
            self.settle_notes(&noted);
        }
        Ok(index)
    }

    /// The history of every key as of HEAD. A commit moves HEAD, so a stale
    /// index is recognised by its head alone and extended by the commits since;
    /// the lock is held while that happens, so two requests after one write do
    /// not both walk the same commits.
    fn history_index(&self) -> Result<Arc<store::HistoryIndex>> {
        let mut held = self.history_index.lock().unwrap();
        // HEAD is read here as well as inside the store's build: this read is what
        // keeps a hit off the build's path, where "same head" costs a clone of the map
        let head = self.store.head_info()?.map(|(sha, _)| sha);
        if let Some(ix) = held.as_ref() {
            if ix.head == head {
                return Ok(ix.clone());
            }
        }
        let next = Arc::new(self.store.history_index(held.as_deref())?);
        *held = Some(next.clone());
        Ok(next)
    }
    fn history_cached(&self, key: &str) -> Result<Vec<store::VersionInfo>> {
        Ok(self.history_index()?.versions(key))
    }
    /// The content an archived key had just before its file was removed: the
    /// cached history names the deletion commit, and the parent of that commit
    /// still holds the file. One blob read instead of a walk over every commit.
    fn archived_version(&self, key: &str) -> Result<Option<model::Entry>> {
        let versions = self.history_cached(key)?;
        match versions.iter().find(|v| v.change == "deleted") {
            Some(del) => self.store.get_at(key, &format!("{}^", del.sha)),
            None => self.store.latest_version(key),
        }
    }
    /// A write to `key` is landing: the link index built before it is stale.
    fn note_write(&self, _key: &str) {
        self.history_gen.fetch_add(1, std::sync::atomic::Ordering::AcqRel);
    }
}

type St = State<Arc<AppState>>;
type Reply = (StatusCode, Json<Value>);

/// What gets embedded for an entry: the headline plus the head of the body,
/// which is where an entry states what it is about. Incidents also carry
/// their service and hosts — the words people will ask by.
fn embed_text(e: &model::Entry) -> String {
    let body: String = e.body.chars().take(1200).collect();
    if e.is_incident() {
        format!("{}. Incident on {} ({}). {}", e.title, e.service, e.hosts.join(", "), body)
    } else {
        format!("{}. {}", e.title, body)
    }
}

fn vector_docs(st: &AppState) -> Option<Vec<(String, String)>> {
    st.semantic.as_ref()?;
    // live tree + archived incidents/tasks: everything the default search
    // covers must be reachable semantically too
    let mut entries = match st.store.list_head() {
        Ok(v) => v,
        Err(e) => {
            eprintln!("kyb: cannot list canon for embeddings: {e:#}");
            return None;
        }
    };
    match st.store.archived_latest() {
        Ok(mut archived) => entries.append(&mut archived),
        Err(e) => eprintln!("kyb: archived entries not embedded: {e:#}"),
    }
    Some(entries.iter().map(|e| (e.key.clone(), embed_text(e))).collect())
}

async fn finish_vector_rebuild(st: &AppState, job: embed::RebuildJob) {
    let Some(sem) = st.semantic.as_ref() else { return };
    match sem.finish_rebuild(job).await {
        Ok(n) => eprintln!("kyb: embedded {n} entries"),
        Err(e) => eprintln!("kyb: embedding failed, staying lexical: {e:#}"),
    }
}

async fn rebuild_vectors(st: &AppState) {
    let Some(sem) = st.semantic.as_ref() else { return };
    let writer = st.writer.lock().await;
    let Some(docs) = vector_docs(st) else { return };
    let job = sem.begin_rebuild(docs).await;
    drop(writer);
    finish_vector_rebuild(st, job).await;
}

/// Decision records are read at start without vectors, so a check works in
/// words from the first request; `embed_confident` adds the vectors after.
fn load_confident(st: &AppState, data_dir: &std::path::Path) {
    let recs = confident_index::Index::load_records(data_dir);
    let n = recs.len();
    for r in recs {
        st.confident.put(r, None);
    }
    if n > 0 {
        eprintln!("kyb: {n} decision records");
    }
}

async fn embed_confident(st: &AppState) {
    let Some(sem) = st.semantic.as_ref() else { return };
    let recs = st.confident.list("", "");
    for r in &recs {
        match sem.embed_passage(&r.gist).await {
            Ok(v) => st.confident.set_vector(&r.id, v),
            Err(e) => {
                eprintln!("kyb: decision records not embedded, checks match by words: {e:#}");
                return;
            }
        }
    }
}

fn build_state(cfg: &config::Config) -> Result<Arc<AppState>> {
    build_state_with(cfg, auth::Auth::from_env()?)
}

fn build_state_with(cfg: &config::Config, auth: auth::Auth) -> Result<Arc<AppState>> {
    let store = store::Store::open(&cfg.data_dir)?;
    // after the canon exists: a link into it is then seen leading there
    auth.refuse_inside(&cfg.data_dir)?;
    let index = index::SearchIndex::open_or_create(&cfg.index_dir)?;
    let mut writer = index.writer()?;
    // the canon may have been hand-edited while the service was down —
    // always rebuild on start
    let (heads, hist) = index.reindex(&mut writer, &store)?;
    eprintln!("kyb: reindex on start — {heads} head entries, {hist} history versions");
    let audit = audit::Audit::open(&cfg.audit_path)?;
    let model_start = std::time::Instant::now();
    let semantic = match embed::Semantic::load(&cfg.model_dir, cfg.index_dir.join("vectors.cache")) {
        Ok(s) => {
            eprintln!(
                "kyb: semantic search on ({}) — model loaded in {:.1}s",
                cfg.model_dir.display(),
                model_start.elapsed().as_secs_f64()
            );
            Some(s)
        }
        Err(e) => {
            eprintln!("kyb: lexical-only search ({e})");
            None
        }
    };
    let st = Arc::new(AppState {
        store,
        index,
        audit,
        semantic,
        writer: Mutex::new(writer),
        audit_path: cfg.audit_path.clone(),
        history_index: std::sync::Mutex::new(None),
        history_gen: std::sync::atomic::AtomicU64::new(0),
        links_cache: std::sync::Mutex::new(None),
        archived_since: std::sync::Mutex::new(Vec::new()),
        note_seq: std::sync::atomic::AtomicU64::new(0),
        auth,
        confident: confident_index::Index::default(),
        confident_deny: confident::deny_from_env(),
    });
    load_confident(&st, &cfg.data_dir);
    // The one full walk over history happens here, not under the first click.
    // Search and writes do not need it, so a walk that fails is reported, not fatal:
    // versions and diffs try again on request and answer with that error.
    let walk = std::time::Instant::now();
    match st.history_index() {
        Ok(ix) => eprintln!("kyb: history index — {} keys in {:.1}s", ix.keys().count(), walk.elapsed().as_secs_f64()),
        Err(e) => eprintln!("kyb: history index not built ({e:#}); versions and diffs will try again on request"),
    }
    Ok(st)
}

// No auth on purpose: we listen on 127.0.0.1 / the internal network only
fn build_app(state: Arc<AppState>) -> Router {
    let api = api_router(state);
    // /mcp serves the same routes to an MCP client, by replaying tool calls
    // through this very router - one implementation, not two.
    api.clone().merge(mcp::router(api))
}

fn api_router(state: Arc<AppState>) -> Router {
    // the read routes answer with the deadline block attached (deadline_api.rs)
    let deadlines = || middleware::from_fn_with_state(state.clone(), deadline_api::attach);
    Router::new()
        .route("/", get(web::serve_ui))
        .route("/api/audit", get(web::api_audit))
        .route("/api/activity", get(web::api_activity))
        .route("/healthz", get(healthz))
        .route("/whoami", get(auth::whoami))
        .route("/knowledge", post(upsert))
        .route("/knowledge/{key}", get(get_one).layer(deadlines()).delete(remove))
        .route("/knowledge/{key}/history", get(history))
        .route("/knowledge/{key}/diff", get(diff))
        .route("/knowledge/{key}/related", get(related))
        .route("/places", get(places))
        .route("/impact", get(impact))
        .route("/incidents", get(list_incidents).layer(deadlines()).post(upsert_incident))
        .route("/incidents/{key}/resolve", post(resolve_incident))
        .route("/tasks", get(list_tasks).layer(deadlines()).post(upsert_task))
        .route("/tasks/{key}/resolve", post(resolve_task))
        .route("/tasks/{key}/transition", post(transition_task))
        .route("/search", get(search).layer(deadlines()))
        .route("/deadlines", get(deadline_api::list))
        .route("/brief", get(brief_api::brief))
        .route("/confident", get(confident_api::list).post(confident_api::ask))
        .route("/confident/check", get(confident_api::check))
        .route("/confident/{id}", get(confident_api::get_one))
        .route("/confident/{id}/decided", post(confident_api::decided))
        .route("/confident/{id}/outcome", post(confident_api::outcome))
        .route("/confident/{id}/abandon", post(confident_api::abandon))
        .route("/export", get(export::export))
        .route("/tags", get(tags))
        .route("/reindex", post(reindex))
        // auth inside audit: a refused request is logged too, with who it was refused to
        .layer(middleware::from_fn_with_state(state.clone(), auth::auth_mw))
        .layer(middleware::from_fn_with_state(state.clone(), audit::audit_mw))
        .with_state(state)
}

#[tokio::main]
async fn main() -> Result<()> {
    // Timed and logged on EVERY start, not measured once.
    //
    // The whole point of the finding is that this grows with the base's age:
    // the index and the vectors are rebuilt from git each time, so a restart is
    // a window in which the fleet has no shared memory at all. A single
    // measurement gives today's number and says nothing about the trend, and
    // until now nothing recorded the duration - so the symptom was
    // indistinguishable from "the service is still coming up", which it is.
    //
    // The split matters as much as the total: when this gets slow again, the log
    // already says whether it was the embeddings (cached, so probably not) or
    // the per-document indexing that is linear in history.
    let boot = std::time::Instant::now();
    let cfg = config::Config::from_env();
    // `kyb-server auth ...` edits the token book and exits; it never starts the service.
    let args: Vec<String> = std::env::args().skip(1).collect();
    if args.first().map(String::as_str) == Some("auth") {
        match auth::cli(&args[1..]) {
            Ok(out) => println!("{out}"),
            Err(e) => {
                eprintln!("{e:#}");
                std::process::exit(2);
            }
        }
        return Ok(());
    }
    let state = build_state(&cfg)?;
    let indexed = boot.elapsed();
    rebuild_vectors(&state).await;
    embed_confident(&state).await;
    let ready = boot.elapsed();
    let state_auth_line = state.auth.describe();
    let app = build_app(state);
    let listener = tokio::net::TcpListener::bind(&cfg.addr).await?;
    eprintln!(
        "kyb: ready in {:.1}s (canon, index and model load {:.1}s, embeddings {:.1}s)",
        ready.as_secs_f64(),
        indexed.as_secs_f64(),
        (ready - indexed).as_secs_f64()
    );
    eprintln!("kyb: listening on http://{}", cfg.addr);
    eprintln!("kyb: {}", state_auth_line);
    // ConnectInfo so the audit log sees the real client IP
    axum::serve(listener, app.into_make_service_with_connect_info::<SocketAddr>()).await?;
    Ok(())
}

fn err500(e: anyhow::Error) -> Reply {
    (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({"error": format!("{e:#}")})))
}

/// `Query`, but rejecting in the same JSON shape as every other error here.
///
/// axum's own rejection is plain text, and a client that parses every other
/// failure as `{"error": ...}` would trip over exactly the response it most
/// needs to read - the one telling it the server does not know the parameter it
/// just sent. Serde's message is kept verbatim: it names the offending
/// parameter and lists the ones that exist, which is the whole answer.
pub struct Q<T>(pub T);

impl<S, T> FromRequestParts<S> for Q<T>
where
    Query<T>: FromRequestParts<S, Rejection = QueryRejection>,
    S: Send + Sync,
{
    type Rejection = Response;

    async fn from_request_parts(
        parts: &mut axum::http::request::Parts,
        state: &S,
    ) -> Result<Self, Self::Rejection> {
        match Query::<T>::from_request_parts(parts, state).await {
            Ok(Query(value)) => Ok(Q(value)),
            Err(rejection) => Err((
                StatusCode::BAD_REQUEST,
                Json(json!({"error": rejection.body_text()})),
            )
                .into_response()),
        }
    }
}

#[derive(Deserialize)]
struct UpsertReq {
    key: String,
    title: String,
    body: String,
    #[serde(default)]
    tags: Vec<String>,
    #[serde(default)]
    refs: Vec<String>,
}

/// What a route hands to [`locked_write`]: the entry to commit plus the extra
/// response fields it wants, or the reply that refuses the write outright.
type Built = Result<(model::Entry, Value), Reply>;

/// The whole read–modify–write of one entry inside a single critical section.
///
/// `build` runs with the global writer lock ALREADY held, so every stored
/// version it reads is still the current one when the commit lands: two
/// partial updates to the same key can no longer both read the same version
/// and silently overwrite each other. A terminal entry is archived in the same
/// section, so no concurrent reopen can slip between the closing commit and
/// the archival and lose its freshly recreated file to it.
///
/// The semantic update gets a generation ticket before the lock is dropped;
/// model computation happens outside the lock and can install its vector only
/// while that ticket still represents the newest committed version.
async fn locked_write(st: &Arc<AppState>, build: impl FnOnce(&AppState) -> Built) -> Reply {
    let mut w = st.writer.lock().await;
    let (entry, extra) = match build(st.as_ref()) {
        Ok(built) => built,
        Err(reply) => return reply,
    };
    let closed = entry.is_closed();
    let key = entry.key.clone();
    st.note_write(&key);
    let (mut reply, committed) = commit_locked(st, &mut w, entry, extra);
    if closed {
        archive_locked(st, &mut w, &key, &mut reply);
    }
    // again after git moved: a scan that began between the first forget and the
    // commit read the old HEAD, and this bump keeps it from being cached
    st.note_write(&key);
    let pending = match (st.semantic.as_ref(), committed) {
        (Some(sem), Some(entry)) => {
            let ticket = sem.begin_upsert(&entry.key).await;
            Some((ticket, entry))
        }
        _ => None,
    };
    drop(w);
    if let (Some(sem), Some((ticket, entry))) = (st.semantic.as_ref(), pending) {
        if let Err(err) = sem.finish_upsert(ticket, &embed_text(&entry)).await {
            eprintln!("kyb: embedding not updated for {}: {err:#}", entry.key);
        }
    }
    reply
}

/// Shared tail of every write route: validate, commit to git, update the
/// index — all under the caller's writer lock, which the `&mut IndexWriter`
/// proves is held. `extra` lets a route add response fields. Returns the entry
/// that actually landed (None when nothing was committed) so the caller can
/// refresh the vector side once the lock is gone.
fn commit_locked(
    st: &AppState,
    w: &mut IndexWriter,
    entry: model::Entry,
    extra: Value,
) -> (Reply, Option<model::Entry>) {
    if let Err(e) = entry.validate() {
        return ((StatusCode::BAD_REQUEST, Json(json!({"error": e.to_string()}))), None);
    }
    if let Err(e) = validate_task_parent_chain(st, &entry) {
        return ((StatusCode::BAD_REQUEST, Json(json!({"error": e.to_string()}))), None);
    }
    let today = chrono::Local::now().format("%Y-%m-%d").to_string();
    // Asked before the write, while "absent from the tree but present in
    // history" is still distinguishable from "just created".
    let had_history = matches!(st.store.get(&entry.key), Ok(None))
        && st.history_cached(&entry.key).map(|v| !v.is_empty()).unwrap_or(false);
    let (c, action) = match st.store.upsert(entry, &today) {
        Err(e) => return (err500(e), None),
        Ok(store::UpsertOutcome::Unchanged(entry)) => {
            return ((StatusCode::OK, Json(json!({"key": entry.key, "changed": false}))), None);
        }
        Ok(store::UpsertOutcome::Created(c)) => (c, "created"),
        Ok(store::UpsertOutcome::Updated(c)) => (c, "updated"),
    };
    // git is already the truth; a broken index heals via /reindex
    if let Err(e) = st
        .index
        .upsert_head(w, &c.entry, &c.sha, c.committed_at)
        .and_then(|_| st.index.commit_and_reload(w))
    {
        return (
            err500(e.context("git committed but the index was not updated — run POST /reindex")),
            None,
        );
    }
    let mut resp = json!({"key": c.entry.key, "sha": c.sha, "changed": true, "action": action});
    // Only on a create, and only as information. Two near-identical keys split
    // one topic in half while both entries answer and nothing fails - the
    // author is the only one who can tell a family apart from a slip.
    if action == "created" {
        // Every key that ever existed, not only the live ones. A retracted entry
        // leaves the working tree, so comparing against the tree alone would be
        // silent about the worst case: re-creating a key somebody deliberately
        // took away. That is not an accidental twin - it is a decision being
        // undone by someone who cannot see that it was made.
        let mut known: std::collections::HashSet<String> =
            st.history_index().map(|ix| ix.keys().cloned().collect()).unwrap_or_default();
        known.extend(st.store.list_head().unwrap_or_default().into_iter().map(|e| e.key));
        let similar = model::similar_keys(&c.entry.key, known.iter().map(String::as_str));
        if !similar.is_empty() {
            resp["similar"] = json!(similar);
        }
        // An exact match is a different message: not "looks like a neighbour"
        // but "this existed and was withdrawn - read why before continuing".
        if had_history {
            resp["revived"] = json!(true);
            resp["hint"] = json!(format!(
                "'{}' existed before and was retracted; see `kyb history {}` for why",
                c.entry.key, c.entry.key
            ));
        }
    }
    if let (Some(obj), Some(add)) = (resp.as_object_mut(), extra.as_object()) {
        obj.extend(add.clone());
    }
    ((StatusCode::OK, Json(resp)), Some(c.entry))
}

async fn upsert(State(st): St, Json(r): Json<UpsertReq>) -> Reply {
    locked_write(&st, move |_| {
        Ok((
            model::Entry {
                key: r.key,
                title: r.title,
                tags: r.tags,
                refs: r.refs,
                body: r.body,
                ..Default::default()
            },
            Value::Null,
        ))
    })
    .await
}

fn default_status() -> String {
    "open".to_string()
}

#[derive(Deserialize)]
struct IncidentReq {
    key: String,
    title: String,
    body: String,
    service: String,
    #[serde(default)]
    hosts: Vec<String>,
    severity: String,
    #[serde(default = "default_status")]
    status: String,
    /// Keys of knowledge entries this incident is tied to.
    #[serde(default)]
    knowledge: Vec<String>,
    /// How it ended; required when status=resolved.
    #[serde(default)]
    resolution: String,
    /// Executable "is it still happening?" check + expected healthy result.
    #[serde(default)]
    detection: String,
    /// Machine-readable poisoned windows: [{scope, from, to}].
    #[serde(default)]
    affected: Vec<model::Window>,
    #[serde(default)]
    started_at: String,
    #[serde(default)]
    detected_at: String,
    #[serde(default)]
    tags: Option<Vec<String>>,
    #[serde(default)]
    refs: Vec<String>,
}

fn now_utc() -> String {
    chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true)
}

/// The stored version of a key: the tree file, or — for archived
/// incidents/tasks — the latest version from history. Lets wholesale updates
/// and resolves work across the archive boundary.
fn stored_version(st: &AppState, key: &str) -> Option<model::Entry> {
    if let Ok(Some(e)) = st.store.get(key) {
        return Some(e);
    }
    st.store.latest_version(key).ok().flatten().filter(|e| e.kind != model::KIND_KNOWLEDGE)
}

/// Server-managed incident timeline. Wholesale upserts must not wipe stamps
/// the server set earlier, so empty timeline fields inherit from the stored
/// version; then status transitions get stamped if the writer left them empty.
fn stamp_timeline(st: &AppState, entry: &mut model::Entry) {
    if let Some(old) = stored_version(st, &entry.key) {
        let inherit = [
            (&mut entry.started_at, old.started_at),
            (&mut entry.detected_at, old.detected_at),
            (&mut entry.mitigated_at, old.mitigated_at),
            (&mut entry.resolved_at, old.resolved_at),
        ];
        for (field, stored) in inherit {
            if field.trim().is_empty() {
                *field = stored;
            }
        }
    }
    if entry.is_incident() && entry.detected_at.trim().is_empty() {
        entry.detected_at = now_utc();
    }
    if entry.status == "mitigated" && entry.mitigated_at.trim().is_empty() {
        entry.mitigated_at = now_utc();
    }
    // resolved incidents and done/dropped tasks both stamp the close time
    if entry.is_closed() && entry.resolved_at.trim().is_empty() {
        entry.resolved_at = now_utc();
    }
}

async fn upsert_incident(State(st): St, Json(r): Json<IncidentReq>) -> Reply {
    locked_write(&st, move |st| {
        let tags = r.tags.unwrap_or_else(|| stored_version(st, &r.key).map(|e| e.tags).unwrap_or_default());
        let mut entry = model::Entry {
            key: r.key,
            title: r.title,
            kind: model::KIND_INCIDENT.into(),
            service: r.service,
            hosts: r.hosts,
            severity: r.severity,
            status: r.status,
            knowledge: r.knowledge,
            resolution: r.resolution,
            detection: r.detection,
            affected: r.affected,
            started_at: r.started_at,
            detected_at: r.detected_at,
            tags,
            refs: r.refs,
            body: r.body,
            ..Default::default()
        };
        stamp_timeline(st, &mut entry);
        // linking to a missing entry is allowed (write the knowledge later),
        // but the writer should know the link is dangling right now
        let mut unknown = vec![];
        for k in &entry.knowledge {
            if model::is_valid_key(k) && !matches!(st.store.get(k), Ok(Some(_))) {
                unknown.push(k.clone());
            }
        }
        // Structure is a convention, not a gate: a report missing its actionable
        // parts is accepted but told exactly what a complete one carries.
        let mut hints = vec![];
        if entry.detection.trim().is_empty() {
            hints.push("no detection: add an executable 'is it still happening?' check with the expected healthy result (--detection)");
        }
        if entry.affected.is_empty() {
            hints.push("no affected windows: if data or a period got poisoned, record {scope,from,to} in --affected so backtests can exclude it programmatically");
        }
        if !entry.body.contains("- [ ]") && !entry.body.contains("- [x]") {
            hints.push("no follow-ups: track loose ends in the body as '- [ ]' checklist items so they are not lost");
        }
        if !entry.body.to_lowercase().contains("root cause") {
            hints.push("no 'Root cause' section: state it and mark the confidence — verified | suspected | unknown");
        }
        let mut extra = serde_json::Map::new();
        if !unknown.is_empty() {
            extra.insert("unknown_knowledge".into(), json!(unknown));
        }
        if !hints.is_empty() {
            extra.insert("hints".into(), json!(hints));
        }
        let extra = if extra.is_empty() { Value::Null } else { Value::Object(extra) };
        Ok((entry, extra))
    })
    .await
}

#[derive(Deserialize)]
struct ResolveReq {
    /// How it ended: what fixed it, or the accepted outcome / closing comment.
    #[serde(default, alias = "outcome")]
    resolution: String,
    /// Target status; the kind's closing status when omitted
    /// ("resolved" for incidents, "done" for tasks).
    status: Option<String>,
}

/// Archive a closed entry: the file leaves the working tree, the latest
/// version (already committed with the final status) stays in the default
/// search. The live index doc and the vector are intentionally kept.
///
/// Runs inside the closing write's critical section — the `&mut IndexWriter`
/// is the proof the writer lock is held — because a terminal commit and its
/// archival must not be separable: a reopen landing in between would have its
/// recreated file deleted by this archive.
fn archive_locked(st: &AppState, _w: &mut IndexWriter, key: &str, reply: &mut Reply) {
    if reply.0 != StatusCode::OK {
        return;
    }
    match st.store.archive(key) {
        Err(e) => eprintln!("kyb: archive failed for {key}: {e:#}"),
        Ok(None) => {} // already archived
        Ok(Some(sha)) => {
            // noted only once the deletion is committed: a rebuild that reads the note
            // then finds the key gone from the tree, and the caller's generation bump
            // that follows invalidates any index built in between
            st.note_archived(key);
            if let Some(obj) = reply.1.as_object_mut() {
                obj.insert("archived".into(), json!(true));
                obj.insert("archive_sha".into(), json!(sha));
            }
        }
    }
}

/// Close the loop on an incident or a task without resending the whole entry:
/// flip the status, record how it ended; every other field stays as stored.
/// A closing status also archives the entry.
///
/// The stored version is read under the global writer lock and stays under it
/// through the commit and the archival, so a close can neither overwrite a
/// concurrent update it never saw nor archive an entry someone just reopened.
async fn close_entry(st: &Arc<AppState>, key: String, want_task: bool, r: ResolveReq) -> Reply {
    if let Some(resp) = bad_key(&key) {
        return resp;
    }
    locked_write(st, move |st| {
        // archived entries can still be closed again (amended resolution) or
        // parked back to a non-closing status, which reopens the file
        let Some(mut e) = stored_version(st, &key) else {
            return Err((
                StatusCode::NOT_FOUND,
                Json(json!({"error": format!("no entry '{key}'")})),
            ));
        };
        if want_task != e.is_task() || (!want_task && !e.is_incident()) {
            let what = if want_task { "a task" } else { "an incident report" };
            return Err((
                StatusCode::BAD_REQUEST,
                Json(json!({"error": format!("'{key}' is not {what}")})),
            ));
        }
        let default_close = if want_task { "done" } else { "resolved" };
        e.status = r.status.unwrap_or_else(|| default_close.to_string());
        // the stored reason describes the block the task is leaving; carrying it
        // into another status would commit a state that contradicts itself
        if e.status != model::STATUS_BLOCKED {
            e.blocked_reason.clear();
        }
        // an empty resolution keeps whatever was recorded before, so closing
        // twice never wipes the outcome
        if !r.resolution.trim().is_empty() {
            e.resolution = r.resolution;
        }
        stamp_timeline(st, &mut e);
        // loose ends do not block a close, but they must not go silent either
        let open = e.open_followups();
        let extra = if open > 0 && e.is_closed() {
            json!({
                "open_followups": open,
                "warning": format!("{open} unfinished follow-up(s) (`- [ ]`) remain in the body — reassign or finish them"),
            })
        } else {
            Value::Null
        };
        Ok((e, extra))
    })
    .await
}

async fn resolve_incident(
    State(st): St,
    Path(key): Path<String>,
    Json(r): Json<ResolveReq>,
) -> Reply {
    close_entry(&st, key, false, r).await
}

async fn resolve_task(State(st): St, Path(key): Path<String>, Json(r): Json<ResolveReq>) -> Reply {
    close_entry(&st, key, true, r).await
}

/// A parent link may point forward — a child can be filed before the task it
/// hangs under — so a missing parent is reported back, never refused. An
/// archived (closed) parent counts as known: it is still part of the record.
fn unknown_parent(st: &AppState, entry: &model::Entry) -> Option<String> {
    let parent = entry.parent_task.trim();
    if parent.is_empty() || !model::is_valid_key(parent) {
        return None;
    }
    stored_version(st, parent).is_none().then(|| parent.to_string())
}

/// Keep task relationships a tree/forest, not merely a set of individually
/// valid edges. This runs while the global write lock is held, so two
/// concurrent updates cannot each observe the other edge as absent and commit
/// a cycle together. A missing parent remains a valid forward reference.
fn validate_task_parent_chain(st: &AppState, entry: &model::Entry) -> Result<()> {
    if !entry.is_task() || entry.parent_task.is_empty() {
        return Ok(());
    }
    let mut cursor = entry.parent_task.clone();
    let mut seen = HashSet::new();
    while !cursor.is_empty() {
        if cursor == entry.key {
            anyhow::bail!(
                "parent_task would create a cycle containing '{}'",
                entry.key
            );
        }
        if !seen.insert(cursor.clone()) {
            anyhow::bail!("parent_task points into an existing task cycle at '{cursor}'");
        }
        let Some(parent) = stored_version(st, &cursor) else {
            break;
        };
        cursor = parent.parent_task;
    }
    Ok(())
}

#[derive(Deserialize)]
struct TaskReq {
    key: String,
    title: String,
    body: String,
    #[serde(default = "default_status")]
    status: String,
    /// Optional ranking: "" | low | medium | high | critical.
    #[serde(default)]
    priority: String,
    /// What the task waits on; only valid together with status=blocked.
    #[serde(default)]
    blocked_reason: String,
    /// Who holds the task: a short, stable, non-secret label. Empty = unclaimed.
    #[serde(default)]
    assignee: String,
    /// The `task-` key this task hangs under; empty = top-level.
    #[serde(default)]
    parent_task: String,
    /// Keys of knowledge entries this task concerns.
    #[serde(default)]
    knowledge: Vec<String>,
    /// What came of it; required when closing (done/dropped).
    #[serde(default)]
    resolution: String,
    #[serde(default)]
    tags: Option<Vec<String>>,
    #[serde(default)]
    refs: Vec<String>,
    /// due, hard, remind_days, waits_on, expected: each one named here is set,
    /// each one left out keeps what the task already says.
    #[serde(flatten)]
    deadline: deadline::DeadlinePatch,
}

async fn upsert_task(State(st): St, Json(r): Json<TaskReq>) -> Reply {
    locked_write(&st, move |st| {
        // a write that names no tags or no deadline keeps the stored ones
        let stored = stored_version(st, &r.key);
        let tags = r.tags.unwrap_or_else(|| stored.as_ref().map(|e| e.tags.clone()).unwrap_or_default());
        let stored = stored.map(|e| e.deadline).unwrap_or_default();
        let mut entry = model::Entry {
            key: r.key,
            title: r.title,
            kind: model::KIND_TASK.into(),
            status: r.status,
            priority: r.priority,
            blocked_reason: r.blocked_reason,
            assignee: r.assignee.trim().to_string(),
            parent_task: r.parent_task.trim().to_string(),
            deadline: r.deadline.apply(stored),
            knowledge: r.knowledge,
            resolution: r.resolution,
            tags,
            refs: r.refs,
            body: r.body,
            ..Default::default()
        };
        // tasks carry one server stamp: when they were closed
        if entry.is_closed() && entry.resolved_at.trim().is_empty() {
            if let Some(old) = stored_version(st, &entry.key) {
                entry.resolved_at = old.resolved_at;
            }
            if entry.resolved_at.trim().is_empty() {
                entry.resolved_at = now_utc();
            }
        }
        let mut unknown = vec![];
        for k in &entry.knowledge {
            if model::is_valid_key(k) && !matches!(st.store.get(k), Ok(Some(_))) {
                unknown.push(k.clone());
            }
        }
        let mut extra = serde_json::Map::new();
        if !unknown.is_empty() {
            extra.insert("unknown_knowledge".into(), json!(unknown));
        }
        if let Some(parent) = unknown_parent(st, &entry) {
            extra.insert("unknown_parent".into(), json!(parent));
        }
        let extra = if extra.is_empty() { Value::Null } else { Value::Object(extra) };
        Ok((entry, extra))
    })
    .await
}

/// A partial task update: move the task between the LIVE statuses and, when the
/// request says so, change who holds it or what it hangs under. Everything the
/// request does not mention — title, body, tags, priority, knowledge, refs —
/// stays exactly as stored, so claiming a task never means resending (or
/// paraphrasing, or losing) the task being claimed.
#[derive(Deserialize)]
struct TransitionReq {
    /// Absent = keep the stored status (to move only a deadline, say); it must
    /// then be a live one.
    status: Option<String>,
    /// Present = set it ("" hands the task back to nobody); absent = keep stored.
    assignee: Option<String>,
    /// Present = set it ("" detaches the task); absent = keep stored.
    parent_task: Option<String>,
    /// Only meaningful with status=blocked; leaving blocked always clears it.
    blocked_reason: Option<String>,
    /// Moving a deadline is a transition like any other: a new version, so
    /// `kyb history` and `kyb diff` show when it moved and who moved it.
    #[serde(flatten)]
    deadline: deadline::DeadlinePatch,
}

/// Closing stays a separate act on purpose: `done`/`dropped` demand an outcome,
/// which is what POST /tasks/{key}/resolve (`kyb done`) is for.
/// A status a transition may not move to: closing needs an outcome, and only the
/// live statuses exist besides.
fn refuse_transition_status(key: &str, status: &str) -> Option<Reply> {
    if model::TASK_TERMINAL_STATUSES.contains(&status) {
        return Some((
            StatusCode::BAD_REQUEST,
            Json(json!({"error": format!(
                "'{status}' closes a task and needs an outcome — use `kyb done {key}` (POST /tasks/{key}/resolve) with a resolution; a transition only moves between {}",
                model::TASK_LIVE_STATUSES.join("|")
            )})),
        ));
    }
    if !model::TASK_LIVE_STATUSES.contains(&status) {
        return Some((
            StatusCode::BAD_REQUEST,
            Json(json!({"error": format!(
                "status must be one of: {}", model::TASK_LIVE_STATUSES.join("|")
            )})),
        ));
    }
    None
}

async fn transition_task(
    State(st): St,
    Path(key): Path<String>,
    Json(r): Json<TransitionReq>,
) -> Reply {
    if let Some(resp) = bad_key(&key) {
        return resp;
    }
    let status = r.status.as_deref().map(str::trim).map(str::to_string);
    if status.is_none()
        && r.deadline.is_empty()
        && r.assignee.is_none()
        && r.parent_task.is_none()
        && r.blocked_reason.is_none()
    {
        return (
            StatusCode::BAD_REQUEST,
            Json(
                json!({"error": "nothing to change: pass a status, or the fields to move (assignee, parent_task, blocked_reason, due, hard, remind_days, waits_on, expected)"}),
            ),
        );
    }
    if let Some(status) = status.as_deref() {
        if let Some(refused) = refuse_transition_status(&key, status) {
            return refused;
        }
    }
    // The stored version is read with the writer lock already held and the
    // commit lands before it is released: two transitions on one key are a
    // strict sequence, so the second sees the first instead of overwriting it.
    locked_write(&st, move |st| {
        // an archived task can be picked back up: the stored version comes from
        // history and the write recreates the file
        let Some(mut e) = stored_version(st, &key) else {
            return Err((
                StatusCode::NOT_FOUND,
                Json(json!({"error": format!("no entry '{key}'")})),
            ));
        };
        if !e.is_task() {
            return Err((
                StatusCode::BAD_REQUEST,
                Json(json!({"error": format!("'{key}' is not a task")})),
            ));
        }
        // without a status a task keeps its own - which only a task still in the
        // tree has: an archived one comes back only when a status says so
        let archived = is_archived(st, &key);
        let status = match status {
            Some(s) => s,
            None if e.is_live_task() && !archived => e.status.clone(),
            None => {
                let state = if archived { format!("archived ({})", e.status) } else { e.status.clone() };
                return Err((
                    StatusCode::BAD_REQUEST,
                    Json(json!({"error": format!(
                        "'{key}' is {state} — pass a status ({}) to reopen it", model::TASK_LIVE_STATUSES.join("|")
                    )})),
                ));
            }
        };
        e.status = status;
        e.deadline = r.deadline.apply(std::mem::take(&mut e.deadline));
        if let Some(assignee) = r.assignee {
            e.assignee = assignee.trim().to_string();
        }
        if let Some(parent) = r.parent_task {
            e.parent_task = parent.trim().to_string();
        }
        // a reason survives only inside the block it describes
        if e.status == model::STATUS_BLOCKED {
            if let Some(reason) = r.blocked_reason {
                e.blocked_reason = reason;
            }
        } else {
            e.blocked_reason.clear();
        }
        let mut extra = serde_json::Map::new();
        extra.insert("status".into(), json!(e.status));
        extra.insert("assignee".into(), json!(e.assignee));
        if !e.deadline.is_empty() {
            extra.insert("deadline".into(), json!(e.deadline));
        }
        if let Some(parent) = unknown_parent(st, &e) {
            extra.insert("unknown_parent".into(), json!(parent));
        }
        Ok((e, Value::Object(extra)))
    })
    .await
}

/// `deny_unknown_fields` on every query struct, deliberately.
///
/// Serde ignores an unknown field by default, and for this service that is the
/// worst available behaviour: a client that asks `?as_of=...` of a server too
/// old to know the parameter gets today's data formatted as a normal 200, and a
/// typo like `?knid=incident` returns the unfiltered set presented as a filtered
/// answer. Nothing fails; the answer is merely wrong, plausibly. For a store
/// whose entire claim is temporal correctness, silence is the one response that
/// must not be available.
///
/// The cost is that an unrecognised parameter is now a 400 rather than a
/// shrug - which is the point: it distinguishes "this server is older than your
/// client" from "nothing changed on that date".
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct IncidentsQ {
    status: Option<String>,
    service: Option<String>,
    /// Exact task priority; incidents carry none, so it never matches there.
    priority: Option<String>,
    /// Exact task ownership filters — same story: task-only fields.
    assignee: Option<String>,
    parent_task: Option<String>,
    /// followups=open keeps only reports with unfinished `- [ ]` items —
    /// the loose ends a session can pick up (archived included).
    followups: Option<String>,
    /// all=true includes archived (closed) entries; the default shows only
    /// what is live in the canon.
    all: Option<String>,
    /// deadlines=false leaves the deadline block off; read by deadline_api::attach
    #[allow(dead_code)]
    deadlines: Option<bool>,
    limit: Option<usize>,
}

/// Open followups of a body: `- [ ]` checklist items (same rule as
/// Entry::open_followups, but hits carry plain text).
fn open_followups_of(body: &str) -> usize {
    body.lines().filter(|l| l.trim_start().starts_with("- [ ]")).count()
}

/// Listings come from the index, not the tree, so archived (closed) entries
/// stay part of the record — but the DEFAULT view is what is live in the
/// canon. Archived rows appear with `?all=true`, with an explicit `?status=`
/// filter, or in the loose-ends view (`?followups=open`). Open first,
/// freshest on top within a group.
fn list_kind(
    st: &AppState,
    kind: &str,
    status_order: &[&str],
    q: &IncidentsQ,
) -> Result<Vec<(index::Hit, bool)>, Reply> {
    // an empty ?status= from the CLI is "no filter", not "match nothing"
    let status = q.status.as_deref().filter(|s| !s.trim().is_empty());
    let service = q.service.as_deref().filter(|s| !s.trim().is_empty());
    let priority = q.priority.as_deref().filter(|s| !s.trim().is_empty());
    let assignee = q.assignee.as_deref().map(str::trim).filter(|s| !s.is_empty());
    let parent = q.parent_task.as_deref().map(str::trim).filter(|s| !s.is_empty());
    let only_open_followups = q.followups.as_deref() == Some("open");
    let all = matches!(q.all.as_deref(), Some("true" | "1" | "yes"));
    let opts = index::SearchOpts {
        limit: 500,
        kind: Some(kind.to_string()),
        status: status.map(String::from),
        service: service.map(String::from),
        priority: priority.map(String::from),
        assignee: assignee.map(String::from),
        parent_task: parent.map(String::from),
        ..Default::default()
    };
    let mut hits = match st.index.search("", &opts) {
        Err(e) => return Err(err500(e)),
        Ok(h) => h,
    };
    if only_open_followups {
        hits.retain(|h| open_followups_of(&h.body) > 0);
    }
    let mut rows: Vec<(index::Hit, bool)> = hits
        .into_iter()
        .map(|h| {
            let archived = is_archived(st, &h.key);
            (h, archived)
        })
        .collect();
    if !all && status.is_none() && !only_open_followups {
        rows.retain(|(_, archived)| !archived);
    }
    let rank = |s: &str| status_order.iter().position(|x| *x == s).unwrap_or(9);
    rows.sort_by(|(a, _), (b, _)| {
        rank(&a.status)
            .cmp(&rank(&b.status))
            // committed_at is exact (ISO); updated_at only has day granularity
            .then(b.committed_at.cmp(&a.committed_at))
            .then(b.updated_at.cmp(&a.updated_at))
            .then(a.key.cmp(&b.key))
    });
    rows.truncate(q.limit.unwrap_or(50).min(1000));
    Ok(rows)
}

/// `archived` on a listing row: the file is gone from the tree, the entry
/// lives on in the index and in git history.
fn is_archived(st: &AppState, key: &str) -> bool {
    !matches!(st.store.get(key), Ok(Some(_)))
}

async fn list_incidents(State(st): St, Q(q): Q<IncidentsQ>) -> Reply {
    let rows = match list_kind(&st, model::KIND_INCIDENT, &model::STATUSES, &q) {
        Err(r) => return r,
        Ok(h) => h,
    };
    let rows: Vec<Value> = rows
        .iter()
        .map(|(h, archived)| {
            json!({
                "key": h.key, "title": h.title, "service": h.service, "hosts": h.hosts,
                "severity": h.severity, "status": h.status, "knowledge": h.knowledge,
                "resolution": h.resolution, "detection": h.detection, "affected": h.affected,
                "started_at": h.started_at, "detected_at": h.detected_at,
                "mitigated_at": h.mitigated_at, "resolved_at": h.resolved_at,
                "open_followups": open_followups_of(&h.body),
                "tags": h.tags, "updated_at": h.updated_at,
                "archived": archived,
            })
        })
        .collect();
    (StatusCode::OK, Json(json!({"count": rows.len(), "incidents": rows})))
}

async fn list_tasks(State(st): St, Q(q): Q<IncidentsQ>) -> Reply {
    let rows = match list_kind(&st, model::KIND_TASK, &model::TASK_STATUSES, &q) {
        Err(r) => return r,
        Ok(h) => h,
    };
    let rows: Vec<Value> = rows
        .iter()
        .map(|(h, archived)| {
            let mut row = json!({
                "key": h.key, "title": h.title, "status": h.status,
                "priority": h.priority, "blocked_reason": h.blocked_reason,
                "assignee": h.assignee, "parent_task": h.parent_task,
                "knowledge": h.knowledge, "resolution": h.resolution,
                "resolved_at": h.resolved_at,
                "open_followups": open_followups_of(&h.body),
                "tags": h.tags, "updated_at": h.updated_at,
                "archived": archived,
            });
            if let (Value::Object(row), Value::Object(fields)) = (&mut row, json!(h.deadline)) {
                row.extend(fields);
            }
            row
        })
        .collect();
    (StatusCode::OK, Json(json!({"count": rows.len(), "tasks": rows})))
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct GetQ {
    at: Option<String>,
    /// deadlines=false leaves the deadline block off; read by deadline_api::attach
    #[allow(dead_code)]
    deadlines: Option<bool>,
}

/// `as_of` in the three shapes an agent actually has to hand.
///
/// A bare date resolves to the END of that day: "what did we believe on the 1st"
/// means once the 1st had happened. A git revision is accepted because that is
/// what a `history` call just handed back, and making the caller convert a sha
/// into a timestamp would be busywork with a rounding error in it.
fn parse_as_of(raw: &str, st: &AppState) -> Option<i64> {
    parse_as_of_bound(raw, st, true)
}

/// `upper` decides what a bare date means: the end of that day for an upper
/// bound, the start of it for a lower one. So `2026-08-01,2026-08-01` is the
/// whole of the 1st rather than an empty instant.
fn parse_as_of_bound(raw: &str, st: &AppState, upper: bool) -> Option<i64> {
    if let Ok(t) = chrono::DateTime::parse_from_rfc3339(raw) {
        return Some(t.timestamp());
    }
    if let Ok(d) = chrono::NaiveDate::parse_from_str(raw, "%Y-%m-%d") {
        let t = if upper { d.and_hms_opt(23, 59, 59) } else { d.and_hms_opt(0, 0, 0) };
        return t.map(|dt| dt.and_utc().timestamp());
    }
    st.store.rev_time(raw).ok().flatten()
}

fn bad_key(key: &str) -> Option<Reply> {
    if model::is_valid_key(key) {
        None
    } else {
        Some((StatusCode::BAD_REQUEST, Json(json!({"error": "invalid key (slug [a-z0-9-])"}))))
    }
}

fn entry_json(e: &model::Entry, archived: bool) -> Value {
    let mut out = json!({
        "key": e.key, "title": e.title, "kind": e.kind, "tags": e.tags, "refs": e.refs,
        "updated_at": e.updated_at, "body": e.body,
    });
    let obj = out.as_object_mut().expect("out is an object");
    if e.is_incident() {
        obj.insert("service".into(), json!(e.service));
        obj.insert("hosts".into(), json!(e.hosts));
        obj.insert("severity".into(), json!(e.severity));
        obj.insert("detection".into(), json!(e.detection));
        obj.insert("affected".into(), json!(e.affected));
        obj.insert("started_at".into(), json!(e.started_at));
        obj.insert("detected_at".into(), json!(e.detected_at));
        obj.insert("mitigated_at".into(), json!(e.mitigated_at));
    }
    if e.is_task() {
        obj.insert("priority".into(), json!(e.priority));
        obj.insert("blocked_reason".into(), json!(e.blocked_reason));
        obj.insert("assignee".into(), json!(e.assignee));
        obj.insert("parent_task".into(), json!(e.parent_task));
        // only the deadline fields that are set, as on a search hit
        if let Value::Object(fields) = json!(e.deadline) {
            obj.extend(fields);
        }
    }
    if e.is_incident() || e.is_task() {
        obj.insert("status".into(), json!(e.status));
        obj.insert("knowledge".into(), json!(e.knowledge));
        obj.insert("resolution".into(), json!(e.resolution));
        obj.insert("resolved_at".into(), json!(e.resolved_at));
        obj.insert("open_followups".into(), json!(e.open_followups()));
    }
    if archived {
        obj.insert("archived".into(), json!(true));
    }
    out
}

async fn get_one(State(st): St, Path(key): Path<String>, Q(q): Q<GetQ>) -> Reply {
    if let Some(r) = bad_key(&key) {
        return r;
    }
    let res = match &q.at {
        Some(rev) => st.store.get_at(&key, rev),
        None => st.store.get(&key),
    };
    match res {
        Err(e) => err500(e),
        Ok(Some(e)) => (StatusCode::OK, Json(entry_json(&e, false))),
        Ok(None) if q.at.is_none() => {
            // not in the tree — an archived incident/task is still readable
            // from history; deleted knowledge stays a 404 (retraction)
            match st.archived_version(&key) {
                Err(e) => err500(e),
                Ok(Some(e)) if e.kind != model::KIND_KNOWLEDGE => {
                    (StatusCode::OK, Json(entry_json(&e, true)))
                }
                _ => (StatusCode::NOT_FOUND, Json(json!({"error": format!("no entry '{key}'")}))),
            }
        }
        Ok(None) => {
            (StatusCode::NOT_FOUND, Json(json!({"error": format!("no entry '{key}'")})))
        }
    }
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct DiffQ {
    /// Git revisions. Omit both to compare the two most recent versions -
    /// "what just changed" is the question that gets asked most. Omit `to`
    /// alone to compare a past version against the current one.
    from: Option<String>,
    to: Option<String>,
}

/// What changed between two versions of one entry.
///
/// `/history` reports *that* a version exists; this reports *what* moved in it.
/// Without it, answering "where did this change" means fetching two versions
/// with `?at=` and comparing them by hand, which is the sort of work an agent
/// gets wrong quietly.
async fn diff(State(st): St, Path(key): Path<String>, Q(q): Q<DiffQ>) -> Reply {
    if let Some(r) = bad_key(&key) {
        return r;
    }
    let versions = match st.history_cached(&key) {
        Err(e) => return err500(e),
        Ok(v) if v.is_empty() => {
            return (
                StatusCode::NOT_FOUND,
                Json(json!({"error": format!("no history for '{key}'")})),
            )
        }
        Ok(v) => v,
    };
    // history is newest-first
    let pick = |o: &Option<String>, fallback: Option<&str>| -> Option<String> {
        o.as_deref()
            .map(str::trim)
            .filter(|s| !s.is_empty())
            .map(str::to_string)
            .or_else(|| fallback.map(str::to_string))
    };
    let to_rev = pick(&q.to, versions.first().map(|v| v.sha.as_str()));
    let from_rev = pick(&q.from, versions.get(1).map(|v| v.sha.as_str()));
    let (Some(from_rev), Some(to_rev)) = (from_rev, to_rev) else {
        return (
            StatusCode::BAD_REQUEST,
            Json(json!({
                "error": format!("'{key}' has only one version; pass ?from=<rev>&to=<rev> explicitly")
            })),
        );
    };

    let resolve_side = |rev: &str| -> Result<Option<(String, String, String, String, bool, model::Entry)>, anyhow::Error> {
        let deduce_kind = || {
            if key.starts_with(model::TASK_PREFIX) {
                model::KIND_TASK.to_string()
            } else if key.starts_with(model::INCIDENT_PREFIX) {
                model::KIND_INCIDENT.to_string()
            } else {
                model::KIND_KNOWLEDGE.to_string()
            }
        };

        if rev == "initial" || rev == "empty" {
            let mut empty = model::Entry::default();
            empty.key = key.clone();
            empty.kind = deduce_kind();
            return Ok(Some((
                "initial".to_string(),
                String::new(),
                "Initial State".to_string(),
                "Initial creation".to_string(),
                false,
                empty,
            )));
        }

        let Some((sha, time, author, msg)) = st.store.commit_details(rev)? else {
            return Ok(None);
        };
        let committed_at = iso_secs(time);

        match st.store.get_at(&key, &sha)? {
            Some(entry) => Ok(Some((sha, committed_at, author, msg, true, entry))),
            None => {
                let in_hist = versions.iter().any(|v| v.sha == sha || v.sha.starts_with(&sha) || sha.starts_with(&v.sha));
                if in_hist {
                    let mut archived = model::Entry::default();
                    archived.key = key.clone();
                    archived.kind = deduce_kind();
                    archived.status = "archived".to_string();
                    archived.title = format!("(Archived: {key})");
                    Ok(Some((sha, committed_at, author, msg, false, archived)))
                } else {
                    Ok(None)
                }
            }
        }
    };

    let from_side = match resolve_side(&from_rev) {
        Err(e) => return err500(e),
        Ok(Some(s)) => s,
        Ok(None) => {
            return (
                StatusCode::NOT_FOUND,
                Json(json!({"error": format!("'{key}' does not exist at revision '{from_rev}'")})),
            );
        }
    };

    let to_side = match resolve_side(&to_rev) {
        Err(e) => return err500(e),
        Ok(Some(s)) => s,
        Ok(None) => {
            return (
                StatusCode::NOT_FOUND,
                Json(json!({"error": format!("'{key}' does not exist at revision '{to_rev}'")})),
            );
        }
    };

    let (from_sha, from_at, from_author, from_msg, from_exists, from_entry) = from_side;
    let (to_sha, to_at, to_author, to_msg, to_exists, to_entry) = to_side;

    let (fields, body) = model::diff_entries(&from_entry, &to_entry);
    let changed = !fields.is_empty() || !body.added.is_empty() || !body.removed.is_empty();

    (
        StatusCode::OK,
        Json(json!({
            "key": key,
            "from": {
                "rev": from_sha,
                "committed_at": from_at,
                "author": from_author,
                "message": from_msg,
                "exists": from_exists,
            },
            "to": {
                "rev": to_sha,
                "committed_at": to_at,
                "author": to_author,
                "message": to_msg,
                "exists": to_exists,
            },
            "changed": changed,
            "fields": fields,
            "body": body,
            "from_entry": entry_json(&from_entry, !from_exists),
            "to_entry": entry_json(&to_entry, !to_exists),
        })),
    )
}

fn iso_secs(secs: i64) -> String {
    chrono::DateTime::from_timestamp(secs, 0).map(|t| t.to_rfc3339()).unwrap_or_default()
}

async fn history(State(st): St, Path(key): Path<String>) -> Reply {
    if let Some(r) = bad_key(&key) {
        return r;
    }
    match st.history_cached(&key) {
        Err(e) => err500(e),
        Ok(v) if v.is_empty() => {
            (StatusCode::NOT_FOUND, Json(json!({"error": format!("no history for '{key}'")})))
        }
        Ok(v) => (StatusCode::OK, Json(json!({"key": key, "versions": v}))),
    }
}

/// What an entry points at and what points at it.
async fn related(State(st): St, Path(key): Path<String>) -> Reply {
    if let Some(r) = bad_key(&key) {
        return r;
    }
    match st.links() {
        Err(e) => err500(e),
        Ok(ix) => (StatusCode::OK, Json(ix.related(&key))),
    }
}

/// Services and hosts named by incidents, the ones with open incidents first.
async fn places(State(st): St) -> Reply {
    match st.links() {
        Err(e) => err500(e),
        Ok(ix) => (StatusCode::OK, Json(ix.places())),
    }
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct ImpactQ {
    service: Option<String>,
    host: Option<String>,
}

/// What is affected on one service or host, each row with the reason it is listed.
async fn impact(State(st): St, Q(q): Q<ImpactQ>) -> Reply {
    let (by_host, name) = match (&q.service, &q.host) {
        (Some(s), None) if !s.trim().is_empty() => (false, s.clone()),
        (None, Some(h)) if !h.trim().is_empty() => (true, h.clone()),
        _ => return (StatusCode::BAD_REQUEST, Json(json!({"error": "pass exactly one of ?service= or ?host="}))),
    };
    match st.links() {
        Err(e) => err500(e),
        Ok(ix) => (StatusCode::OK, Json(ix.impact(by_host, &name))),
    }
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct SearchQ {
    q: Option<String>,
    tag: Option<String>,
    history: Option<bool>,
    /// as_of=<RFC3339 | YYYY-MM-DD | git revision>: answer as the base stood
    /// then. A bare date means the END of that day, because "what did we
    /// believe on the 1st" means after the 1st happened, not before it began.
    as_of: Option<String>,
    /// changed_between=<start>,<end>: which entries moved inside that window.
    /// Each side takes the same three shapes as as_of; a bare start date means
    /// the START of that day and a bare end date the END, so a single day is
    /// written `2026-08-01,2026-08-01` and means all of it.
    changed_between: Option<String>,
    limit: Option<usize>,
    /// sort=recent orders by commit time instead of relevance
    sort: Option<String>,
    /// semantic=false forces pure lexical search
    semantic: Option<bool>,
    /// kind=knowledge|incident; absent = both
    kind: Option<String>,
    /// incident filters (exact terms)
    status: Option<String>,
    service: Option<String>,
    /// task filters (exact terms)
    priority: Option<String>,
    assignee: Option<String>,
    parent_task: Option<String>,
    /// deadlines=false leaves the deadline block off; read by deadline_api::attach
    #[allow(dead_code)]
    deadlines: Option<bool>,
}

async fn search(State(st): St, Q(p): Q<SearchQ>) -> Reply {
    let tags: Vec<String> = p
        .tag
        .map(|t| t.split(',').map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect())
        .unwrap_or_default();
    let q = p.q.as_deref().unwrap_or("");
    // Exact tag listings serve the console across all three entry kinds.
    // Text/semantic searches keep their existing small result budget.
    let max_limit = if q.trim().is_empty() && !tags.is_empty() { 1000 } else { 100 };
    let limit = p.limit.unwrap_or(10).min(max_limit);
    // an empty ?sort= from the CLI means "unspecified"
    let sort = p.sort.as_deref().filter(|s| !s.trim().is_empty());
    // relevance is meaningless without a query: an empty q is a listing,
    // and listings read newest first
    let recent = sort == Some("recent") || (q.trim().is_empty() && sort.is_none());
    let history = p.history.unwrap_or(false);
    let as_of = match p.as_of.as_deref().map(str::trim).filter(|s| !s.is_empty()) {
        None => None,
        Some(raw) => match parse_as_of(raw, &st) {
            Some(t) => Some(t),
            None => {
                return (
                    StatusCode::BAD_REQUEST,
                    Json(json!({"error": "as_of: expected an RFC3339 timestamp, a YYYY-MM-DD date, or a git revision that resolves"})),
                )
            }
        },
    };
    let window = match p.changed_between.as_deref().map(str::trim).filter(|s| !s.is_empty()) {
        None => None,
        Some(raw) => {
            let Some((a, b)) = raw.split_once(',') else {
                return (
                    StatusCode::BAD_REQUEST,
                    Json(json!({"error": "changed_between: expected <start>,<end>"})),
                );
            };
            match (parse_as_of_bound(a.trim(), &st, false), parse_as_of_bound(b.trim(), &st, true)) {
                (Some(lo), Some(hi)) if lo <= hi => Some((lo, hi)),
                (Some(_), Some(_)) => {
                    return (
                        StatusCode::BAD_REQUEST,
                        Json(json!({"error": "changed_between: start is after end"})),
                    )
                }
                _ => {
                    return (
                        StatusCode::BAD_REQUEST,
                        Json(json!({"error": "changed_between: each side must be an RFC3339 timestamp, a YYYY-MM-DD date, or a git revision that resolves"})),
                    )
                }
            }
        }
    };
    if as_of.is_some() && window.is_some() {
        return (
            StatusCode::BAD_REQUEST,
            Json(json!({"error": "as_of and changed_between ask different questions; pass one"})),
        );
    }
    // Semantic retrieval covers current knowledge only - the vector index holds
    // one vector per key, for the head version. A history, as_of or
    // changed_between question is about a specific past version, which no head
    // vector can represent, so those queries stay lexical rather than silently
    // matching today's text.
    //
    // PROVISIONAL, and tied to exactly one fact: vectors are head-only. Extend
    // the vector index to (key, sha) and this restriction has no remaining
    // justification - it must be revisited in the same change, not left to
    // outlive the reason it was written for. It is also the reason a versioned
    // search is lexical while a current-state search is hybrid, which is a
    // difference no benchmark comparing the two can be allowed to inherit.
    let want_semantic = !recent
        && !history
        && as_of.is_none()
        && window.is_none()
        && !q.trim().is_empty()
        && st.semantic.is_some()
        && p.semantic != Some(false);
    // an empty ?kind= from the CLI is "no filter", not "match nothing"
    let norm = |o: &Option<String>| o.clone().filter(|s| !s.trim().is_empty());
    let opts = index::SearchOpts {
        tags: tags.clone(),
        history,
        as_of,
        changed_between: window,
        limit: if want_semantic { limit.max(24) } else { limit },
        recent,
        kind: norm(&p.kind),
        status: norm(&p.status),
        service: norm(&p.service),
        priority: norm(&p.priority),
        assignee: norm(&p.assignee),
        parent_task: norm(&p.parent_task),
    };
    let mut hits = match st.index.search(q, &opts) {
        Err(e) => return err500(e),
        Ok(h) => h,
    };
    let mut semantic_used = false;
    if want_semantic {
        semantic_used = hybrid(&st, q, &opts, limit, &mut hits).await;
    }
    hits.truncate(limit);
    let count = hits.len();
    (StatusCode::OK, Json(json!({"count": count, "semantic": semantic_used, "hits": hits})))
}

/// Blend lexical hits with vector search over the whole base.
///
/// The vector side can contribute entries BM25 never saw — that is the point:
/// a question phrased in Russian, or in words the entry does not use, has no
/// lexical anchor at all. Failure is never fatal; the lexical order is already
/// a valid answer, so a broken model just means plain BM25.
async fn hybrid(
    st: &Arc<AppState>,
    q: &str,
    opts: &index::SearchOpts,
    limit: usize,
    hits: &mut Vec<index::Hit>,
) -> bool {
    let Some(sem) = st.semantic.as_ref() else { return false };
    let scored = match sem.search(q, limit.max(24)).await {
        Ok(s) => s,
        Err(e) => {
            eprintln!("kyb: semantic search skipped: {e:#}");
            return false;
        }
    };
    let sims: std::collections::HashMap<&str, f32> =
        scored.iter().map(|(k, s)| (k.as_str(), *s)).collect();
    let lexical_keys: Vec<String> = hits.iter().map(|h| h.key.clone()).collect();
    let mut by_key: std::collections::HashMap<String, index::Hit> =
        hits.drain(..).map(|h| (h.key.clone(), h)).collect();

    for key in embed::fuse_lists(&lexical_keys, &scored, 0.6) {
        let hit = match by_key.remove(&key) {
            Some(h) => Some(h),
            // semantic-only candidate: materialize its live doc (tree version
            // or archived latest), but only if it passes the same filters the
            // lexical side applied
            None => match st.index.get_live(&key) {
                Ok(Some(h)) => {
                    let keeps = opts
                        .tags
                        .iter()
                        .all(|t| h.tags.iter().any(|x| x.eq_ignore_ascii_case(t)))
                        && opts.kind.as_deref().is_none_or(|k| h.kind == k)
                        && opts.status.as_deref().is_none_or(|s| h.status == s)
                        && opts.priority.as_deref().is_none_or(|p| h.priority == p)
                        && opts.assignee.as_deref().is_none_or(|a| h.assignee == a)
                        && opts.parent_task.as_deref().is_none_or(|p| h.parent_task == p)
                        && opts
                            .service
                            .as_deref()
                            .is_none_or(|s| h.service.eq_ignore_ascii_case(s));
                    keeps.then_some(h)
                }
                _ => None,
            },
        };
        if let Some(mut h) = hit {
            // report similarity when we have one: it explains the placement
            if let Some(s) = sims.get(h.key.as_str()) {
                h.score = *s;
            }
            hits.push(h);
            if hits.len() >= limit {
                break;
            }
        }
    }
    true
}

/// Which topics does the base actually cover? Without this an agent can only
/// filter by a tag it already guessed. Counted from the canon, not the index.
async fn tags(State(st): St) -> Reply {
    let entries = match st.store.list_head() {
        Err(e) => return err500(e),
        Ok(v) => v,
    };
    let mut counts: std::collections::HashMap<String, usize> = std::collections::HashMap::new();
    for e in &entries {
        for t in &e.tags {
            *counts.entry(t.to_lowercase()).or_default() += 1;
        }
    }
    let mut rows: Vec<(String, usize)> = counts.into_iter().collect();
    rows.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
    let tags: Vec<Value> = rows.into_iter().map(|(t, c)| json!({"tag": t, "count": c})).collect();
    (StatusCode::OK, Json(json!({"count": tags.len(), "tags": tags})))
}

/// DELETE by kind: knowledge is retracted (drops out of the default search),
/// an incident/task is archived (its latest version stays searchable).
async fn remove(State(st): St, Path(key): Path<String>) -> Reply {
    if let Some(r) = bad_key(&key) {
        return r;
    }
    let mut w = st.writer.lock().await;
    let entry = match st.store.get(&key) {
        Err(e) => return err500(e),
        Ok(None) => {
            return (StatusCode::NOT_FOUND, Json(json!({"error": format!("no entry '{key}'")})))
        }
        Ok(Some(e)) => e,
    };
    // Archiving an incident or task is everyday work. Deleting knowledge is a
    // retraction - it leaves the default search - and takes the admin role.
    if entry.kind == model::KIND_KNOWLEDGE && auth::role() < auth::Role::Admin {
        return (StatusCode::FORBIDDEN, Json(json!({"error": "retracting a knowledge entry needs the admin role", "needs": "admin"})));
    }
    // both branches change the key's git history: a deletion or an archive commit.
    // Forgotten before (no stale answer is served meanwhile) and after (no scan
    // that began meanwhile can cache the pre-commit history).
    st.note_write(&key);
    let reply = remove_committed(&st, &mut w, &key, &entry).await;
    st.note_write(&key);
    reply
}

async fn remove_committed(
    st: &Arc<AppState>,
    w: &mut tokio::sync::MutexGuard<'_, IndexWriter>,
    key: &str,
    entry: &model::Entry,
) -> Reply {
    if entry.kind == model::KIND_KNOWLEDGE {
        match st.store.delete(key) {
            Err(e) => err500(e),
            Ok(None) => {
                (StatusCode::NOT_FOUND, Json(json!({"error": format!("no entry '{key}'")})))
            }
            Ok(Some(sha)) => {
                st.index.delete_head(w, key);
                let at = st
                    .store
                    .rev_time(&sha)
                    .ok()
                    .flatten()
                    .unwrap_or_else(|| chrono::Utc::now().timestamp());
                st.index.retract(key, at);
                if let Err(e) = st.index.commit_and_reload(w) {
                    return err500(
                        e.context("git committed but the index was not updated — run POST /reindex"),
                    );
                }
                if let Some(sem) = st.semantic.as_ref() {
                    sem.invalidate(key).await;
                }
                (StatusCode::OK, Json(json!({"key": key, "deleted": true, "sha": sha})))
            }
        }
    } else {
        // live index doc and vector stay: archived means findable
        match st.store.archive(key) {
            Err(e) => err500(e),
            Ok(None) => {
                (StatusCode::NOT_FOUND, Json(json!({"error": format!("no entry '{key}'")})))
            }
            Ok(Some(sha)) => {
                // after the commit, before the caller's generation bump (see archive_locked)
                st.note_archived(key);
                (StatusCode::OK, Json(json!({"key": key, "archived": true, "sha": sha})))
            }
        }
    }
}

async fn reindex(State(st): St) -> Reply {
    let mut w = st.writer.lock().await;
    let res = st.index.reindex(&mut w, &st.store);
    let vector_job = match (&res, st.semantic.as_ref()) {
        (Ok(_), Some(sem)) => match vector_docs(&st) {
            Some(docs) => Some(sem.begin_rebuild(docs).await),
            None => None,
        },
        _ => None,
    };
    drop(w);
    match res {
        Err(e) => err500(e),
        Ok((heads, hist)) => {
            if let Some(job) = vector_job {
                finish_vector_rebuild(&st, job).await;
            }
            (StatusCode::OK, Json(json!({"ok": true, "head_docs": heads, "history_docs": hist})))
        }
    }
}

/// What this build can answer, for a client to check BEFORE it asks.
///
/// `deny_unknown_fields` protects a server that has it. The configuration that
/// will actually be common after a release is the opposite one - a CLI updated
/// through brew talking to a server nobody has redeployed yet - and that server
/// cannot object to a parameter it has never heard of. It will answer a question
/// about the past with today's data and a 200.
///
/// So the check has to happen on the client, before the request, against a list
/// the server publishes. Names match the query parameters exactly; entries are
/// only ever added, never renamed, because an older CLI matches on the string.
const CAPABILITIES: [&str; 7] = ["as_of", "brief", "changed_between", "confident", "deadlines", "diff", "export"];

async fn healthz(State(st): St) -> Reply {
    let heads = st.store.list_head().unwrap_or_default();
    let open_incidents =
        heads.iter().filter(|e| e.is_incident() && e.status == "open").count();
    // every live status counts: a blocked task is still work waiting on someone
    let open_tasks = heads.iter().filter(|e| e.is_live_task()).count();
    let index_docs = st.index.reader.searcher().num_docs();
    let last = st.store.head_info().ok().flatten();
    (
        StatusCode::OK,
        Json(json!({
            "ok": true,
            "entries": heads.len(),
            "open_incidents": open_incidents,
            "open_tasks": open_tasks,
            "index_docs": index_docs,
            "last_commit": last.map(|(sha, time)| json!({"sha": sha, "time": time})),
            "version": env!("CARGO_PKG_VERSION"),
            "capabilities": CAPABILITIES,
        })),
    )
}

#[cfg(test)]
mod api_tests {
    use super::*;
    use axum::body::Body;
    use axum::http::Request;
    use http_body_util::BodyExt;
    use rstest::rstest;
    use tower::util::ServiceExt;

    pub(super) async fn call(app: &Router, method: &str, uri: &str, body: Option<Value>) -> (StatusCode, Value) {
        let b = Request::builder().method(method).uri(uri);
        let req = match body {
            Some(v) => b
                .header("content-type", "application/json")
                .body(Body::from(v.to_string()))
                .unwrap(),
            None => b.body(Body::empty()).unwrap(),
        };
        let resp = app.clone().oneshot(req).await.unwrap();
        let status = resp.status();
        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
        let val: Value = serde_json::from_slice(&bytes).unwrap_or(Value::Null);
        (status, val)
    }

    // The title is Russian on purpose: one API-level ru-stem check below
    // searches «стримах» and must match «стримы» from this title.
    pub(super) fn upsert_body(key: &str, body: &str) -> Value {
        json!({"key": key, "title": "NATS стримы", "body": body, "tags": ["nats"]})
    }

    /// Same app, plus the state behind it — the interleaving tests need the
    /// writer mutex itself to hold requests at a chosen point.
    fn app_with_state() -> (Router, Arc<AppState>, tempfile::TempDir, tempfile::TempDir) {
        let data = tempfile::tempdir().unwrap();
        let idx = tempfile::tempdir().unwrap();
        let cfg = config::Config {
            data_dir: data.path().to_path_buf(),
            index_dir: idx.path().to_path_buf(),
            audit_path: idx.path().join("audit.jsonl"),
            // API tests assert lexical behaviour; point at a dir with no model
            model_dir: idx.path().join("no-model"),
            addr: String::new(),
        };
        // the tests must not depend on what KYB_AUTH happens to be in the environment
        let state = build_state_with(&cfg, auth::Auth::off()).unwrap();
        (build_app(state.clone()), state, data, idx)
    }

    /// An app that asks for tokens, with one principal per role. Returns the
    /// tokens as (read, write, admin).
    fn app_with_auth(mode: auth::Mode, anon: Option<auth::Role>) -> (Router, [String; 3], tempfile::TempDir, tempfile::TempDir) {
        let data = tempfile::tempdir().unwrap();
        let idx = tempfile::tempdir().unwrap();
        let cfg = config::Config {
            data_dir: data.path().to_path_buf(),
            index_dir: idx.path().to_path_buf(),
            audit_path: idx.path().join("audit.jsonl"),
            model_dir: idx.path().join("no-model"),
            addr: String::new(),
        };
        let mut book = auth::Book::default();
        let read = book.add("reader", "Rita Reader", "", auth::Role::Read, "").unwrap();
        let write = book.add("agent-w", "Agent W", "w@fleet", auth::Role::Write, "").unwrap();
        let admin = book.add("owner", "The Owner", "o@fleet", auth::Role::Admin, "").unwrap();
        let book_path = idx.path().join("auth.json");
        book.save(&book_path).unwrap();
        let state = build_state_with(&cfg, auth::Auth::new(mode, anon, book_path)).unwrap();
        (build_app(state), [read, write, admin], data, idx)
    }

    async fn call_as(app: &Router, token: Option<&str>, method: &str, uri: &str, body: Option<Value>) -> (StatusCode, Value) {
        let mut b = Request::builder().method(method).uri(uri);
        if let Some(t) = token {
            b = b.header("authorization", format!("Bearer {t}"));
        }
        let req = match body {
            Some(v) => b.header("content-type", "application/json").body(Body::from(v.to_string())).unwrap(),
            None => b.body(Body::empty()).unwrap(),
        };
        let resp = app.clone().oneshot(req).await.unwrap();
        let status = resp.status();
        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
        (status, serde_json::from_slice(&bytes).unwrap_or(Value::Null))
    }

    #[tokio::test]
    async fn required_auth_holds_every_route_to_a_role_and_signs_commits() {
        let (app, [read, write, admin], _data, idx) = app_with_auth(auth::Mode::Required, None);
        let (r, w, a) = (Some(read.as_str()), Some(write.as_str()), Some(admin.as_str()));

        // nameless: only the page, the probe and whoami
        assert_eq!(call_as(&app, None, "GET", "/search?q=x", None).await.0, StatusCode::UNAUTHORIZED);
        assert_eq!(call_as(&app, None, "POST", "/knowledge", Some(upsert_body("n", "b"))).await.0, StatusCode::UNAUTHORIZED);
        assert_eq!(call_as(&app, None, "GET", "/healthz", None).await.0, StatusCode::OK);
        let (st, me) = call_as(&app, None, "GET", "/whoami", None).await;
        assert_eq!((st, me["auth"].clone(), me["role"].clone(), me["actor"].clone()), (StatusCode::OK, json!("required"), json!("read"), Value::Null));
        let (st, e) = call_as(&app, Some("kyb_never-issued"), "GET", "/search?q=x", None).await;
        assert_eq!(st, StatusCode::UNAUTHORIZED);
        assert!(e["error"].as_str().unwrap().contains("not known"));

        // read: reads, cannot write
        assert_eq!(call_as(&app, r, "GET", "/search?q=x", None).await.0, StatusCode::OK);
        let (st, e) = call_as(&app, r, "POST", "/knowledge", Some(upsert_body("note", "body"))).await;
        assert_eq!((st, e["needs"].clone(), e["role"].clone()), (StatusCode::FORBIDDEN, json!("write"), json!("read")));
        let (_, me) = call_as(&app, r, "GET", "/whoami", None).await;
        assert_eq!((me["role"].clone(), me["actor"]["id"].clone(), me["actor"]["name"].clone()), (json!("read"), json!("reader"), json!("Rita Reader")));

        // write: writes, files and resolves; the commit carries its name
        assert_eq!(call_as(&app, w, "POST", "/knowledge", Some(upsert_body("note", "body"))).await.0, StatusCode::OK);
        let (_, h) = call_as(&app, r, "GET", "/knowledge/note/history", None).await;
        assert_eq!(h["versions"][0]["author"], "Agent W <w@fleet>");
        assert_eq!(call_as(&app, w, "POST", "/incidents", Some(json!({"key": "inc-a", "title": "A", "service": "s", "severity": "low", "body": "b"}))).await.0, StatusCode::OK);
        assert_eq!(call_as(&app, w, "POST", "/incidents/inc-a/resolve", Some(json!({"resolution": "ok"}))).await.0, StatusCode::OK);
        assert_eq!(call_as(&app, w, "POST", "/incidents", Some(json!({"key": "inc-b", "title": "B", "service": "s", "severity": "low", "body": "b"}))).await.0, StatusCode::OK);
        // archiving an open incident is write work; retracting knowledge and reindexing are not
        assert_eq!(call_as(&app, w, "DELETE", "/knowledge/inc-b", None).await.0, StatusCode::OK);
        let (st, e) = call_as(&app, w, "DELETE", "/knowledge/note", None).await;
        assert_eq!((st, e["needs"].clone()), (StatusCode::FORBIDDEN, json!("admin")));
        assert_eq!(call_as(&app, w, "POST", "/reindex", None).await.0, StatusCode::FORBIDDEN);

        // admin: everything; a second author on the same entry is its own version
        assert_eq!(call_as(&app, a, "POST", "/knowledge", Some(upsert_body("note", "body two"))).await.0, StatusCode::OK);
        let (_, h) = call_as(&app, a, "GET", "/knowledge/note/history", None).await;
        assert_eq!((h["versions"][0]["author"].clone(), h["versions"][1]["author"].clone()), (json!("The Owner <o@fleet>"), json!("Agent W <w@fleet>")));
        assert_eq!(call_as(&app, a, "POST", "/reindex", None).await.0, StatusCode::OK);
        assert_eq!(call_as(&app, a, "DELETE", "/knowledge/note", None).await.0, StatusCode::OK);

        // MCP: the token travels with the tool call, and the API decides
        let mcp = |token: Option<&str>, name: &str, args: Value| {
            let app = app.clone();
            let token = token.map(str::to_string);
            let payload = json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": name, "arguments": args}});
            async move { call_as(&app, token.as_deref(), "POST", "/mcp", Some(payload)).await.1 }
        };
        let add = json!({"key": "via-mcp", "title": "T", "body": "b"});
        let refused = mcp(r, "kyb_add", add.clone()).await;
        assert_eq!(refused["result"]["isError"], json!(true));
        assert!(refused["result"]["content"][0]["text"].as_str().unwrap().contains("403"), "{refused}");
        let nameless = mcp(None, "kyb_get", json!({"key": "via-mcp"})).await;
        assert!(nameless["result"]["content"][0]["text"].as_str().unwrap().contains("401"), "{nameless}");
        assert_ne!(mcp(w, "kyb_add", add).await["result"]["isError"], json!(true));
        let (_, h) = call_as(&app, r, "GET", "/knowledge/via-mcp/history", None).await;
        assert_eq!(h["versions"][0]["author"], "Agent W <w@fleet>");

        // the raw request log (addresses, other callers' queries) is the admin's alone
        assert_eq!(call_as(&app, r, "GET", "/api/audit", None).await.0, StatusCode::FORBIDDEN);
        assert_eq!(call_as(&app, w, "GET", "/api/audit", None).await.0, StatusCode::FORBIDDEN);
        assert_eq!(call_as(&app, a, "GET", "/api/audit", None).await.0, StatusCode::OK);
        assert_eq!(call_as(&app, r, "GET", "/api/activity", None).await.0, StatusCode::OK);

        // the audit log says who, including who was refused
        let log = std::fs::read_to_string(idx.path().join("audit.jsonl")).unwrap();
        let actors: Vec<String> = log.lines().filter_map(|l| serde_json::from_str::<Value>(l).ok()).map(|v| v["actor"].as_str().unwrap_or("?").to_string()).collect();
        for who in ["reader", "agent-w", "owner", "refused"] {
            assert!(actors.iter().any(|a| a == who), "no audit line for {who}: {actors:?}");
        }
    }

    #[tokio::test]
    async fn compat_keeps_the_nameless_working_and_a_demo_reads_without_a_token() {
        let (app, [read, write, _], _data, _idx) = app_with_auth(auth::Mode::Compat, None);
        // no token: as before, and the commit is unattributed
        assert_eq!(call_as(&app, None, "POST", "/knowledge", Some(upsert_body("old-client", "b"))).await.0, StatusCode::OK);
        let (_, h) = call_as(&app, None, "GET", "/knowledge/old-client/history", None).await;
        assert_eq!(h["versions"][0]["author"], "");
        let (_, me) = call_as(&app, None, "GET", "/whoami", None).await;
        assert_eq!((me["auth"].clone(), me["role"].clone()), (json!("compat"), json!("admin")));
        // a token that is sent is believed and held to its role
        assert_eq!(call_as(&app, Some(&write), "POST", "/knowledge", Some(upsert_body("new-client", "b"))).await.0, StatusCode::OK);
        assert_eq!(call_as(&app, Some(&read), "POST", "/knowledge", Some(upsert_body("x", "b"))).await.0, StatusCode::FORBIDDEN);

        let (demo, [_, write, _], _d, _i) = app_with_auth(auth::Mode::Required, Some(auth::Role::Read));
        assert_eq!(call_as(&demo, None, "GET", "/search?q=x", None).await.0, StatusCode::OK);
        // a visitor of the demo cannot read what other visitors asked, or from where
        assert_eq!(call_as(&demo, None, "GET", "/api/audit", None).await.0, StatusCode::FORBIDDEN);
        assert_eq!(call_as(&demo, None, "POST", "/knowledge", Some(upsert_body("x", "b"))).await.0, StatusCode::FORBIDDEN);
        assert_eq!(call_as(&demo, Some(&write), "POST", "/knowledge", Some(upsert_body("x", "b"))).await.0, StatusCode::OK);
    }

    pub(super) fn app_with_tmp() -> (Router, tempfile::TempDir, tempfile::TempDir) {
        let (app, _state, data, idx) = app_with_state();
        (app, data, idx)
    }

    #[tokio::test]
    async fn api_full_flow() {
        let (app, _data, _idx) = app_with_tmp();

        // healthz on an empty registry
        let (st, v) = call(&app, "GET", "/healthz", None).await;
        assert_eq!(st, StatusCode::OK);
        assert_eq!(v["entries"], 0);

        // create
        let (st, v) = call(&app, "POST", "/knowledge", Some(upsert_body("nats-streams", "Primary version about streams."))).await;
        assert_eq!(st, StatusCode::OK, "{v}");
        assert_eq!(v["action"], "created");
        let sha1 = v["sha"].as_str().unwrap().to_string();
        assert_eq!(sha1.len(), 40);

        // same content -> no-op
        let (_, v) = call(&app, "POST", "/knowledge", Some(upsert_body("nats-streams", "Primary version about streams."))).await;
        assert_eq!(v["changed"], false);

        // update -> new sha
        let (_, v) = call(&app, "POST", "/knowledge", Some(upsert_body("nats-streams", "Secondary version: the rule moved."))).await;
        assert_eq!(v["action"], "updated");
        let sha2 = v["sha"].as_str().unwrap().to_string();
        assert_ne!(sha1, sha2);

        // get current
        let (st, v) = call(&app, "GET", "/knowledge/nats-streams", None).await;
        assert_eq!(st, StatusCode::OK);
        assert!(v["body"].as_str().unwrap().contains("Secondary"));

        // get old version by sha
        let (_, v) = call(&app, "GET", &format!("/knowledge/nats-streams?at={sha1}"), None).await;
        assert!(v["body"].as_str().unwrap().contains("Primary"));

        // history: 2 versions
        let (_, v) = call(&app, "GET", "/knowledge/nats-streams/history", None).await;
        assert_eq!(v["versions"].as_array().unwrap().len(), 2);

        // API-level russian stem: query «стримах» matches «стримы» in the title
        let (_, v) = call(&app, "GET", "/search?q=%D1%81%D1%82%D1%80%D0%B8%D0%BC%D0%B0%D1%85", None).await;
        assert_eq!(v["count"], 1);
        assert_eq!(v["hits"][0]["key"], "nats-streams");
        assert_eq!(v["hits"][0]["is_head"], true);

        // old text: absent in HEAD, present in history
        let q_old = "/search?q=Primary";
        let (_, v) = call(&app, "GET", q_old, None).await;
        assert_eq!(v["count"], 0);
        let (_, v) = call(&app, "GET", &format!("{q_old}&history=true"), None).await;
        assert!(v["count"].as_u64().unwrap() >= 1);
        assert_eq!(v["hits"][0]["is_head"], false);
        assert_eq!(v["hits"][0]["sha"], sha1);

        // tag filter
        let (_, v) = call(&app, "GET", "/search?q=nats&tag=nats", None).await;
        assert_eq!(v["count"], 1);
        let (_, v) = call(&app, "GET", "/search?q=nats&tag=missing", None).await;
        assert_eq!(v["count"], 0);

        // delete: head goes away, history remains searchable
        let (_, v) = call(&app, "DELETE", "/knowledge/nats-streams", None).await;
        assert_eq!(v["deleted"], true);
        let (st, _) = call(&app, "GET", "/knowledge/nats-streams", None).await;
        assert_eq!(st, StatusCode::NOT_FOUND);
        let (_, v) = call(&app, "GET", "/search?q=nats", None).await;
        assert_eq!(v["count"], 0);
        let (_, v) = call(&app, "GET", "/search?q=nats&history=true", None).await;
        assert!(v["count"].as_u64().unwrap() >= 2);

        // reindex from git restores the picture
        let (_, v) = call(&app, "POST", "/reindex", None).await;
        assert_eq!(v["ok"], true);
        assert_eq!(v["head_docs"], 0);
        assert_eq!(v["history_docs"], 2);

        // validation: bad key and secret in body -> 400
        let (st, _) = call(&app, "POST", "/knowledge", Some(json!({"key": "Bad Key", "title": "t", "body": "x"}))).await;
        assert_eq!(st, StatusCode::BAD_REQUEST);
        let (st, v) = call(&app, "POST", "/knowledge", Some(json!({"key": "leak", "title": "t", "body": "token: ghp_abcdefghijklmnopqrstuvwxyz123456"}))).await;
        assert_eq!(st, StatusCode::BAD_REQUEST);
        assert!(v["error"].as_str().unwrap().contains("secret"));

        // 404 on missing
        let (st, _) = call(&app, "GET", "/knowledge/nope", None).await;
        assert_eq!(st, StatusCode::NOT_FOUND);
        let (st, _) = call(&app, "GET", "/knowledge/nope/history", None).await;
        assert_eq!(st, StatusCode::NOT_FOUND);
    }

    #[tokio::test]
    async fn relations_follow_the_repository() {
        let (app, state, _data, _idx) = app_with_state();
        let state_of = |_: &Router| state.clone();
        call(&app, "POST", "/knowledge", Some(upsert_body("redis-runbook", "How to restart redis."))).await;
        let (st, v) = call(&app, "GET", "/knowledge/redis-runbook/related", None).await;
        assert_eq!(st, StatusCode::OK);
        assert_eq!((v["known"].clone(), v["incoming"].as_array().unwrap().len()), (json!(true), 0));

        // an incident citing the runbook appears as a backlink right after the write (the cached index is dropped)
        let (st, _) = call(&app, "POST", "/incidents", Some(json!({
            "key": "inc-redis-oom", "title": "Redis OOM", "service": "Redis", "hosts": ["cache-01"],
            "severity": "high", "knowledge": ["redis-runbook"], "body": "See [[redis-runbook]]."
        }))).await;
        assert_eq!(st, StatusCode::OK);
        let (_, v) = call(&app, "GET", "/knowledge/redis-runbook/related", None).await;
        assert_eq!(v["incoming"][0]["key"], "inc-redis-oom");
        assert_eq!((v["incoming"][0]["via"].clone(), v["incoming"][0]["live"].clone()), (json!("knowledge"), json!(true)));

        let (st, p) = call(&app, "GET", "/places", None).await;
        assert_eq!(st, StatusCode::OK);
        assert_eq!((p["services"][0]["name"].clone(), p["services"][0]["open"].clone(), p["hosts"][0]["name"].clone()), (json!("redis"), json!(1), json!("cache-01")));

        let (st, i) = call(&app, "GET", "/impact?service=redis", None).await;
        assert_eq!(st, StatusCode::OK);
        assert_eq!((i["open"].clone(), i["incidents"][0]["key"].clone(), i["runbooks"][0]["key"].clone()), (json!(1), json!("inc-redis-oom"), json!("redis-runbook")));
        assert_eq!(i["runbooks"][0]["because"], json!(["inc-redis-oom"]));
        let (_, h) = call(&app, "GET", "/impact?host=cache-01", None).await;
        assert_eq!((h["kind"].clone(), h["incidents"].as_array().unwrap().len()), (json!("host"), 1));

        // resolved: archived, no longer open, still a backlink
        let (st, _) = call(&app, "POST", "/incidents/inc-redis-oom/resolve", Some(json!({"resolution": "raised maxmemory"}))).await;
        assert_eq!(st, StatusCode::OK);
        let (_, v) = call(&app, "GET", "/knowledge/redis-runbook/related", None).await;
        assert_eq!((v["incoming"][0]["live"].clone(), v["incoming"][0]["archived"].clone()), (json!(false), json!(true)));
        let (_, p) = call(&app, "GET", "/places", None).await;
        assert_eq!((p["services"][0]["open"].clone(), p["services"][0]["total"].clone()), (json!(0), json!(1)));

        // a second incident closed after the index exists is picked up without a history walk,
        // a retracted note takes its edges with it, and a key filed again is live again
        call(&app, "POST", "/incidents", Some(json!({"key": "inc-two", "title": "Two", "service": "redis", "severity": "low", "knowledge": ["redis-runbook"], "body": "b"}))).await;
        call(&app, "GET", "/places", None).await;
        call(&app, "POST", "/incidents/inc-two/resolve", Some(json!({"resolution": "ok"}))).await;
        // filed and closed with no build in between: the tree never showed it to the index
        call(&app, "POST", "/incidents", Some(json!({"key": "inc-flash", "title": "Flash", "service": "redis", "severity": "low", "knowledge": ["redis-runbook"], "body": "b"}))).await;
        call(&app, "POST", "/incidents/inc-flash/resolve", Some(json!({"resolution": "ok"}))).await;
        let (_, v) = call(&app, "GET", "/knowledge/redis-runbook/related", None).await;
        let incoming: Vec<(String, bool)> = v["incoming"].as_array().unwrap().iter().map(|r| (r["key"].as_str().unwrap().to_string(), r["archived"] == json!(true))).collect();
        assert!(incoming.contains(&("inc-two".to_string(), true)) && incoming.contains(&("inc-redis-oom".to_string(), true)) && incoming.contains(&("inc-flash".to_string(), true)), "{incoming:?}");
        call(&app, "POST", "/knowledge", Some(upsert_body("pointer", "See [[redis-runbook]]."))).await;
        let (_, v) = call(&app, "GET", "/knowledge/redis-runbook/related", None).await;
        assert!(v["incoming"].as_array().unwrap().iter().any(|r| r["key"] == "pointer"));
        call(&app, "DELETE", "/knowledge/pointer", None).await;
        let (_, v) = call(&app, "GET", "/knowledge/redis-runbook/related", None).await;
        assert!(!v["incoming"].as_array().unwrap().iter().any(|r| r["key"] == "pointer"), "a retracted note keeps no edges");
        call(&app, "POST", "/incidents", Some(json!({"key": "inc-two", "title": "Two again", "service": "redis", "severity": "high", "knowledge": ["redis-runbook"], "body": "b"}))).await;
        let (_, v) = call(&app, "GET", "/knowledge/redis-runbook/related", None).await;
        let again = v["incoming"].as_array().unwrap().iter().find(|r| r["key"] == "inc-two").unwrap().clone();
        assert_eq!((again["archived"].clone(), again["live"].clone(), again["title"].clone()), (json!(false), json!(true), json!("Two again")));

        // archived and filed again before any build: the live entry wins and the note is settled, not kept forever
        let st = state_of(&app);
        call(&app, "POST", "/incidents", Some(json!({"key": "inc-refile", "title": "R", "service": "redis", "severity": "low", "knowledge": ["redis-runbook"], "body": "b"}))).await;
        call(&app, "POST", "/incidents/inc-refile/resolve", Some(json!({"resolution": "ok"}))).await;
        call(&app, "POST", "/incidents", Some(json!({"key": "inc-refile", "title": "R again", "service": "redis", "severity": "high", "knowledge": ["redis-runbook"], "body": "b"}))).await;
        let noted = |k: &str| st.archived_since.lock().unwrap().iter().any(|(_, key)| key == k);
        assert!(noted("inc-refile"), "the archive was noted");
        let (_, v) = call(&app, "GET", "/knowledge/redis-runbook/related", None).await;
        let r = v["incoming"].as_array().unwrap().iter().find(|r| r["key"] == "inc-refile").cloned().unwrap();
        assert_eq!((r["archived"].clone(), r["live"].clone(), r["title"].clone()), (json!(false), json!(true), json!("R again")));
        assert!(!noted("inc-refile"), "the note is settled by the build that saw the key live");
        // a note pushed while a build runs is not lost: it is simply next
        st.note_archived("inc-pushed-later");
        call(&app, "GET", "/places", None).await;                                  // a cache hit: no build, the note waits
        assert_eq!(st.archived_since.lock().unwrap().len(), 1);
        st.note_write("anything");                                              // the next write; the next build settles it
        call(&app, "GET", "/places", None).await;
        assert!(st.archived_since.lock().unwrap().is_empty(), "a note for a key nowhere in the tree is settled by the next build");
        // two builds overlapping: the older one settles only the notes it read, never a newer note for the same key
        st.note_archived("inc-twice");
        let snapshot = st.archived_since.lock().unwrap().clone();     // what an older build read
        st.note_archived("inc-twice");                                 // archived again after that build's snapshot
        st.settle_notes(&snapshot);
        let left = st.archived_since.lock().unwrap().clone();
        assert_eq!(left.len(), 1, "the newer note survives: {left:?}");
        assert!(left[0].0 > snapshot[0].0 && left[0].1 == "inc-twice");
        st.settle_notes(&left);
        assert!(st.archived_since.lock().unwrap().is_empty());

        for bad in ["/impact", "/impact?service=a&host=b", "/impact?service=%20", "/impact?host="] {
            let (st, v) = call(&app, "GET", bad, None).await;
            assert_eq!(st, StatusCode::BAD_REQUEST, "{bad}: {v}");
        }
        let (st, _) = call(&app, "GET", "/knowledge/Bad_Key/related", None).await;
        assert_eq!(st, StatusCode::BAD_REQUEST);
        let (st, v) = call(&app, "GET", "/knowledge/never-written/related", None).await;
        assert_eq!((st, v["known"].clone()), (StatusCode::OK, json!(false)));
    }

    #[tokio::test]
    async fn healthz_advertises_version_and_capabilities() {
        let (app, _data, _idx) = app_with_tmp();
        let (st, v) = call(&app, "GET", "/healthz", None).await;
        assert_eq!(st, StatusCode::OK);
        assert_eq!(v["version"], env!("CARGO_PKG_VERSION"));
        let caps: Vec<&str> =
            v["capabilities"].as_array().unwrap().iter().map(|c| c.as_str().unwrap()).collect();
        for want in ["as_of", "brief", "changed_between", "diff"] {
            assert!(caps.contains(&want), "healthz must advertise {want}, got {caps:?}");
        }
    }

    /// The failure this prevents is not a crash - it is a plausible answer.
    /// `?knid=incident` used to return the unfiltered set as though it had been
    /// filtered, and `?as_of=...` against a server too old to know the parameter
    /// used to return today's data as a normal 200.
    #[rstest]
    #[case("/search?q=x&knid=incident", "knid")]
    #[case("/search?q=x&zzz_nonsense=1", "zzz_nonsense")]
    #[case("/search?q=x&as_off=2026-08-01", "as_off")]
    #[case("/knowledge/demo?att=abc", "att")]
    #[case("/knowledge/demo/diff?frm=a", "frm")]
    #[case("/incidents?statuss=open", "statuss")]
    #[case("/tasks?priorty=high", "priorty")]
    #[tokio::test]
    async fn unknown_query_parameters_are_refused(#[case] uri: &str, #[case] offender: &str) {
        let (app, _data, _idx) = app_with_tmp();
        call(&app, "POST", "/knowledge", Some(upsert_body("demo", "body"))).await;
        let (st, v) = call(&app, "GET", uri, None).await;
        assert_eq!(st, StatusCode::BAD_REQUEST, "{uri} must be refused, got {v}");
        let msg = v["error"].as_str().unwrap_or_default();
        assert!(msg.contains(offender), "the error must name the parameter: {msg}");
    }

    /// A silent ignore and a real answer have to be distinguishable, so the
    /// parameters that DO exist must keep working unchanged.
    #[rstest]
    #[case("/search?q=x&kind=knowledge")]
    #[case("/search?q=x&as_of=2999-01-01")]
    #[case("/search?q=x&changed_between=2000-01-01,2999-01-01")]
    #[case("/knowledge/demo")]
    #[case("/incidents?status=open")]
    #[case("/tasks?priority=high")]
    #[tokio::test]
    async fn known_query_parameters_still_pass(#[case] uri: &str) {
        let (app, _data, _idx) = app_with_tmp();
        call(&app, "POST", "/knowledge", Some(upsert_body("demo", "body"))).await;
        let (st, v) = call(&app, "GET", uri, None).await;
        assert_eq!(st, StatusCode::OK, "{uri} must still work, got {v}");
    }

    /// Re-creating a key somebody deliberately retracted is worse than an
    /// accidental twin: a decision is being undone by someone who cannot see it
    /// was made. The tree has forgotten the key; history has not.
    #[tokio::test]
    async fn a_retracted_key_is_flagged_when_it_comes_back() {
        let (app, _data, _idx) = app_with_tmp();
        call(&app, "POST", "/knowledge", Some(upsert_body("withdrawn", "the first take"))).await;
        call(&app, "DELETE", "/knowledge/withdrawn", None).await;
        assert_eq!(call(&app, "GET", "/knowledge/withdrawn", None).await.0, StatusCode::NOT_FOUND);

        let (st, v) =
            call(&app, "POST", "/knowledge", Some(upsert_body("withdrawn", "a second take"))).await;
        assert_eq!(st, StatusCode::OK);
        assert_eq!(v["action"], "created", "the tree has forgotten it");
        assert_eq!(v["revived"], true, "history has not, and says so");
        assert!(v["hint"].as_str().unwrap().contains("retracted"), "{v}");

        // a plain create carries neither flag
        let (_, v) = call(&app, "POST", "/knowledge", Some(upsert_body("brand-new", "x"))).await;
        assert!(v["revived"].is_null());
        assert!(v["hint"].is_null());
    }

    /// The twin check looks past the working tree too: a near-twin of a
    /// retracted key is exactly the case a tree-only comparison would miss.
    #[tokio::test]
    async fn a_twin_of_a_retracted_key_is_still_surfaced() {
        let (app, _data, _idx) = app_with_tmp();
        call(&app, "POST", "/knowledge", Some(upsert_body("rule-name-your-comparison-baseline", "x")))
            .await;
        call(&app, "DELETE", "/knowledge/rule-name-your-comparison-baseline", None).await;

        let (_, v) =
            call(&app, "POST", "/knowledge", Some(upsert_body("rule-name-your-comparison-base", "y")))
                .await;
        let similar: Vec<&str> =
            v["similar"].as_array().map(|a| a.iter().filter_map(|x| x.as_str()).collect()).unwrap_or_default();
        assert!(
            similar.contains(&"rule-name-your-comparison-baseline"),
            "a retracted near-twin must still be surfaced, got {v}"
        );
    }

    #[tokio::test]
    async fn diff_endpoint() {
        let (app, _data, _idx) = app_with_tmp();
        call(&app, "POST", "/knowledge", Some(upsert_body("svc", "the port is 8080"))).await;

        // one version: there is nothing to compare it against, and saying so
        // beats inventing an empty diff
        let (st, v) = call(&app, "GET", "/knowledge/svc/diff", None).await;
        assert_eq!(st, StatusCode::BAD_REQUEST);
        assert!(v["error"].as_str().unwrap().contains("only one version"));

        call(&app, "POST", "/knowledge", Some(upsert_body("svc", "the port is 9090"))).await;

        // no revisions: the two most recent, which is "what just changed"
        let (st, v) = call(&app, "GET", "/knowledge/svc/diff", None).await;
        assert_eq!(st, StatusCode::OK);
        assert_eq!(v["changed"], true);
        assert_eq!(v["body"]["removed"][0], "the port is 8080");
        assert_eq!(v["body"]["added"][0], "the port is 9090");

        // explicit revisions, and a version compared with itself changes nothing
        let (_, h) = call(&app, "GET", "/knowledge/svc/history", None).await;
        let newest = h["versions"][0]["sha"].as_str().unwrap().to_string();
        let oldest = h["versions"][1]["sha"].as_str().unwrap().to_string();
        let (st, v) =
            call(&app, "GET", &format!("/knowledge/svc/diff?from={oldest}&to={newest}"), None).await;
        assert_eq!(st, StatusCode::OK);
        assert_eq!(v["body"]["added"][0], "the port is 9090");
        let (_, v) =
            call(&app, "GET", &format!("/knowledge/svc/diff?from={newest}&to={newest}"), None).await;
        assert_eq!(v["changed"], false);
        assert!(v["fields"].as_array().unwrap().is_empty());

        // reversing the pair reverses the diff
        let (_, v) =
            call(&app, "GET", &format!("/knowledge/svc/diff?from={newest}&to={oldest}"), None).await;
        assert_eq!(v["body"]["removed"][0], "the port is 9090");
        assert_eq!(v["body"]["added"][0], "the port is 8080");

        // initial revision diff: comparing from empty initial state
        let (st, v) =
            call(&app, "GET", &format!("/knowledge/svc/diff?from=initial&to={oldest}"), None).await;
        assert_eq!(st, StatusCode::OK);
        assert_eq!(v["changed"], true);
        assert_eq!(v["from"]["exists"], false);
        assert_eq!(v["to"]["exists"], true);
        assert_eq!(v["body"]["added"][0], "the port is 8080");

        // diff includes commit details (author, message) and entries
        assert!(v["to"]["author"].as_str().is_some());
        assert!(v["to"]["message"].as_str().is_some());
        assert_eq!(v["to_entry"]["key"], "svc");

        // archiving an item does not break diff
        call(&app, "POST", "/tasks", Some(json!({"key": "task-clean-logs", "title": "Clean logs", "body": "clear /tmp/logs"}))).await;
        call(&app, "POST", "/tasks/task-clean-logs/resolve", Some(json!({"resolution": "done"}))).await;
        let (st, v) = call(&app, "GET", "/knowledge/task-clean-logs/diff", None).await;
        assert_eq!(st, StatusCode::OK);
        assert_eq!(v["changed"], true);
        assert_eq!(v["to"]["exists"], false);
        assert_eq!(v["to_entry"]["status"], "archived");

        // an unresolvable revision is a 404, never a 500
        let (st, _) = call(&app, "GET", "/knowledge/svc/diff?from=zzz&to=zzz", None).await;
        assert_eq!(st, StatusCode::NOT_FOUND);
        let (st, _) = call(&app, "GET", "/knowledge/nope/diff", None).await;
        assert_eq!(st, StatusCode::NOT_FOUND);
    }

    #[test]
    fn attribution_trailers_round_trip_and_stay_on_one_line() {
        let by = auth::By::new("claude", "sess-1", "kyb/ui", "cli");
        let msg = auth::message_with_trailers("kyb: upsert x", Some(&by));
        assert_eq!(msg, "kyb: upsert x\n\nKyb-Agent: claude\nKyb-Session: sess-1\nKyb-Workspace: kyb/ui\nKyb-Via: cli\n");
        assert_eq!(auth::By::from_message(&msg), Some(by.clone()));
        assert_eq!(auth::message_with_trailers("kyb: upsert x", None), "kyb: upsert x");
        assert_eq!(auth::By::from_message("kyb: upsert x"), None);
        // a value cannot smuggle a second trailer or a newline into the message
        let sly = auth::By::new("codex\nKyb-Agent: root", "", "", "cli");
        assert_eq!(sly.agent, "codexKyb-Agent: root");
        assert_eq!(auth::By::from_message(&auth::message_with_trailers("m", Some(&sly))).unwrap().agent, "codexKyb-Agent: root");
        // a message with a body paragraph before the trailers still reads them
        assert_eq!(auth::By::from_message("summary\n\nsome body\n\nKyb-Agent: antigravity\nKyb-Via: meta").unwrap().agent, "antigravity");
        // only fields that are set are written; session and workspace alone still count
        assert_eq!(auth::By::new("", "s", "", "").trailers(), "Kyb-Session: s\n");
        assert!(auth::By::new("", "", "", "hook").is_empty(), "a via alone is nobody");
    }

    #[tokio::test]
    async fn attribution_from_headers_hook_and_meta_lands_on_the_commit() {
        let (app, _data, _idx) = app_with_tmp();
        // the CLI way: headers on the write
        let req = Request::builder().method("POST").uri("/knowledge").header("content-type", "application/json")
            .header("x-kyb-agent", "claude").header("x-kyb-session", "18970ebf").header("x-kyb-workspace", "knowyourbusiness/scripts").header("x-kyb-via", "cli")
            .body(Body::from(upsert_body("by-cli", "written by the cli").to_string())).unwrap();
        assert_eq!(app.clone().oneshot(req).await.unwrap().status(), StatusCode::OK);
        let (_, h) = call(&app, "GET", "/knowledge/by-cli/history", None).await;
        assert_eq!(h["versions"][0]["by"], json!({"agent": "claude", "session": "18970ebf", "workspace": "knowyourbusiness/scripts", "via": "cli"}));
        // the activity ledger carries it too
        let (_, act) = call(&app, "GET", "/api/activity?limit=5", None).await;
        let ev = act["activity"].as_array().unwrap();
        assert_eq!(ev.iter().find(|e| e["key"] == "by-cli").unwrap()["by"]["agent"], "claude");
        // whoami echoes what a request claims
        let req = Request::builder().method("GET").uri("/whoami").header("x-kyb-agent", "codex").header("x-kyb-workspace", "btcr").body(Body::empty()).unwrap();
        let resp = app.clone().oneshot(req).await.unwrap();
        let me: Value = serde_json::from_slice(&resp.into_body().collect().await.unwrap().to_bytes()).unwrap();
        assert_eq!(me["by"], json!({"agent": "codex", "workspace": "btcr"}));
        // a write without any of it: no trailer, no `by`
        call(&app, "POST", "/knowledge", Some(upsert_body("by-nobody", "plain"))).await;
        let (_, h) = call(&app, "GET", "/knowledge/by-nobody/history", None).await;
        assert!(h["versions"][0].get("by").is_none());

        // the MCP way, with a hook's _ctx in the arguments: it is stripped before the API sees it
        let rpc = |id: u64, name: &str, args: Value, meta: Option<Value>| {
            let mut params = json!({"name": name, "arguments": args});
            if let Some(m) = meta { params["_meta"] = m; }
            json!({"jsonrpc": "2.0", "id": id, "method": "tools/call", "params": params})
        };
        let (st, v) = call(&app, "POST", "/mcp", Some(rpc(1, "kyb_task", json!({"key": "task-by-hook", "title": "T", "body": "b",
            "_ctx": {"agent": "claude", "session": "sess-9", "workspace": "voiceofchain"}}), None))).await;
        assert_eq!(st, StatusCode::OK, "{v}");
        assert_eq!(v["result"]["isError"], Value::Null, "{v}");
        let (_, h) = call(&app, "GET", "/knowledge/task-by-hook/history", None).await;
        assert_eq!(h["versions"][0]["by"], json!({"agent": "claude", "session": "sess-9", "workspace": "voiceofchain", "via": "hook"}));
        // the client's own metadata: Antigravity names its conversation, Codex its session, Claude Code only the tool use
        let (_, v) = call(&app, "POST", "/mcp", Some(rpc(2, "kyb_task", json!({"key": "task-by-ag", "title": "T", "body": "b"}),
            Some(json!({"antigravity.google/conversation_id": "conv-42"}))))).await;
        assert_eq!(v["result"]["isError"], Value::Null, "{v}");
        let (_, h) = call(&app, "GET", "/knowledge/task-by-ag/history", None).await;
        assert_eq!(h["versions"][0]["by"], json!({"agent": "antigravity", "session": "conv-42", "via": "meta"}));
        call(&app, "POST", "/mcp", Some(rpc(3, "kyb_task", json!({"key": "task-by-cx", "title": "T", "body": "b"}),
            Some(json!({"x-codex-turn-metadata": {"session_id": "thr-7", "turn_id": "t1"}}))))).await;
        let (_, h) = call(&app, "GET", "/knowledge/task-by-cx/history", None).await;
        assert_eq!(h["versions"][0]["by"], json!({"agent": "codex", "session": "thr-7", "via": "meta"}));
        call(&app, "POST", "/mcp", Some(rpc(4, "kyb_task", json!({"key": "task-by-cc", "title": "T", "body": "b"}),
            Some(json!({"claudecode/toolUseId": "toolu_1"}))))).await;
        let (_, h) = call(&app, "GET", "/knowledge/task-by-cc/history", None).await;
        assert_eq!(h["versions"][0]["by"], json!({"agent": "claude", "via": "meta"}));
        // a hook's _ctx wins over the metadata, and an empty _ctx falls through to it
        call(&app, "POST", "/mcp", Some(rpc(5, "kyb_task", json!({"key": "task-by-both", "title": "T", "body": "b", "_ctx": {}}),
            Some(json!({"claudecode/toolUseId": "toolu_2"}))))).await;
        let (_, h) = call(&app, "GET", "/knowledge/task-by-both/history", None).await;
        assert_eq!(h["versions"][0]["by"]["via"], "meta");
        // a partial _ctx (workspace only) is completed from the metadata: agent from there, via names the agent's source
        call(&app, "POST", "/mcp", Some(rpc(6, "kyb_task", json!({"key": "task-by-part", "title": "T", "body": "b", "_ctx": {"workspace": "btcr"}}),
            Some(json!({"antigravity.google/conversation_id": "conv-9"}))))).await;
        let (_, h) = call(&app, "GET", "/knowledge/task-by-part/history", None).await;
        assert_eq!(h["versions"][0]["by"], json!({"agent": "antigravity", "session": "conv-9", "workspace": "btcr", "via": "meta"}));
        // Codex may send its turn metadata JSON-encoded as a string
        call(&app, "POST", "/mcp", Some(rpc(7, "kyb_task", json!({"key": "task-by-cxs", "title": "T", "body": "b"}),
            Some(json!({"x-codex-turn-metadata": "{\"thread_id\": \"thr-s\"}"}))))).await;
        let (_, h) = call(&app, "GET", "/knowledge/task-by-cxs/history", None).await;
        assert_eq!(h["versions"][0]["by"]["session"], "thr-s");
        // a client with neither hook nor metadata: the X-Kyb headers on the MCP request itself
        let req = Request::builder().method("POST").uri("/mcp").header("content-type", "application/json")
            .header("x-kyb-agent", "cursor").header("x-kyb-workspace", "landing-rs")
            .body(Body::from(rpc(8, "kyb_task", json!({"key": "task-by-hdr", "title": "T", "body": "b"}), None).to_string())).unwrap();
        assert_eq!(app.clone().oneshot(req).await.unwrap().status(), StatusCode::OK);
        let (_, h) = call(&app, "GET", "/knowledge/task-by-hdr/history", None).await;
        assert_eq!(h["versions"][0]["by"], json!({"agent": "cursor", "workspace": "landing-rs", "via": "headers"}));
        // and those headers only fill what the call itself did not say
        let req = Request::builder().method("POST").uri("/mcp").header("content-type", "application/json")
            .header("x-kyb-agent", "cursor").header("x-kyb-workspace", "landing-rs")
            .body(Body::from(rpc(9, "kyb_task", json!({"key": "task-by-hdr2", "title": "T", "body": "b"}), Some(json!({"antigravity.google/conversation_id": "conv-h"}))).to_string())).unwrap();
        app.clone().oneshot(req).await.unwrap();
        let (_, h) = call(&app, "GET", "/knowledge/task-by-hdr2/history", None).await;
        assert_eq!(h["versions"][0]["by"], json!({"agent": "antigravity", "session": "conv-h", "workspace": "landing-rs", "via": "meta"}));
        // a session is one agent's conversation: a source naming another agent never lends its session
        call(&app, "POST", "/mcp", Some(rpc(10, "kyb_task", json!({"key": "task-by-x1", "title": "T", "body": "b", "_ctx": {"agent": "claude"}}),
            Some(json!({"x-codex-turn-metadata": {"session_id": "cx-1"}}))))).await;
        let (_, h) = call(&app, "GET", "/knowledge/task-by-x1/history", None).await;
        assert_eq!(h["versions"][0]["by"], json!({"agent": "claude", "via": "hook"}));
        let req = Request::builder().method("POST").uri("/mcp").header("content-type", "application/json")
            .header("x-kyb-agent", "cursor").header("x-kyb-session", "cursor-1").header("x-kyb-workspace", "landing-rs")
            .body(Body::from(rpc(11, "kyb_task", json!({"key": "task-by-x2", "title": "T", "body": "b"}), Some(json!({"claudecode/toolUseId": "toolu_9"}))).to_string())).unwrap();
        app.clone().oneshot(req).await.unwrap();
        let (_, h) = call(&app, "GET", "/knowledge/task-by-x2/history", None).await;
        assert_eq!(h["versions"][0]["by"], json!({"agent": "claude", "workspace": "landing-rs", "via": "meta"}), "the workspace is a place and may come from the headers; cursor's session may not");
        // a session with no agent attached is taken by whichever agent is then named
        call(&app, "POST", "/mcp", Some(rpc(12, "kyb_task", json!({"key": "task-by-x3", "title": "T", "body": "b", "_ctx": {"session": "s-only"}}),
            Some(json!({"claudecode/toolUseId": "toolu_10"}))))).await;
        let (_, h) = call(&app, "GET", "/knowledge/task-by-x3/history", None).await;
        assert_eq!(h["versions"][0]["by"], json!({"agent": "claude", "session": "s-only", "via": "meta"}));
        // but an agent that brings its own session keeps it over an unattached one
        call(&app, "POST", "/mcp", Some(rpc(13, "kyb_task", json!({"key": "task-by-x4", "title": "T", "body": "b", "_ctx": {"session": "s-only"}}),
            Some(json!({"antigravity.google/conversation_id": "conv-x"}))))).await;
        let (_, h) = call(&app, "GET", "/knowledge/task-by-x4/history", None).await;
        assert_eq!(h["versions"][0]["by"]["session"], "conv-x");
    }

    #[tokio::test]
    async fn search_changed_between() {
        let (app, _data, _idx) = app_with_tmp();
        call(&app, "POST", "/knowledge", Some(upsert_body("svc", "the port is 8080"))).await;

        // a window that contains today catches it; one in the past does not
        let (st, v) =
            call(&app, "GET", "/search?q=port&changed_between=2000-01-01,2999-01-01", None).await;
        assert_eq!(st, StatusCode::OK);
        assert_eq!(v["count"], 1);
        assert_eq!(v["semantic"], false, "a window question is not a head question");

        let (_, v) =
            call(&app, "GET", "/search?q=port&changed_between=2000-01-01,2000-12-31", None).await;
        assert_eq!(v["count"], 0);

        // a busy key still reports once
        for body in ["revision a", "revision b", "revision c"] {
            call(&app, "POST", "/knowledge", Some(upsert_body("busy", body))).await;
        }
        let (_, v) =
            call(&app, "GET", "/search?q=revision&changed_between=2000-01-01,2999-01-01", None).await;
        assert_eq!(v["count"], 1, "one row per key that moved");
        assert!(v["hits"][0]["body"].as_str().unwrap().contains("revision c"));
    }

    #[rstest]
    #[case("2026-08-01", "expected <start>,<end>")]
    #[case("nonsense,2026-08-02", "must be an RFC3339")]
    #[case("2026-08-05,2026-08-01", "start is after end")]
    #[tokio::test]
    async fn search_changed_between_rejects_garbage(#[case] value: &str, #[case] hint: &str) {
        let (app, _data, _idx) = app_with_tmp();
        call(&app, "POST", "/knowledge", Some(upsert_body("svc", "body"))).await;
        let (st, v) = call(&app, "GET", &format!("/search?changed_between={value}"), None).await;
        assert_eq!(st, StatusCode::BAD_REQUEST, "{value} must be refused, got {v}");
        assert!(v["error"].as_str().unwrap().contains(hint), "{v}");
    }

    /// One instant and one window are different questions; answering both at
    /// once would silently pick one.
    #[tokio::test]
    async fn as_of_and_changed_between_are_mutually_exclusive() {
        let (app, _data, _idx) = app_with_tmp();
        call(&app, "POST", "/knowledge", Some(upsert_body("svc", "body"))).await;
        let (st, v) = call(
            &app,
            "GET",
            "/search?as_of=2026-08-01&changed_between=2026-08-01,2026-08-02",
            None,
        )
        .await;
        assert_eq!(st, StatusCode::BAD_REQUEST);
        assert!(v["error"].as_str().unwrap().contains("different questions"));
    }

    #[tokio::test]
    async fn search_as_of_over_http() {
        let (app, _data, _idx) = app_with_tmp();
        call(&app, "POST", "/knowledge", Some(upsert_body("svc", "the port is 8080"))).await;
        call(&app, "POST", "/knowledge", Some(upsert_body("svc", "the port is 9090"))).await;

        // a date in the past: the entry did not exist yet
        let (st, v) = call(&app, "GET", "/search?q=port&as_of=2000-01-01", None).await;
        assert_eq!(st, StatusCode::OK);
        assert_eq!(v["count"], 0);

        // a date in the future: one row, the current value, and never semantic -
        // the vector index holds head vectors only
        let (st, v) = call(&app, "GET", "/search?q=port&as_of=2999-01-01", None).await;
        assert_eq!(st, StatusCode::OK);
        assert_eq!(v["count"], 1, "as_of returns one version per key");
        assert_eq!(v["semantic"], false, "as_of must not be answered from head vectors");
        assert!(v["hits"][0]["body"].as_str().unwrap().contains("9090"));

        // a git revision is accepted: it is what /history just handed back
        let (_, h) = call(&app, "GET", "/knowledge/svc/history", None).await;
        let sha = h["versions"][0]["sha"].as_str().unwrap().to_string();
        let (st, v) = call(&app, "GET", &format!("/search?q=port&as_of={sha}"), None).await;
        assert_eq!(st, StatusCode::OK);
        assert_eq!(v["count"], 1);

        // an RFC3339 instant is accepted too
        let (st, _) =
            call(&app, "GET", "/search?q=port&as_of=2026-08-01T12%3A00%3A00Z", None).await;
        assert_eq!(st, StatusCode::OK);
    }

    /// A deletion made through the API is a retraction the snapshot sees at
    /// once, without a reindex; history still knows the entry existed.
    #[tokio::test]
    async fn search_as_of_forgets_an_entry_deleted_over_http() {
        let (app, _data, _idx) = app_with_tmp();
        call(&app, "POST", "/knowledge", Some(upsert_body("svc", "the port is 8080"))).await;
        assert_eq!(call(&app, "DELETE", "/knowledge/svc", None).await.0, StatusCode::OK);
        let (_, v) = call(&app, "GET", "/search?q=port&as_of=2999-01-01", None).await;
        assert_eq!(v["count"], 0, "retracted before T: no current version, got {v}");
        let (_, v) = call(&app, "GET", "/search?q=port&history=true", None).await;
        assert_eq!(v["count"], 1, "history still has the version that existed");
    }

    #[rstest]
    #[case("not-a-date")]
    #[case("2026-13-99")]
    #[case("deadbeefdeadbeefdeadbeefdeadbeefdeadbeef")]
    #[tokio::test]
    async fn search_as_of_rejects_garbage(#[case] value: &str) {
        let (app, _data, _idx) = app_with_tmp();
        call(&app, "POST", "/knowledge", Some(upsert_body("svc", "body"))).await;
        let (st, v) = call(&app, "GET", &format!("/search?as_of={value}"), None).await;
        assert_eq!(st, StatusCode::BAD_REQUEST, "as_of={value} must be refused, got {v}");
        assert!(v["error"].as_str().unwrap().contains("as_of"));
    }

    #[tokio::test]
    async fn api_edge_cases() {
        let (app, _data, _idx) = app_with_tmp();

        call(&app, "POST", "/knowledge", Some(upsert_body("alpha", "body one"))).await;

        // unknown/garbage rev in ?at= -> 404, not 500
        let (st, _) = call(
            &app,
            "GET",
            "/knowledge/alpha?at=deadbeefdeadbeefdeadbeefdeadbeefdeadbeef",
            None,
        )
        .await;
        assert_eq!(st, StatusCode::NOT_FOUND);
        let (st, _) = call(&app, "GET", "/knowledge/alpha?at=zzz", None).await;
        assert_eq!(st, StatusCode::NOT_FOUND);

        // delete -> re-add with the same key: created again, chain kept in history
        call(&app, "DELETE", "/knowledge/alpha", None).await;
        let (_, v) = call(&app, "POST", "/knowledge", Some(upsert_body("alpha", "body two"))).await;
        assert_eq!(v["action"], "created");
        let (_, v) = call(&app, "GET", "/knowledge/alpha/history", None).await;
        let changes: Vec<&str> = v["versions"]
            .as_array()
            .unwrap()
            .iter()
            .map(|x| x["change"].as_str().unwrap())
            .collect();
        assert_eq!(changes, vec!["added", "deleted", "added"]);

        // empty q = list everything current; limit works
        call(&app, "POST", "/knowledge", Some(upsert_body("beta", "another entry"))).await;
        let (_, v) = call(&app, "GET", "/search?q=", None).await;
        assert_eq!(v["count"], 2);
        let (_, v) = call(&app, "GET", "/search?q=&limit=1", None).await;
        assert_eq!(v["count"], 1);

        // broken query syntax must not fail the search (lenient parser)
        let (st, _) = call(&app, "GET", "/search?q=title%3A%28%28%28%20AND%20OR", None).await;
        assert_eq!(st, StatusCode::OK);

        // tags are case-insensitive
        call(
            &app,
            "POST",
            "/knowledge",
            Some(json!({"key": "gamma", "title": "t", "body": "tagged body", "tags": ["Infra"]})),
        )
        .await;
        let (_, v) = call(&app, "GET", "/search?q=&tag=infra", None).await;
        assert_eq!(v["count"], 1);

        // garbage payload -> 4xx, not 500
        let (st, _) = call(&app, "POST", "/knowledge", Some(json!({"key": "x"}))).await;
        assert!(st.is_client_error());

        // rm of a missing key -> 404
        let (st, _) = call(&app, "DELETE", "/knowledge/void", None).await;
        assert_eq!(st, StatusCode::NOT_FOUND);
    }

    #[tokio::test]
    async fn audit_log_written() {
        let (app, _data, idx) = app_with_tmp();
        call(&app, "GET", "/healthz", None).await;
        call(&app, "POST", "/knowledge", Some(upsert_body("k", "plain body"))).await;
        call(&app, "GET", "/search?q=plain", None).await;

        let content = std::fs::read_to_string(idx.path().join("audit.jsonl")).unwrap();
        let lines: Vec<&str> = content.lines().collect();
        assert_eq!(lines.len(), 2, "healthz must not be audited:\n{content}");
        let first: Value = serde_json::from_str(lines[0]).unwrap();
        assert_eq!(first["method"], "POST");
        assert_eq!(first["path"], "/knowledge");
        assert_eq!(first["status"], 200);
        assert!(first["ts"].as_str().unwrap().contains('T'));
        let second: Value = serde_json::from_str(lines[1]).unwrap();
        assert_eq!(second["path"], "/search");
        assert!(second["query"].as_str().unwrap().starts_with("q="));
    }

    // --- traversal and garbage keys in path params: 400, not a filesystem walk ---
    #[rstest]
    #[case("GET", "/knowledge/..%2F..%2Fetc")]
    #[case("GET", "/knowledge/.git")]
    #[case("GET", "/knowledge/UPPER")]
    #[case("GET", "/knowledge/a.b")]
    #[case("DELETE", "/knowledge/..%2Fx")]
    #[case("DELETE", "/knowledge/a_b")]
    #[case("GET", "/knowledge/..%2Fx/history")]
    #[case("GET", "/knowledge/%D0%BA%D0%BB%D1%8E%D1%87")]
    #[tokio::test]
    async fn traversal_and_bad_keys_rejected(#[case] method: &str, #[case] uri: &str) {
        let (app, _data, _idx) = app_with_tmp();
        let (st, _) = call(&app, method, uri, None).await;
        assert_eq!(st, StatusCode::BAD_REQUEST, "{method} {uri}");
    }

    // --- status codes per route ---
    #[rstest]
    #[case("GET", "/nope", 404)]
    #[case("POST", "/search", 405)]
    #[case("DELETE", "/search", 405)]
    #[case("GET", "/reindex", 405)]
    #[case("PUT", "/knowledge", 405)]
    #[case("DELETE", "/knowledge", 405)]
    #[case("POST", "/knowledge/some-key", 405)]
    #[case("POST", "/healthz", 405)]
    #[case("GET", "/knowledge/no-such-key", 404)]
    #[case("GET", "/knowledge/no-such-key/history", 404)]
    #[case("DELETE", "/knowledge/no-such-key", 404)]
    #[tokio::test]
    async fn route_status_matrix(#[case] method: &str, #[case] uri: &str, #[case] expect: u16) {
        let (app, _data, _idx) = app_with_tmp();
        let (st, _) = call(&app, method, uri, None).await;
        assert_eq!(st.as_u16(), expect, "{method} {uri}");
    }

    // --- upsert payload validation ---
    #[rstest]
    #[case(json!({"key": "k"}), 422)] // required fields missing
    #[case(json!({"key": "k", "title": "t"}), 422)] // no body
    #[case(json!({"key": "", "title": "t", "body": "x"}), 400)]
    #[case(json!({"key": "K", "title": "t", "body": "x"}), 400)]
    #[case(json!({"key": "../up", "title": "t", "body": "x"}), 400)]
    #[case(json!({"key": "k", "title": "", "body": "x"}), 400)]
    #[case(json!({"key": "k", "title": "   ", "body": "x"}), 400)]
    #[case(json!({"key": "k", "title": "t", "body": "password: super123secret"}), 400)]
    #[case(json!({"key": "k", "title": "t", "body": "x", "refs": ["ghp_abcdefghijklmnopqrstuvwxyz1234"]}), 400)]
    #[case(json!({"key": "k", "title": "t", "body": "clean body"}), 200)]
    #[case(json!({"key": "k2", "title": "t", "body": ""}), 200)] // empty body is allowed
    #[case(json!({"key": "k3", "title": "t", "body": "x", "tags": [], "refs": []}), 200)]
    #[tokio::test]
    async fn upsert_validation_matrix(#[case] payload: Value, #[case] expect: u16) {
        let (app, _data, _idx) = app_with_tmp();
        let (st, v) = call(&app, "POST", "/knowledge", Some(payload)).await;
        assert_eq!(st.as_u16(), expect, "response: {v}");
    }

    // 12 parallel writes to ONE key: the mutex serializes them, history is complete
    #[tokio::test]
    async fn api_concurrent_same_key() {
        let (app, _data, _idx) = app_with_tmp();
        let mut set = tokio::task::JoinSet::new();
        for i in 0..12 {
            let app = app.clone();
            set.spawn(async move {
                let body = json!({
                    "key": "same-key",
                    "title": "Shared key",
                    "body": format!("unique body {i}"),
                });
                call(&app, "POST", "/knowledge", Some(body)).await
            });
        }
        while let Some(res) = set.join_next().await {
            let (st, v) = res.unwrap();
            assert_eq!(st, StatusCode::OK, "{v}");
            assert_eq!(v["changed"], true);
        }
        // all 12 versions landed in git sequentially, none lost
        let (_, v) = call(&app, "GET", "/knowledge/same-key/history", None).await;
        assert_eq!(v["versions"].as_array().unwrap().len(), 12);
        let (_, v) = call(&app, "POST", "/reindex", None).await;
        assert_eq!(v["head_docs"], 1);
        assert_eq!(v["history_docs"], 12);
        // the current body is one of the twelve
        let (_, v) = call(&app, "GET", "/knowledge/same-key", None).await;
        assert!(v["body"].as_str().unwrap().starts_with("unique body"));
    }

    fn incident_body(key: &str, status: &str, body: &str) -> Value {
        json!({
            "key": key, "title": "orders_api OOM on host-a", "body": body,
            "service": "orders_api", "hosts": ["host-a"], "severity": "high", "status": status,
            "knowledge": ["orders-api-architecture"], "tags": ["acme"],
        })
    }

    #[tokio::test]
    async fn incident_full_flow() {
        let (app, _data, _idx) = app_with_tmp();

        // the knowledge entry the incident will link to
        call(&app, "POST", "/knowledge", Some(json!({
            "key": "orders-api-architecture", "title": "orders_api: gRPC gateway",
            "body": "The single write path into ClickHouse.", "tags": ["acme"],
        }))).await;

        // file a report; the link resolves, so no unknown_knowledge warning
        let key = "inc-2026-07-22-orders-api-oom";
        let (st, v) = call(&app, "POST", "/incidents",
            Some(incident_body(key, "open", "What happened: OOM. Workaround: restart."))).await;
        assert_eq!(st, StatusCode::OK, "{v}");
        assert_eq!(v["action"], "created");
        assert!(v.get("unknown_knowledge").is_none(), "{v}");

        // a dangling knowledge link is allowed but reported
        let (_, v) = call(&app, "POST", "/incidents", Some(json!({
            "key": "inc-2026-07-21-landing-gap", "title": "landing gap", "body": "Data gap.",
            "service": "web_app", "severity": "medium",
            "knowledge": ["landing-architecture"],
        }))).await;
        assert_eq!(v["unknown_knowledge"], json!(["landing-architecture"]));

        // status omitted -> open
        let (_, v) = call(&app, "GET", "/knowledge/inc-2026-07-21-landing-gap", None).await;
        assert_eq!(v["status"], "open");
        assert_eq!(v["kind"], "incident");

        // GET returns the incident fields
        let (_, v) = call(&app, "GET", &format!("/knowledge/{key}"), None).await;
        assert_eq!(v["service"], "orders_api");
        assert_eq!(v["severity"], "high");
        assert_eq!(v["hosts"], json!(["host-a"]));
        assert_eq!(v["knowledge"], json!(["orders-api-architecture"]));

        // a knowledge entry does not grow incident fields
        let (_, v) = call(&app, "GET", "/knowledge/orders-api-architecture", None).await;
        assert_eq!(v["kind"], "knowledge");
        assert!(v.get("status").is_none(), "{v}");

        // healthz counts open incidents
        let (_, v) = call(&app, "GET", "/healthz", None).await;
        assert_eq!(v["open_incidents"], 2);

        // list: open first, filters work; empty params (CLI style) = no filter
        let (_, v) = call(&app, "GET", "/incidents", None).await;
        assert_eq!(v["count"], 2);
        let (_, v) = call(&app, "GET", "/incidents?status=&service=&limit=50", None).await;
        assert_eq!(v["count"], 2, "{v}");
        let (_, v) = call(&app, "GET", "/incidents?service=ORDERS_API", None).await;
        assert_eq!(v["count"], 1, "service filter is case-insensitive: {v}");
        assert_eq!(v["incidents"][0]["key"], key);

        // search: kind filter separates worlds; incident fields ride on hits
        let (_, v) = call(&app, "GET", "/search?q=&kind=incident", None).await;
        assert_eq!(v["count"], 2);
        let (_, v) = call(&app, "GET", "/search?q=&kind=knowledge", None).await;
        assert_eq!(v["count"], 1);
        // empty filter params (what the CLI sends) mean "no filter", not "match nothing"
        let (_, v) = call(&app, "GET", "/search?q=&kind=&status=&service=", None).await;
        assert_eq!(v["count"], 3);
        // free text "orders api" reaches the incident via service/knowledge meta
        let (_, v) = call(&app, "GET", "/search?q=orders%20api&kind=incident&status=open&service=orders_api", None).await;
        assert_eq!(v["count"], 1, "{v}");
        assert_eq!(v["hits"][0]["key"], key);
        assert_eq!(v["hits"][0]["status"], "open");

        // closing without saying how it ended is refused
        let (st, v) = call(&app, "POST", &format!("/incidents/{key}/resolve"), Some(json!({}))).await;
        assert_eq!(st, StatusCode::BAD_REQUEST, "{v}");
        assert!(v["error"].as_str().unwrap().contains("resolution"));

        // close it properly: status flips, the outcome is recorded, and the
        // report is archived — the file leaves the tree
        let (st, v) = call(&app, "POST", &format!("/incidents/{key}/resolve"),
            Some(json!({"resolution": "Raised the memory limit to 2G; fixed the batch flush leak."}))).await;
        assert_eq!(st, StatusCode::OK, "{v}");
        assert_eq!(v["action"], "updated");
        assert_eq!(v["archived"], true, "{v}");
        let (_, v) = call(&app, "GET", "/incidents?status=open", None).await;
        assert_eq!(v["count"], 1);
        let (_, v) = call(&app, "GET", "/healthz", None).await;
        assert_eq!(v["open_incidents"], 1);
        // the archived report still reads in full, marked as archived
        let (_, v) = call(&app, "GET", &format!("/knowledge/{key}"), None).await;
        assert_eq!(v["status"], "resolved");
        assert_eq!(v["archived"], true, "{v}");
        assert!(v["resolution"].as_str().unwrap().contains("memory limit"));
        assert_eq!(v["service"], "orders_api");
        assert_eq!(v["knowledge"], json!(["orders-api-architecture"]));
        assert!(v["body"].as_str().unwrap().contains("What happened"));
        // the default listing shows only live reports; --all adds the archive
        let (_, v) = call(&app, "GET", "/incidents", None).await;
        assert_eq!(v["count"], 1, "archived hidden by default: {v}");
        let (_, v) = call(&app, "GET", "/incidents?all=true", None).await;
        assert_eq!(v["count"], 2);
        assert_eq!(v["incidents"][1]["key"], key);
        assert_eq!(v["incidents"][1]["status"], "resolved");
        assert_eq!(v["incidents"][1]["archived"], true);
        // an explicit status filter looks into the archive on its own
        let (_, v) = call(&app, "GET", "/incidents?status=resolved", None).await;
        assert_eq!(v["count"], 1, "{v}");
        // history: filed, resolved, archived
        let (_, v) = call(&app, "GET", &format!("/knowledge/{key}/history"), None).await;
        assert_eq!(v["versions"].as_array().unwrap().len(), 3);
        assert_eq!(v["versions"][0]["change"], "deleted");
        assert!(v["versions"][0]["message"].as_str().unwrap().contains("archive"));

        // the recorded outcome is searchable in the DEFAULT search even though
        // the file is gone — "how did we fix it" lands here
        let (_, v) = call(&app, "GET", "/search?q=memory%20limit&kind=incident", None).await;
        assert_eq!(v["count"], 1, "{v}");
        assert!(v["hits"][0]["resolution"].as_str().unwrap().contains("2G"));
        assert_eq!(v["hits"][0]["is_head"], true);

        // parking an archived report back to mitigated reopens it (the file
        // returns); the empty resolution keeps the recorded outcome
        let (_, v) = call(&app, "POST", &format!("/incidents/{key}/resolve"),
            Some(json!({"status": "mitigated"}))).await;
        assert_eq!(v["action"], "created", "reopen recreates the file: {v}");
        let (_, v) = call(&app, "GET", &format!("/knowledge/{key}"), None).await;
        assert_eq!(v["status"], "mitigated");
        assert!(v.get("archived").is_none(), "back in the tree: {v}");
        assert!(v["resolution"].as_str().unwrap().contains("memory limit"), "kept: {v}");
    }

    // detection / affected windows / timeline: the "control panel" fields
    #[tokio::test]
    async fn incident_actionable_fields_flow() {
        let (app, _data, _idx) = app_with_tmp();
        let key = "inc-2026-07-22-symbol-mismap";
        let (st, v) = call(&app, "POST", "/incidents", Some(json!({
            "key": key, "title": "prices 50x off after symbol remap", "service": "web_app2",
            "hosts": ["host-b"], "severity": "high",
            "detection": "per (exchange,symbol): price > 50x yesterday max; healthy = 0 rows",
            "affected": [
                {"scope": "okx",    "from": "2026-07-22T08:09:40Z", "to": "2026-07-22T21:09:37Z"},
                {"scope": "gateio", "from": "2026-07-22T08:20:09Z", "to": "2026-07-22T20:04:41Z"},
            ],
            "started_at": "2026-07-22T08:09:40Z",
            "body": "Symptom: heatmap shows +38,000,000% gainers.\n\nFollow-ups:\n- [ ] guard dev NATS\n- [x] webui sanity filter\n",
        }))).await;
        assert_eq!(st, StatusCode::OK, "{v}");

        // GET: everything back; detected_at was stamped by the server
        let (_, v) = call(&app, "GET", &format!("/knowledge/{key}"), None).await;
        assert_eq!(v["affected"].as_array().unwrap().len(), 2);
        assert_eq!(v["affected"][0]["scope"], "okx");
        assert_eq!(v["started_at"], "2026-07-22T08:09:40Z");
        assert!(v["detected_at"].as_str().unwrap().contains('T'), "stamped: {v}");
        assert_eq!(v["resolved_at"], "");
        assert_eq!(v["open_followups"], 1);

        // listing carries the control-panel fields and the followups filter works
        let (_, v) = call(&app, "GET", "/incidents", None).await;
        assert!(v["incidents"][0]["detection"].as_str().unwrap().contains("50x"));
        assert_eq!(v["incidents"][0]["open_followups"], 1);
        let (_, v) = call(&app, "GET", "/incidents?followups=open", None).await;
        assert_eq!(v["count"], 1);

        // search hit carries them too (backtester can read windows from a hit)
        let (_, v) = call(&app, "GET", "/search?q=mismap&kind=incident", None).await;
        assert_eq!(v["hits"][0]["affected"].as_array().unwrap().len(), 2, "{v}");
        assert!(v["hits"][0]["detection"].as_str().unwrap().contains("healthy"));

        // detection text is searchable
        let (_, v) = call(&app, "GET", "/search?q=yesterday%20max", None).await;
        assert_eq!(v["count"], 1);

        // resolve with an open follow-up: closes (and archives), but warns
        let (_, v) = call(&app, "POST", &format!("/incidents/{key}/resolve"),
            Some(json!({"resolution": "Recorders restarted; windows purged from CH."}))).await;
        assert_eq!(v["open_followups"], 1, "{v}");
        assert!(v["warning"].as_str().unwrap().contains("follow-up"));
        assert_eq!(v["archived"], true);
        let (_, v) = call(&app, "GET", &format!("/knowledge/{key}"), None).await;
        assert!(v["resolved_at"].as_str().unwrap().contains('T'));
        let (_, v) = call(&app, "GET", "/incidents?followups=open", None).await;
        assert_eq!(v["count"], 1, "resolved but loose ends still listed");

        // wholesale re-add without timestamps must NOT wipe server stamps,
        // even across the archive boundary
        let (_, v) = call(&app, "POST", "/incidents", Some(json!({
            "key": key, "title": "prices 50x off after symbol remap", "service": "web_app2",
            "hosts": ["host-b"], "severity": "high", "status": "resolved",
            "resolution": "Recorders restarted; windows purged from CH.",
            "body": "Everything from before, follow-ups all done:\n- [x] guard dev NATS\n",
        }))).await;
        assert_eq!(v["action"], "created", "re-filing an archived report recreates the file: {v}");
        assert_eq!(v["archived"], true, "and a closed status archives it again: {v}");
        let (_, v) = call(&app, "GET", &format!("/knowledge/{key}"), None).await;
        assert_eq!(v["started_at"], "2026-07-22T08:09:40Z", "inherited: {v}");
        assert!(v["resolved_at"].as_str().unwrap().contains('T'), "inherited: {v}");
        assert_eq!(v["open_followups"], 0);
        let (_, v) = call(&app, "GET", "/incidents?followups=open", None).await;
        assert_eq!(v["count"], 0);
    }

    // a mitigated transition stamps mitigated_at
    #[tokio::test]
    async fn mitigated_timestamp_stamped() {
        let (app, _data, _idx) = app_with_tmp();
        let key = "inc-2026-07-23-nats-lag";
        call(&app, "POST", "/incidents", Some(json!({
            "key": key, "title": "lag", "body": "x", "service": "nats", "severity": "low",
        }))).await;
        call(&app, "POST", &format!("/incidents/{key}/resolve"),
            Some(json!({"status": "mitigated", "resolution": "hourly restart cron while the fix bakes"}))).await;
        let (_, v) = call(&app, "GET", &format!("/knowledge/{key}"), None).await;
        assert_eq!(v["status"], "mitigated");
        assert!(v["mitigated_at"].as_str().unwrap().contains('T'), "{v}");
        assert_eq!(v["resolved_at"], "");
    }

    #[rstest]
    #[case::window_missing_to(json!({"key": "inc-w", "title": "t", "body": "x", "service": "s", "severity": "low",
        "affected": [{"scope": "okx", "from": "2026-07-22T08:00:00Z", "to": ""}]}), 400)]
    #[case::window_ok(json!({"key": "inc-w", "title": "t", "body": "x", "service": "s", "severity": "low",
        "affected": [{"scope": "okx", "from": "2026-07-22T08:00:00Z", "to": "2026-07-22T09:00:00Z"}]}), 200)]
    #[tokio::test]
    async fn affected_window_validation(#[case] payload: Value, #[case] expect: u16) {
        let (app, _data, _idx) = app_with_tmp();
        let (st, v) = call(&app, "POST", "/incidents", Some(payload)).await;
        assert_eq!(st.as_u16(), expect, "response: {v}");
    }

    // a bare report is accepted but told what a complete one carries;
    // a structured one gets no hints
    #[tokio::test]
    async fn structure_hints() {
        let (app, _data, _idx) = app_with_tmp();
        let (st, v) = call(&app, "POST", "/incidents", Some(json!({
            "key": "inc-2026-07-23-bare", "title": "t", "body": "something broke",
            "service": "s", "severity": "low",
        }))).await;
        assert_eq!(st, StatusCode::OK);
        let hints = v["hints"].as_array().unwrap();
        assert_eq!(hints.len(), 4, "{v}");
        assert!(hints.iter().any(|h| h.as_str().unwrap().contains("detection")));

        let (_, v) = call(&app, "POST", "/incidents", Some(json!({
            "key": "inc-2026-07-23-full", "title": "t",
            "body": "Symptom: x.\nRoot cause (verified): y.\nFollow-ups:\n- [ ] z\n",
            "service": "s", "severity": "low",
            "detection": "check: 0 rows when healthy",
            "affected": [{"scope": "a", "from": "b", "to": "c"}],
        }))).await;
        assert!(v.get("hints").is_none(), "{v}");
    }

    // resolve endpoint edge cases: missing key, not an incident
    #[tokio::test]
    async fn resolve_edge_cases() {
        let (app, _data, _idx) = app_with_tmp();
        let (st, _) = call(&app, "POST", "/incidents/inc-nope/resolve",
            Some(json!({"resolution": "x"}))).await;
        assert_eq!(st, StatusCode::NOT_FOUND);
        call(&app, "POST", "/knowledge", Some(upsert_body("plain", "a fact"))).await;
        let (st, v) = call(&app, "POST", "/knowledge/../resolve", Some(json!({"resolution": "x"}))).await;
        assert!(st.is_client_error(), "{v}");
        let (st, v) = call(&app, "POST", "/incidents/plain/resolve",
            Some(json!({"resolution": "x"}))).await;
        assert_eq!(st, StatusCode::BAD_REQUEST, "{v}");
        assert!(v["error"].as_str().unwrap().contains("not an incident"));
    }

    // --- incident payload validation ---
    #[rstest]
    #[case::key_without_prefix(json!({"key": "orders-api-oom", "title": "t", "body": "x", "service": "s", "severity": "high"}), 400)]
    #[case::missing_service(json!({"key": "inc-a", "title": "t", "body": "x", "severity": "high"}), 422)]
    #[case::empty_service(json!({"key": "inc-a", "title": "t", "body": "x", "service": " ", "severity": "high"}), 400)]
    #[case::bad_severity(json!({"key": "inc-a", "title": "t", "body": "x", "service": "s", "severity": "huge"}), 400)]
    #[case::bad_status(json!({"key": "inc-a", "title": "t", "body": "x", "service": "s", "severity": "low", "status": "wip"}), 400)]
    #[case::bad_knowledge(json!({"key": "inc-a", "title": "t", "body": "x", "service": "s", "severity": "low", "knowledge": ["Bad Key"]}), 400)]
    #[case::secret_in_body(json!({"key": "inc-a", "title": "t", "body": "password: super123secret", "service": "s", "severity": "low"}), 400)]
    #[case::resolved_needs_resolution(json!({"key": "inc-a", "title": "t", "body": "x", "service": "s", "severity": "low", "status": "resolved"}), 400)]
    #[case::resolved_with_resolution(json!({"key": "inc-a", "title": "t", "body": "x", "service": "s", "severity": "low", "status": "resolved", "resolution": "fixed by restart"}), 200)]
    #[case::minimal_ok(json!({"key": "inc-a", "title": "t", "body": "x", "service": "s", "severity": "low"}), 200)]
    #[tokio::test]
    async fn incident_validation_matrix(#[case] payload: Value, #[case] expect: u16) {
        let (app, _data, _idx) = app_with_tmp();
        let (st, v) = call(&app, "POST", "/incidents", Some(payload)).await;
        assert_eq!(st.as_u16(), expect, "response: {v}");
    }

    // the inc- namespace is fenced off from plain knowledge writes
    #[tokio::test]
    async fn knowledge_cannot_take_inc_keys() {
        let (app, _data, _idx) = app_with_tmp();
        let (st, v) = call(&app, "POST", "/knowledge",
            Some(json!({"key": "inc-2026-07-22-fake", "title": "t", "body": "x"}))).await;
        assert_eq!(st, StatusCode::BAD_REQUEST, "{v}");
        assert!(v["error"].as_str().unwrap().contains("reserved"));
    }

    // filing a report that is already resolved archives it immediately;
    // archived reports stay listed, searchable and readable
    #[tokio::test]
    async fn incident_delete_and_history_search() {
        let (app, _data, _idx) = app_with_tmp();
        let key = "inc-2026-07-20-nats-lag";
        let (_, v) = call(&app, "POST", "/incidents", Some(json!({
            "key": key, "title": "NATS consumer lag", "body": "Consumers fell behind.",
            "service": "nats", "severity": "low", "status": "resolved",
            "resolution": "Consumers caught up after the stream limit was raised.",
        }))).await;
        assert_eq!(v["archived"], true, "{v}");
        // gone from the tree: a second DELETE has nothing to remove
        let (st, _) = call(&app, "DELETE", &format!("/knowledge/{key}"), None).await;
        assert_eq!(st, StatusCode::NOT_FOUND);
        // still part of the record: listed with --all, found by default search
        let (_, v) = call(&app, "GET", "/incidents", None).await;
        assert_eq!(v["count"], 0, "archived hidden from the default listing: {v}");
        let (_, v) = call(&app, "GET", "/incidents?all=true", None).await;
        assert_eq!(v["count"], 1);
        assert_eq!(v["incidents"][0]["archived"], true);
        let (_, v) = call(&app, "GET", "/search?q=consumer&kind=incident", None).await;
        assert_eq!(v["count"], 1, "{v}");
        assert_eq!(v["hits"][0]["is_head"], true);
        assert!(v["hits"][0]["resolution"].as_str().unwrap().contains("stream limit"));
        let (_, v) = call(&app, "GET", "/search?q=consumer&history=true&kind=incident", None).await;
        assert_eq!(v["count"], 1, "{v}");
        assert_eq!(v["hits"][0]["is_head"], false);
        // an OPEN incident deletes as an archive, not a retraction
        let key2 = "inc-2026-07-21-open-one";
        call(&app, "POST", "/incidents", Some(json!({
            "key": key2, "title": "open one", "body": "x", "service": "nats", "severity": "low",
        }))).await;
        let (_, v) = call(&app, "DELETE", &format!("/knowledge/{key2}"), None).await;
        assert_eq!(v["archived"], true, "{v}");
        let (_, v) = call(&app, "GET", &format!("/knowledge/{key2}"), None).await;
        assert_eq!(v["archived"], true, "readable after archive: {v}");
    }

    // tasks: the third kind — lightweight notes/ideas with a resolution loop
    #[tokio::test]
    async fn task_full_flow() {
        let (app, _data, _idx) = app_with_tmp();

        // the task- namespace is fenced off from plain knowledge
        let (st, v) = call(&app, "POST", "/knowledge",
            Some(json!({"key": "task-fake", "title": "t", "body": "x"}))).await;
        assert_eq!(st, StatusCode::BAD_REQUEST, "{v}");
        assert!(v["error"].as_str().unwrap().contains("reserved"));
        // and task keys must carry the prefix
        let (st, v) = call(&app, "POST", "/tasks",
            Some(json!({"key": "fix-logs", "title": "t", "body": "x"}))).await;
        assert_eq!(st, StatusCode::BAD_REQUEST, "{v}");

        // file a task; an idea is just a task tagged accordingly
        let key = "task-raise-log-retention";
        let (st, v) = call(&app, "POST", "/tasks", Some(json!({
            "key": key, "title": "Raise container log retention to 72h",
            "body": "Short retention loses evidence.\n\n- [ ] measure log volume first\n",
            "tags": ["idea", "observability"],
            "knowledge": ["web-app-architecture"],
        }))).await;
        assert_eq!(st, StatusCode::OK, "{v}");
        assert_eq!(v["action"], "created");
        assert_eq!(v["unknown_knowledge"], json!(["web-app-architecture"]));

        let (_, v) = call(&app, "GET", "/tasks", None).await;
        assert_eq!(v["count"], 1);
        assert_eq!(v["tasks"][0]["status"], "open");
        assert_eq!(v["tasks"][0]["archived"], false);
        assert_eq!(v["tasks"][0]["open_followups"], 1);
        let (_, v) = call(&app, "GET", "/healthz", None).await;
        assert_eq!(v["open_tasks"], 1);
        let (_, v) = call(&app, "GET", "/search?q=&kind=task", None).await;
        assert_eq!(v["count"], 1);

        // closing without saying what came of it is refused
        let (st, v) = call(&app, "POST", &format!("/tasks/{key}/resolve"), Some(json!({}))).await;
        assert_eq!(st, StatusCode::BAD_REQUEST, "{v}");
        assert!(v["error"].as_str().unwrap().contains("resolution"));

        // done: closed, archived — out of the default listing, kept in --all
        let (st, v) = call(&app, "POST", &format!("/tasks/{key}/resolve"),
            Some(json!({"resolution": "Retention raised to 72h with a 2G disk budget."}))).await;
        assert_eq!(st, StatusCode::OK, "{v}");
        assert_eq!(v["archived"], true, "{v}");
        let (_, v) = call(&app, "GET", "/tasks", None).await;
        assert_eq!(v["count"], 0, "archived hidden by default: {v}");
        let (_, v) = call(&app, "GET", "/tasks?all=true", None).await;
        assert_eq!(v["count"], 1);
        assert_eq!(v["tasks"][0]["status"], "done");
        assert_eq!(v["tasks"][0]["archived"], true);
        let (_, v) = call(&app, "GET", "/healthz", None).await;
        assert_eq!(v["open_tasks"], 0);
        let (_, v) = call(&app, "GET", &format!("/knowledge/{key}"), None).await;
        assert_eq!(v["kind"], "task");
        assert_eq!(v["archived"], true);
        assert!(v["resolved_at"].as_str().unwrap().contains('T'), "stamped: {v}");
        let (_, v) = call(&app, "GET", "/search?q=retention%20disk&kind=task", None).await;
        assert_eq!(v["count"], 1, "{v}");
        assert_eq!(v["hits"][0]["is_head"], true);

        // dropped needs a reason too, and ranks below done in the --all listing
        call(&app, "POST", "/tasks", Some(json!({
            "key": "task-try-foo", "title": "Try foo", "body": "x",
        }))).await;
        let (_, v) = call(&app, "POST", "/tasks/task-try-foo/resolve",
            Some(json!({"status": "dropped", "resolution": "Obsolete after the bar rewrite."}))).await;
        assert_eq!(v["archived"], true, "{v}");
        let (_, v) = call(&app, "GET", "/tasks?all=true", None).await;
        assert_eq!(v["count"], 2);
        assert_eq!(v["tasks"][0]["status"], "done");
        assert_eq!(v["tasks"][1]["status"], "dropped");

        // the incident endpoint refuses tasks
        let (st, v) = call(&app, "POST", &format!("/incidents/{key}/resolve"),
            Some(json!({"resolution": "x"}))).await;
        assert_eq!(st, StatusCode::BAD_REQUEST, "{v}");
        assert!(v["error"].as_str().unwrap().contains("not an incident"));
    }

    // priority + the widened lifecycle: create, filter, transition, archive
    #[tokio::test]
    async fn task_priority_and_status_flow() {
        let (app, _data, _idx) = app_with_tmp();

        // priority rides through create -> GET -> listing -> search
        let key = "task-raise-log-retention";
        let (st, v) = call(&app, "POST", "/tasks", Some(json!({
            "key": key, "title": "Raise container log retention to 72h",
            "body": "Short retention loses evidence.", "priority": "high",
        }))).await;
        assert_eq!(st, StatusCode::OK, "{v}");
        let (_, v) = call(&app, "GET", &format!("/knowledge/{key}"), None).await;
        assert_eq!(v["priority"], "high");
        assert_eq!(v["blocked_reason"], "");
        assert_eq!(v["status"], "open");

        // an unranked task is the default and stays empty, never guessed
        call(&app, "POST", "/tasks", Some(json!({
            "key": "task-try-foo", "title": "Try foo", "body": "an idea",
        }))).await;
        let (_, v) = call(&app, "GET", "/knowledge/task-try-foo", None).await;
        assert_eq!(v["priority"], "", "{v}");

        // a second ranked task, plus one that is in flight
        call(&app, "POST", "/tasks", Some(json!({
            "key": "task-swap-disk", "title": "Swap the failing disk", "body": "x",
            "priority": "critical", "status": "in_progress",
        }))).await;

        // the exact priority filter on the listing
        let (_, v) = call(&app, "GET", "/tasks?priority=high", None).await;
        assert_eq!(v["count"], 1, "{v}");
        assert_eq!(v["tasks"][0]["key"], key);
        assert_eq!(v["tasks"][0]["priority"], "high");
        let (_, v) = call(&app, "GET", "/tasks?priority=low", None).await;
        assert_eq!(v["count"], 0);
        // an empty ?priority= (what the CLI sends) is "no filter"
        let (_, v) = call(&app, "GET", "/tasks?status=&priority=&limit=50", None).await;
        assert_eq!(v["count"], 3, "{v}");
        // it combines with the status filter
        let (_, v) = call(&app, "GET", "/tasks?status=in_progress&priority=critical", None).await;
        assert_eq!(v["count"], 1, "{v}");
        assert_eq!(v["tasks"][0]["key"], "task-swap-disk");
        // and search takes the same exact filter
        let (_, v) = call(&app, "GET", "/search?q=&kind=task&priority=critical", None).await;
        assert_eq!(v["count"], 1, "{v}");
        assert_eq!(v["hits"][0]["key"], "task-swap-disk");
        assert_eq!(v["hits"][0]["priority"], "critical");

        // block it: the reason is recorded and comes back everywhere
        let (st, v) = call(&app, "POST", "/tasks", Some(json!({
            "key": "task-swap-disk", "title": "Swap the failing disk", "body": "x",
            "priority": "critical", "status": "blocked",
            "blocked_reason": "waiting on the replacement disk to arrive",
        }))).await;
        assert_eq!(st, StatusCode::OK, "{v}");
        assert!(v.get("archived").is_none(), "blocked is not an ending: {v}");
        let (_, v) = call(&app, "GET", "/knowledge/task-swap-disk", None).await;
        assert_eq!(v["status"], "blocked");
        assert_eq!(v["blocked_reason"], "waiting on the replacement disk to arrive");
        assert!(v.get("archived").is_none(), "still live in the canon: {v}");
        let (_, v) = call(&app, "GET", "/tasks?status=blocked", None).await;
        assert_eq!(v["tasks"][0]["blocked_reason"], "waiting on the replacement disk to arrive");
        let (_, v) = call(&app, "GET", "/search?q=&kind=task&status=blocked", None).await;
        assert_eq!(v["hits"][0]["blocked_reason"], "waiting on the replacement disk to arrive");

        // all three live statuses are live: listed by default and counted
        let (_, v) = call(&app, "GET", "/tasks", None).await;
        assert_eq!(v["count"], 3, "open + in_progress(now blocked) + open: {v}");
        let (_, v) = call(&app, "GET", "/healthz", None).await;
        assert_eq!(v["open_tasks"], 3, "blocked and in_progress count as work: {v}");

        // moving off blocked clears the stale reason instead of committing a
        // state that contradicts itself
        let (_, v) = call(&app, "POST", "/tasks/task-swap-disk/resolve",
            Some(json!({"status": "in_progress"}))).await;
        assert_eq!(v["changed"], true, "{v}");
        let (_, v) = call(&app, "GET", "/knowledge/task-swap-disk", None).await;
        assert_eq!(v["status"], "in_progress");
        assert_eq!(v["blocked_reason"], "", "stale reason dropped: {v}");
        assert_eq!(v["priority"], "critical", "priority survives the transition: {v}");

        // only the terminal statuses close and archive
        let (_, v) = call(&app, "POST", "/tasks/task-swap-disk/resolve",
            Some(json!({"resolution": "New disk installed and the array rebuilt."}))).await;
        assert_eq!(v["archived"], true, "{v}");
        let (_, v) = call(&app, "GET", "/healthz", None).await;
        assert_eq!(v["open_tasks"], 2);
        let (_, v) = call(&app, "GET", "/tasks", None).await;
        assert_eq!(v["count"], 2, "archived hidden by default: {v}");
        // the archived task keeps its priority in the record
        let (_, v) = call(&app, "GET", "/knowledge/task-swap-disk", None).await;
        assert_eq!(v["archived"], true);
        assert_eq!(v["priority"], "critical", "{v}");
        assert_eq!(v["status"], "done");
        let (_, v) = call(&app, "GET", "/tasks?all=true&priority=critical", None).await;
        assert_eq!(v["count"], 1, "the archive answers the priority filter too: {v}");
        assert_eq!(v["tasks"][0]["archived"], true);

        // closing a blocked task directly: the reason is dropped, not carried
        call(&app, "POST", "/tasks", Some(json!({
            "key": "task-try-foo", "title": "Try foo", "body": "an idea",
            "status": "blocked", "blocked_reason": "waiting on the bar rewrite",
        }))).await;
        let (_, v) = call(&app, "POST", "/tasks/task-try-foo/resolve",
            Some(json!({"status": "dropped", "resolution": "Obsolete after the bar rewrite."}))).await;
        assert_eq!(v["archived"], true, "{v}");
        let (_, v) = call(&app, "GET", "/knowledge/task-try-foo", None).await;
        assert_eq!(v["status"], "dropped");
        assert_eq!(v["blocked_reason"], "", "{v}");
    }

    // ownership and the parent link: create -> GET -> listing -> search
    #[tokio::test]
    async fn task_ownership_and_parent_flow() {
        let (app, _data, _idx) = app_with_tmp();

        // an umbrella task, claimed under a stable public label
        let parent = "task-migrate-logs";
        let (st, v) = call(&app, "POST", "/tasks", Some(json!({
            "key": parent, "title": "Migrate the log pipeline", "body": "The umbrella task.",
            "status": "in_progress", "priority": "high", "assignee": "agent-a",
        }))).await;
        assert_eq!(st, StatusCode::OK, "{v}");
        assert!(v.get("unknown_parent").is_none(), "a top-level task has no parent: {v}");

        // a child hangs under it
        let child = "task-migrate-logs-step-one";
        let (st, v) = call(&app, "POST", "/tasks", Some(json!({
            "key": child, "title": "Step one: measure the volume", "body": "x",
            "assignee": "agent-b", "parent_task": parent,
        }))).await;
        assert_eq!(st, StatusCode::OK, "{v}");
        assert!(v.get("unknown_parent").is_none(), "the parent exists: {v}");

        // a forward reference is reported, not refused — the parent may be
        // filed after the child
        let (st, v) = call(&app, "POST", "/tasks", Some(json!({
            "key": "task-orphan", "title": "Filed before its parent", "body": "x",
            "parent_task": "task-not-written-yet",
        }))).await;
        assert_eq!(st, StatusCode::OK, "{v}");
        assert_eq!(v["unknown_parent"], "task-not-written-yet");

        // GET carries both fields; an unclaimed task carries them empty
        let (_, v) = call(&app, "GET", &format!("/knowledge/{child}"), None).await;
        assert_eq!(v["assignee"], "agent-b");
        assert_eq!(v["parent_task"], parent);
        let (_, v) = call(&app, "GET", "/knowledge/task-orphan", None).await;
        assert_eq!(v["assignee"], "", "{v}");
        assert_eq!(v["parent_task"], "task-not-written-yet");

        // the listing filters exactly
        let (_, v) = call(&app, "GET", "/tasks?assignee=agent-a", None).await;
        assert_eq!(v["count"], 1, "{v}");
        assert_eq!(v["tasks"][0]["key"], parent);
        assert_eq!(v["tasks"][0]["assignee"], "agent-a");
        let (_, v) = call(&app, "GET", &format!("/tasks?parent_task={parent}"), None).await;
        assert_eq!(v["count"], 1, "{v}");
        assert_eq!(v["tasks"][0]["key"], child);
        assert_eq!(v["tasks"][0]["parent_task"], parent);
        let (_, v) = call(&app, "GET", "/tasks?assignee=agent-nobody", None).await;
        assert_eq!(v["count"], 0);
        // empty params (what the CLI sends) are "no filter", not "match nothing"
        let (_, v) = call(&app, "GET", "/tasks?assignee=&parent_task=&limit=50", None).await;
        assert_eq!(v["count"], 3, "{v}");

        // and search takes the same exact filters
        let (_, v) = call(&app, "GET", "/search?q=&kind=task&assignee=agent-b", None).await;
        assert_eq!(v["count"], 1, "{v}");
        assert_eq!(v["hits"][0]["key"], child);
        assert_eq!(v["hits"][0]["assignee"], "agent-b");
        assert_eq!(v["hits"][0]["parent_task"], parent);
        let (_, v) =
            call(&app, "GET", &format!("/search?q=&kind=task&parent_task={parent}"), None).await;
        assert_eq!(v["count"], 1, "{v}");
        let (_, v) = call(&app, "GET", "/search?q=&kind=task&assignee=&parent_task=", None).await;
        assert_eq!(v["count"], 3, "{v}");

        // an archived parent is still a known parent: the record outlives the file
        call(&app, "POST", &format!("/tasks/{parent}/resolve"),
            Some(json!({"resolution": "Pipeline migrated."}))).await;
        let (_, v) = call(&app, "POST", "/tasks", Some(json!({
            "key": "task-migrate-logs-step-two", "title": "Step two", "body": "x",
            "parent_task": parent,
        }))).await;
        assert!(v.get("unknown_parent").is_none(), "an archived parent still exists: {v}");
    }

    // the partial transition: move a task without resending what it says
    #[tokio::test]
    async fn task_transition_partial_updates() {
        let (app, _data, _idx) = app_with_tmp();
        let key = "task-raise-log-retention";
        call(&app, "POST", "/tasks", Some(json!({
            "key": key, "title": "Raise container log retention to 72h",
            "body": "Short retention loses evidence.\n\n- [ ] measure log volume first\n",
            "priority": "high", "tags": ["observability"],
            "knowledge": ["web-app-architecture"], "refs": ["see the compose file on the log host"],
        }))).await;

        // pick it up: status plus an owner label, nothing else resent
        let (st, v) = call(&app, "POST", &format!("/tasks/{key}/transition"),
            Some(json!({"status": "in_progress", "assignee": "agent-a"}))).await;
        assert_eq!(st, StatusCode::OK, "{v}");
        assert_eq!(v["changed"], true);
        assert_eq!(v["action"], "updated");
        assert_eq!(v["status"], "in_progress");
        assert_eq!(v["assignee"], "agent-a");
        let (_, v) = call(&app, "GET", &format!("/knowledge/{key}"), None).await;
        assert_eq!(v["status"], "in_progress");
        assert_eq!(v["assignee"], "agent-a");
        assert_eq!(v["title"], "Raise container log retention to 72h", "title kept: {v}");
        assert_eq!(v["priority"], "high", "omitted metadata survives: {v}");
        assert_eq!(v["tags"], json!(["observability"]));
        assert_eq!(v["refs"], json!(["see the compose file on the log host"]));
        assert_eq!(v["knowledge"], json!(["web-app-architecture"]));
        assert!(v["body"].as_str().unwrap().contains("measure log volume"), "body kept: {v}");
        assert_eq!(v["open_followups"], 1);
        assert!(v.get("archived").is_none(), "a live transition never archives: {v}");
        let (_, v) = call(&app, "GET", "/healthz", None).await;
        assert_eq!(v["open_tasks"], 1, "still work in flight: {v}");

        // block it: the reason lands, everything else stays
        let (_, v) = call(&app, "POST", &format!("/tasks/{key}/transition"),
            Some(json!({"status": "blocked", "blocked_reason": "waiting on the disk budget approval"}))).await;
        assert_eq!(v["status"], "blocked", "{v}");
        let (_, v) = call(&app, "GET", &format!("/knowledge/{key}"), None).await;
        assert_eq!(v["blocked_reason"], "waiting on the disk budget approval");
        assert_eq!(v["assignee"], "agent-a", "an omitted assignee is kept: {v}");
        assert_eq!(v["priority"], "high");

        // leaving blocked clears the reason even though the request never named it
        let (_, v) = call(&app, "POST", &format!("/tasks/{key}/transition"),
            Some(json!({"status": "in_progress"}))).await;
        assert_eq!(v["changed"], true, "{v}");
        let (_, v) = call(&app, "GET", &format!("/knowledge/{key}"), None).await;
        assert_eq!(v["blocked_reason"], "", "stale reason dropped: {v}");
        assert_eq!(v["status"], "in_progress");

        // hand it back: an explicit empty assignee unclaims it
        let (_, v) = call(&app, "POST", &format!("/tasks/{key}/transition"),
            Some(json!({"status": "open", "assignee": ""}))).await;
        assert_eq!(v["assignee"], "", "{v}");
        let (_, v) = call(&app, "GET", &format!("/knowledge/{key}"), None).await;
        assert_eq!(v["assignee"], "");
        assert_eq!(v["status"], "open");

        // relate it to a parent without touching anything else
        let (_, v) = call(&app, "POST", &format!("/tasks/{key}/transition"),
            Some(json!({"status": "in_progress", "parent_task": "task-migrate-logs"}))).await;
        assert_eq!(v["unknown_parent"], "task-migrate-logs", "forward reference reported: {v}");
        let (_, v) = call(&app, "GET", &format!("/knowledge/{key}"), None).await;
        assert_eq!(v["parent_task"], "task-migrate-logs");
        assert_eq!(v["priority"], "high", "{v}");

        // every transition is a git version: history + get --at reconstruct who
        // held the task, and in which status, at any point
        let (_, v) = call(&app, "GET", &format!("/knowledge/{key}/history"), None).await;
        let versions = v["versions"].as_array().unwrap().clone();
        assert_eq!(versions.len(), 6, "create + 5 transitions: {versions:?}");
        let claimed = versions[versions.len() - 2]["sha"].as_str().unwrap().to_string();
        let (_, v) = call(&app, "GET", &format!("/knowledge/{key}?at={claimed}"), None).await;
        assert_eq!(v["assignee"], "agent-a", "the earlier owner is reconstructable: {v}");
        assert_eq!(v["status"], "in_progress");

        // closing still goes through resolve, and the record keeps the owner
        let (_, v) = call(&app, "POST", &format!("/tasks/{key}/resolve"),
            Some(json!({"resolution": "Raised to 72h with a 2G disk budget."}))).await;
        assert_eq!(v["archived"], true, "{v}");
        let (_, v) = call(&app, "GET", &format!("/knowledge/{key}"), None).await;
        assert_eq!(v["status"], "done");
        assert_eq!(v["parent_task"], "task-migrate-logs", "{v}");

        // an archived task can be picked back up: the file returns
        let (_, v) = call(&app, "POST", &format!("/tasks/{key}/transition"),
            Some(json!({"status": "in_progress", "assignee": "agent-b"}))).await;
        assert_eq!(v["action"], "created", "reopening recreates the file: {v}");
        let (_, v) = call(&app, "GET", &format!("/knowledge/{key}"), None).await;
        assert!(v.get("archived").is_none(), "back in the canon: {v}");
        assert_eq!(v["assignee"], "agent-b");
    }

    // Parent links form a chain, never a ring — for both wholesale writes and
    // partial transitions, including cycles longer than self-parenting.
    #[tokio::test]
    async fn task_parent_cycles_rejected() {
        let (app, _data, _idx) = app_with_tmp();
        for (key, parent) in [
            ("task-project", ""),
            ("task-project-step-one", "task-project"),
            ("task-project-step-two", "task-project-step-one"),
        ] {
            let (st, v) = call(&app, "POST", "/tasks", Some(json!({
                "key": key, "title": key, "body": "x", "parent_task": parent,
            }))).await;
            assert_eq!(st, StatusCode::OK, "{v}");
        }

        // project -> step two -> step one -> project would be a three-node cycle
        let (st, v) = call(&app, "POST", "/tasks", Some(json!({
            "key": "task-project", "title": "task-project", "body": "x",
            "parent_task": "task-project-step-two",
        }))).await;
        assert_eq!(st, StatusCode::BAD_REQUEST, "{v}");
        assert!(v["error"].as_str().unwrap().contains("cycle"), "{v}");

        let (st, v) = call(&app, "POST", "/tasks/task-project/transition", Some(json!({
            "status": "in_progress", "parent_task": "task-project-step-two",
        }))).await;
        assert_eq!(st, StatusCode::BAD_REQUEST, "{v}");
        assert!(v["error"].as_str().unwrap().contains("cycle"), "{v}");

        // Neither rejected write changed the root.
        let (_, v) = call(&app, "GET", "/knowledge/task-project", None).await;
        assert_eq!(v["status"], "open", "{v}");
        assert_eq!(v["parent_task"], "", "{v}");
    }

    // the transition endpoint is not a closing endpoint, and not a way past
    // validation either
    #[tokio::test]
    async fn task_transition_rejections() {
        let (app, _data, _idx) = app_with_tmp();
        let key = "task-swap-disk";
        call(&app, "POST", "/tasks", Some(json!({
            "key": key, "title": "Swap the failing disk", "body": "x", "priority": "critical",
        }))).await;
        call(&app, "POST", "/knowledge", Some(upsert_body("plain-note", "a fact"))).await;

        // the terminal statuses need an outcome — and say where to give one
        for status in ["done", "dropped"] {
            let (st, v) = call(&app, "POST", &format!("/tasks/{key}/transition"),
                Some(json!({"status": status}))).await;
            assert_eq!(st, StatusCode::BAD_REQUEST, "{status}: {v}");
            let err = v["error"].as_str().unwrap();
            assert!(err.contains("kyb done"), "{status}: {err}");
            assert!(err.contains("/resolve"), "{status}: {err}");
        }

        let bad = [
            json!({"status": "wip"}),
            json!({"status": ""}),
            json!({"status": "mitigated"}),
            json!({"status": "in_progress", "assignee": "token: ghp_abcdefghijklmnopqrstuvwxyz123456"}),
            json!({"status": "in_progress", "assignee": "x".repeat(model::ASSIGNEE_MAX_LEN + 1)}),
            json!({"status": "in_progress", "parent_task": "not-a-task-key"}),
            json!({"status": "in_progress", "parent_task": "inc-2026-08-15-oom"}),
        ];
        for payload in bad {
            let (st, v) =
                call(&app, "POST", &format!("/tasks/{key}/transition"), Some(payload.clone())).await;
            assert_eq!(st, StatusCode::BAD_REQUEST, "payload {payload}: {v}");
        }
        // a task cannot hang under itself — the smallest broken tree
        let (st, v) = call(&app, "POST", &format!("/tasks/{key}/transition"),
            Some(json!({"status": "in_progress", "parent_task": key}))).await;
        assert_eq!(st, StatusCode::BAD_REQUEST, "self-parenting: {v}");
        assert!(v["error"].as_str().unwrap().contains("own parent"), "{v}");

        // wrong kind, missing key, garbage key
        let (st, v) = call(&app, "POST", "/tasks/plain-note/transition",
            Some(json!({"status": "in_progress"}))).await;
        assert_eq!(st, StatusCode::BAD_REQUEST, "{v}");
        assert!(v["error"].as_str().unwrap().contains("not a task"), "{v}");
        let (st, _) = call(&app, "POST", "/tasks/task-nope/transition",
            Some(json!({"status": "in_progress"}))).await;
        assert_eq!(st, StatusCode::NOT_FOUND);
        let (st, _) = call(&app, "POST", "/tasks/Bad%20Key/transition",
            Some(json!({"status": "in_progress"}))).await;
        assert_eq!(st, StatusCode::BAD_REQUEST);
        let (st, _) = call(&app, "POST", &format!("/tasks/{key}/transition"), Some(json!({}))).await;
        assert!(st.is_client_error(), "status is required");

        // through all of that the task never moved
        let (_, v) = call(&app, "GET", &format!("/knowledge/{key}"), None).await;
        assert_eq!(v["status"], "open", "{v}");
        assert_eq!(v["assignee"], "");
        assert_eq!(v["parent_task"], "");
        assert_eq!(v["priority"], "critical");
    }

    // tasks written before this feature carry neither field and keep working:
    // they list, they filter, and they can be claimed with one transition
    #[tokio::test]
    async fn legacy_task_without_ownership_still_works() {
        let (app, _data, _idx) = app_with_tmp();
        let key = "task-old-note";
        let (st, v) = call(&app, "POST", "/tasks", Some(json!({
            "key": key, "title": "An old note", "body": "written before ownership existed",
        }))).await;
        assert_eq!(st, StatusCode::OK, "{v}");
        let (_, v) = call(&app, "GET", &format!("/knowledge/{key}"), None).await;
        assert_eq!(v["assignee"], "", "{v}");
        assert_eq!(v["parent_task"], "");
        assert_eq!(v["status"], "open");
        let (_, v) = call(&app, "GET", "/tasks", None).await;
        assert_eq!(v["count"], 1);
        assert_eq!(v["tasks"][0]["assignee"], "");
        assert_eq!(v["tasks"][0]["parent_task"], "");

        // claiming it needs neither the title nor the body
        let (st, v) = call(&app, "POST", &format!("/tasks/{key}/transition"),
            Some(json!({"status": "in_progress", "assignee": "agent-a"}))).await;
        assert_eq!(st, StatusCode::OK, "{v}");
        let (_, v) = call(&app, "GET", &format!("/knowledge/{key}"), None).await;
        assert_eq!(v["assignee"], "agent-a");
        assert!(v["body"].as_str().unwrap().contains("before ownership"), "{v}");
    }

    // --- task payload validation: the new fields ---
    #[rstest]
    #[case::priority_high(json!({"key": "task-a", "title": "t", "body": "x", "priority": "high"}), 200)]
    #[case::priority_absent(json!({"key": "task-a", "title": "t", "body": "x"}), 200)]
    #[case::priority_empty(json!({"key": "task-a", "title": "t", "body": "x", "priority": ""}), 200)]
    #[case::priority_unknown(json!({"key": "task-a", "title": "t", "body": "x", "priority": "urgent"}), 400)]
    #[case::priority_wrong_case(json!({"key": "task-a", "title": "t", "body": "x", "priority": "HIGH"}), 400)]
    #[case::status_in_progress(json!({"key": "task-a", "title": "t", "body": "x", "status": "in_progress"}), 200)]
    #[case::status_blocked_bare(json!({"key": "task-a", "title": "t", "body": "x", "status": "blocked"}), 200)]
    #[case::status_blocked_with_reason(json!({"key": "task-a", "title": "t", "body": "x", "status": "blocked", "blocked_reason": "waiting on vendor"}), 200)]
    #[case::status_unknown(json!({"key": "task-a", "title": "t", "body": "x", "status": "wip"}), 400)]
    #[case::stale_reason_on_open(json!({"key": "task-a", "title": "t", "body": "x", "blocked_reason": "waiting on vendor"}), 400)]
    #[case::stale_reason_on_in_progress(json!({"key": "task-a", "title": "t", "body": "x", "status": "in_progress", "blocked_reason": "waiting on vendor"}), 400)]
    #[case::stale_reason_on_done(json!({"key": "task-a", "title": "t", "body": "x", "status": "done", "resolution": "shipped", "blocked_reason": "waiting on vendor"}), 400)]
    #[case::secret_in_reason(json!({"key": "task-a", "title": "t", "body": "x", "status": "blocked", "blocked_reason": "password: super123secret"}), 400)]
    #[case::in_progress_needs_no_resolution(json!({"key": "task-a", "title": "t", "body": "x", "status": "in_progress"}), 200)]
    #[case::done_still_needs_resolution(json!({"key": "task-a", "title": "t", "body": "x", "status": "done"}), 400)]
    #[case::assignee_absent(json!({"key": "task-a", "title": "t", "body": "x"}), 200)]
    #[case::assignee_label(json!({"key": "task-a", "title": "t", "body": "x", "assignee": "agent-a"}), 200)]
    #[case::assignee_blank_is_unclaimed(json!({"key": "task-a", "title": "t", "body": "x", "assignee": "   "}), 200)]
    #[case::assignee_secret(json!({"key": "task-a", "title": "t", "body": "x", "assignee": "password: super123secret"}), 400)]
    #[case::parent_absent(json!({"key": "task-a", "title": "t", "body": "x"}), 200)]
    #[case::parent_task_key(json!({"key": "task-a", "title": "t", "body": "x", "parent_task": "task-parent"}), 200)]
    #[case::parent_not_a_task(json!({"key": "task-a", "title": "t", "body": "x", "parent_task": "nats-streams"}), 400)]
    #[case::parent_malformed(json!({"key": "task-a", "title": "t", "body": "x", "parent_task": "task-Bad Key"}), 400)]
    #[case::parent_traversal(json!({"key": "task-a", "title": "t", "body": "x", "parent_task": "../task-x"}), 400)]
    #[case::parent_self(json!({"key": "task-a", "title": "t", "body": "x", "parent_task": "task-a"}), 400)]
    #[tokio::test]
    async fn task_validation_matrix(#[case] payload: Value, #[case] expect: u16) {
        let (app, _data, _idx) = app_with_tmp();
        let (st, v) = call(&app, "POST", "/tasks", Some(payload)).await;
        assert_eq!(st.as_u16(), expect, "response: {v}");
    }

    // the task-only fields must not leak onto the other kinds
    #[rstest]
    #[case::knowledge_priority("/knowledge", json!({"key": "k", "title": "t", "body": "x", "priority": "high"}))]
    #[case::knowledge_assignee("/knowledge", json!({"key": "k", "title": "t", "body": "x", "assignee": "agent-a"}))]
    #[case::knowledge_parent("/knowledge", json!({"key": "k", "title": "t", "body": "x", "parent_task": "task-x"}))]
    #[case::incident_priority("/incidents", json!({"key": "inc-a", "title": "t", "body": "x", "service": "s", "severity": "low", "priority": "high"}))]
    #[case::incident_assignee("/incidents", json!({"key": "inc-a", "title": "t", "body": "x", "service": "s", "severity": "low", "assignee": "agent-a"}))]
    #[case::incident_parent("/incidents", json!({"key": "inc-a", "title": "t", "body": "x", "service": "s", "severity": "low", "parent_task": "task-x"}))]
    #[tokio::test]
    async fn task_only_fields_ignored_on_other_kinds(#[case] path: &str, #[case] payload: Value) {
        let (app, _data, _idx) = app_with_tmp();
        // unknown fields are dropped by the request types, so the write lands
        // clean rather than smuggling a task field into another kind
        let (st, v) = call(&app, "POST", path, Some(payload)).await;
        assert_eq!(st, StatusCode::OK, "{v}");
        let key = v["key"].as_str().unwrap().to_string();
        let (_, v) = call(&app, "GET", &format!("/knowledge/{key}"), None).await;
        assert!(v.get("priority").is_none(), "priority is task-only: {v}");
        assert!(v.get("blocked_reason").is_none(), "blocked_reason is task-only: {v}");
        assert!(v.get("assignee").is_none(), "assignee is task-only: {v}");
        assert!(v.get("parent_task").is_none(), "parent_task is task-only: {v}");
    }

    #[tokio::test]
    async fn tags_endpoint_and_tag_search() {
        let (app, _data, _idx) = app_with_tmp();
        let post = |k: &str, tags: Value| {
            json!({"key": k, "title": "t", "body": "apples and bicycles", "tags": tags})
        };
        call(&app, "POST", "/knowledge", Some(post("a", json!(["Infra", "nats"])))).await;
        call(&app, "POST", "/knowledge", Some(post("b", json!(["infra"])))).await;
        call(&app, "POST", "/knowledge", Some(post("c", json!(["kubernetes"])))).await;

        // the base can report which topics it covers, most used first
        let (st, v) = call(&app, "GET", "/tags", None).await;
        assert_eq!(st, StatusCode::OK);
        assert_eq!(v["count"], 3);
        assert_eq!(v["tags"][0]["tag"], "infra");
        assert_eq!(v["tags"][0]["count"], 2, "case-folded and counted: {v}");

        // a tag is findable by free text even though no body mentions it
        let (_, v) = call(&app, "GET", "/search?q=kubernetes", None).await;
        assert_eq!(v["count"], 1);
        assert_eq!(v["hits"][0]["key"], "c");

        // deleting an entry drops its tag from the listing
        call(&app, "DELETE", "/knowledge/c", None).await;
        let (_, v) = call(&app, "GET", "/tags", None).await;
        assert_eq!(v["count"], 2);
    }

    #[tokio::test]
    async fn search_sort_recent() {
        let (app, _data, _idx) = app_with_tmp();
        call(&app, "POST", "/knowledge", Some(upsert_body("older", "shared shared shared"))).await;
        call(&app, "POST", "/knowledge", Some(upsert_body("newer", "shared once"))).await;

        let (_, v) = call(&app, "GET", "/search?q=shared", None).await;
        assert_eq!(v["hits"][0]["key"], "older", "relevance favours the denser match");
        let (_, v) = call(&app, "GET", "/search?q=shared&sort=recent", None).await;
        assert_eq!(v["hits"][0]["key"], "newer", "recent sort puts the latest first");
        // an empty query is a listing, and listings read newest first
        let (_, v) = call(&app, "GET", "/search?q=&sort=", None).await;
        assert_eq!(v["hits"][0]["key"], "newer", "empty q defaults to recent: {v}");
    }

    // reindex is idempotent: N runs — same numbers
    #[tokio::test]
    async fn reindex_idempotent() {
        let (app, _data, _idx) = app_with_tmp();
        call(&app, "POST", "/knowledge", Some(upsert_body("a", "one"))).await;
        call(&app, "POST", "/knowledge", Some(upsert_body("a", "two"))).await;
        call(&app, "POST", "/knowledge", Some(upsert_body("b", "three"))).await;
        for _ in 0..3 {
            let (_, v) = call(&app, "POST", "/reindex", None).await;
            assert_eq!(v["head_docs"], 2);
            assert_eq!(v["history_docs"], 3);
        }
        let (_, v) = call(&app, "GET", "/search?q=two", None).await;
        assert_eq!(v["count"], 1, "search must be alive after reindex");
    }

    // 10 parallel writes to distinct keys: the single writer mutex must
    // serialize them with no losses and no broken commits
    #[tokio::test]
    async fn api_concurrent_upserts() {
        let (app, _data, _idx) = app_with_tmp();
        let mut set = tokio::task::JoinSet::new();
        for i in 0..10 {
            let app = app.clone();
            set.spawn(async move {
                let body = json!({
                    "key": format!("key-{i}"),
                    "title": format!("Entry {i}"),
                    "body": format!("body {i}"),
                });
                call(&app, "POST", "/knowledge", Some(body)).await
            });
        }
        while let Some(res) = set.join_next().await {
            let (st, v) = res.unwrap();
            assert_eq!(st, StatusCode::OK, "{v}");
            assert_eq!(v["changed"], true);
        }
        let (_, v) = call(&app, "GET", "/healthz", None).await;
        assert_eq!(v["entries"], 10);
        let (_, v) = call(&app, "GET", "/search?q=&limit=50", None).await;
        assert_eq!(v["count"], 10);
        // history intact: exactly one version per key
        let (_, v) = call(&app, "POST", "/reindex", None).await;
        assert_eq!(v["head_docs"], 10);
        assert_eq!(v["history_docs"], 10);
    }

    // --- same-key interleavings, replayed exactly ---
    //
    // These do not stress the server and hope: the test holds the global writer
    // lock, parks the competing requests on it one after another, and then lets
    // them go. The order is the queue order, so every run reproduces the same
    // interleaving — the one that used to lose a write.

    /// Park a POST on the writer lock the test is holding.
    ///
    /// The test runtime is single-threaded and the request has no other
    /// suspension point on its way to that lock, so by the time the spawned
    /// task has signalled and the scheduler has drained, it is queued on the
    /// mutex — behind whoever was parked before it — with nothing read yet.
    async fn park_on_writer_lock(
        app: &Router,
        uri: String,
        body: Value,
    ) -> tokio::task::JoinHandle<(StatusCode, Value)> {
        let app = app.clone();
        let (started, ready) = tokio::sync::oneshot::channel();
        let task = tokio::spawn(async move {
            let _ = started.send(());
            call(&app, "POST", &uri, Some(body)).await
        });
        ready.await.expect("the request task must start");
        // drain anything already runnable, so the request is parked on the lock
        // before the caller queues the next one behind it
        for _ in 0..8 {
            tokio::task::yield_now().await;
        }
        task
    }

    fn open_task(key: &str) -> Value {
        json!({
            "key": key, "title": "Rotate the internal TLS certificates",
            "body": "They expire in a week.\n\n- [ ] schedule the restart window\n",
            "priority": "high", "tags": ["security"],
        })
    }

    // Two partial transitions on ONE key: the second must build on the version
    // the first committed, not on the one it replaced.
    #[tokio::test]
    async fn concurrent_transitions_keep_the_earlier_update() {
        let (app, state, _data, _idx) = app_with_state();
        let key = "task-rotate-tls-certs";
        let (st, v) = call(&app, "POST", "/tasks", Some(open_task(key))).await;
        assert_eq!(st, StatusCode::OK, "{v}");

        let guard = state.writer.lock().await;
        let claim = park_on_writer_lock(
            &app,
            format!("/tasks/{key}/transition"),
            json!({"status": "in_progress", "assignee": "agent-a"}),
        )
        .await;
        let block = park_on_writer_lock(
            &app,
            format!("/tasks/{key}/transition"),
            json!({"status": "blocked", "blocked_reason": "waiting on the CA"}),
        )
        .await;
        drop(guard); // the claim parked first, so the claim runs first

        let (st, claimed) = claim.await.unwrap();
        assert_eq!(st, StatusCode::OK, "{claimed}");
        let (st, blocked) = block.await.unwrap();
        assert_eq!(st, StatusCode::OK, "{blocked}");
        assert_eq!(claimed["assignee"], "agent-a");
        assert_eq!(blocked["status"], "blocked");
        assert_eq!(
            blocked["assignee"], "agent-a",
            "the second transition read the first one's commit: {blocked}"
        );

        let (_, v) = call(&app, "GET", &format!("/knowledge/{key}"), None).await;
        assert_eq!(v["status"], "blocked");
        assert_eq!(v["blocked_reason"], "waiting on the CA");
        assert_eq!(v["assignee"], "agent-a", "the claim was not overwritten: {v}");
        assert_eq!(v["priority"], "high", "untouched metadata survives: {v}");
        let (_, v) = call(&app, "GET", &format!("/knowledge/{key}/history"), None).await;
        assert_eq!(
            v["versions"].as_array().unwrap().len(),
            3,
            "create plus both transitions, none dropped: {v}"
        );
    }

    // A close archives the entry it committed — never one that has been
    // reopened behind its back.
    #[tokio::test]
    async fn a_close_cannot_archive_a_task_reopened_behind_it() {
        let (app, state, _data, _idx) = app_with_state();
        let key = "task-rotate-tls-certs";
        call(&app, "POST", "/tasks", Some(open_task(key))).await;

        let guard = state.writer.lock().await;
        let close = park_on_writer_lock(
            &app,
            format!("/tasks/{key}/resolve"),
            json!({"resolution": "Rotated by hand; automation filed separately."}),
        )
        .await;
        let reopen = park_on_writer_lock(
            &app,
            format!("/tasks/{key}/transition"),
            json!({"status": "in_progress", "assignee": "agent-b"}),
        )
        .await;
        drop(guard); // close first, reopen second

        let (st, closed) = close.await.unwrap();
        assert_eq!(st, StatusCode::OK, "{closed}");
        assert_eq!(closed["archived"], true, "the close archived what it closed: {closed}");
        let (st, reopened) = reopen.await.unwrap();
        assert_eq!(st, StatusCode::OK, "{reopened}");
        assert_eq!(reopened["status"], "in_progress");

        // the reopen came after the archival and stays: a live task must never
        // be left with its file deleted under it
        let (_, v) = call(&app, "GET", &format!("/knowledge/{key}"), None).await;
        assert_eq!(v["status"], "in_progress");
        assert_eq!(v["assignee"], "agent-b");
        assert!(v.get("archived").is_none(), "the reopened task is back in the canon: {v}");
        assert!(
            v["resolution"].as_str().unwrap().contains("Rotated by hand"),
            "the recorded outcome survives the reopen: {v}"
        );
        let (_, v) = call(&app, "GET", "/healthz", None).await;
        assert_eq!(v["open_tasks"], 1, "work in flight is still counted: {v}");
        let (_, v) = call(&app, "GET", "/tasks", None).await;
        assert_eq!(v["count"], 1, "and it still lists: {v}");
        assert_eq!(v["tasks"][0]["archived"], false);
    }

    // The mirror image: the reopen wins the lock first, so the close must carry
    // what the reopen wrote instead of the version it read before it.
    #[tokio::test]
    async fn a_close_after_a_reopen_carries_the_reopened_state() {
        let (app, state, _data, _idx) = app_with_state();
        let key = "task-rotate-tls-certs";
        call(&app, "POST", "/tasks", Some(open_task(key))).await;

        let guard = state.writer.lock().await;
        let reopen = park_on_writer_lock(
            &app,
            format!("/tasks/{key}/transition"),
            json!({"status": "in_progress", "assignee": "agent-b"}),
        )
        .await;
        let close = park_on_writer_lock(
            &app,
            format!("/tasks/{key}/resolve"),
            json!({"resolution": "Rotated by hand; automation filed separately."}),
        )
        .await;
        drop(guard); // reopen first, close second

        let (st, reopened) = reopen.await.unwrap();
        assert_eq!(st, StatusCode::OK, "{reopened}");
        let (st, closed) = close.await.unwrap();
        assert_eq!(st, StatusCode::OK, "{closed}");
        assert_eq!(closed["archived"], true, "{closed}");

        let (_, v) = call(&app, "GET", &format!("/knowledge/{key}"), None).await;
        assert_eq!(v["status"], "done");
        assert_eq!(v["archived"], true, "a closed task leaves the tree: {v}");
        assert_eq!(
            v["assignee"], "agent-b",
            "the close committed the claim it never resent: {v}"
        );
        assert!(v["resolution"].as_str().unwrap().contains("Rotated by hand"), "{v}");
        let (_, v) = call(&app, "GET", "/healthz", None).await;
        assert_eq!(v["open_tasks"], 0, "{v}");
        let (_, v) = call(&app, "GET", "/tasks", None).await;
        assert_eq!(v["count"], 0, "closed tasks leave the live listing: {v}");
        let (_, v) = call(&app, "GET", "/tasks?all=true", None).await;
        assert_eq!(v["count"], 1, "and stay in the record: {v}");
        assert_eq!(v["tasks"][0]["assignee"], "agent-b");
    }
}

/// Published claims, checked against the software that is supposed to back them.
///
/// A section that says what a system does NOT do is the only part of a document
/// invalidated by our own progress, so it rots fastest and exactly when nobody
/// is rereading it. "Remember to check it last" is an intention; this is a gate.
///
/// Each claim below pairs a sentence that must still be present in a published
/// file with a check of the behaviour it describes. It fails in both directions
/// on purpose:
///
///   - the sentence is there but the behaviour contradicts it -> the text lies;
///   - the sentence is gone -> the table is stale, and whoever rewrote the
///     paragraph has to say what the new claim is and how it is checked.
///
/// The second direction is the one that matters. Without it, a rewrite silently
/// disables the gate.
#[cfg(test)]
mod published_claims {
    use super::api_tests::*;
    use axum::http::StatusCode;

    const BLOG: &str = "docs/blog/agent-memory-that-keeps-its-mistakes/index.html";

    fn published(rel: &str) -> String {
        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join(rel);
        std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("cannot read {rel}: {e}"))
    }

    fn claims(rel: &str, phrase: &str) {
        assert!(
            published(rel).contains(phrase),
            "{rel} no longer contains the claim {phrase:?}.\n\
             The published text changed but this check did not. Update the claim \
             and its check together, or the gate stops guarding anything."
        );
    }

    /// The post says as_of, changed_between and /diff work. They must.
    #[tokio::test]
    async fn the_post_promises_three_temporal_questions_and_gets_them() {
        claims(BLOG, "<code>--as-of</code> gives the base as");
        claims(BLOG, "<code>--changed-between</code> gives what moved inside a window");
        claims(BLOG, "<code>/diff</code> says what moved <em>inside</em> one");

        let (app, _data, _idx) = app_with_tmp();
        call(&app, "POST", "/knowledge", Some(upsert_body("svc", "the port is 8080"))).await;
        call(&app, "POST", "/knowledge", Some(upsert_body("svc", "the port is 9090"))).await;

        let (st, v) = call(&app, "GET", "/search?q=port&as_of=2999-01-01", None).await;
        assert_eq!(st, StatusCode::OK, "the post promises --as-of");
        assert_eq!(v["count"], 1, "as_of returns one version per key, as the post says");

        let (st, v) =
            call(&app, "GET", "/search?q=port&changed_between=2000-01-01,2999-01-01", None).await;
        assert_eq!(st, StatusCode::OK, "the post promises --changed-between");
        assert_eq!(v["count"], 1);

        let (st, v) = call(&app, "GET", "/knowledge/svc/diff", None).await;
        assert_eq!(st, StatusCode::OK, "the post promises /diff");
        assert_eq!(v["changed"], true);
    }

    /// The post says all three are lexical, and explains why: one vector per key,
    /// for the head version.
    ///
    /// This one is checked at the source rather than through a response, because
    /// the test app runs without an embedding model and reports semantic=false
    /// for every query - which would make a behavioural assertion pass while
    /// proving nothing. The guard below IS the claim, and removing it is exactly
    /// the change (vectors keyed by version) that makes the sentence false.
    #[test]
    fn the_post_says_the_temporal_questions_are_lexical_and_the_guard_is_still_there() {
        claims(BLOG, "All three are lexical");
        claims(BLOG, "one vector per key,");

        let src = published("src/main.rs");
        let guard = src
            .split("let want_semantic")
            .nth(1)
            .and_then(|tail| tail.split(';').next())
            .unwrap_or_default()
            .to_string();
        for needed in ["!history", "as_of.is_none()", "window.is_none()"] {
            assert!(
                guard.contains(needed),
                "want_semantic no longer excludes {needed}, so a versioned query can now be \
                 answered semantically - which makes {BLOG} wrong where it says the temporal \
                 questions are lexical. Update both together."
            );
        }
    }

    /// The post states the second-granularity limit. The behaviour behind it is
    /// covered by index::tests::as_of_is_second_granular; here the sentence is
    /// tied to the constant that keeps it true.
    #[tokio::test]
    async fn the_post_states_the_second_granularity_limit() {
        claims(BLOG, "two versions written inside the same
      second cannot be told apart");

        let (app, _data, _idx) = app_with_tmp();
        call(&app, "POST", "/knowledge", Some(upsert_body("svc", "value one"))).await;
        call(&app, "POST", "/knowledge", Some(upsert_body("svc", "value two"))).await;
        let (_, h) = call(&app, "GET", "/knowledge/svc/history", None).await;
        let older = h["versions"][1]["sha"].as_str().unwrap().to_string();
        let (st, v) = call(&app, "GET", &format!("/search?q=value&as_of={older}"), None).await;
        assert_eq!(st, StatusCode::OK);
        assert_eq!(v["count"], 1, "one row per key even when the bound cannot separate versions");
    }

    /// The capability list is a promise to clients that check it before asking.
    /// Every name on it must be backed by an endpoint, and the CLI must gate the
    /// same names - a rename on one side and not the other turns the preflight
    /// into a permanent refusal or a silent pass.
    #[tokio::test]
    async fn every_advertised_capability_is_backed_and_gated() {
        let (app, _data, _idx) = app_with_tmp();
        call(&app, "POST", "/knowledge", Some(upsert_body("svc", "one"))).await;
        call(&app, "POST", "/knowledge", Some(upsert_body("svc", "two"))).await;

        let probes = [
            ("as_of", "/search?q=one&as_of=2999-01-01"),
            ("brief", "/brief"),
            ("changed_between", "/search?q=one&changed_between=2000-01-01,2999-01-01"),
            ("confident", "/confident/check?gist=release%20patch%20vs%20minor"),
            ("deadlines", "/deadlines"),
            ("diff", "/knowledge/svc/diff"),
            ("export", "/export"),
        ];
        assert_eq!(probes.len(), super::CAPABILITIES.len(), "a capability was added without a probe");

        let cli = published("skills/kyb/bin/kyb");
        for (cap, uri) in probes {
            assert!(super::CAPABILITIES.contains(&cap), "{cap} is probed but not advertised");
            let (st, v) = call(&app, "GET", uri, None).await;
            assert_eq!(st, StatusCode::OK, "advertised {cap} but {uri} answered {st}: {v}");
            assert!(
                cli.contains(&format!("require_capability {cap} ")),
                "the CLI does not gate {cap}, so it would send it to a server that cannot honour it"
            );
        }
    }

    /// README and the agent skill document the same three commands. An agent
    /// that reads the skill and finds a command that does not exist is worse off
    /// than one that never read it.
    #[tokio::test]
    async fn the_skill_and_readme_document_commands_that_exist() {
        for doc in ["README.md", "skills/kyb/SKILL.md"] {
            claims(doc, "--as-of");
            claims(doc, "--changed-between");
            claims(doc, "kyb diff");
            claims(doc, "kyb export");
            claims(doc, "kyb deadlines");
        }
        let cli = published("skills/kyb/bin/kyb");
        for flag in ["--as-of", "--changed-between"] {
            assert!(cli.contains(flag), "the docs promise {flag} but the CLI does not parse it");
        }
        assert!(cli.contains("  diff)"), "the docs promise `kyb diff` but the CLI has no such verb");
        assert!(cli.contains("  export)"), "the docs promise `kyb export` but the CLI has no such verb");
        assert!(cli.contains("  deadlines)"), "the docs promise `kyb deadlines` but the CLI has no such verb");
    }

    #[tokio::test]
    async fn web_ui_served_at_root() {
        let (app, _data, _idx) = app_with_tmp();
        let req = axum::http::Request::builder().uri("/").body(axum::body::Body::empty()).unwrap();
        let resp = tower::ServiceExt::oneshot(app.clone(), req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let ctype = resp.headers().get("content-type").unwrap().to_str().unwrap();
        assert!(ctype.contains("text/html"), "expected text/html, got {ctype}");
        let bytes = http_body_util::BodyExt::collect(resp.into_body()).await.unwrap().to_bytes();
        let body_str = String::from_utf8_lossy(&bytes);
        assert!(body_str.contains("KYB — Fleet Memory & Control Room"));
        assert!(body_str.contains("placesList"));
    }

    #[tokio::test]
    async fn api_audit_returns_entries() {
        let (app, _data, _idx) = app_with_tmp();
        let (st, v) = call(&app, "GET", "/api/audit", None).await;
        assert_eq!(st, StatusCode::OK);
        assert!(v.get("entries").is_some());
        assert!(v.get("count").is_some());
    }
}