onetaskgraph-core 0.3.1

The onetaskgraph engine: the plugin registry, global-id qualification, and the plan every response carries.
Documentation
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
//! The query engine: fan-out, capability compensation, and the plan it reports.
//!
//! Given the sources a configuration resolved to and a query, the engine addresses one,
//! several or every one of them **at once**, and decides per source and per predicate
//! whether to push the predicate down or to apply it itself. A predicate a source
//! declares [`Native`](Support::Native) is passed in the query and never re-applied. A
//! predicate it declares [`Unsupported`](Support::Unsupported) is **removed** from what
//! that source sees — the source would ignore it anyway, and leaving it in would invite
//! a source to half-apply it — and the engine narrows the wider result set in memory.
//!
//! What makes that worth the machinery is that the two are not the same plan. A source
//! with real server-side search keeps it, and a folder of Markdown beside it is
//! compensated for, and the caller can see which of the two it got: every response
//! carries a [`QueryPlan`], `--explain` renders it, and `--json` publishes it.
//!
//! Nothing here writes anything down. See [`fetch`] for the walk that makes that true.

mod comment;
mod copy;
mod delivery;
mod fetch;
mod join;
mod local;
mod metadata;
mod narrow;
mod rendered;
mod resume;
mod update;

use std::collections::BTreeMap;
use std::num::NonZeroU32;
use std::sync::atomic::{AtomicU32, Ordering};

use chrono::{DateTime, Utc};
use onetaskgraph_plugin_api::{
    Capabilities, Cursor, DependencyEdge, Direction, Document, DocumentQuery, Label, LabelFilter,
    MetadataMatch, MetadataRecord, NativeId, Page, PageRequest, Priority, Project, ProjectFilter,
    ProjectQuery, Repository, SecretResolver, SourceError, SourceName, StatusCategory, Task,
    TaskQuery, TextFields, TextQuery,
};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

use crate::GlobalId;
use crate::config::{Config, Placement, Routes};
use crate::plan::{PageToken, Predicate, QueryPlan, QueryResponse, SourceFailure, SourcePlan};
use crate::resolve::{ResolvedSource, UnavailableSource, resolve_available};

use fetch::{Fetched, Stream, fits, merge, unrepeated, walk};
use join::join_all;
use local::{LocalDocuments, LocalProjects, LocalTasks};
pub(crate) use resume::{Owed, Resumption, StreamState};
use resume::{Resume, StreamKind};

pub use comment::{CommentList, DeletedComment, TaskDetail, TaskDetails};
pub(crate) use copy::malformed_links;
pub use copy::{
    BudgetSpent, CopyAction, CopyItems, CopyLink, CopyLookup, CopyOutcome, CopyReport, CopyRequest,
    CopyScope, CopyVia, MatchBy, NoCounterpart, Spent,
};
pub use delivery::{Delivered, DeliveryOutcome, TaskStatusSet, settled};
pub use local::ProjectSelector;
pub use metadata::MetadataSet;
pub use narrow::{TaskContentSet, TaskPrioritySet};
pub use rendered::{
    Body, DocumentCreate, Regenerated, Regeneration, RenderRequest, RenderTemplate, RenderedRecord,
    TaskCreate, TaskCreated, TemplateAnswers, UnusedAnswers,
};
pub use update::TaskUpdated;

/// One item, under the qualified id the engine addresses it by.
///
/// A plugin only ever deals in its own [`NativeId`]; qualifying one is the engine's job,
/// so this type is the engine's and a plugin never constructs one.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct Qualified<T> {
    /// `<source>:<native>`, the form a user types back at the command line.
    pub id: GlobalId,
    /// The item as its source reported it, unchanged.
    pub item: T,
}

/// One dependency edge with both ends qualified.
///
/// An end may belong to another source. The near plugin owns that qualified far id and the
/// engine reports it without resolving or fetching the far source, so it holds no index.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct QualifiedEdge {
    /// The item the edge starts at, and the one that **depends on** the other.
    ///
    /// The direction a caller asked in says which end they named, not which end the edge
    /// starts at: a forward read and the matching reverse read report the same edge.
    pub from: QualifiedEndpoint,
    /// The item the edge points at, and the one that must finish first.
    pub to: QualifiedEndpoint,
    /// What the edge means.
    pub kind: onetaskgraph_plugin_api::DependencyKind,
}

/// One typed, qualified endpoint in an engine dependency response.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct QualifiedEndpoint {
    /// `<source>:<native>`, preserved when a plugin reports another source.
    pub id: GlobalId,
    /// Whether this endpoint names a task or project.
    pub kind: onetaskgraph_plugin_api::ItemKind,
}

impl std::fmt::Display for QualifiedEndpoint {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.id.fmt(formatter)
    }
}

/// One hit of a search that may cross entities.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "kind", rename_all = "kebab-case")]
pub enum SearchHit {
    /// A task matched.
    Task(Qualified<Task>),
    /// A project matched.
    Project(Qualified<Project>),
}

/// Which entities a search covers.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "kebab-case")]
pub enum SearchKind {
    /// Tasks only.
    Tasks,
    /// Projects only.
    Projects,
    /// Both, interleaved.
    #[default]
    Both,
}

/// What one configured source is, as `sources list` reports it.
#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
pub struct SourceListing {
    /// The name the configuration gave it.
    pub source: SourceName,
    /// The plugin kind behind it.
    ///
    /// A `String` because the vocabulary is open, not because it was not thought about:
    /// this is the kind a source reports, and a subprocess-hosted plugin reports one
    /// arriving over the wire from a binary this workspace never compiled. No
    /// compile-time enumeration can hold that, and a newtype over the same string would
    /// only move where an unrelated value is accepted.
    // llmlint: ignore[invalid_states_unrepresentable] the reason above, and the one
    // recorded for the same field of `SourcePlan` in plan.rs: `kind` is an open
    // vocabulary a subprocess plugin extends at run time, and `SourcePlan.kind: String`
    // is approved contract text this field is rendered beside.
    pub kind: String,
    /// Whether it built, and what it can do if it did.
    #[serde(flatten)]
    pub state: SourceState,
}

/// Whether a configured source is answering.
#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
#[serde(tag = "state", rename_all = "kebab-case")]
pub enum SourceState {
    /// The source built, and declares this.
    Available {
        /// What it applies itself.
        capabilities: Capabilities,
    },
    /// The source could not be built at all.
    Unavailable {
        /// Why not.
        error: SourceError,
    },
}

/// Which page of a result set the caller wants.
#[derive(Debug, Clone, PartialEq)]
pub struct Paging {
    /// The most items to return.
    pub limit: NonZeroU32,
    /// Where to resume, or `None` to start at the beginning.
    pub token: Option<PageToken>,
}

/// The filters every list verb shares.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Filters {
    /// Free-text search, when the caller asked for one.
    pub text: Option<TextQuery>,
    /// Label membership, by name.
    pub labels: LabelFilter,
    /// Status categories to keep. Empty means unfiltered.
    pub statuses: Vec<StatusCategory>,
}

/// A request for a page of tasks.
#[derive(Debug, Clone)]
pub struct TaskRequest {
    /// Which sources to address. Empty means the configuration's own selection.
    pub sources: Vec<SourceName>,
    /// What to keep.
    pub filters: Filters,
    /// Which project the tasks belong to.
    pub project: ProjectSelector,
    /// Priorities to keep: a task matches when its priority is any one of these. Empty means
    /// unfiltered.
    ///
    /// Here rather than in [`Filters`], because a project has no priority: the filters a
    /// project list shares with a task list are the ones both kinds of item carry.
    pub priorities: Vec<Priority>,
    /// Comment activity to keep: a task matches when one of its comments was created, or last
    /// edited, at or after this instant. `None` means unfiltered.
    ///
    /// Here rather than in [`Filters`] for the reason [`priorities`](Self::priorities) is: a
    /// project has no comments. A source that does not apply it natively is narrowed by a read
    /// of its comments for every task its other predicates kept.
    pub commented_since: Option<DateTime<Utc>>,
    /// Caller-defined metadata values to keep: a task matches when it holds every one.
    /// Empty means unfiltered.
    ///
    /// Here rather than in [`Filters`] for the reason [`priorities`](Self::priorities) is:
    /// the predicate is a task query's alone.
    pub metadata: Vec<MetadataMatch>,
    /// The copy origin to keep: a task matches when it was copied from this item. `None`
    /// means unfiltered.
    pub origin: Option<GlobalId>,
    /// With a [`ProjectSelector::Qualified`] project, whether the tasks of every member
    /// project that project names at `onetaskgraph.members` are read beside its own, each
    /// under its own source. Ignored for any other selector.
    ///
    /// The members are learned by reading the home on every request — never kept — so a
    /// member added between two pages is a different query, and its token is refused.
    // llmlint: ignore[invalid_states_unrepresentable] The field's name, type and default are the contract this task states (R5: "`TaskRequest` gains `include_members: bool` (default `false`)"), which the downstream engine reads plans with; the combination with any other selector is refused at the command line (`--members` requires a qualified `--project`) and documented here as ignored.
    pub include_members: bool,
    /// Which page.
    pub paging: Paging,
}

/// A request for a page of projects.
#[derive(Debug, Clone)]
pub struct ProjectRequest {
    /// Which sources to address. Empty means the configuration's own selection.
    pub sources: Vec<SourceName>,
    /// What to keep.
    pub filters: Filters,
    /// Which page.
    pub paging: Paging,
}

/// The filters a document list carries.
///
/// Its own type rather than [`Filters`], and the difference is the whole of it: there are
/// no statuses here. A document is not work and carries no status, so a status filter has
/// nothing to compare against — and a shared type with a `statuses` field would let a
/// caller write one down and leave every reader to decide what it meant.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct DocumentFilters {
    /// Free-text search, when the caller asked for one.
    pub text: Option<TextQuery>,
    /// Label membership, by name.
    pub labels: LabelFilter,
}

/// A request for a page of documents.
#[derive(Debug, Clone)]
pub struct DocumentRequest {
    /// Which sources to address. Empty means the configuration's own selection.
    pub sources: Vec<SourceName>,
    /// What to keep.
    pub filters: DocumentFilters,
    /// Which project the documents live in.
    pub project: ProjectSelector,
    /// Which page.
    pub paging: Paging,
}

/// A request for a page of labels.
#[derive(Debug, Clone)]
pub struct LabelRequest {
    /// Which sources to address. Empty means the configuration's own selection.
    pub sources: Vec<SourceName>,
    /// Which page.
    pub paging: Paging,
}

/// A request for a page of search hits.
#[derive(Debug, Clone)]
pub struct SearchRequest {
    /// Which sources to address. Empty means the configuration's own selection.
    pub sources: Vec<SourceName>,
    /// What to look for, and where.
    pub text: TextQuery,
    /// Which entities to cover.
    pub kind: SearchKind,
    /// Which page.
    pub paging: Paging,
}

/// A request for a page of one item's dependency edges.
#[derive(Debug, Clone)]
pub struct DependencyRequest {
    /// The qualified item to walk from.
    pub id: GlobalId,
    /// Which way to walk.
    pub direction: Direction,
    /// Which page.
    pub paging: Paging,
}

/// What the engine refuses before it asks any source.
///
/// Distinct from a [`SourceFailure`], which is one source failing while the others
/// answer: everything here means the request itself cannot be run at all.
///
/// `Eq` is deliberately absent: three variants carry the [`SourceError`] the source
/// itself gave, which is what a user has to act on, and that type is `PartialEq` alone.
#[derive(Debug, Clone, PartialEq, thiserror::Error)]
pub enum EngineError {
    /// A `--source` named something no configuration configures.
    #[error(
        "no source named {name:?} is configured\n\
         next: name one of the configured sources ({configured}), or add {name:?} under \
         `sources` — `onetaskgraph sources list` shows what this configuration has."
    )]
    UnknownSource {
        /// The name that was asked for.
        name: String,
        /// The names that exist, for the message.
        configured: String,
    },

    /// A `--page` token that decodes but does not belong to this query.
    #[error(
        "{message}\n\
         next: page with a token exactly as the previous page reported it, and against \
         the same configuration — or drop `--page` to start the walk again."
    )]
    Token {
        /// What the token claims that this configuration cannot honour.
        message: String,
    },

    /// Nothing at all is configured, so there is nothing to ask.
    #[error(
        "no sources are configured\n\
         next: add one under `sources` in onetaskgraph.yaml — `onetaskgraph schema` \
         prints what each plugin accepts."
    )]
    NoSources,

    /// A copy named a destination whose plugin has no write side.
    #[error(
        "source {name} cannot be written: its plugin is {kind}, which has no write \
         side\n\
         next: copy into a source whose plugin can be written — `onetaskgraph sources \
         list` reports each one's plugin."
    )]
    NotWritable {
        /// The configured name of the destination.
        name: String,
        /// The plugin behind it.
        kind: String,
    },

    /// A document read or write named a source whose plugin has no documents.
    ///
    /// The same shape [`NotWritable`](Self::NotWritable) has, and for the same reason: the
    /// declaration is read once at the handshake, so a source that says it has no
    /// documents is refused before anything is read rather than asked and then apologised
    /// for.
    #[error(
        "source {name} has no documents: its plugin is {kind}, which holds none\n\
         next: name a source whose plugin has documents — `onetaskgraph sources list` \
         reports each one's plugin and what it declares."
    )]
    NoDocuments {
        /// The configured name of the source.
        name: String,
        /// The plugin behind it.
        kind: String,
    },

    /// A comment verb named a task of a source whose plugin has no comments.
    ///
    /// The shape [`NoDocuments`](Self::NoDocuments) has, for its reason: the declaration is
    /// read once at the handshake, so the source is refused before anything is read.
    #[error(
        "source {name} has no comments: its plugin is {kind}, whose tasks hold none\n\
         next: name a task of a source whose plugin has comments — `onetaskgraph sources \
         list` reports each one's plugin."
    )]
    NoComments {
        /// The configured name of the source.
        name: String,
        /// The plugin behind it.
        kind: String,
    },

    /// A comment verb that writes named a source whose comments can be read but not written.
    #[error(
        "source {name} cannot be written: its plugin is {kind}, whose comments can be read \
         but not added to, edited or removed\n\
         next: list them with `onetaskgraph task comment list`, or comment on a task of a \
         source whose plugin can be written — `onetaskgraph sources list` reports each \
         one's plugin."
    )]
    CommentsNotWritable {
        /// The configured name of the source.
        name: String,
        /// The plugin behind it.
        kind: String,
    },

    /// `task status set` named a source whose plugin has no write side.
    #[error(
        "source {name} cannot write a status: its plugin is {kind}, which has no write side\n\
         next: set the status in that source itself, or name a task of a source whose plugin \
         can be written — `onetaskgraph sources list` reports each one's plugin."
    )]
    StatusNotWritable {
        /// The configured name of the source.
        name: String,
        /// The plugin behind it.
        kind: String,
    },

    /// A metadata verb named a record of a source whose plugin has no write side.
    #[error(
        "source {name} cannot write a {record}'s metadata: its plugin is {kind}, which has no \
         write side\n\
         next: set the key in that source itself, or name a {record} of a source whose plugin \
         can be written — `onetaskgraph sources list` reports each one's plugin."
    )]
    MetadataNotWritable {
        /// The configured name of the source.
        name: String,
        /// The plugin behind it.
        kind: String,
        /// Which kind of record was named.
        record: MetadataRecord,
    },

    /// `task priority set` named a source whose plugin has no write side.
    #[error(
        "source {name} cannot write a priority: its plugin is {kind}, which has no write side\n\
         next: set the priority in that source itself, or name a task of a source whose plugin \
         can be written — `onetaskgraph sources list` reports each one's plugin."
    )]
    PriorityNotWritable {
        /// The configured name of the source.
        name: String,
        /// The plugin behind it.
        kind: String,
    },

    /// `task content set` named a source whose plugin has no write side.
    #[error(
        "source {name} cannot write a task's content: its plugin is {kind}, which has no write \
         side\n\
         next: edit the content in that source itself, or name a task of a source whose plugin \
         can be written — `onetaskgraph sources list` reports each one's plugin."
    )]
    ContentNotWritable {
        /// The configured name of the source.
        name: String,
        /// The plugin behind it.
        kind: String,
    },

    /// `task update` named a source whose plugin has no write side.
    #[error(
        "source {name} cannot update a task: its plugin is {kind}, which has no write side\n\
         next: change the task in that source itself, or name a task of a source whose plugin \
         can be written — `onetaskgraph sources list` reports each one's plugin."
    )]
    UpdateNotWritable {
        /// The configured name of the source.
        name: String,
        /// The plugin behind it.
        kind: String,
    },

    /// `task create` or `document create` named a source whose plugin has no write side.
    #[error(
        "source {name} cannot create a {record}: its plugin is {kind}, which has no write side\n\
         next: create it in a source whose plugin can be written — `onetaskgraph sources list` \
         reports each one's plugin."
    )]
    NotCreatable {
        /// The configured name of the source.
        name: String,
        /// The plugin behind it.
        kind: String,
        /// Which kind of record was to be created.
        record: MetadataRecord,
    },

    /// `task render` or `document render` named a source whose plugin has no write side.
    #[error(
        "source {name} cannot write a {record}'s rendering: its plugin is {kind}, which has no \
         write side\n\
         next: render it with --dry-run to read the result, or regenerate a {record} of a source \
         whose plugin can be written."
    )]
    RenderingNotWritable {
        /// The configured name of the source.
        name: String,
        /// The plugin behind it.
        kind: String,
        /// A task or a document.
        record: RenderedRecord,
    },

    /// A regenerate left required variables unanswered, because the answers stored beside the
    /// item could not be used or did not cover them.
    #[error(
        "supply every required answer to regenerate {id}: {} unanswered, and {reason}\n\
         next: answer {} with --var NAME=VALUE or an answers file (--answers FILE), or run \
         interactively to be asked.",
        names.join(", "),
        if names.len() == 1 { "it" } else { "each" }
    )]
    MissingAnswers {
        /// The item regenerated.
        id: String,
        /// Every required variable left unanswered, in declaration order.
        names: Vec<String>,
        /// What became of the stored answers, as a clause: why they were not the base, or
        /// that they were and did not answer these.
        reason: String,
    },

    /// A template could not be loaded or rendered, or refused the answers it was given.
    #[error("{error}")]
    Template {
        /// What the template refused.
        error: crate::template::TemplateError,
    },

    /// An answers read named an item with no answers stored beside it.
    #[error(
        "{record} {id} has no stored template answers: {reason}\n\
         next: regenerate it with every required answer (`onetaskgraph {record} render {id} \
         --var NAME=VALUE`), or read its provenance with `onetaskgraph {record} show {id}`."
    )]
    NoStoredAnswers {
        /// A task or a document.
        record: RenderedRecord,
        /// The item.
        id: String,
        /// Why none are there.
        reason: String,
    },

    /// A regenerate named no template, and the item records none.
    #[error(
        "{record} {id} records no template it was rendered from, and none was given\n\
         next: name one with --template FILE or --template-loader FILE."
    )]
    NoTemplate {
        /// A task or a document.
        record: RenderedRecord,
        /// The item.
        id: String,
    },

    /// A regenerate named no template, and the item's `onetaskgraph.template` entry is not one
    /// this product writes, so it names nothing to render.
    #[error(
        "{record} {id} records a template entry this product did not write — {problem}\n\
         next: regenerate it with --template FILE or --template-loader FILE and every required \
         answer, which records a fresh entry."
    )]
    MalformedProvenance {
        /// A task or a document.
        record: RenderedRecord,
        /// The item.
        id: String,
        /// What is wrong with the entry.
        problem: String,
    },

    /// A regenerate named no template, and the one the item records is not a readable file.
    #[error(
        "{record} {id} was rendered from {reference:?}, which is not a readable file, so it \
         cannot be re-read; a recorded reference is never turned into a location\n\
         next: supply the template with --template-loader FILE (a loader document naming what \
         to render), or name a template file with --template FILE."
    )]
    TemplateNotAFile {
        /// A task or a document.
        record: RenderedRecord,
        /// The item.
        id: String,
        /// The provenance `template` it records.
        reference: String,
    },

    /// A priority other than `none` was to be written — by `task priority set` or by a copy —
    /// to a source whose plugin declares it holds no priority.
    ///
    /// Refused before that source is asked anything, so a copy it stops has written nothing.
    #[error(
        "source {name} cannot hold the field priority, so {task}'s priority {priority} cannot \
         be written to it: its plugin is {kind}, which declares priority unsupported\n\
         next: write to a source whose plugin holds a priority — `onetaskgraph sources list` \
         reports what each declares — or set the task's priority to none first; a \
         github-projects source holds one once its configuration sets priority_mapping."
    )]
    NoPriority {
        /// The configured name of the source that cannot hold it.
        name: String,
        /// The plugin behind it.
        kind: String,
        /// The qualified id of the task whose priority it is.
        task: String,
        /// The priority that could not be written.
        priority: onetaskgraph_plugin_api::Priority,
    },

    /// A metadata verb named a project its source does not hold.
    #[error(
        "no project with the id {id}\n\
         next: check the id, or list what is there — `onetaskgraph project list` reports every \
         project the configured sources hold."
    )]
    NoSuchProject {
        /// The qualified id that named nothing.
        id: String,
    },

    /// A metadata verb named a document its source does not hold.
    #[error(
        "no document with the id {id}\n\
         next: check the id, or list what is there — `onetaskgraph document list` reports every \
         document the configured sources hold."
    )]
    NoSuchDocument {
        /// The qualified id that named nothing.
        id: String,
    },

    /// A comment verb named a task its source does not hold.
    #[error(
        "no task with the id {id}\n\
         next: check the id, or list what is there — `onetaskgraph task list` reports every \
         task the configured sources hold."
    )]
    NoSuchTask {
        /// The qualified id that named nothing.
        id: String,
    },

    /// A comment verb named a comment the task does not have.
    #[error(
        "task {task} has no comment with the id {comment}\n\
         next: list its comments — `onetaskgraph task comment list {task}` reports each \
         one's id."
    )]
    NoSuchComment {
        /// The qualified id of the task.
        task: String,
        /// The comment id that named nothing on it.
        comment: String,
    },

    /// A source the verb reads or writes one item of is configured but could not be built.
    ///
    /// Distinct from [`DestinationUnavailable`](Self::DestinationUnavailable), whose next
    /// action is about a copy.
    #[error(
        "source {name} could not be built: {error}\n\
         next: fix that source — `onetaskgraph sources list` reports its state — then run the \
         command again."
    )]
    SourceUnavailable {
        /// The configured name of the source.
        name: String,
        /// Why it did not build.
        error: SourceError,
    },

    /// A source refused, or failed, the one call a verb made of it.
    ///
    /// Distinct from [`SourceRefused`](Self::SourceRefused), whose next action is about a
    /// copy, and from a [`SourceFailure`], which leaves other sources' results standing: a
    /// comment is one call to one source, so there is nothing else to report beside it.
    #[error(
        "source {name} could not do it: {error}\n\
         next: fix what the source named above, then run the command again."
    )]
    SourceFailed {
        /// The source that failed.
        name: String,
        /// What it said.
        error: SourceError,
    },

    /// A copy named a destination that is configured but could not be built.
    #[error(
        "the destination source {name} could not be built: {error}\n\
         next: fix that source — `onetaskgraph sources list` reports its state — then \
         copy again."
    )]
    DestinationUnavailable {
        /// The configured name of the destination.
        name: String,
        /// Why it did not build.
        error: SourceError,
    },

    /// A copy named an id its own source does not hold.
    #[error(
        "no item with the id {id}\n\
         next: check the id, or list what is there — `onetaskgraph task list` and \
         `onetaskgraph project list` report what the configured sources hold."
    )]
    NoSuchItem {
        /// The qualified id that named nothing.
        id: String,
    },

    /// An item's recorded origin names an item the destination no longer holds.
    ///
    /// Refused rather than created: the destination item was deleted or moved on purpose,
    /// and creating a second one there would duplicate work somebody removed.
    #[error(
        "{item} was copied from {origin}, which that destination no longer holds\n\
         next: re-run with --recreate to create a new item there instead, or restore \
         {origin}."
    )]
    StaleOrigin {
        /// The item being copied.
        item: String,
        /// The origin it records.
        origin: String,
    },

    /// An item's recorded copy link names an item the destination no longer holds.
    ///
    /// Refused rather than created, for the reason [`Self::StaleOrigin`] is: the item the
    /// last copy landed on was deleted at the destination, and creating another would
    /// duplicate work somebody removed.
    #[error(
        "{item} was last copied to {link}, which that destination no longer holds\n\
         next: re-run with --recreate to create a new item there instead, or restore \
         {link}."
    )]
    StaleLink {
        /// The item being copied.
        item: String,
        /// The destination item its `onetaskgraph.copies` entry names.
        link: String,
    },

    /// `--create` was given beside a flag that says how to look for a counterpart, when
    /// `--create` says there is none to look for.
    #[error(
        "--create cannot be given with {flag}: --create asserts the destination holds no \
         counterpart, so there is nothing for {flag} to look for\n\
         next: drop {flag} to create each item without looking, or drop --create to look."
    )]
    CreateWith {
        /// The flag given beside `--create`.
        flag: CopyLookup,
    },

    /// `--create` named an item that itself records a counterpart at the destination.
    ///
    /// Refused rather than created: the item's own `onetaskgraph.copies` link — or its
    /// origin — names an item there, so the caller's assertion that the destination holds
    /// none is wrong for it, and creating another would duplicate it.
    #[error(
        "{item} already records a counterpart at the destination, {carrier}, and --create \
         asserts it has none\n\
         next: copy it without --create, which updates {carrier}."
    )]
    CreateCarried {
        /// The item being copied.
        item: GlobalId,
        /// The destination item its link or its origin names.
        carrier: GlobalId,
    },

    /// A member copy named a task that is not a member of the project being copied.
    ///
    /// Refused before anything is written, because a copy that names members names the
    /// part of one project it carries: a task of some other project, or of no project, is
    /// not a narrower version of that copy but a different one.
    #[error(
        "{id} is not a task of {project}, so it cannot be copied as one of its members\n\
         next: name a task `onetaskgraph task list --project {project}` reports, or copy \
         {id} on its own with `onetaskgraph task copy`.",
        project = .projects.iter().map(ToString::to_string).collect::<Vec<_>>().join(", ")
    )]
    NotAMember {
        /// The id that was named as a member.
        id: GlobalId,
        /// The projects the copy carries, none of which it is a member of.
        projects: Vec<GlobalId>,
    },

    /// A member copy's item depends on a member it was not told to carry, and that member
    /// records no origin naming the destination.
    ///
    /// Refused before anything is written. The destination id of a member the copy does
    /// not carry comes from that member's own recorded origin and from nowhere else — not
    /// from a walk of the destination, which is the read a member copy exists to avoid —
    /// and writing the edge without it would either drop it silently or point it at the
    /// id the member has at its source, which the destination has never heard of.
    #[error(
        "{item} depends on {member}, which this copy was not told to carry and which records \
         no origin in {destination}\n\
         next: name {member} with --member as well, record its {destination} id at \
         onetaskgraph.origin, or copy the whole project without --member."
    )]
    UnrecordedMember {
        /// The item whose edge could not be resolved.
        item: GlobalId,
        /// The member that edge points at.
        member: GlobalId,
        /// The destination it records no origin in.
        destination: SourceName,
    },

    /// A routed copy found an item's existing counterpart in a source other than the one its
    /// repositories route it to now.
    ///
    /// Refused before anything is written. A repository changed after a copy is a person's
    /// decision about where the work lives, and moving it silently would leave the
    /// counterpart where it was, unlinked, beside a second one.
    #[error(
        "{item} was copied to {counterpart}, but its repositories now route it to {route}\n\
         next: move or remove {counterpart} by hand and copy again, or restore {item}'s \
         repositories so it routes to {source} again.",
        source = .counterpart.source
    )]
    Misrouted {
        /// The item being copied.
        item: GlobalId,
        /// The counterpart it already has.
        counterpart: GlobalId,
        /// The source it routes to now.
        route: SourceName,
    },

    /// A source refused something the copy asked of it.
    ///
    /// Distinct from a [`SourceFailure`], which leaves the other sources' results
    /// standing: a copy is one write into one destination, and half of one is not an
    /// answer.
    #[error(
        "source {name} could not do it: {error}\n\
         next: fix what the source named above, then copy again."
    )]
    SourceRefused {
        /// The source that refused.
        name: String,
        /// What it said.
        error: SourceError,
    },

    /// A copy failed, and the destination could not be put back the way it was found.
    ///
    /// A copy is either complete or it never happened, and the engine undoes its own
    /// writes to make that true. When the destination will not take one of them back, the
    /// failure has to say so and name what is still there: a user told only that the copy
    /// failed would copy again over a destination nobody has described to them, which is
    /// the retry that trips a hosted destination's rate limiter.
    #[error(
        "the copy failed and could not be undone.\n\
         it failed because: {error}\n\
         it could not be undone because: {refusal}\n\
         so these still hold what it wrote: {left_behind}\n\
         next: remove or put back those items, then copy again."
    )]
    CopyNotUndone {
        /// Why the copy failed in the first place.
        error: Box<EngineError>,
        /// The items the copy created or overwrote and could not take back.
        ///
        /// The ids themselves rather than a sentence about them: a caller acting on this —
        /// removing them, or reporting them — needs the ids, and the joined form only the
        /// message needs is [`LeftBehind`]'s own `Display`.
        left_behind: LeftBehind,
        /// What the destination said when the copy tried to take them back.
        refusal: SourceError,
    },
}

/// The items a failed copy left at the destination — one of them at least, always.
///
/// A plain `Vec` here would let [`EngineError::CopyNotUndone`] be built naming nothing
/// still there, and naming what is still there is the whole reason that failure is
/// distinct from the one it wraps: a user told only that the copy could not be undone,
/// and then handed an empty list, has been told about a destination nobody described to
/// them, which is exactly the blind retry this mechanism exists to remove. The first id
/// is a field of its own, so the empty case cannot be written down.
#[derive(Debug, Clone, PartialEq)]
pub struct LeftBehind {
    /// The first item the destination would not take back.
    first: GlobalId,
    /// The ones it would not take back after that, in the order it refused them.
    rest: Vec<GlobalId>,
}

impl LeftBehind {
    /// The list holding the one item every such refusal has to name.
    #[must_use]
    pub fn new(first: GlobalId) -> Self {
        Self {
            first,
            rest: Vec::new(),
        }
    }

    /// Record another item the destination would not take back.
    pub fn push(&mut self, id: GlobalId) {
        self.rest.push(id);
    }

    /// Every item still at the destination, in the order the destination refused them.
    pub fn iter(&self) -> impl Iterator<Item = &GlobalId> {
        std::iter::once(&self.first).chain(self.rest.iter())
    }
}

impl std::fmt::Display for LeftBehind {
    /// The qualified ids, comma-separated — the form the failure message reads in.
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(formatter, "{}", self.first)?;
        for id in &self.rest {
            write!(formatter, ", {id}")?;
        }
        Ok(())
    }
}

/// One configured source, in exactly one of the two states a configured source has.
///
/// A sum rather than two lists side by side: with a `ready` vector and an `unavailable`
/// one, a source appearing in both is a shape the type permits and every reader has to
/// decide about — and they would not all decide the same way, since one of them fans a
/// query out and another names failures.
pub enum ConfiguredSource {
    /// It built, and answers queries.
    Ready(ResolvedSource),
    /// It did not, and every response says so instead.
    Unavailable(UnavailableSource),
}

impl ConfiguredSource {
    /// The name the configuration gave it, whichever state it is in.
    #[must_use]
    pub fn name(&self) -> &SourceName {
        match self {
            Self::Ready(source) => source.name(),
            Self::Unavailable(source) => source.name(),
        }
    }
}

/// The sources a configuration resolved to, and the queries they answer.
pub struct Engine {
    /// Every configured source, in configured-name order, each in one state.
    sources: Vec<ConfiguredSource>,
    /// Which sources answer when a request names none.
    selection: Vec<SourceName>,
    /// Where an item written to a source goes instead. Read from configuration and never
    /// from a source, so it holds nothing of anybody's work.
    routes: Routes,
}

impl Engine {
    /// Build every source a configuration names.
    ///
    /// A source whose plugin refuses to build — a credential that is not there, a
    /// plugin whose implementation has not landed — is **not** fatal: it becomes an
    /// entry in every response's `errors`, exactly as a source that fails mid-query
    /// does, and the other sources still answer. A user with three sources and one
    /// expired token gets the other two rather than nothing.
    #[must_use]
    pub fn build(config: &Config, secrets: &dyn SecretResolver) -> Self {
        let (ready, unavailable) = resolve_available(config, secrets);
        Self::new(
            ready
                .into_iter()
                .map(ConfiguredSource::Ready)
                .chain(unavailable.into_iter().map(ConfiguredSource::Unavailable))
                .collect(),
            config.selected_sources(),
        )
        .with_routes(config.routes())
    }

    /// Drive sources built elsewhere — the engine's own tests, and any caller holding a
    /// source it did not resolve from a configuration document.
    #[must_use]
    pub fn new(sources: Vec<ConfiguredSource>, selection: Vec<SourceName>) -> Self {
        Self {
            sources,
            selection,
            routes: Routes::default(),
        }
    }

    /// The same engine, placing what is written to each source by `routes`.
    ///
    /// [`build`](Self::build) takes them from the configuration; a caller holding sources
    /// it built itself states them here, checked by [`Routes::new`].
    #[must_use]
    pub fn with_routes(mut self, routes: Routes) -> Self {
        self.routes = routes;
        self
    }

    /// Where an item with `repositories`, written to `source`, lands.
    #[must_use]
    pub fn place(&self, source: &SourceName, repositories: &[Repository]) -> Placement {
        self.routes.place(source, repositories)
    }

    /// Every source that built, in configured-name order.
    fn ready(&self) -> impl Iterator<Item = &ResolvedSource> {
        self.sources.iter().filter_map(|source| match source {
            ConfiguredSource::Ready(ready) => Some(ready),
            ConfiguredSource::Unavailable(_) => None,
        })
    }

    /// Every source that did not, in the same order.
    fn unavailable(&self) -> impl Iterator<Item = &UnavailableSource> {
        self.sources.iter().filter_map(|source| match source {
            ConfiguredSource::Unavailable(unavailable) => Some(unavailable),
            ConfiguredSource::Ready(_) => None,
        })
    }

    /// Every configured source, whether or not it built, in name order.
    #[must_use]
    pub fn listing(&self) -> Vec<SourceListing> {
        let mut listings: Vec<SourceListing> = self
            .ready()
            .map(|source| SourceListing {
                source: source.name().clone(),
                kind: source.kind().to_owned(),
                state: SourceState::Available {
                    capabilities: source.source().capabilities(),
                },
            })
            .chain(self.unavailable().map(|source| SourceListing {
                source: source.name().clone(),
                kind: source.kind().to_owned(),
                state: SourceState::Unavailable {
                    error: source.error().clone(),
                },
            }))
            .collect();
        listings.sort_by(|left, right| left.source.cmp(&right.source));
        listings
    }

    /// Whether this configuration has a source called `name`, built or not.
    ///
    /// A caller reading a `--project` argument needs this: `urn:project:1` is a qualified
    /// id only if `urn` is a source here, and a native id full of colons otherwise. That
    /// rule cannot be applied without knowing what is configured.
    #[must_use]
    pub fn has(&self, name: &SourceName) -> bool {
        self.sources.iter().any(|source| source.name() == name)
    }

    /// End one command on every source this engine holds, so the next command reads afresh.
    ///
    /// A caller holding one engine for many units of work — a worker writing settlement after
    /// settlement back over hours — calls this between them. A source may reuse what it read
    /// within one command, so without this call a person's edit made between two units can be
    /// overwritten by the next write. After it, no source answers a read or bases a write on
    /// item content, statuses, board contents or search results it held before. What a source
    /// keeps is its own decision, made under [`TaskSource::end_command`]'s rule; nothing here
    /// names a plugin.
    ///
    /// The binary never calls it: one command line is one process, which drops everything at
    /// exit.
    ///
    /// # Errors
    ///
    /// Returns [`EngineError::SourceFailed`] for the first source that could not end its
    /// command. Every source is asked whether or not one before it failed.
    ///
    /// [`TaskSource::end_command`]: onetaskgraph_plugin_api::TaskSource::end_command
    pub async fn end_command(&self) -> Result<(), EngineError> {
        let mut first = None;
        for source in self.ready() {
            if let Err(error) = source.source().end_command().await
                && first.is_none()
            {
                first = Some(EngineError::SourceFailed {
                    name: source.name().to_string(),
                    error,
                });
            }
        }
        first.map_or(Ok(()), Err)
    }

    /// One page of tasks.
    ///
    /// # Errors
    ///
    /// Returns [`EngineError`] when the request names a source nothing configures, or
    /// carries a page token this engine did not issue. One source failing is not an
    /// error: it lands in the response's `errors`.
    pub async fn tasks(
        &self,
        request: &TaskRequest,
    ) -> Result<QueryResponse<Qualified<Task>>, EngineError> {
        let mut names = self.resolve_selection(&request.sources)?;
        // A qualified project id names one project of one source, so no other source can
        // hold a task in it. Narrowing here means the plan reports the source that was
        // actually asked rather than a row of empty entries for sources that could not
        // have answered.
        let mut members: Vec<GlobalId> = Vec::new();
        let mut unread: Vec<SourceFailure> = Vec::new();
        if let ProjectSelector::Qualified(id) = &request.project {
            self.known(&id.source)?;
            names.retain(|name| name == &id.source);
            // Its members join it, each asked for in its own source: a home has at most one
            // member per source, so one source still answers for one project.
            if request.include_members {
                (members, unread) = self.members(id).await;
                names.extend(members.iter().map(|member| member.source.clone()));
            }
        }
        let selector = |name: &SourceName| -> ProjectSelector {
            members
                .iter()
                .find(|member| &member.source == name)
                .map_or_else(
                    || request.project.clone(),
                    |member| ProjectSelector::Qualified(member.clone()),
                )
        };
        let query = shape(
            "task-list",
            &names,
            &(
                &request.filters,
                &request.project,
                &request.priorities,
                &request.commented_since,
                &request.metadata,
                &request.origin,
                &members,
            ),
        );
        let states = resumption(
            self,
            request.paging.token.as_ref(),
            &[StreamKind::Items],
            &query,
        )?;
        let budget = request.paging.limit.get();

        let mut answer = Answer::new();
        answer.errors.extend(unread);
        let (ready, starts) = walking(answer.split(self, &names), &states, StreamKind::Items);

        let shapes: Vec<TaskShape> = ready
            .iter()
            .map(|source| {
                shape_tasks(
                    &source.source().capabilities(),
                    &request.filters,
                    &project_filter(&selector(source.name())),
                    &request.priorities,
                    request.commented_since,
                    &request.metadata,
                    request.origin.as_ref(),
                )
            })
            .collect();
        let counters: Vec<AtomicU32> = ready.iter().map(|_| AtomicU32::new(0)).collect();
        let outcomes: Vec<Outcomes> = shapes.iter().map(|shape| shape.outcomes.clone()).collect();

        let walks = ready
            .iter()
            .enumerate()
            .map(|(index, source)| {
                fetch_tasks(
                    source,
                    &shapes[index],
                    &starts[index],
                    budget,
                    &counters[index],
                )
            })
            .collect();

        let streams = answer.collect(&ready, join_all(walks).await, &counters, outcomes);
        answer.finish(
            streams,
            budget,
            owed(&states),
            &query,
            |name, task: Task| {
                delivery::qualified_task(GlobalId::new(name.clone(), task.id.clone()), task)
            },
        )
    }

    /// The member projects `home` names at `onetaskgraph.members` that can be read, and a
    /// failure for each that cannot.
    ///
    /// Read from the home on every call and kept nowhere. A member in a source nothing
    /// configures, one its source does not hold, and one whose source fails the read are
    /// each reported rather than left out, because a plan missing a member without saying
    /// so reads exactly like a plan that has none. So is a home its source fails to read or
    /// does not hold: its members cannot be learned, and a page of its own tasks alone must
    /// not pass for the whole plan. A home whose source did not build is reported by the
    /// walk, as any unavailable source is.
    async fn members(&self, home: &GlobalId) -> (Vec<GlobalId>, Vec<SourceFailure>) {
        let mut members = Vec::new();
        let mut unread = Vec::new();
        let Some(source) = self.ready().find(|source| source.name() == &home.source) else {
            return (members, unread);
        };
        let held = match source.source().get_project(&home.native).await {
            Ok(Some(held)) => held,
            Ok(None) => {
                unread.push(SourceFailure {
                    source: home.source.clone(),
                    error: SourceError::Refused {
                        message: format!(
                            "{home} names no project {} holds, so its member projects cannot \
                             be read",
                            home.source
                        ),
                    },
                });
                return (members, unread);
            }
            Err(error) => {
                unread.push(SourceFailure {
                    source: home.source.clone(),
                    error,
                });
                return (members, unread);
            }
        };
        let named = match copy::members_of(home, &held.metadata) {
            Ok(named) => named,
            // A list nobody can read is a home whose plan cannot be read whole, which is a
            // failure of the home's source to report rather than a plan with no members.
            Err(message) => {
                unread.push(SourceFailure {
                    source: home.source.clone(),
                    error: SourceError::Malformed { message },
                });
                return (members, unread);
            }
        };
        for member in named {
            if !self.has(&member.source) {
                unread.push(SourceFailure {
                    source: member.source.clone(),
                    error: SourceError::Config {
                        message: format!(
                            "{home} names {member} as a member project, but no source named \
                             {} is configured",
                            member.source
                        ),
                    },
                });
                continue;
            }
            // A member whose source did not build is reported by the walk, as any
            // unavailable source is.
            let Some(there) = self.ready().find(|source| source.name() == &member.source) else {
                members.push(member);
                continue;
            };
            match there.source().get_project(&member.native).await {
                Ok(Some(_)) => members.push(member),
                Ok(None) => unread.push(SourceFailure {
                    source: member.source.clone(),
                    error: SourceError::Refused {
                        message: format!(
                            "{home} names {member} as a member project, and {} holds no such \
                             project",
                            member.source
                        ),
                    },
                }),
                Err(error) => unread.push(SourceFailure {
                    source: member.source.clone(),
                    error,
                }),
            }
        }
        (members, unread)
    }

    /// One page of projects.
    ///
    /// # Errors
    ///
    /// As [`tasks`](Self::tasks).
    pub async fn projects(
        &self,
        request: &ProjectRequest,
    ) -> Result<QueryResponse<Qualified<Project>>, EngineError> {
        let names = self.resolve_selection(&request.sources)?;
        let query = shape("project-list", &names, &request.filters);
        let states = resumption(
            self,
            request.paging.token.as_ref(),
            &[StreamKind::Items],
            &query,
        )?;
        let budget = request.paging.limit.get();

        let mut answer = Answer::new();
        // A source declaring `projects: unsupported` has no project table at all, so
        // there is nothing to compensate for and nothing to ask: the predicate is
        // reported unavailable and that source contributes no rows. This is the one
        // outcome the engine cannot narrow its way out of, which is what `unavailable`
        // in the plan is for.
        let mut with_projects = Vec::new();
        for source in answer.split(self, &names) {
            if source.source().capabilities().projects.is_native() {
                with_projects.push(source);
            } else {
                answer.unreachable_predicate(source, Predicate::Project);
            }
        }
        let (ready, starts) = walking(with_projects, &states, StreamKind::Items);

        let shapes: Vec<ProjectShape> = ready
            .iter()
            .map(|source| shape_projects(&source.source().capabilities(), &request.filters))
            .collect();
        let counters: Vec<AtomicU32> = ready.iter().map(|_| AtomicU32::new(0)).collect();
        let outcomes: Vec<Outcomes> = shapes.iter().map(|shape| shape.outcomes.clone()).collect();

        let walks = ready
            .iter()
            .enumerate()
            .map(|(index, source)| {
                fetch_projects(
                    source,
                    &shapes[index],
                    &starts[index],
                    budget,
                    &counters[index],
                )
            })
            .collect();

        let streams = answer.collect(&ready, join_all(walks).await, &counters, outcomes);
        answer.finish(
            streams,
            budget,
            owed(&states),
            &query,
            |name, project: Project| Qualified {
                id: GlobalId::new(name.clone(), project.id.clone()),
                item: project,
            },
        )
    }

    /// One page of documents.
    ///
    /// A source declaring it has no documents is **not asked**: the declaration is read
    /// once here, that source contributes no rows, and the plan reports
    /// [`Predicate::Document`] unavailable for it. So a document list spanning a mixed set
    /// of sources answers with what the document-bearing ones hold and says nothing
    /// alarming about the others — the same shape a source with no project table takes.
    ///
    /// # Errors
    ///
    /// As [`tasks`](Self::tasks).
    pub async fn documents(
        &self,
        request: &DocumentRequest,
    ) -> Result<QueryResponse<Qualified<Document>>, EngineError> {
        let mut names = self.resolve_selection(&request.sources)?;
        // A qualified project id names one project of one source, exactly as it does for
        // tasks, so no other source can hold a document in it.
        if let ProjectSelector::Qualified(id) = &request.project {
            self.known(&id.source)?;
            names.retain(|name| name == &id.source);
        }
        let query = shape(
            "document-list",
            &names,
            &(&request.filters, &request.project),
        );
        let states = resumption(
            self,
            request.paging.token.as_ref(),
            &[StreamKind::Items],
            &query,
        )?;
        let budget = request.paging.limit.get();

        let mut answer = Answer::new();
        let mut with_documents = Vec::new();
        for source in answer.split(self, &names) {
            if source.source().capabilities().documents.is_native() {
                with_documents.push(source);
            } else {
                answer.unreachable_predicate(source, Predicate::Document);
            }
        }
        let (ready, starts) = walking(with_documents, &states, StreamKind::Items);

        let shapes: Vec<DocumentShape> = ready
            .iter()
            .map(|source| {
                shape_documents(
                    &source.source().capabilities(),
                    &request.filters,
                    &project_filter(&request.project),
                )
            })
            .collect();
        let counters: Vec<AtomicU32> = ready.iter().map(|_| AtomicU32::new(0)).collect();
        let outcomes: Vec<Outcomes> = shapes.iter().map(|shape| shape.outcomes.clone()).collect();

        let walks = ready
            .iter()
            .enumerate()
            .map(|(index, source)| {
                fetch_documents(
                    source,
                    &shapes[index],
                    &starts[index],
                    budget,
                    &counters[index],
                )
            })
            .collect();

        let streams = answer.collect(&ready, join_all(walks).await, &counters, outcomes);
        answer.finish(
            streams,
            budget,
            owed(&states),
            &query,
            |name, document: Document| Qualified {
                id: GlobalId::new(name.clone(), document.id.clone()),
                item: document,
            },
        )
    }

    /// One page of labels.
    ///
    /// # Errors
    ///
    /// As [`tasks`](Self::tasks).
    pub async fn labels(
        &self,
        request: &LabelRequest,
    ) -> Result<QueryResponse<Qualified<Label>>, EngineError> {
        let names = self.resolve_selection(&request.sources)?;
        let query = shape("label-list", &names, &());
        let states = resumption(
            self,
            request.paging.token.as_ref(),
            &[StreamKind::Items],
            &query,
        )?;
        let budget = request.paging.limit.get();

        let mut answer = Answer::new();
        let (ready, starts) = walking(answer.split(self, &names), &states, StreamKind::Items);
        let counters: Vec<AtomicU32> = ready.iter().map(|_| AtomicU32::new(0)).collect();
        let outcomes: Vec<Outcomes> = ready.iter().map(|_| Outcomes::default()).collect();

        let walks = ready
            .iter()
            .enumerate()
            .map(|(index, source)| fetch_labels(source, &starts[index], budget, &counters[index]))
            .collect();

        let streams = answer.collect(&ready, join_all(walks).await, &counters, outcomes);
        answer.finish(
            streams,
            budget,
            owed(&states),
            &query,
            |name, label: Label| Qualified {
                id: GlobalId::new(name.clone(), label.id.clone()),
                item: label,
            },
        )
    }

    /// One page of search hits, over tasks, projects, or both.
    ///
    /// # Errors
    ///
    /// As [`tasks`](Self::tasks).
    pub async fn search(
        &self,
        request: &SearchRequest,
    ) -> Result<QueryResponse<SearchHit>, EngineError> {
        let names = self.resolve_selection(&request.sources)?;
        // The streams this search reads, which is what a token resuming it may name. A
        // `--kind both` walk that has exhausted one half carries only the other, so this
        // is what a token may name rather than what it must.
        let reads: &[StreamKind] = match request.kind {
            SearchKind::Tasks => &[StreamKind::Tasks],
            SearchKind::Projects => &[StreamKind::Projects],
            SearchKind::Both => &[StreamKind::Tasks, StreamKind::Projects],
        };
        // The scope is deliberately not in the fingerprint: which streams a search covers
        // is exactly what `reads` checks below, name by name and with a message that says
        // which half a token names. Folding it in here would refuse the same mistake one
        // layer earlier and less clearly, and leave that check unreachable.
        let query = shape("search", &names, &request.text);
        let states = resumption(self, request.paging.token.as_ref(), reads, &query)?;
        let budget = request.paging.limit.get();
        let filters = Filters {
            text: Some(request.text.clone()),
            ..Filters::default()
        };

        let mut answer = Answer::new();

        // One stream per (source, entity), because a search over both entities reads two
        // result sets from each source and each has its own place to resume.
        let mut ready = Vec::new();
        let mut kinds = Vec::new();
        let mut starts = Vec::new();
        for source in answer.split(self, &names) {
            let mut streams = Vec::new();
            if matches!(request.kind, SearchKind::Tasks | SearchKind::Both) {
                streams.push(StreamKind::Tasks);
            }
            if matches!(request.kind, SearchKind::Projects | SearchKind::Both) {
                if source.source().capabilities().projects.is_native() {
                    streams.push(StreamKind::Projects);
                } else {
                    answer.unreachable_predicate(source, Predicate::Project);
                }
            }
            for stream in streams {
                if let Some(resume) = resume_at(&states, source.name(), stream) {
                    ready.push(source);
                    kinds.push(stream);
                    starts.push(resume);
                }
            }
        }

        let shapes: Vec<HitShape> = ready
            .iter()
            .zip(kinds.iter())
            .map(|(source, kind)| shape_hits(&source.source().capabilities(), &filters, *kind))
            .collect();
        let counters: Vec<AtomicU32> = ready.iter().map(|_| AtomicU32::new(0)).collect();
        let outcomes: Vec<Outcomes> = shapes.iter().map(|shape| shape.outcomes.clone()).collect();

        let walks = ready
            .iter()
            .enumerate()
            .map(|(index, source)| {
                fetch_hits(
                    source,
                    &shapes[index],
                    &starts[index],
                    budget,
                    &counters[index],
                )
            })
            .collect();

        let streams =
            answer.collect_streams(&ready, &kinds, join_all(walks).await, &counters, outcomes);
        answer.finish(
            streams,
            budget,
            owed(&states),
            &query,
            |name, found: Found| match found {
                Found::Task(task) => SearchHit::Task(delivery::qualified_task(
                    GlobalId::new(name.clone(), task.id.clone()),
                    task,
                )),
                Found::Project(project) => SearchHit::Project(Qualified {
                    id: GlobalId::new(name.clone(), project.id.clone()),
                    item: project,
                }),
            },
        )
    }

    /// One task by its qualified id, or an empty page when there is no such task.
    ///
    /// # Errors
    ///
    /// Returns [`EngineError::UnknownSource`] when the id names a source nothing
    /// configures.
    pub async fn task(&self, id: &GlobalId) -> Result<QueryResponse<Qualified<Task>>, EngineError> {
        let name = self.known(&id.source)?;
        let mut answer = Answer::new();
        let selected = answer.split(self, std::slice::from_ref(&name));
        let Some(source) = selected.first() else {
            return answer.nothing();
        };
        let found = source.source().get_task(&id.native).await;
        let qualified = GlobalId::new(source.name().clone(), id.native.clone());
        answer.one(source, found, |task| {
            delivery::qualified_task(qualified, task)
        })
    }

    /// One project by its qualified id, or an empty page when there is no such project.
    ///
    /// # Errors
    ///
    /// As [`task`](Self::task).
    pub async fn project(
        &self,
        id: &GlobalId,
    ) -> Result<QueryResponse<Qualified<Project>>, EngineError> {
        let name = self.known(&id.source)?;
        let mut answer = Answer::new();
        let selected = answer.split(self, std::slice::from_ref(&name));
        let Some(source) = selected.first() else {
            return answer.nothing();
        };
        let found = source.source().get_project(&id.native).await;
        let qualified = GlobalId::new(source.name().clone(), id.native.clone());
        answer.one(source, found, |project| Qualified {
            id: qualified,
            item: project,
        })
    }

    /// One document by its qualified id, or an empty page when there is no such document.
    ///
    /// A source declaring it has no documents holds none, so it is not asked and the
    /// answer is the empty page with [`Predicate::Document`] reported unavailable — the
    /// same answer the list verb gives, rather than a failure.
    ///
    /// # Errors
    ///
    /// As [`task`](Self::task).
    pub async fn document(
        &self,
        id: &GlobalId,
    ) -> Result<QueryResponse<Qualified<Document>>, EngineError> {
        let name = self.known(&id.source)?;
        let mut answer = Answer::new();
        let selected = answer.split(self, std::slice::from_ref(&name));
        let Some(source) = selected.first() else {
            return answer.nothing();
        };
        if !source.source().capabilities().documents.is_native() {
            answer.unreachable_predicate(source, Predicate::Document);
            return answer.nothing();
        }
        let found = source.source().get_document(&id.native).await;
        let qualified = GlobalId::new(source.name().clone(), id.native.clone());
        answer.one(source, found, |document| Qualified {
            id: qualified,
            item: document,
        })
    }

    /// One page of a task's dependency edges.
    ///
    /// # Errors
    ///
    /// As [`task`](Self::task), plus [`EngineError::Token`] for a page token this engine
    /// did not issue.
    pub async fn task_dependencies(
        &self,
        request: &DependencyRequest,
    ) -> Result<QueryResponse<QualifiedEdge>, EngineError> {
        self.dependencies(request, Entity::Task).await
    }

    /// One page of a project's dependency edges.
    ///
    /// # Errors
    ///
    /// As [`task_dependencies`](Self::task_dependencies).
    pub async fn project_dependencies(
        &self,
        request: &DependencyRequest,
    ) -> Result<QueryResponse<QualifiedEdge>, EngineError> {
        self.dependencies(request, Entity::Project).await
    }

    /// Both dependency verbs, which differ only in which of a source's two edge sets
    /// they read and which of its two declarations governs the reverse direction.
    async fn dependencies(
        &self,
        request: &DependencyRequest,
        entity: Entity,
    ) -> Result<QueryResponse<QualifiedEdge>, EngineError> {
        let name = self.known(&request.id.source)?;
        let query = shape(
            "dependencies",
            std::slice::from_ref(&name),
            &(entity, &request.id.native, request.direction),
        );
        let states = resumption(
            self,
            request.paging.token.as_ref(),
            &[StreamKind::Items],
            &query,
        )?;
        let budget = request.paging.limit.get();

        let mut answer = Answer::new();
        let (ready, starts) = walking(
            answer.split(self, std::slice::from_ref(&name)),
            &states,
            StreamKind::Items,
        );
        let Some(source) = ready.first() else {
            return answer.nothing();
        };

        let capabilities = source.source().capabilities();
        let support = match entity {
            Entity::Task => capabilities.task_dependencies,
            Entity::Project => capabilities.project_dependencies,
        };
        // `DependencySupport` has no unsupported variant on purpose: a dependency read is
        // answered natively or emulated by the scan below, never abandoned and never
        // silently empty.
        let emulating = request.direction == Direction::DependedOnBy && !support.answers_reverse();
        let mut outcomes = Outcomes::default();
        if request.direction == Direction::DependedOnBy {
            if emulating {
                outcomes.record(Predicate::ReverseDependencies, Outcome::Emulated);
            } else {
                outcomes.record(Predicate::ReverseDependencies, Outcome::PushedDown);
            }
        }

        let counters = vec![AtomicU32::new(0)];
        let walked = fetch_edges(
            source,
            &request.id.native,
            request.direction,
            entity,
            emulating,
            &starts[0],
            budget,
            &counters[0],
        )
        .await;

        let streams = answer.collect(&ready, vec![walked], &counters, vec![outcomes]);
        answer.finish(
            streams,
            budget,
            owed(&states),
            &query,
            |name, edge: DependencyEdge| QualifiedEdge {
                from: qualify_endpoint(name, edge.from),
                to: qualify_endpoint(name, edge.to),
                kind: edge.kind,
            },
        )
    }

    /// The names a request addresses: the ones it gave, or the configuration's own.
    fn resolve_selection(&self, asked: &[SourceName]) -> Result<Vec<SourceName>, EngineError> {
        if asked.is_empty() {
            if self.selection.is_empty() {
                return Err(EngineError::NoSources);
            }
            return Ok(self.selection.clone());
        }
        asked.iter().map(|name| self.known(name)).collect()
    }

    /// `name` when this configuration has a source called that.
    fn known(&self, name: &SourceName) -> Result<SourceName, EngineError> {
        if self.has(name) {
            return Ok(name.clone());
        }
        if self.sources.is_empty() {
            return Err(EngineError::NoSources);
        }
        Err(EngineError::UnknownSource {
            name: name.to_string(),
            configured: self
                .listing()
                .iter()
                .map(|listing| listing.source.to_string())
                .collect::<Vec<_>>()
                .join(", "),
        })
    }
}

fn qualify_endpoint(
    source: &SourceName,
    endpoint: onetaskgraph_plugin_api::DependencyEndpoint,
) -> QualifiedEndpoint {
    let kind = endpoint.kind;
    let is_qualified = endpoint.is_qualified();
    let endpoint_id = endpoint.into_id();
    QualifiedEndpoint {
        id: if is_qualified {
            endpoint_id
                .parse()
                .expect("plugin-api validates qualified dependency endpoints")
        } else {
            GlobalId::new(source.clone(), NativeId(endpoint_id))
        },
        kind,
    }
}

/// Which of a source's two dependency graphs a request walks.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Entity {
    /// Task dependencies.
    Task,
    /// Project dependencies.
    Project,
}

/// A search hit before it is qualified.
enum Found {
    /// A task matched.
    Task(Task),
    /// A project matched.
    Project(Project),
}

/// What happened to one predicate against one source.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Outcome {
    /// Applied by the source itself.
    PushedDown,
    /// Applied by the engine over a wider result set.
    AppliedLocally,
    /// Answered by a bounded scan of the source.
    Emulated,
    /// Neither side could answer it, so this source contributed nothing for it.
    Unavailable,
}

/// What happened to each predicate against one source.
///
/// Keyed by predicate, one outcome each, because those are the only states there are: a
/// predicate the source applied was not also applied here, and one nobody could answer
/// was not also pushed down. The four lists [`SourcePlan`] carries are this map fanned
/// out at the boundary — held *as* four lists a predicate could sit in all four at once,
/// and four contradictory claims about one predicate is the one thing the part of the
/// answer whose whole job is to say which of them is true must not be able to say.
///
/// A `BTreeMap` rather than a `HashMap` so the lists come out in one order and two runs
/// of a query render the same plan.
#[derive(Debug, Clone, Default, PartialEq)]
struct Outcomes(BTreeMap<Predicate, Outcome>);

impl Outcomes {
    /// Record what happened to one predicate, replacing whatever was recorded before.
    ///
    /// Replacing rather than refusing: shaping a query decides each predicate once, and a
    /// second decision about the same one is the later one — there is no case here where
    /// both were meant to stand.
    fn record(&mut self, predicate: Predicate, outcome: Outcome) {
        self.0.insert(predicate, outcome);
    }

    /// Record the same outcome for several predicates, as a text search does for the two
    /// fields it covers.
    fn record_all(&mut self, predicates: impl IntoIterator<Item = Predicate>, outcome: Outcome) {
        for predicate in predicates {
            self.record(predicate, outcome);
        }
    }

    /// The predicates this outcome befell, in the map's own stable order.
    fn with(&self, outcome: Outcome) -> Vec<Predicate> {
        self.0
            .iter()
            .filter(|(_, recorded)| **recorded == outcome)
            .map(|(predicate, _)| *predicate)
            .collect()
    }
}

/// The query one source sees, and the predicates left to the engine.
struct TaskShape {
    /// What the source is asked.
    pushed: TaskQuery,
    /// What the engine narrows afterwards.
    local: LocalTasks,
    /// What to report.
    outcomes: Outcomes,
}

/// As [`TaskShape`], for projects.
struct ProjectShape {
    /// What the source is asked.
    pushed: ProjectQuery,
    /// What the engine narrows afterwards.
    local: LocalProjects,
    /// What to report.
    outcomes: Outcomes,
}

/// As [`TaskShape`], for documents.
struct DocumentShape {
    /// What the source is asked.
    pushed: DocumentQuery,
    /// What the engine narrows afterwards.
    local: LocalDocuments,
    /// What to report.
    outcomes: Outcomes,
}

/// As [`TaskShape`], for one entity's half of a search.
struct HitShape {
    /// Which entity this stream reads.
    stream: StreamKind,
    /// What a task stream asks.
    tasks: TaskQuery,
    /// What a project stream asks.
    projects: ProjectQuery,
    /// What the engine narrows afterwards, for tasks.
    local_tasks: LocalTasks,
    /// What the engine narrows afterwards, for projects.
    local_projects: LocalProjects,
    /// What to report.
    outcomes: Outcomes,
}

/// The plan and the failures a response carries, accumulated as the verb runs.
///
/// One type rather than three parallel vectors threaded through every verb, because the
/// rule they enforce together is one rule: a source that fails contributes an error and
/// still leaves every other source's results standing.
struct Answer {
    /// One entry per source the engine addressed, merged by source at the end.
    plans: Vec<SourcePlan>,
    /// Every source that could not answer.
    errors: Vec<SourceFailure>,
}

impl Answer {
    fn new() -> Self {
        Self {
            plans: Vec::new(),
            errors: Vec::new(),
        }
    }

    /// The selected sources that built, recording the ones that did not as failures.
    ///
    /// A source that never built is reported and skipped rather than fatal: that is the
    /// same rule as a source failing mid-query, applied one step earlier.
    fn split<'a>(&mut self, engine: &'a Engine, names: &[SourceName]) -> Vec<&'a ResolvedSource> {
        let mut selected = Vec::new();
        for name in names {
            match engine.sources.iter().find(|source| source.name() == name) {
                Some(ConfiguredSource::Ready(source)) => selected.push(source),
                Some(ConfiguredSource::Unavailable(source)) => {
                    self.errors.push(source.failure());
                }
                None => {}
            }
        }
        selected
    }

    /// Record that a source could answer nothing for `predicate`.
    fn unreachable_predicate(&mut self, source: &ResolvedSource, predicate: Predicate) {
        let mut outcomes = Outcomes::default();
        outcomes.record(predicate, Outcome::Unavailable);
        self.plans.push(plan_for(source, outcomes, 0));
    }

    /// Turn each source's walk into a stream, keeping a failed source's failure.
    fn collect<T>(
        &mut self,
        ready: &[&ResolvedSource],
        walked: Vec<Result<Fetched<T>, SourceError>>,
        counters: &[AtomicU32],
        outcomes: Vec<Outcomes>,
    ) -> Vec<Stream<T>> {
        let kinds = vec![StreamKind::Items; ready.len()];
        self.collect_streams(ready, &kinds, walked, counters, outcomes)
    }

    /// As [`collect`](Self::collect), where a source may contribute more than one stream.
    fn collect_streams<T>(
        &mut self,
        ready: &[&ResolvedSource],
        kinds: &[StreamKind],
        walked: Vec<Result<Fetched<T>, SourceError>>,
        counters: &[AtomicU32],
        outcomes: Vec<Outcomes>,
    ) -> Vec<Stream<T>> {
        let mut streams = Vec::new();
        for (index, result) in walked.into_iter().enumerate() {
            let source = ready[index];
            let pages = counters[index].load(Ordering::Relaxed);
            self.plans
                .push(plan_for(source, outcomes[index].clone(), pages));
            match result {
                Ok(fetched) => streams.push(Stream {
                    source: source.name().clone(),
                    kind: kinds[index],
                    fetched,
                }),
                // A stream that failed leaves the token, so a walk always terminates: a
                // source failing on every page would otherwise page forever.
                Err(error) => self.errors.push(SourceFailure {
                    source: source.name().clone(),
                    error,
                }),
            }
        }
        streams
    }

    /// The response for a verb that reads exactly one item from exactly one source.
    fn one<T, U>(
        self,
        source: &ResolvedSource,
        found: Result<Option<T>, SourceError>,
        qualify: impl FnOnce(T) -> U,
    ) -> Result<QueryResponse<U>, EngineError> {
        Ok(self.one_response(source, found, qualify))
    }

    /// [`one`](Self::one), for a caller with no refusal to thread through.
    fn one_response<T, U>(
        mut self,
        source: &ResolvedSource,
        found: Result<Option<T>, SourceError>,
        qualify: impl FnOnce(T) -> U,
    ) -> QueryResponse<U> {
        self.plans.push(plan_for(source, Outcomes::default(), 1));
        let items = match found {
            Ok(Some(item)) => vec![qualify(item)],
            Ok(None) => Vec::new(),
            Err(error) => {
                self.errors.push(SourceFailure {
                    source: source.name().clone(),
                    error,
                });
                Vec::new()
            }
        };
        QueryResponse {
            items,
            next: None,
            plan: QueryPlan {
                per_source: merge_plans(self.plans),
            },
            errors: self.errors,
        }
    }

    /// The response for a verb with nothing left to ask.
    fn nothing<U>(self) -> Result<QueryResponse<U>, EngineError> {
        Ok(QueryResponse {
            items: Vec::new(),
            next: None,
            plan: QueryPlan {
                per_source: merge_plans(self.plans),
            },
            errors: self.errors,
        })
    }

    /// Merge the streams into the caller's page and mint the token that resumes it.
    ///
    /// `first` is the stream the token being resumed says is owed the next row, so the
    /// round-robin picks up where the previous page stopped rather than restarting.
    fn finish<T, U>(
        self,
        streams: Vec<Stream<T>>,
        budget: u32,
        first: Option<&Owed>,
        query: &str,
        qualify: impl Fn(&SourceName, T) -> U,
    ) -> Result<QueryResponse<U>, EngineError> {
        let (rows, states, owed) = merge(streams, budget, first);
        let next = (!states.is_empty()).then(|| PageToken::encode(query, owed, &states));
        Ok(QueryResponse {
            items: rows
                .into_iter()
                .map(|(name, item)| qualify(&name, item))
                .collect(),
            next,
            plan: QueryPlan {
                per_source: merge_plans(self.plans),
            },
            errors: self.errors,
        })
    }
}

/// One source's plan entry: the outcomes fanned out into the four lists the contract's
/// [`SourcePlan`] carries, each in one order so two runs read the same.
fn plan_for(source: &ResolvedSource, outcomes: Outcomes, pages: u32) -> SourcePlan {
    SourcePlan {
        source: source.name().clone(),
        kind: source.kind().to_owned(),
        pushed_down: outcomes.with(Outcome::PushedDown),
        applied_locally: outcomes.with(Outcome::AppliedLocally),
        emulated: outcomes.with(Outcome::Emulated),
        unavailable: outcomes.with(Outcome::Unavailable),
        pages_fetched: pages,
    }
}

/// One entry per source, however many streams that source contributed.
///
/// `search --kind both` reads two streams from each source, and a plan is per source:
/// two entries for one name would say the engine addressed it twice.
fn merge_plans(plans: Vec<SourcePlan>) -> Vec<SourcePlan> {
    let mut merged: Vec<SourcePlan> = Vec::new();
    for plan in plans {
        if let Some(existing) = merged
            .iter_mut()
            .find(|existing| existing.source == plan.source)
        {
            existing.pushed_down.extend(plan.pushed_down);
            existing.applied_locally.extend(plan.applied_locally);
            existing.emulated.extend(plan.emulated);
            existing.unavailable.extend(plan.unavailable);
            existing.pages_fetched = existing.pages_fetched.saturating_add(plan.pages_fetched);
            for list in [
                &mut existing.pushed_down,
                &mut existing.applied_locally,
                &mut existing.emulated,
                &mut existing.unavailable,
            ] {
                list.sort_unstable();
                list.dedup();
            }
        } else {
            merged.push(plan);
        }
    }
    merged
}

/// The sources still walking, with where each picks up.
///
/// A token names every stream that has more to give, so a source **absent** from one has
/// been exhausted and is not asked again. Without that, the second page of a walk would
/// restart every finished source from its first row.
fn walking<'a>(
    selected: Vec<&'a ResolvedSource>,
    states: &Option<Resumption>,
    kind: StreamKind,
) -> (Vec<&'a ResolvedSource>, Vec<Resume>) {
    let mut ready = Vec::new();
    let mut starts = Vec::new();
    for source in selected {
        if let Some(resume) = resume_at(states, source.name(), kind) {
            ready.push(source);
            starts.push(resume);
        }
    }
    (ready, starts)
}

/// A fingerprint of everything about a query that decides which rows it returns, and in
/// what order — the verb, the sources it addresses, and every filter it carries.
///
/// Written from the request's own [`Debug`] rather than field by field, and that is the
/// point: a filter added to `Filters` next year joins the fingerprint by existing. A
/// hand-written canonical form would keep compiling with the new field missing, and the
/// tokens it minted would silently stop distinguishing the queries that differ by it —
/// which is the whole failure this exists to prevent, reintroduced quietly.
///
/// Hashed rather than carried whole so a token stays a thing a person can paste. This is
/// not a signature and there is nothing secret in a token — see [`PageToken`]. It detects
/// a caller resuming the wrong walk, which is a mistake rather than an attack, so FNV-1a
/// is enough and needs no dependency the supply-chain gate would then have to weigh.
///
/// [`Debug`] output is not promised to be stable across compiler releases, and that is
/// survivable here: a token outstanding across a rebuild is refused with the message
/// above rather than honoured wrongly, which is the safe direction to fail in.
fn shape(verb: &str, sources: &[SourceName], filters: &impl std::fmt::Debug) -> String {
    let names: Vec<&str> = sources.iter().map(SourceName::as_str).collect();
    fingerprint(&format!("{verb}|{names:?}|{filters:?}"))
}

/// FNV-1a over `text`, as sixteen hex digits.
fn fingerprint(text: &str) -> String {
    let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
    for byte in text.as_bytes() {
        hash ^= u64::from(*byte);
        hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
    }
    format!("{hash:016x}")
}

/// The stream a token says is owed the next row, or `None` when it says none is.
///
/// A fresh query has no token and every token whose last round ended evenly carries no
/// such stream, so `None` is the common case and means "begin at the first stream".
fn owed(document: &Option<Resumption>) -> Option<&Owed> {
    document.as_ref()?.owed.as_ref()
}

/// Where one stream picks up, or `None` when the token says it is finished.
fn resume_at(states: &Option<Resumption>, source: &SourceName, kind: StreamKind) -> Option<Resume> {
    match states {
        None => Some(Resume::default()),
        Some(document) => document
            .streams
            .iter()
            .find(|state| &state.source == source && state.stream == kind)
            .map(|state| state.resume.clone()),
    }
}

/// Read a caller's page token against the sources this configuration has.
///
/// [`PageToken::parse`] has already established that the string is this engine's own
/// resume document — that is structural and happens where the caller's string enters.
/// What it cannot establish is that the document belongs *here*, because only the engine
/// knows which sources are configured and what page ceiling each one declares. So the
/// three things a token this engine wrote is always true of are checked here:
///
/// 1. every stream it names belongs to a configured source, so a token carried over from
///    another configuration is refused rather than quietly resuming half a walk;
/// 2. every stream it names is one **this verb reads**. A token minted by
///    `search --kind both` carries task and project streams, and `task list` reads
///    neither; without this it would find nothing to resume, drop every source, and
///    answer with an empty page and a zero exit — a wrong answer that looks like an
///    exhausted walk, which is the worst shape this failure could take;
/// 3. no stream appears twice, because a walk has one place to pick up per stream;
/// 4. no `skip` reaches a source's declared page ceiling, because the engine's `skip` is
///    an index among the surviving rows of one source page and can never reach it.
///
/// 5. the stream owed the next row, when the document names one, is a stream the
///    document also resumes.
///
/// A sixth thing needs no check here: at most one stream is owed the next row, because
/// [`Resumption`] holds that as one optional stream rather than as a flag on each of
/// them, so a document naming two has no spelling.
///
/// None of this is a security boundary and a page token is not a credential: nothing in
/// one is secret, and a forged cursor is handed straight back to the source that would
/// have issued it and refused there. What it buys is that a stale or hand-edited token
/// fails saying so, instead of silently returning a page from somewhere else in the walk.
fn resumption(
    engine: &Engine,
    token: Option<&PageToken>,
    reads: &[StreamKind],
    query: &str,
) -> Result<Option<Resumption>, EngineError> {
    let Some(document) = token.map(PageToken::decode) else {
        return Ok(None);
    };

    // Every cursor below is an offset into the result set *one* query produced. Handed to
    // a different one — the same verb with another `--label`, another `--search`, another
    // `--direction` — each source picks up at a position that meant something in a walk
    // the caller is no longer doing, and the rows that come back are real rows at exit
    // zero. Nothing about that answer says it is arbitrary, which is what makes it worth
    // refusing rather than serving.
    if document.query != query {
        return Err(EngineError::Token {
            message: "this page token was written by a different query — resume the walk it \
                      came from, or drop --page to start this one from the beginning"
                .to_owned(),
        });
    }
    let states = &document.streams;

    let mut seen: Vec<(&SourceName, StreamKind)> = Vec::new();
    for state in states {
        if !reads.contains(&state.stream) {
            return Err(EngineError::Token {
                message: format!(
                    "this page token resumes {}, which this command does not read — it \
                     was written by a different query",
                    state.stream.describe()
                ),
            });
        }
        let ceiling = engine
            .ready()
            .find(|source| source.name() == &state.source)
            .map(ceiling);
        if ceiling.is_none() && !engine.has(&state.source) {
            return Err(EngineError::Token {
                message: format!(
                    "this page token resumes a source called {:?}, which this \
                     configuration does not have",
                    state.source.as_str()
                ),
            });
        }
        if let Some(ceiling) = ceiling
            && state.resume.skip >= ceiling
        {
            return Err(EngineError::Token {
                message: format!(
                    "this page token resumes {} rows into a page of source {:?}, which \
                     serves at most {ceiling}",
                    state.resume.skip,
                    state.source.as_str()
                ),
            });
        }
        if seen.contains(&(&state.source, state.stream)) {
            return Err(EngineError::Token {
                message: format!(
                    "this page token gives source {:?} two places to resume from",
                    state.source.as_str()
                ),
            });
        }
        seen.push((&state.source, state.stream));
    }

    // The stream owed the next row has to be one of the streams this document resumes.
    // Ignoring a stray one would be harmless in its effect — the merge would start at the
    // first stream instead — but it would be a value from outside accepted without a
    // reading, and the next thing to depend on it would inherit that.
    if let Some(owed) = &document.owed
        && !document
            .streams
            .iter()
            .any(|state| state.source == owed.source && state.stream == owed.stream)
    {
        return Err(EngineError::Token {
            message: format!(
                "this page token owes the next row to a stream it does not resume, \
                 {:?}'s {}",
                owed.source.as_str(),
                owed.stream.describe()
            ),
        });
    }

    Ok(Some(document))
}

/// Which project a task must belong to, as a source sees it.
///
/// A qualified id becomes a plain native one because by the time this runs the selection
/// holds only that id's own source — so there is no "some other source" case to get
/// wrong, and none to leave untested.
fn project_filter(selector: &ProjectSelector) -> ProjectFilter {
    match selector {
        ProjectSelector::Any => ProjectFilter::Any,
        ProjectSelector::Orphans => ProjectFilter::Orphans,
        ProjectSelector::Native(id) => ProjectFilter::Is(id.clone()),
        ProjectSelector::Qualified(id) => ProjectFilter::Is(id.native.clone()),
    }
}

/// The predicates one text query is made of.
fn text_predicates(fields: TextFields) -> Vec<Predicate> {
    match fields {
        TextFields::Title => vec![Predicate::SearchTitle],
        TextFields::Content => vec![Predicate::SearchContent],
        TextFields::TitleOrContent => vec![Predicate::SearchTitle, Predicate::SearchContent],
    }
}

/// Whether a source searches **every** field this query names.
///
/// Every, not any: a `title-or-content` search pushed to a source that searches only
/// titles would come back missing every row that matches in the body alone — a narrower
/// result than the truth, which is the one thing compensation cannot repair. So a
/// half-capable source is not asked at all and the engine searches both fields itself.
fn searches_natively(capabilities: &Capabilities, fields: TextFields) -> bool {
    match fields {
        TextFields::Title => capabilities.search_title.is_native(),
        TextFields::Content => capabilities.search_content.is_native(),
        TextFields::TitleOrContent => {
            capabilities.search_title.is_native() && capabilities.search_content.is_native()
        }
    }
}

/// Split a task query between the source and the engine.
fn shape_tasks(
    capabilities: &Capabilities,
    filters: &Filters,
    project: &ProjectFilter,
    priorities: &[Priority],
    commented_since: Option<DateTime<Utc>>,
    metadata: &[MetadataMatch],
    origin: Option<&GlobalId>,
) -> TaskShape {
    let mut pushed = TaskQuery::default();
    let mut local = LocalTasks::default();
    let mut outcomes = Outcomes::default();

    if !filters.labels.is_empty() {
        if capabilities.filter_by_label.is_native() {
            pushed.labels = filters.labels.clone();
            outcomes.record(Predicate::Label, Outcome::PushedDown);
        } else {
            local.labels = Some(filters.labels.clone());
            outcomes.record(Predicate::Label, Outcome::AppliedLocally);
        }
    }
    if !filters.statuses.is_empty() {
        if capabilities.filter_by_status.is_native() {
            pushed.statuses.clone_from(&filters.statuses);
            outcomes.record(Predicate::Status, Outcome::PushedDown);
        } else {
            local.statuses.clone_from(&filters.statuses);
            outcomes.record(Predicate::Status, Outcome::AppliedLocally);
        }
    }
    if !priorities.is_empty() {
        if capabilities.filter_by_priority.is_native() {
            pushed.priorities = priorities.to_vec();
            outcomes.record(Predicate::Priority, Outcome::PushedDown);
        } else {
            local.priorities = priorities.to_vec();
            outcomes.record(Predicate::Priority, Outcome::AppliedLocally);
        }
    }
    if let Some(since) = commented_since {
        if capabilities.filter_by_comment_activity.is_native() {
            pushed.commented_since = Some(since);
            outcomes.record(Predicate::CommentedSince, Outcome::PushedDown);
        } else {
            local.commented_since = Some(since);
            outcomes.record(Predicate::CommentedSince, Outcome::AppliedLocally);
        }
    }
    if !metadata.is_empty() {
        if capabilities.filter_by_metadata.is_native() {
            pushed.metadata = metadata.to_vec();
            outcomes.record(Predicate::Metadata, Outcome::PushedDown);
        } else {
            local.metadata = metadata.to_vec();
            outcomes.record(Predicate::Metadata, Outcome::AppliedLocally);
        }
    }
    if let Some(origin) = origin {
        if capabilities.filter_by_origin.is_native() {
            // The qualified id as a copy stores it: a source compares the string and never
            // parses it.
            pushed.origin = Some(origin.to_string());
            outcomes.record(Predicate::Origin, Outcome::PushedDown);
        } else {
            local.origin = Some(origin.clone());
            outcomes.record(Predicate::Origin, Outcome::AppliedLocally);
        }
    }
    if let Some(text) = &filters.text {
        let predicates = text_predicates(text.fields);
        if searches_natively(capabilities, text.fields) {
            pushed.text = Some(text.clone());
            outcomes.record_all(predicates, Outcome::PushedDown);
        } else {
            local.text = Some(text.clone());
            outcomes.record_all(predicates, Outcome::AppliedLocally);
        }
    }
    match project {
        ProjectFilter::Any => {}
        ProjectFilter::Orphans => {
            if capabilities.orphan_tasks.is_native() {
                pushed.project = ProjectFilter::Orphans;
                outcomes.record(Predicate::Project, Outcome::PushedDown);
            } else {
                local.project = Some(ProjectFilter::Orphans);
                outcomes.record(Predicate::Project, Outcome::AppliedLocally);
            }
        }
        ProjectFilter::Is(id) => {
            if capabilities.projects.is_native() {
                pushed.project = ProjectFilter::Is(id.clone());
                outcomes.record(Predicate::Project, Outcome::PushedDown);
            } else {
                local.project = Some(ProjectFilter::Is(id.clone()));
                outcomes.record(Predicate::Project, Outcome::AppliedLocally);
            }
        }
    }

    TaskShape {
        pushed,
        local,
        outcomes,
    }
}

/// Split a project query between the source and the engine.
fn shape_projects(capabilities: &Capabilities, filters: &Filters) -> ProjectShape {
    let mut pushed = ProjectQuery::default();
    let mut local = LocalProjects::default();
    let mut outcomes = Outcomes::default();

    if !filters.labels.is_empty() {
        if capabilities.filter_by_label.is_native() {
            pushed.labels = filters.labels.clone();
            outcomes.record(Predicate::Label, Outcome::PushedDown);
        } else {
            local.labels = Some(filters.labels.clone());
            outcomes.record(Predicate::Label, Outcome::AppliedLocally);
        }
    }
    if !filters.statuses.is_empty() {
        if capabilities.filter_by_status.is_native() {
            pushed.statuses.clone_from(&filters.statuses);
            outcomes.record(Predicate::Status, Outcome::PushedDown);
        } else {
            local.statuses.clone_from(&filters.statuses);
            outcomes.record(Predicate::Status, Outcome::AppliedLocally);
        }
    }
    if let Some(text) = &filters.text {
        let predicates = text_predicates(text.fields);
        if searches_natively(capabilities, text.fields) {
            pushed.text = Some(text.clone());
            outcomes.record_all(predicates, Outcome::PushedDown);
        } else {
            local.text = Some(text.clone());
            outcomes.record_all(predicates, Outcome::AppliedLocally);
        }
    }

    ProjectShape {
        pushed,
        local,
        outcomes,
    }
}

/// Split a document query between the source and the engine.
///
/// The same three predicates a task query is split by, minus the status filter a document
/// has nothing to compare against.
fn shape_documents(
    capabilities: &Capabilities,
    filters: &DocumentFilters,
    project: &ProjectFilter,
) -> DocumentShape {
    let mut pushed = DocumentQuery::default();
    let mut local = LocalDocuments::default();
    let mut outcomes = Outcomes::default();

    if !filters.labels.is_empty() {
        if capabilities.filter_by_label.is_native() {
            pushed.labels = filters.labels.clone();
            outcomes.record(Predicate::Label, Outcome::PushedDown);
        } else {
            local.labels = Some(filters.labels.clone());
            outcomes.record(Predicate::Label, Outcome::AppliedLocally);
        }
    }
    if let Some(text) = &filters.text {
        let predicates = text_predicates(text.fields);
        if searches_natively(capabilities, text.fields) {
            pushed.text = Some(text.clone());
            outcomes.record_all(predicates, Outcome::PushedDown);
        } else {
            local.text = Some(text.clone());
            outcomes.record_all(predicates, Outcome::AppliedLocally);
        }
    }
    match project {
        ProjectFilter::Any => {}
        ProjectFilter::Orphans => {
            if capabilities.orphan_tasks.is_native() {
                pushed.project = ProjectFilter::Orphans;
                outcomes.record(Predicate::Project, Outcome::PushedDown);
            } else {
                local.project = Some(ProjectFilter::Orphans);
                outcomes.record(Predicate::Project, Outcome::AppliedLocally);
            }
        }
        ProjectFilter::Is(id) => {
            if capabilities.projects.is_native() {
                pushed.project = ProjectFilter::Is(id.clone());
                outcomes.record(Predicate::Project, Outcome::PushedDown);
            } else {
                local.project = Some(ProjectFilter::Is(id.clone()));
                outcomes.record(Predicate::Project, Outcome::AppliedLocally);
            }
        }
    }

    DocumentShape {
        pushed,
        local,
        outcomes,
    }
}

/// Split one entity's half of a search between the source and the engine.
fn shape_hits(capabilities: &Capabilities, filters: &Filters, stream: StreamKind) -> HitShape {
    match stream {
        StreamKind::Projects => {
            let shaped = shape_projects(capabilities, filters);
            HitShape {
                stream,
                tasks: TaskQuery::default(),
                projects: shaped.pushed,
                local_tasks: LocalTasks::default(),
                local_projects: shaped.local,
                outcomes: shaped.outcomes,
            }
        }
        StreamKind::Items | StreamKind::Tasks => {
            let shaped = shape_tasks(
                capabilities,
                filters,
                &ProjectFilter::Any,
                &[],
                None,
                &[],
                None,
            );
            HitShape {
                stream,
                tasks: shaped.pushed,
                projects: ProjectQuery::default(),
                local_tasks: shaped.local,
                local_projects: LocalProjects::default(),
                outcomes: shaped.outcomes,
            }
        }
    }
}

/// How large a page to ask a source for.
///
/// Exactly what is needed when every predicate went down, and the source's own ceiling
/// when the engine is narrowing — because a compensating walk cannot know how many rows
/// of a page will survive, and asking for the caller's limit would turn one filtered
/// page into a page per surviving row.
fn page_size(compensating: bool, budget: u32, ceiling: u32) -> u32 {
    if compensating {
        ceiling
    } else {
        budget.min(ceiling)
    }
}

/// The largest page this source will serve, never zero.
fn ceiling(source: &ResolvedSource) -> u32 {
    source.source().capabilities().max_page_size.max(1)
}

/// Walk one source's tasks, narrowing whatever it did not apply itself.
async fn fetch_tasks(
    source: &ResolvedSource,
    shape: &TaskShape,
    start: &Resume,
    budget: u32,
    calls: &AtomicU32,
) -> Result<Fetched<Task>, SourceError> {
    let compensating = shape.local != LocalTasks::default();
    walk(
        start,
        budget,
        page_size(compensating, budget, ceiling(source)),
        |task| shape.local.keeps(task),
        |cursor, limit| async move {
            calls.fetch_add(1, Ordering::Relaxed);
            let request = PageRequest { cursor, limit };
            let page = source.source().query_tasks(&shape.pushed, &request).await?;
            match shape.local.commented_since {
                None => Ok(page),
                Some(since) => comment::commented_since(source, &shape.local, page, since).await,
            }
        },
    )
    .await
}

/// Walk one source's projects, narrowing whatever it did not apply itself.
async fn fetch_projects(
    source: &ResolvedSource,
    shape: &ProjectShape,
    start: &Resume,
    budget: u32,
    calls: &AtomicU32,
) -> Result<Fetched<Project>, SourceError> {
    let compensating = shape.local != LocalProjects::default();
    walk(
        start,
        budget,
        page_size(compensating, budget, ceiling(source)),
        |project| shape.local.keeps(project),
        |cursor, limit| async move {
            calls.fetch_add(1, Ordering::Relaxed);
            let request = PageRequest { cursor, limit };
            source
                .source()
                .query_projects(&shape.pushed, &request)
                .await
        },
    )
    .await
}

/// Walk one source's documents, narrowing whatever it did not apply itself.
async fn fetch_documents(
    source: &ResolvedSource,
    shape: &DocumentShape,
    start: &Resume,
    budget: u32,
    calls: &AtomicU32,
) -> Result<Fetched<Document>, SourceError> {
    let compensating = shape.local != LocalDocuments::default();
    walk(
        start,
        budget,
        page_size(compensating, budget, ceiling(source)),
        |document| shape.local.keeps(document),
        |cursor, limit| async move {
            calls.fetch_add(1, Ordering::Relaxed);
            let request = PageRequest { cursor, limit };
            source
                .source()
                .query_documents(&shape.pushed, &request)
                .await
        },
    )
    .await
}

/// Walk one source's labels. There is no predicate to compensate for.
async fn fetch_labels(
    source: &ResolvedSource,
    start: &Resume,
    budget: u32,
    calls: &AtomicU32,
) -> Result<Fetched<Label>, SourceError> {
    walk(
        start,
        budget,
        page_size(false, budget, ceiling(source)),
        |_| true,
        |cursor, limit| async move {
            calls.fetch_add(1, Ordering::Relaxed);
            let request = PageRequest { cursor, limit };
            source.source().labels(&request).await
        },
    )
    .await
}

/// Walk one entity's half of a search.
async fn fetch_hits(
    source: &ResolvedSource,
    shape: &HitShape,
    start: &Resume,
    budget: u32,
    calls: &AtomicU32,
) -> Result<Fetched<Found>, SourceError> {
    let ceiling = ceiling(source);
    match shape.stream {
        StreamKind::Projects => {
            let compensating = shape.local_projects != LocalProjects::default();
            walk(
                start,
                budget,
                page_size(compensating, budget, ceiling),
                |found| match found {
                    Found::Project(project) => shape.local_projects.keeps(project),
                    Found::Task(_) => true,
                },
                |cursor, limit| async move {
                    calls.fetch_add(1, Ordering::Relaxed);
                    let request = PageRequest { cursor, limit };
                    let page = source
                        .source()
                        .query_projects(&shape.projects, &request)
                        .await?;
                    Ok(Page {
                        items: page.items.into_iter().map(Found::Project).collect(),
                        next: page.next,
                    })
                },
            )
            .await
        }
        StreamKind::Items | StreamKind::Tasks => {
            let compensating = shape.local_tasks != LocalTasks::default();
            walk(
                start,
                budget,
                page_size(compensating, budget, ceiling),
                |found| match found {
                    Found::Task(task) => shape.local_tasks.keeps(task),
                    Found::Project(_) => true,
                },
                |cursor, limit| async move {
                    calls.fetch_add(1, Ordering::Relaxed);
                    let request = PageRequest { cursor, limit };
                    let page = source.source().query_tasks(&shape.tasks, &request).await?;
                    Ok(Page {
                        items: page.items.into_iter().map(Found::Task).collect(),
                        next: page.next,
                    })
                },
            )
            .await
        }
    }
}

/// One page of an item's forward edges.
async fn forward_edges(
    source: &ResolvedSource,
    entity: Entity,
    id: &NativeId,
    request: &PageRequest,
) -> Result<Page<DependencyEdge>, SourceError> {
    match entity {
        Entity::Task => {
            source
                .source()
                .task_dependencies(id, Direction::DependsOn, request)
                .await
        }
        Entity::Project => {
            source
                .source()
                .project_dependencies(id, Direction::DependsOn, request)
                .await
        }
    }
}

/// Walk one item's dependency edges, emulating the reverse direction when the source
/// only reports forward ones.
///
/// The emulation is the bounded page-by-page scan the contract describes: a page of the
/// source's items, each asked for its own forward edges, keeping the ones that point at
/// `native`. It is indexless by construction — nothing is retained between pages beyond
/// the caller's own page — which is why a source that cannot walk backwards costs a scan
/// rather than a stored reverse index.
#[expect(
    clippy::too_many_arguments,
    reason = "every argument is one axis of one walk — the source, the item, the \
              direction, which of its two graphs, whether the reverse is emulated, where \
              to resume, how many rows to return and where to count calls. Grouping them \
              into a struct would name the same eight values one indirection further from \
              the loop that reads them."
)]
async fn fetch_edges(
    source: &ResolvedSource,
    native: &NativeId,
    direction: Direction,
    entity: Entity,
    emulating: bool,
    start: &Resume,
    budget: u32,
    calls: &AtomicU32,
) -> Result<Fetched<DependencyEdge>, SourceError> {
    let ceiling = ceiling(source);
    if !emulating {
        return walk(
            start,
            budget,
            page_size(false, budget, ceiling),
            |_| true,
            |cursor, limit| async move {
                calls.fetch_add(1, Ordering::Relaxed);
                let request = PageRequest { cursor, limit };
                match entity {
                    Entity::Task => {
                        source
                            .source()
                            .task_dependencies(native, direction, &request)
                            .await
                    }
                    Entity::Project => {
                        source
                            .source()
                            .project_dependencies(native, direction, &request)
                            .await
                    }
                }
            },
        )
        .await;
    }

    walk(
        start,
        budget,
        ceiling,
        |_| true,
        |cursor, limit| async move {
            calls.fetch_add(1, Ordering::Relaxed);
            let request = PageRequest { cursor, limit };
            let (ids, next) = match entity {
                Entity::Task => {
                    let page = source
                        .source()
                        .query_tasks(&TaskQuery::default(), &request)
                        .await?;
                    let ids: Vec<NativeId> = page.items.into_iter().map(|task| task.id).collect();
                    (ids, page.next)
                }
                Entity::Project => {
                    let page = source
                        .source()
                        .query_projects(&ProjectQuery::default(), &request)
                        .await?;
                    let ids: Vec<NativeId> =
                        page.items.into_iter().map(|project| project.id).collect();
                    (ids, page.next)
                }
            };

            let mut edges = Vec::new();
            for id in ids {
                let mut inner: Option<Cursor> = None;
                loop {
                    calls.fetch_add(1, Ordering::Relaxed);
                    let request = PageRequest {
                        cursor: inner.clone(),
                        limit,
                    };
                    let page = forward_edges(source, entity, &id, &request).await?;
                    // The inner half of the same bound the walk holds on its own pages:
                    // this scan keeps every matching edge of one source page, so a source
                    // that overruns here overruns the engine's memory just as surely.
                    fits(page.items.len(), limit)?;
                    edges.extend(page.items.into_iter().filter(|edge| &edge.to == native));
                    unrepeated(
                        page.next.as_ref(),
                        inner.as_ref(),
                        "its forward edges were being scanned",
                    )?;
                    match page.next {
                        Some(cursor) => inner = Some(cursor),
                        None => break,
                    }
                }
            }

            Ok(Page { items: edges, next })
        },
    )
    .await
}