onetaskgraph-linear 0.12.13

A onetaskgraph source over the Linear API.
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
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
//! Every capability this source declares, driven against Linear's real API.
//!
//! The lane builds its own fixture on the scratch team `LINEAR_WRITE_TEAM` names — two
//! projects, one issue filed under each, one issue filed under neither, two documents
//! filed the same way, two labels and two workflow states — because that shape is what
//! makes an honoured predicate and an ignored one *different answers*. A workspace holding
//! one project, or one where every issue carries the label, answers a filter the same way
//! whether or not the source applies it.
//!
//! It is an ordinary test in this crate's ordinary `test` target: change this plugin and
//! it runs in the required check, change anything else and affected selection does not
//! select it. Without `LINEAR_API_KEY` or without the scratch team `LINEAR_WRITE_TEAM`
//! names it skips, printing why — a contributor with no keys, and a pull request from a
//! fork, which the host gives no secrets. Where one *is* expected the run sets
//! `ONETASKGRAPH_LIVE_REQUIRED=1` and each of those skips becomes a failure naming the
//! variable, so the required lane cannot pass green for want of a credential.
//!
//! Ordinary CI reuses three explicitly initialized, team-owned documents and their parent.
//! Daily fresh mode removes its disposable documents after exercising creation and deletion.
//! Invocation-owned local sets retire on cleanup. Both modes also recover what a run killed
//! between its writes and its cleanup left behind — but only
//! artifacts the kernel says no live run owns, and only once its own journey is over. See
//! [`sweep_orphans`].

use std::{collections::BTreeMap, env};

use onetaskgraph_live::artifact::{Run, Sweep, now_micros};
use onetaskgraph_live::{Credential, Exclusivity, Session, missing, required};
use onetaskgraph_plugin_api::{
    Capabilities, DependencyEdge, DependencyEndpoint, DependencyKind, DependencySupport, Direction,
    Document, DocumentQuery, ItemKind, ItemWrite, Label, LabelFilter, Location, MetadataMatch,
    NativeId, PageRequest, Priority, Project, ProjectFilter, SecretResolver, SourceError,
    SourceName, SourcePlugin, Status, StatusCategory, Support, Task, TaskQuery, TaskSource,
    TextFields, TextQuery,
};
use secrecy::SecretString;
mod document_lifecycle;
use document_lifecycle::{Mode, Standing};
use onetaskgraph_linear::live_artifact::{Scope, Slot};
use serde_json::{Value, json};

struct Environment;
impl SecretResolver for Environment {
    fn get(&self, var: &str) -> Option<SecretString> {
        env::var(var).ok().map(SecretString::from)
    }
}

/// A live assertion that returns rather than panics.
///
/// Every check inside the journey has to reach [`run_then_cleanup`] as an `Err`: a panic
/// would unwind past the cleanup and leave this run's issues, projects and labels in the
/// scratch team for the next run to find.
macro_rules! ensure {
    ($condition:expr, $($message:tt)+) => {
        if !$condition {
            return Err(format!($($message)+));
        }
    };
}

// `cleanup` is shared with `tests/sweep_gate.rs`, which drives the same code against a
// loopback stand-in. What this target does not reach is that drive's — the endpoint seam it
// uses to be pointed somewhere other than Linear — rather than dead code.
#[allow(dead_code)]
mod cleanup;

use cleanup::{
    ISSUE_PAGE_PROBE, LABEL_CREATE, PROJECT_STATUSES, SESSION_NAME, TEAM_STATES, artifact_label,
    artifact_title, is_this_runs, linear, remove_artifacts, run_then_cleanup, sweep_orphans,
};

// `settle` is shared with `tests/settle_gate.rs`, which drives these reads against a loopback
// workspace whose index lags, and the read after a change against a replica that lags.
mod settle;

use settle::{
    Bound, LINEAR_DOCUMENT_LISTING, LINEAR_INDEX, LINEAR_REPLICA, resolving_labels, settled,
    settled_content, settled_document_absent, settled_documents, settled_label, settled_projects,
    settled_tasks, settled_walk, task_titles, token_moved,
};

/// The two workflow states this fixture files its issues under.
///
/// Chosen by Linear's own `WorkflowState.type` rather than by name, because the display
/// names of a team's states are the team's business: `unstarted` is what this product
/// reads as `todo` and `completed` is what it reads as `done`, so a team that has both
/// gives the fixture two categories a status filter can separate however it spells them.
async fn fixture_states(key: &str, team_key: &str) -> Result<(String, String), String> {
    let data = linear(
        key,
        TEAM_STATES,
        json!({"key":team_key}),
        "live workflow state discovery",
    )
    .await?;
    let states = data
        .pointer("/teams/nodes/0/states/nodes")
        .and_then(Value::as_array)
        .ok_or_else(|| {
            format!("LINEAR_WRITE_TEAM={team_key} names no team this credential can see")
        })?;
    let named = |wanted: &str| {
        states
            .iter()
            .find(|state| state.get("type").and_then(Value::as_str) == Some(wanted))
            .and_then(|state| state.get("name").and_then(Value::as_str))
            .map(str::to_owned)
    };
    match (named("unstarted"), named("completed")) {
        (Some(open), Some(done)) => Ok((open, done)),
        _ => Err(format!(
            "team {team_key} has no workflow state of type unstarted and one of type \
             completed, which this lane needs to file two issues a status filter can \
             separate; add them to that team or point LINEAR_WRITE_TEAM at a scratch team \
             that has them"
        )),
    }
}

/// A project status name this workspace resolves uniquely.
///
/// The source resolves a project status by name across the whole workspace and refuses a
/// name two statuses answer to, so the fixture picks one nothing else is spelled like
/// rather than assuming a default.
async fn fixture_project_status(key: &str) -> Result<String, String> {
    let data = linear(
        key,
        PROJECT_STATUSES,
        json!({}),
        "live project status discovery",
    )
    .await?;
    let statuses = data
        .pointer("/projectStatuses/nodes")
        .and_then(Value::as_array)
        .ok_or_else(|| "live project status discovery returned no statuses".to_owned())?;
    let names = statuses
        .iter()
        .filter_map(|status| status.get("name").and_then(Value::as_str))
        .collect::<Vec<_>>();
    // Case-insensitively, because that is how the source's own lookup compares: a name
    // two statuses answer to under `eqIgnoreCase` is one it refuses.
    names
        .iter()
        .find(|name| {
            names
                .iter()
                .filter(|other| other.eq_ignore_ascii_case(name))
                .count()
                == 1
        })
        .map(|name| (*name).to_owned())
        .ok_or_else(|| {
            "this workspace has no project status name that resolves uniquely, and the \
             source refuses one two statuses answer to"
                .to_owned()
        })
}

async fn create_label(key: &str, team: &str, name: &str) -> Result<(), String> {
    let data = linear(
        key,
        LABEL_CREATE,
        json!({"input":{"name":name,"teamId":team,"color":"#bec2c8"}}),
        "live label creation",
    )
    .await?;
    if data
        .pointer("/issueLabelCreate/issueLabel/name")
        .and_then(Value::as_str)
        != Some(name)
    {
        return Err(format!(
            "Linear did not confirm creating the label {name:?}"
        ));
    }
    Ok(())
}

fn label(name: &str) -> Label {
    // Only the name reaches Linear: the source resolves a label by name and never sends
    // an id or a colour it was handed.
    Label {
        id: NativeId("live-source-label".into()),
        name: name.to_owned(),
        color: None,
    }
}

fn blocks(far: &NativeId, kind: ItemKind) -> DependencyEdge {
    DependencyEdge {
        // Only `to` decides where the relation goes: the source names the near end from
        // the item it is writing, which has no id until Linear creates it.
        from: DependencyEndpoint::from_native(NativeId("live-source-item".into()), kind),
        to: DependencyEndpoint::from_native(far.clone(), kind),
        kind: DependencyKind::Blocks,
    }
}

fn page(limit: u32) -> PageRequest {
    PageRequest {
        cursor: None,
        limit,
    }
}

fn sorted(mut titles: Vec<String>) -> Vec<String> {
    titles.sort();
    titles
}

/// `write`, a task naming labels this run created, through [`resolving_labels`]: Linear's
/// label filter has answered such a label with no match on the plugin's own lookup a moment
/// after it answered it three times in a row to [`settled_label`], so the write is sent again
/// within `bound` while that is its refusal, and ends with that same refusal once `bound` is
/// spent rather than creating the label or dropping it.
async fn write_labelled_task(
    bound: Bound,
    source: &dyn TaskSource,
    write: &ItemWrite<Task>,
) -> Result<NativeId, SourceError> {
    resolving_labels(bound, || source.write_task(write)).await
}

/// Everything this lane needs to reach the one team it may write to.
struct LiveRun {
    endpoint: String,
    key: String,
    /// Which run this is: the machine that can vouch for it and the process on it. Every
    /// artifact below carries it, which is what its own cleanup finds them by and what a
    /// later run's sweep looks this run up by before deciding anything about them.
    id: Run,
    stamp_micros: u64,
    open_state: String,
    done_state: String,
    project_status: String,
    document_mode: Mode,
    standing: Standing,
}

impl LiveRun {
    async fn linear(&self, query: &str, variables: Value, _what: &str) -> Result<Value, String> {
        document_lifecycle::send(&self.endpoint, &self.key, query, variables).await
    }
}

/// Drives every field of the source's declared `Capabilities` against Linear's real API.
///
/// Nothing here panics: every failure returns, so the caller's cleanup runs over a
/// workspace this run is still holding artifacts in.
async fn drive_every_declared_capability(
    run: &LiveRun,
    source: &dyn TaskSource,
    team_id: &str,
) -> Result<(), String> {
    let title = |offset: u64| artifact_title(run.id, run.stamp_micros + offset);
    let (alpha, beta) = (title(0), title(1));
    let (first, second, orphan) = (title(2), title(3), title(4));
    let run_label = artifact_label(run.id, run.stamp_micros);
    let only_label = artifact_label(run.id, run.stamp_micros + 1);
    create_label(&run.key, team_id, &run_label).await?;
    create_label(&run.key, team_id, &only_label).await?;
    // The first task write names both, and the source resolves a label by name through
    // Linear's label filter, which holds a label only some while after it was created — and
    // for a while after that may answer it on one read and not the next.
    for name in [&run_label, &only_label] {
        settled_label(LINEAR_INDEX, name, |query, variables| {
            run.linear(query, variables, "live label lookup")
        })
        .await?;
    }
    let open = Status {
        category: StatusCategory::Todo,
        name: run.open_state.clone(),
    };
    let done = Status {
        category: StatusCategory::Done,
        name: run.done_state.clone(),
    };
    let project_status = Status {
        category: StatusCategory::Todo,
        name: run.project_status.clone(),
    };
    // A syntactically valid nil UUID names no issue in the nominated test workspace.
    // Exercise the actual mutation error through the public source boundary: if Linear
    // rewords both recognised messages, this lane fails rather than trusting the fixture.
    let missing = source
        .set_task_status(
            &NativeId("00000000-0000-0000-0000-000000000000".into()),
            StatusCategory::Todo,
        )
        .await
        .map_err(|error| format!("the live missing-issue status contract drifted: {error}"))?;
    ensure!(
        missing.is_none(),
        "a status mutation to a nonexistent issue was not not-found"
    );
    // And the same for a project, whose spelling `PROJECT_NOT_FOUND_MESSAGE` and its
    // presentable alternative record: a project status write to no project is no such project.
    let missing = source
        .set_project_status(
            &NativeId("00000000-0000-0000-0000-000000000000".into()),
            StatusCategory::Todo,
        )
        .await
        .map_err(|error| format!("the live missing-project status contract drifted: {error}"))?;
    ensure!(
        missing.is_none(),
        "a status mutation to a nonexistent project was not not-found"
    );
    // Every listing below is scoped by the label all three issues carry, because Linear's
    // `issues` connection is the whole workspace: without it these would be containments
    // rather than the exact sets that tell an honoured predicate from an ignored one.
    let scoped = || TaskQuery {
        labels: LabelFilter {
            any_of: vec![run_label.clone()],
            ..LabelFilter::default()
        },
        ..TaskQuery::default()
    };
    let project = |name: &str| Project {
        version: None,
        id: NativeId("live-source-item".into()),
        title: name.to_owned(),
        content: Some("temporary credentialed write; the live lane removes this".into()),
        status: project_status.clone(),
        labels: vec![],
        url: None,
        location: None,
        created_at: None,
        updated_at: None,
        metadata: BTreeMap::new(),
        repositories: vec![],
        classification: Default::default(),
    };
    let task = |name: &str, status: &Status, under: Option<&NativeId>, labels: Vec<Label>| Task {
        version: None,
        id: NativeId("live-source-item".into()),
        key: None,
        title: name.to_owned(),
        content: Some("temporary credentialed write; the live lane removes this".into()),
        status: status.clone(),
        labels,
        priority: Priority::None,
        project: under.cloned(),
        url: None,
        location: None,
        created_at: None,
        updated_at: None,
        metadata: BTreeMap::new(),
        repositories: vec![],
        delivers: Vec::new(),
        delivered_by: Vec::new(),
        classification: Default::default(),
    };

    let alpha_id = source
        .write_project(&ItemWrite {
            target: None,
            item: project(&alpha),
            depends_on: vec![],
        })
        .await
        .map_err(|error| format!("live project write of {alpha:?} failed: {error}"))?;
    let beta_id = source
        .write_project(&ItemWrite {
            target: None,
            item: project(&beta),
            depends_on: vec![blocks(&alpha_id, ItemKind::Project)],
        })
        .await
        .map_err(|error| format!("live project write of {beta:?} failed: {error}"))?;
    let first_id = write_labelled_task(
        LINEAR_INDEX,
        source,
        &ItemWrite {
            target: None,
            item: task(
                &first,
                &open,
                Some(&alpha_id),
                vec![label(&run_label), label(&only_label)],
            ),
            depends_on: vec![],
        },
    )
    .await
    .map_err(|error| format!("live task write of {first:?} failed: {error}"))?;
    let second_id = write_labelled_task(
        LINEAR_INDEX,
        source,
        &ItemWrite {
            target: None,
            item: task(&second, &open, Some(&beta_id), vec![label(&run_label)]),
            depends_on: vec![blocks(&first_id, ItemKind::Task)],
        },
    )
    .await
    .map_err(|error| format!("live task write of {second:?} failed: {error}"))?;
    let orphan_id = write_labelled_task(
        LINEAR_INDEX,
        source,
        &ItemWrite {
            target: None,
            item: task(&orphan, &done, None, vec![label(&run_label)]),
            depends_on: vec![],
        },
    )
    .await
    .map_err(|error| format!("live task write of {orphan:?} failed: {error}"))?;

    // Linear indexes a created issue before it answers a filtered query over it, so the
    // reads below wait for the fixture rather than racing it — each one, through `settle`,
    // because the index does not catch up on every filter at once.
    let all_three = sorted(vec![first.clone(), second.clone(), orphan.clone()]);
    settled_tasks(
        LINEAR_INDEX,
        source,
        &scoped(),
        &format!("the three issues this run created, labelled {run_label},"),
        &all_three,
    )
    .await?;

    // `projects`: two are held, and a listing scoped to one keeps the issue filed under
    // it and no other. Unscoped on purpose — the workspace holds issues of its own, so a
    // filter declared and then ignored returns them too.
    let listed = settled_projects(LINEAR_INDEX, source, &[alpha.clone(), beta.clone()]).await?;
    ensure!(
        listed.contains(&alpha) && listed.contains(&beta),
        "the two projects this run created are not in Linear's own project listing"
    );
    let under = |id: &NativeId| TaskQuery {
        project: ProjectFilter::Is(id.clone()),
        ..TaskQuery::default()
    };
    settled_tasks(
        LINEAR_INDEX,
        source,
        &under(&alpha_id),
        "the issues of one of this run's two projects",
        std::slice::from_ref(&first),
    )
    .await?;
    settled_tasks(
        LINEAR_INDEX,
        source,
        &under(&beta_id),
        "the issues of the other of this run's two projects",
        std::slice::from_ref(&second),
    )
    .await?;

    // `orphan_tasks`: the one issue filed under neither project.
    settled_tasks(
        LINEAR_INDEX,
        source,
        &TaskQuery {
            project: ProjectFilter::Orphans,
            ..scoped()
        },
        "this run's issues belonging to no project",
        std::slice::from_ref(&orphan),
    )
    .await?;

    // `filter_by_label`: one of the three carries the second label, and the exclusion
    // keeps exactly the other two.
    settled_tasks(
        LINEAR_INDEX,
        source,
        &TaskQuery {
            labels: LabelFilter {
                any_of: vec![only_label.clone()],
                ..LabelFilter::default()
            },
            ..TaskQuery::default()
        },
        "this run's issues carrying its second label",
        std::slice::from_ref(&first),
    )
    .await?;
    settled_tasks(
        LINEAR_INDEX,
        source,
        &TaskQuery {
            labels: LabelFilter {
                any_of: vec![run_label.clone()],
                none_of: vec![only_label.clone()],
                ..LabelFilter::default()
            },
            ..TaskQuery::default()
        },
        "this run's issues not carrying its second label",
        &[second.clone(), orphan.clone()],
    )
    .await?;

    // `filter_by_status`: two issues sit in an `unstarted` state and one in a `completed`
    // one, so the normalised categories separate them.
    settled_tasks(
        LINEAR_INDEX,
        source,
        &TaskQuery {
            statuses: vec![StatusCategory::Todo],
            ..scoped()
        },
        "this run's unstarted issues",
        &[first.clone(), second.clone()],
    )
    .await?;
    settled_tasks(
        LINEAR_INDEX,
        source,
        &TaskQuery {
            statuses: vec![StatusCategory::Done],
            ..scoped()
        },
        "this run's completed issue",
        std::slice::from_ref(&orphan),
    )
    .await?;

    // `search_title` and `search_content` are declared `Native`: the source narrows by each
    // and returns exactly what the case-insensitive substring rule keeps. The first issue's
    // title is in no issue's content, and every issue's content holds the lane's own sentence.
    for (terms, fields, expected) in [
        (first.clone(), TextFields::Title, vec![first.clone()]),
        (first.clone(), TextFields::Content, Vec::new()),
        (
            first.clone(),
            TextFields::TitleOrContent,
            vec![first.clone()],
        ),
        (
            "TEMPORARY CREDENTIALED WRITE".to_owned(),
            TextFields::Content,
            all_three.clone(),
        ),
    ] {
        settled_tasks(
            LINEAR_INDEX,
            source,
            &TaskQuery {
                text: Some(TextQuery { terms, fields }),
                ..scoped()
            },
            &format!("a {fields:?} search this source narrows itself"),
            &expected,
        )
        .await?;
    }

    // `task_dependencies` and `project_dependencies`, both directions each. One relation
    // reads the same from either end: the waiting item is `from` whichever of Linear's
    // `relations` and `inverseRelations` answered it.
    let task_edge = DependencyEdge {
        from: DependencyEndpoint::from_native(second_id.clone(), ItemKind::Task),
        to: DependencyEndpoint::from_native(first_id.clone(), ItemKind::Task),
        kind: DependencyKind::Blocks,
    };
    let project_edge = DependencyEdge {
        from: DependencyEndpoint::from_native(beta_id.clone(), ItemKind::Project),
        to: DependencyEndpoint::from_native(alpha_id.clone(), ItemKind::Project),
        kind: DependencyKind::Blocks,
    };
    for (near, direction, expected, level) in [
        (&second_id, Direction::DependsOn, &task_edge, "task"),
        (&first_id, Direction::DependedOnBy, &task_edge, "task"),
        (&beta_id, Direction::DependsOn, &project_edge, "project"),
        (&alpha_id, Direction::DependedOnBy, &project_edge, "project"),
    ] {
        let read = if level == "task" {
            source.task_dependencies(near, direction, &page(50)).await
        } else {
            source
                .project_dependencies(near, direction, &page(50))
                .await
        }
        .map_err(|error| format!("live {level} {direction:?} dependency read failed: {error}"))?;
        ensure!(
            read.items == vec![expected.clone()],
            "the {level} {direction:?} read of {} returned {:?}",
            near.0,
            read.items
        );
    }

    // Paging: a limit smaller than the result set walks to exhaustion, reaching every row
    // exactly once and in the order one whole page reports them. The walk and the page are
    // listings like the others and wait out the index together, so the order is compared over
    // a pair read once the index has caught up rather than over two reads that raced it.
    let walk = "a walk in pages of one over this run's own three issues";
    settled_walk(LINEAR_INDEX, source, &scoped(), 10, walk, &all_three).await?;

    // `max_page_size`: the source clamps a limit one above its declared ceiling to that
    // ceiling instead of passing it on, so the read succeeds rather than being refused
    // for a page size Linear's connection cannot serve.
    let ceiling = source.capabilities().max_page_size;
    let over_the_ceiling = scoped();
    let what = "a read at a limit one above the declared ceiling, which this source clamps \
                rather than refuses,";
    settled(LINEAR_INDEX, what, &all_three, || {
        task_titles(source, &over_the_ceiling, ceiling + 1, what)
    })
    .await?;
    // And that the ceiling itself is a page Linear really serves, rather than a number
    // this source guessed at. What Linear does with one row *more* is its own business and
    // is documented nowhere, so nothing here asserts on it.
    run.linear(
        ISSUE_PAGE_PROBE,
        json!({"first":ceiling}),
        "page size probe at the declared maximum",
    )
    .await?;

    // The values a copy carries: what was written reads back by its own id.
    let written = source
        .get_task(&first_id)
        .await
        .map_err(|error| format!("live task read-back failed: {error}"))?
        .ok_or_else(|| "the written issue was not readable by its own id".to_owned())?;
    ensure!(
        written.title == first && written.status.category == StatusCategory::Todo,
        "the live write did not round-trip its title and status: {written:?}"
    );
    let closed_back = source
        .get_task(&orphan_id)
        .await
        .map_err(|error| format!("live completed-issue read-back failed: {error}"))?
        .ok_or_else(|| "the completed issue was not readable by its own id".to_owned())?;
    ensure!(
        closed_back.status.category == StatusCategory::Done,
        "the live write filed under done read back as {:?}",
        closed_back.status.category
    );

    drive_document_paths(run, source, &alpha_id, None).await?;
    // Renamed to another of this run's own titles, so the artifact cleanup still knows it.
    every_field_change_moves_a_linear_tasks_token(
        source,
        (&second_id, &first_id, &orphan_id),
        (&title(11), &label(&only_label)),
    )
    .await
}

/// The common document-mode entry used by the real capability lane and HTTP replay.
async fn drive_document_paths(
    run: &LiveRun,
    source: &dyn TaskSource,
    alpha_id: &NativeId,
    journal: Option<&document_lifecycle::journal::Journal>,
) -> Result<(), String> {
    let title = |offset: u64| artifact_title(run.id, run.stamp_micros + offset);
    let document_parent = run.standing.parent.as_ref().map(|id| NativeId(id.clone()));
    let document_parent = document_parent.as_ref().unwrap_or(alpha_id);
    let filed_title = run
        .standing
        .titles
        .get("filed")
        .cloned()
        .unwrap_or_else(|| title(5));
    let loose_title = run
        .standing
        .titles
        .get("loose")
        .cloned()
        .unwrap_or_else(|| title(6));
    if let Some(journal) = journal {
        journal.journey("drive_documents");
    }
    drive_documents(run, source, document_parent, &filed_title, &loose_title).await?;
    let follow_up_title = run
        .standing
        .titles
        .get("follow-up")
        .cloned()
        .unwrap_or_else(|| title(9));
    if let Some(journal) = journal {
        journal.journey("drive_follow_ups");
    }
    drive_follow_ups(
        run,
        source,
        &title(7),
        &title(8),
        &follow_up_title,
        &title(10),
    )
    .await
}

/// A Linear task carries a `lin1` change token through every kind of change a copy has to see,
/// and every change to a member the token covers moves it — to a later one, or to one never
/// ordered beside the last — and what this lane learns along the way is printed as evidence.
///
/// `docs/plugin-protocol.md` §4.13d states what `lin1` covers: a task's fields always, its
/// forward edges only with the store's cache attached — which this source, built without one,
/// is not — and its comments never. So each change is made to one of this run's tasks in turn,
/// a second apart, and every read after it is held to carrying a token; a field change is held
/// to moving it, and a comment or a relation change, which the token does not vouch for here,
/// is only recorded. Whether `updated_at` and the token moved is printed beside each change.
async fn every_field_change_moves_a_linear_tasks_token(
    source: &dyn TaskSource,
    (task, first, orphan): (&NativeId, &NativeId, &NativeId),
    (renamed, extra_label): (&str, &Label),
) -> Result<(), String> {
    use onetaskgraph_plugin_api::{CommentBody, MetadataKey, NewComment, TaskUpdate};
    let read = || async {
        let held = source
            .get_task(task)
            .await
            .map_err(|error| format!("live read of the task failed: {error}"))?
            .ok_or_else(|| "the task was not there".to_owned())?;
        ensure!(
            held.version
                .as_deref()
                .is_some_and(|token| token.starts_with("lin1|")),
            "Linear gave the task {:?} rather than a `lin1` change token, which \
             docs/plugin-protocol.md §4.13d says every whole read carries",
            held.version
        );
        Ok::<Task, String>(held)
    };
    let pause = || tokio::time::sleep(std::time::Duration::from_millis(1_100));
    let mut evidence = Vec::new();
    let mut before = read().await?;
    let mut note = |kind: &str, before: &Task, after: &Task| {
        evidence.push(format!(
            "{kind}: updatedAt {} → {}, token {}",
            before
                .updated_at
                .map_or("none".to_owned(), |at| at.to_rfc3339()),
            after
                .updated_at
                .map_or("none".to_owned(), |at| at.to_rfc3339()),
            if before.version == after.version {
                "unmoved"
            } else {
                "moved"
            },
        ));
    };
    let body = |text: &str| {
        CommentBody::new(text).map_err(|error| format!("a live comment body: {error}"))
    };

    pause().await;
    let comment = source
        .add_comment(
            task,
            &NewComment {
                body: body("temporary credentialed comment; the live lane removes it")?,
                author: None,
            },
        )
        .await
        .map_err(|error| format!("live comment write failed: {error}"))?
        .ok_or_else(|| "the task to comment on was not there".to_owned())?;
    let after = read().await?;
    note("a comment added", &before, &after);
    before = after;

    pause().await;
    source
        .edit_comment(
            task,
            &comment.id,
            &body("temporary credentialed comment, edited")?,
        )
        .await
        .map_err(|error| format!("live comment edit failed: {error}"))?
        .ok_or_else(|| "the comment to edit was not there".to_owned())?;
    let after = read().await?;
    note("a comment edited", &before, &after);
    before = after;

    pause().await;
    source
        .delete_comment(task, &comment.id)
        .await
        .map_err(|error| format!("live comment deletion failed: {error}"))?
        .ok_or_else(|| "the comment to delete was not there".to_owned())?;
    let after = read().await?;
    note("a comment deleted", &before, &after);
    before = after;

    pause().await;
    source
        .set_task_content(task, "temporary credentialed write, its body edited")
        .await
        .map_err(|error| format!("live content write failed: {error}"))?
        .ok_or_else(|| "the task to edit was not there".to_owned())?;
    let after = token_moved(source, LINEAR_REPLICA, "a body edit", &before, &read).await?;
    note("a body edit", &before, &after);
    before = after;

    pause().await;
    source
        .update_task(
            task,
            &TaskUpdate {
                title: Some(renamed.to_owned()),
                ..TaskUpdate::default()
            },
        )
        .await
        .map_err(|error| format!("live title write failed: {error}"))?
        .ok_or_else(|| "the task to rename was not there".to_owned())?;
    let after = token_moved(source, LINEAR_REPLICA, "a title edit", &before, &read).await?;
    note("a title edit", &before, &after);
    before = after;

    pause().await;
    let mut labelled = before.clone();
    labelled.labels.push(extra_label.clone());
    let edges = source
        .task_dependencies(task, Direction::DependsOn, &page(50))
        .await
        .map_err(|error| format!("live dependency read failed: {error}"))?
        .items;
    write_labelled_task(
        LINEAR_INDEX,
        source,
        &ItemWrite {
            target: Some(task.clone()),
            item: labelled,
            depends_on: edges,
        },
    )
    .await
    .map_err(|error| format!("live label write failed: {error}"))?;
    let after = token_moved(source, LINEAR_REPLICA, "a label change", &before, &read).await?;
    note("a label change", &before, &after);
    before = after;

    pause().await;
    source
        .set_task_metadata(
            task,
            &MetadataKey::new("live.change_kind").map_err(|error| format!("a key: {error}"))?,
            &json!("metadata"),
        )
        .await
        .map_err(|error| format!("live metadata write failed: {error}"))?
        .ok_or_else(|| "the task to annotate was not there".to_owned())?;
    let after = token_moved(source, LINEAR_REPLICA, "a metadata change", &before, &read).await?;
    note("a metadata change", &before, &after);
    before = after;

    pause().await;
    source
        .set_task_priority(task, Priority::Low)
        .await
        .map_err(|error| format!("live priority write failed: {error}"))?
        .ok_or_else(|| "the task to prioritise was not there".to_owned())?;
    let after = token_moved(source, LINEAR_REPLICA, "a priority change", &before, &read).await?;
    note("a priority change", &before, &after);
    before = after;

    for (kind, on) in [
        ("a dependency added", vec![first, orphan]),
        ("a dependency removed", vec![first]),
    ] {
        pause().await;
        source
            .update_task(
                task,
                &TaskUpdate {
                    depends_on: Some(
                        on.into_iter()
                            .map(|far| blocks(far, ItemKind::Task))
                            .collect(),
                    ),
                    ..TaskUpdate::default()
                },
            )
            .await
            .map_err(|error| format!("live dependency write failed: {error}"))?
            .ok_or_else(|| "the task to make depend was not there".to_owned())?;
        let after = read().await?;
        note(kind, &before, &after);
        before = after;
    }

    pause().await;
    source
        .set_task_status(task, StatusCategory::Done)
        .await
        .map_err(|error| format!("live status write failed: {error}"))?
        .ok_or_else(|| "the task to finish was not there".to_owned())?;
    let after = token_moved(source, LINEAR_REPLICA, "a status change", &before, &read).await?;
    note("a status change", &before, &after);

    eprintln!(
        "Linear's Issue.updatedAt and lin1 token across every change a copy has to see:\n  {}",
        evidence.join("\n  ")
    );
    Ok(())
}

/// One issue's raw `description`, as Linear hands it back.
async fn raw_description(run: &LiveRun, id: &NativeId) -> Result<String, String> {
    run.linear(
        "query($id:String!){ issue(id:$id){ description } }",
        json!({"id":id.0}),
        "live raw issue read",
    )
    .await?
    .pointer("/issue/description")
    .and_then(Value::as_str)
    .map(str::to_owned)
    .ok_or_else(|| format!("issue {} carried no description", id.0))
}

/// One document's raw `content`, as Linear hands it back.
async fn raw_content(run: &LiveRun, id: &NativeId, expected: &str) -> Result<String, String> {
    settled_content(LINEAR_REPLICA, expected, || async {
        run.linear(
            "query($id:String!){ document(id:$id){ content } }",
            json!({"id":id.0}),
            "live raw document read",
        )
        .await?
        .pointer("/document/content")
        .and_then(Value::as_str)
        .map(str::to_owned)
        .ok_or_else(|| format!("document {} carried no content", id.0))
    })
    .await
}

/// The text the lane writes into an issue's description, a comment's body and a document's
/// content, to see what Linear does to an HTML comment in each: one on one line holding a
/// domain-like value and an array, one closing on a line of its own, and one on one line with
/// its JSON inside a code span.
const PROBE: &str = "P.\n\n<!-- probe {\"site\":\"example.com\",\"list\":[1]} -->\n\n<!-- probe\n{\"k\":\"v\"}\n-->\n\n<!-- probe `{\"site\":\"example.com\",\"list\":[1]}` -->";

/// What Linear hands [`PROBE`] back as from an issue's description and a document's content,
/// observed 2026-10-02 and recorded in the plugin's module documentation: inside the first
/// comment the domain-like value is autolinked and the array's brackets escaped, the second
/// comment's closing line is escaped, and the code span comes back as it was written.
const PROBE_STORED: &str = "P.\n\n<!-- probe {\"site\":\"[example.com](<http://example.com>)\",\"list\":\\[1\\]} -->\n\n<!-- probe\n{\"k\":\"v\"}\n\\-->\n\n<!-- probe `{\"site\":\"example.com\",\"list\":[1]}` -->";

/// One instance of each rewrite Linear was observed to make of Markdown on write but the lone
/// image, which `linear_assets`' live journey writes with real uploads: a
/// bullet the next lines run on from, a URL, two domain-like tokens, brackets, a tilde, an
/// underscore emphasis, an escaped quote, a backslash before a letter, a line opening `-->`, a
/// fenced block and a line after it, each set apart, the same text inside the fence and an
/// inline code span, where it is kept, a run of blank lines, and last a table, whose delimiter
/// row is one only outside a list item and which ends the content with no line break after it.
const MARKDOWN_PROBE: &str = "- bullet\n| a | b |\n| --- | --- |\nsee https://example.com/a.\nexample.com and \"caller.live\"\n[x] done ~5 _y_\nsay \\\"hi\\\" a \\d b\n-->\n```\n- [x] _y_ example.com ~\n```\nkept `- [x] _y_ example.com ~` span\n\n\n\n| a | b |\n| --- | --- |\n";

/// What Linear stores [`MARKDOWN_PROBE`] as, and what the live leg asserts Linear hands back: byte
/// for byte what real Linear handed back from an issue's description in CI run 39375395042, of
/// this probe as it was then — one blank line where it now holds a run of them, and no line
/// break after the table. The plugin predicts none of it; it reads what Linear stores off each
/// write's own answer.
const MARKDOWN_PROBE_STORED: &str = "* bullet\n  | a | b |\n  | --- | --- |\n  see [https://example.com/a](<https://example.com/a>).\n  [example.com](<http://example.com>) and \"[caller.live](<http://caller.live>)\"\n  \\[x\\] done \\~5 *y*\n  say \"hi\" a \\\\d b\n  \\-->\n\n```\n- [x] _y_ example.com ~\n```\n\nkept `- [x] _y_ example.com ~` span\n\n| a | b |\n| -- | -- |\n";

/// What the follow-up flow rests on, against Linear itself: what Linear does to an HTML comment
/// in an issue's description, a comment's body and a document's content, recorded in the
/// plugin's module documentation; the metadata slot, written as a code span, keeping values
/// Linear rewrites everywhere else; each of the follow-up searches narrowed by Linear and
/// confirmed in process — a decoy whose prose carries every phrase is kept out — and a narrow
/// metadata write that moves only the slot.
async fn drive_follow_ups(
    run: &LiveRun,
    source: &dyn TaskSource,
    matching: &str,
    decoy: &str,
    document_title: &str,
    probe_title: &str,
) -> Result<(), String> {
    let tag = format!("otg-live-{}", run.stamp_micros);
    let origin = format!("elsewhere:{tag}");
    let issue = |title: &str, content: String, metadata: Value, priority: Priority| Task {
        version: None,
        id: NativeId("live-source-item".into()),
        key: None,
        title: title.to_owned(),
        content: Some(content),
        status: Status {
            category: StatusCategory::Todo,
            name: run.open_state.clone(),
        },
        labels: Vec::new(),
        priority,
        project: None,
        url: None,
        location: None,
        created_at: None,
        updated_at: None,
        metadata: serde_json::from_value(metadata).unwrap_or_default(),
        repositories: Vec::new(),
        delivers: Vec::new(),
        delivered_by: Vec::new(),
        classification: Default::default(),
    };
    // `caller.live` is a key Linear autolinks anywhere but a code span, and `caller.site`
    // holds a URL-like value, an emphasis-shaped one and an array: each is something Linear
    // rewrites in an HTML comment, and the slot has to keep every one.
    let hostile = json!(["github.com/a/b", "_y_", "a --> b"]);
    let matching_metadata = json!({"caller.tag": tag, "caller.key": tag, "caller.live": tag,
        "caller.site": hostile, "onetaskgraph.origin": origin});
    let matching_id = source
        .write_task(&ItemWrite {
            target: None,
            item: issue(
                matching,
                "A follow-up the lane searches for.".to_owned(),
                matching_metadata.clone(),
                Priority::High,
            ),
            depends_on: Vec::new(),
        })
        .await
        .map_err(|error| format!("live write of {matching:?} failed: {error}"))?;
    let decoy_id = source
        .write_task(&ItemWrite {
            target: None,
            item: issue(
                decoy,
                format!(
                    "Quotes \"caller.key\":\"{tag}\" and \"onetaskgraph.origin\":\"{origin}\" \
                     in its prose, and {tag}-prose."
                ),
                // `caller.key` and `onetaskgraph.origin` are keys Linear leaves alone in
                // prose, so the phrases above make this a candidate Linear returns for both
                // narrowings, and only the confirmation over its slot keeps it out.
                json!({"caller.tag": tag, "caller.key": format!("{tag}-other")}),
                Priority::Low,
            ),
            depends_on: Vec::new(),
        })
        .await
        .map_err(|error| format!("live write of {decoy:?} failed: {error}"))?;
    let read_back = source
        .get_task(&matching_id)
        .await
        .map_err(|error| format!("live read of {matching:?} failed: {error}"))?
        .ok_or_else(|| format!("{matching:?} was not readable by its own id"))?;
    for key in ["caller.tag", "caller.key", "caller.live", "caller.site"] {
        ensure!(
            read_back.metadata.get(key) == matching_metadata.get(key),
            "the metadata slot did not keep {key}: wrote {}, read {:?}",
            matching_metadata[key],
            read_back.metadata.get(key)
        );
    }
    let held = raw_description(run, &matching_id).await?;
    ensure!(
        held.starts_with("A follow-up the lane searches for.\n\n<!-- onetaskgraph.metadata `")
            && held.ends_with("` -->"),
        "the slot did not come back in the one-line code-span spelling: {held:?}"
    );

    // The comment the activity search below finds the matching issue by.
    source
        .add_comment(
            &matching_id,
            &onetaskgraph_plugin_api::NewComment {
                body: onetaskgraph_plugin_api::CommentBody::new(
                    "A comment the activity search finds.".to_owned(),
                )
                .map_err(|error| error.to_string())?,
                author: None,
            },
        )
        .await
        .map_err(|error| format!("live comment add failed: {error}"))?
        .ok_or_else(|| "the matching issue had no comments".to_owned())?;

    // An HTML comment in an issue's description, a comment's body and a document's content.
    let probe_id = source
        .write_task(&ItemWrite {
            target: None,
            item: issue(probe_title, "probe".to_owned(), json!({}), Priority::None),
            depends_on: Vec::new(),
        })
        .await
        .map_err(|error| format!("live write of {probe_title:?} failed: {error}"))?;
    run.linear("mutation($id:String!,$input:IssueUpdateInput!){ issueUpdate(id:$id,input:$input){success} }",
        json!({"id":probe_id.0,"input":{"description":PROBE}}),
        "live description probe",
    )
    .await?;
    let stored = raw_description(run, &probe_id).await?;
    ensure!(
        stored == PROBE_STORED,
        "an issue description's HTML comments came back as {stored:?}, not as recorded"
    );
    let added = source
        .add_comment(
            &probe_id,
            &onetaskgraph_plugin_api::NewComment {
                body: onetaskgraph_plugin_api::CommentBody::new(PROBE.to_owned())
                    .map_err(|error| error.to_string())?,
                author: None,
            },
        )
        .await
        .map_err(|error| format!("live comment add failed: {error}"))?
        .ok_or_else(|| "the probe issue had no comments".to_owned())?;
    ensure!(
        added.body.as_str() == PROBE,
        "a comment body's HTML comments did not survive byte for byte: {:?}",
        added.body.as_str()
    );
    let document_id = source
        .write_document(&ItemWrite {
            target: run.standing.ids.get("follow-up").cloned().map(NativeId),
            item: Document {
                version: None,
                id: NativeId("live-source-item".into()),
                title: document_title.to_owned(),
                content: Some("A probed document.".to_owned()),
                project: None,
                labels: Vec::new(),
                url: None,
                location: None,
                created_at: None,
                updated_at: None,
                metadata: serde_json::from_value(json!({"caller.live": tag})).unwrap_or_default(),
                repositories: Vec::new(),
                classification: Default::default(),
            },
            depends_on: Vec::new(),
        })
        .await
        .map_err(|error| format!("live document write failed: {error}"))?;
    let document = source
        .get_document(&document_id)
        .await
        .map_err(|error| format!("live document read failed: {error}"))?
        .ok_or_else(|| "the probed document was not readable by its own id".to_owned())?;
    ensure!(
        document.metadata.get("caller.live") == Some(&json!(tag))
            && document.content.as_deref() == Some("A probed document."),
        "a document's slot did not keep its metadata: {document:?}"
    );
    let updated = run.linear(
        "mutation($id:String!,$input:DocumentUpdateInput!){ documentUpdate(id:$id,input:$input){success document{content}} }",
        json!({"id":document_id.0,"input":{"content":PROBE}}),
        "live content probe",
    )
    .await?;
    ensure!(
        updated
            .pointer("/documentUpdate/success")
            .and_then(Value::as_bool)
            == Some(true)
            && updated
                .pointer("/documentUpdate/document/content")
                .and_then(Value::as_str)
                == Some(PROBE_STORED),
        "the document update did not acknowledge the exact stored content: {updated:?}"
    );
    let content = raw_content(run, &document_id, PROBE_STORED).await?;
    ensure!(
        content == PROBE_STORED,
        "a document's HTML comments came back as {content:?}, not as recorded"
    );

    // What Linear does to Markdown on write, rule by rule, in both long-form fields.
    run.linear("mutation($id:String!,$input:IssueUpdateInput!){ issueUpdate(id:$id,input:$input){success} }",
        json!({"id":probe_id.0,"input":{"description":MARKDOWN_PROBE}}),
        "live Markdown description probe",
    )
    .await?;
    let stored = raw_description(run, &probe_id).await?;
    ensure!(
        stored == MARKDOWN_PROBE_STORED,
        "an issue description's Markdown came back as {stored:?}, not as the ruling declares"
    );
    let read = source
        .get_task(&probe_id)
        .await
        .map_err(|error| format!("the Markdown probe's issue could not be read: {error}"))?
        .and_then(|task| task.content);
    ensure!(
        read.as_deref() == Some(MARKDOWN_PROBE_STORED),
        "a read of the Markdown probe's issue handed back {read:?}, not its stored form"
    );
    let updated = run.linear(
        "mutation($id:String!,$input:DocumentUpdateInput!){ documentUpdate(id:$id,input:$input){success document{content}} }",
        json!({"id":document_id.0,"input":{"content":MARKDOWN_PROBE}}),
        "live Markdown content probe",
    )
    .await?;
    ensure!(
        updated
            .pointer("/documentUpdate/success")
            .and_then(Value::as_bool)
            == Some(true)
            && updated
                .pointer("/documentUpdate/document/content")
                .and_then(Value::as_str)
                == Some(MARKDOWN_PROBE_STORED),
        "the document update did not acknowledge the exact stored content: {updated:?}"
    );
    let content = raw_content(run, &document_id, MARKDOWN_PROBE_STORED).await?;
    ensure!(
        content == MARKDOWN_PROBE_STORED,
        "a document's Markdown came back as {content:?}, not as the ruling declares"
    );
    let read = Some(
        settled_content(LINEAR_REPLICA, MARKDOWN_PROBE_STORED, || async {
            source
                .get_document(&document_id)
                .await
                .map_err(|error| {
                    format!("the Markdown probe's document could not be read: {error}")
                })?
                .and_then(|document| document.content)
                .ok_or_else(|| "the Markdown probe's document carried no content".to_owned())
        })
        .await?,
    );
    ensure!(
        read.as_deref() == Some(MARKDOWN_PROBE_STORED),
        "a read of the Markdown probe's document handed back {read:?}, not its stored form"
    );
    // And with this source's metadata slot after it: the table keeps its line break, and the
    // slot follows one blank line later, so a read hands the content back as it was written.
    let tabled = "Owners:\n\n| a | b |\n| -- | -- |\n".to_owned();
    source
        .write_document(&ItemWrite {
            target: Some(document_id.clone()),
            item: Document {
                version: None,
                id: document_id.clone(),
                title: document_title.to_owned(),
                content: Some(tabled.clone()),
                project: None,
                labels: Vec::new(),
                url: None,
                location: None,
                created_at: None,
                updated_at: None,
                metadata: serde_json::from_value(json!({"caller.live": tag})).unwrap_or_default(),
                repositories: Vec::new(),
                classification: Default::default(),
            },
            depends_on: Vec::new(),
        })
        .await
        .map_err(|error| format!("live table document write failed: {error}"))?;
    let read = source
        .get_document(&document_id)
        .await
        .map_err(|error| format!("the table document could not be read: {error}"))?;
    ensure!(
        read.as_ref()
            .and_then(|document| document.content.as_deref())
            == Some(tabled.as_str())
            && read
                .as_ref()
                .and_then(|document| document.metadata.get("caller.live"))
                == Some(&json!(tag)),
        "a document ending in a table, written with a slot, read back as {read:?}, not as {tabled:?}"
    );

    // Each follow-up search, narrowed by Linear and confirmed here: the decoy's prose carries
    // the metadata and origin phrases, and its slot holds another value.
    let both = vec![decoy.to_owned(), matching.to_owned()];
    let only = vec![matching.to_owned()];
    let tag_match = MetadataMatch::new("caller.tag", Vec::new(), tag.clone())?;
    let base = TaskQuery {
        metadata: vec![tag_match.clone()],
        ..TaskQuery::default()
    };
    settled_tasks(LINEAR_INDEX, source, &base, "the two tagged issues", &both).await?;
    for (query, what, expected) in [
        (
            TaskQuery {
                metadata: vec![
                    tag_match.clone(),
                    MetadataMatch::new("caller.key", Vec::new(), tag.clone())?,
                ],
                ..TaskQuery::default()
            },
            "a metadata match the decoy carries only in prose",
            only.clone(),
        ),
        (
            TaskQuery {
                origin: Some(origin.clone()),
                ..base.clone()
            },
            "an origin the decoy carries only in prose",
            only.clone(),
        ),
        (
            TaskQuery {
                priorities: vec![Priority::High],
                ..base.clone()
            },
            "a priority",
            only.clone(),
        ),
        (
            TaskQuery {
                commented_since: chrono::Utc::now()
                    .checked_sub_signed(chrono::Duration::minutes(10)),
                ..base.clone()
            },
            "comment activity in the last ten minutes",
            only.clone(),
        ),
        (
            TaskQuery {
                commented_since: chrono::Utc::now().checked_add_signed(chrono::Duration::days(1)),
                ..base.clone()
            },
            "comment activity tomorrow",
            Vec::new(),
        ),
        (
            TaskQuery {
                text: Some(TextQuery {
                    terms: format!("{tag}-PROSE"),
                    fields: TextFields::Content,
                }),
                ..base.clone()
            },
            "a content search, any case",
            vec![decoy.to_owned()],
        ),
    ] {
        settled_tasks(LINEAR_INDEX, source, &query, what, &expected).await?;
    }

    // Linear's own comparators, as the module documentation records them: `contains` reads
    // the slot and is case-sensitive, `containsIgnoreCase` is not.
    let narrowed = |filter: Value| async move {
        let data = run
            .linear(
                "query($filter:IssueFilter){ issues(first:10,filter:$filter){ nodes{ title } } }",
                json!({ "filter": filter }),
                "live comparator probe",
            )
            .await?;
        let mut titles = data
            .pointer("/issues/nodes")
            .and_then(Value::as_array)
            .ok_or_else(|| "the comparator probe answered no issues".to_owned())?
            .iter()
            .filter_map(|node| node["title"].as_str().map(str::to_owned))
            .collect::<Vec<_>>();
        titles.sort();
        Ok::<_, String>(titles)
    };
    let phrase = format!("\"caller.tag\":\"{tag}\"");
    for (filter, what, expected) in [
        (
            json!({"description":{"contains":phrase}}),
            "`contains` of a phrase both slots hold",
            both.clone(),
        ),
        (
            json!({"description":{"contains":phrase.to_uppercase()}}),
            "`contains` of the same phrase upper-cased",
            Vec::new(),
        ),
        (
            json!({"description":{"containsIgnoreCase":phrase.to_uppercase()}}),
            "`containsIgnoreCase` of it upper-cased",
            both.clone(),
        ),
    ] {
        settled(LINEAR_INDEX, what, &expected, || narrowed(filter.clone())).await?;
    }

    // A narrow metadata write moves only the slot: every byte above it is as it was.
    let before = raw_description(run, &decoy_id).await?;
    let key = onetaskgraph_plugin_api::MetadataKey::new("caller.review")?;
    source
        .set_task_metadata(&decoy_id, &key, &json!({"approved": true}))
        .await
        .map_err(|error| format!("live metadata write failed: {error}"))?
        .ok_or_else(|| "the decoy was not held".to_owned())?;
    let after = raw_description(run, &decoy_id).await?;
    let above = |field: &str| {
        field
            .rfind("<!-- onetaskgraph.metadata")
            .map(|start| field[..start].to_owned())
    };
    ensure!(
        above(&before).is_some() && above(&before) == above(&after),
        "a narrow metadata write moved bytes above the slot:\n{before:?}\n{after:?}"
    );
    ensure!(
        after.contains("\"caller.review\":{\"approved\":true}"),
        "the narrow metadata write did not land in the slot: {after:?}"
    );
    Ok(())
}

/// `documents`, against Linear's own first-class document type.
///
/// Two of them, filed the way the issues above are — one under a project, one under none —
/// because that difference is what tells a project predicate this source applied from one
/// it ignored, and because a document under no project is the case that needs the
/// configured team to give it a home.
async fn drive_documents(
    run: &LiveRun,
    source: &dyn TaskSource,
    under: &NativeId,
    filed: &str,
    loose: &str,
) -> Result<(), String> {
    let document = |title: &str, project: Option<&NativeId>| Document {
        version: None,
        id: NativeId("live-source-item".into()),
        title: title.to_owned(),
        content: Some("temporary credentialed write; the live lane removes this".into()),
        project: project.cloned(),
        // Linear's own document type has no labels; a write carrying one is refused by
        // name, which is asserted below rather than assumed.
        labels: vec![],
        url: None,
        location: None,
        created_at: None,
        updated_at: None,
        metadata: [
            ("caller.count".to_owned(), json!(3)),
            ("caller.run".to_owned(), json!(run.stamp_micros)),
        ]
        .into_iter()
        .collect(),
        repositories: vec![],
        classification: Default::default(),
    };
    let write = |item: Document| ItemWrite {
        target: if item.title == filed {
            run.standing.ids.get("filed")
        } else {
            run.standing.ids.get("loose")
        }
        .cloned()
        .map(NativeId),
        item,
        depends_on: vec![],
    };

    let filed_id = source
        .write_document(&write(document(filed, Some(under))))
        .await
        .map_err(|error| format!("live document write of {filed:?} failed: {error}"))?;
    let loose_id = source
        .write_document(&write(document(loose, None)))
        .await
        .map_err(|error| format!("live document write of {loose:?} failed: {error}"))?;

    // Read back by its own id: the caller's key keeps its JSON type through the slot, the
    // visible body is the text without the slot, and where it is is a link.
    let read = source
        .get_document(&filed_id)
        .await
        .map_err(|error| format!("live document read-back failed: {error}"))?
        .ok_or_else(|| "the written document was not readable by its own id".to_owned())?;
    ensure!(
        read.title == filed,
        "the live document write did not round-trip its title: {read:?}"
    );
    ensure!(
        read.content.as_deref() == Some("temporary credentialed write; the live lane removes this"),
        "the visible body a read reports is the text a person wrote: {:?}",
        read.content
    );
    ensure!(
        read.metadata.get("caller.count") == Some(&json!(3)),
        "a caller's key did not round-trip with its JSON type: {:?}",
        read.metadata
    );
    ensure!(
        read.metadata.get("caller.run") == Some(&json!(run.stamp_micros)),
        "the retained document did not reset caller.run to this invocation: {:?}",
        read.metadata.get("caller.run")
    );
    ensure!(
        read.labels.is_empty(),
        "Linear's own document type has no labels, so a read reports none: {:?}",
        read.labels
    );
    ensure!(
        matches!(&read.location, Some(Location::Url(url)) if url.starts_with("https://")),
        "a document says where it is, as a link: {:?}",
        read.location
    );
    ensure!(
        read.project.as_ref() == Some(under),
        "the document filed under this run's project read back filed under {:?}",
        read.project
    );

    // A label is a field this source cannot carry, and it is refused by name rather than
    // dropped — the one answer a copy must never turn into a silent success.
    let refusal = source
        .write_document(&write(Document {
            labels: vec![label(&artifact_label(run.id, run.stamp_micros))],
            ..document(filed, Some(under))
        }))
        .await;
    ensure!(
        refusal
            .as_ref()
            .err()
            .is_some_and(|error| error.to_string().contains("labels")),
        "a document write carrying a label must be refused by name, and was {refusal:?}"
    );

    // Both this run's documents come back, the project predicate keeps one and the orphan
    // predicate the other, and a label demanded of a document keeps neither. Each listing
    // waits out the index as the issue listings do: a document's project filter has come back
    // without the document filed there while the unfiltered listing already held it.
    settled_documents(
        LINEAR_INDEX,
        LINEAR_DOCUMENT_LISTING,
        source,
        &DocumentQuery::default(),
        &[filed_id.clone(), loose_id.clone()],
        "the two documents this run created",
        &[
            (filed_id.clone(), filed.to_owned()),
            (loose_id.clone(), loose.to_owned()),
        ],
    )
    .await?;
    settled_documents(
        LINEAR_INDEX,
        LINEAR_DOCUMENT_LISTING,
        source,
        &DocumentQuery {
            project: ProjectFilter::Is(under.clone()),
            ..DocumentQuery::default()
        },
        &[filed_id.clone(), loose_id.clone()],
        "a document listing narrowed to this run's project",
        &[(filed_id.clone(), filed.to_owned())],
    )
    .await?;
    settled_documents(
        LINEAR_INDEX,
        LINEAR_DOCUMENT_LISTING,
        source,
        &DocumentQuery {
            project: ProjectFilter::Orphans,
            ..DocumentQuery::default()
        },
        &[filed_id.clone(), loose_id.clone()],
        "a document listing narrowed to the orphans",
        &[(loose_id.clone(), loose.to_owned())],
    )
    .await?;
    settled_documents(
        LINEAR_INDEX,
        LINEAR_DOCUMENT_LISTING,
        source,
        &DocumentQuery {
            labels: LabelFilter {
                any_of: vec![artifact_label(run.id, run.stamp_micros)],
                ..LabelFilter::default()
            },
            ..DocumentQuery::default()
        },
        &[filed_id.clone(), loose_id.clone()],
        "a document listing demanding a label, which no Linear document carries,",
        &[],
    )
    .await?;

    // And removed again, which is what lets a copy that could not finish take one back.
    // The sweep would clear them anyway; driving the verb is what proves it works.
    for (id, title) in [(&filed_id, filed), (&loose_id, loose)]
        .into_iter()
        .filter(|_| run.document_mode == Mode::Fresh)
    {
        source
            .delete_document(id)
            .await
            .map_err(|error| format!("live document removal failed: {error}"))?;
        settled_document_absent(LINEAR_INDEX, source, id, title).await?;
    }
    Ok(())
}

#[tokio::test]
async fn real_linear_applies_every_declared_capability_and_leaves_no_residue() {
    // llmlint: ignore-block[live_tier_compiles_and_requires_credential,tests_assert_real_behavior] An absent credential or an unnamed scratch team skips only where none was expected — a contributor with no keys, and a fork pull request, which the host gives no secrets. `ONETASKGRAPH_LIVE_REQUIRED=1`, which .github/workflows/ci.yml sets on the one lane the credentials reach, turns each skip below into the failure this rule asks for.
    let live_required = required(
        env::var(onetaskgraph_live::REQUIRED_VARIABLE)
            .ok()
            .as_deref(),
    )
    .unwrap_or_else(|error| panic!("the Linear live lane cannot run: {error}"));
    let skip = |reason: &str| -> Option<String> {
        match missing(live_required, SESSION_NAME, reason) {
            Ok(reason) => {
                eprintln!("skipped live Linear journey: {reason}");
                None
            }
            Err(error) => panic!("the Linear live lane cannot run: {error}"),
        }
    };
    // `Credential::new` is what decides a key is usable, rather than a second reading of
    // "empty" here: the session this lane opens takes one of those and nothing else, and a
    // host expands a secret it does not have to the empty string rather than omitting it.
    let Some(key) = env::var("LINEAR_API_KEY").ok().and_then(Credential::new) else {
        skip("LINEAR_API_KEY is not set");
        return;
    };
    // llmlint: ignore[contracts_have_one_source_or_a_drift_gate] .github/workflows/ci.yml spells this name too, and the drift gate is this lane's own refusal: that workflow sets ONETASKGRAPH_LIVE_REQUIRED=1 on the lane it hands the credential to, so a name spelled differently on either side fails the required check naming the variable rather than skipping green.
    let Some(team) = env::var("LINEAR_WRITE_TEAM")
        .ok()
        .filter(|value| !value.trim().is_empty())
    else {
        skip(
            "LINEAR_WRITE_TEAM is not set, and this lane writes only to the scratch team that \
             name gives rather than discovering one; no mutation was sent. Set it to that \
             team's key — in CI it is the LINEAR_WRITE_TEAM repository variable, and locally \
             it is an environment variable",
        );
        return;
    };
    // llmlint: ignore-end[live_tier_compiles_and_requires_credential,tests_assert_real_behavior]
    // The one gate: nothing below may reach Linear until the session is open, because the
    // key below is the one this returns rather than the one the environment held. A session
    // that is refused did not run and did not pass, and says so.
    //
    // `OneAtATime`: this lane still asks for a seat. Not because its cleanup needs one —
    // every artifact it writes carries this run's process id, its own cleanup removes only
    // those, and what it recovers of an interrupted run's is decided by that artifact's own
    // stamp — but because a seat is the one precondition that can decline this lane without
    // a credential and without reaching Linear, and `scripts/check-live-decline.sh` drives
    // that decline through to a red check. What a seat does not cover, and never did, is two
    // hosted runners: a file on one machine excludes nothing on another.
    let session = Session::open(SESSION_NAME, key, Exclusivity::OneAtATime)
        .unwrap_or_else(|declined| declined.refuse());
    let key = session.credential().expose().to_owned();
    let document_mode = Mode::read().unwrap_or_else(|e| panic!("{e}"));
    let owner = Run::current();
    let stamp = onetaskgraph_live::artifact::Stamp::new(owner, now_micros()).to_string();
    let team_key = team.to_ascii_uppercase();
    let ci = env::var("GITHUB_ACTIONS").as_deref() == Ok("true");
    let scope = if ci {
        Scope::ci(&team_key).unwrap()
    } else {
        Scope::local(&team_key, &stamp).unwrap()
    };
    let effective_mode = document_mode;
    if !ci && document_mode == Mode::Initialize {
        eprintln!(
            "non-CI creation pass: initialize invocation-owned plugin document slots, exercise reuse assertions, and retire the set"
        );
    }
    let journal = document_lifecycle::journal::Journal::new("plugin", effective_mode.name())
        .durable(
            std::env::current_exe()
                .unwrap()
                .parent()
                .unwrap()
                .parent()
                .unwrap()
                .join("telemetry/onetaskgraph-linear/live")
                .join(&stamp),
        )
        .unwrap();
    let endpoint = document_lifecycle::observer::start(
        "https://api.linear.app/graphql",
        &key,
        journal.clone(),
    );
    // The names the fixture files its issues and projects under are what this source's
    // `status_mapping` gives `todo` and `done`: Linear has no built-in names, so a source
    // without a mapping refuses every status write and reads every item as `unknown`.
    let (open_state, done_state) = fixture_states(&key, &team)
        .await
        .unwrap_or_else(|error| panic!("the Linear live lane cannot file its fixture: {error}"));
    let project_status = fixture_project_status(&key)
        .await
        .unwrap_or_else(|error| panic!("the Linear live lane cannot file its projects: {error}"));
    let source = onetaskgraph_linear::Plugin
        .build(
            &SourceName::new("live").unwrap(),
            &json!({"endpoint":endpoint,"team":team,"status_mapping":{
                "todo":{"task":open_state,"project":project_status},
                "done":{"task":done_state},
            }}),
            &Environment,
        )
        .unwrap_or_else(|error| panic!("the Linear live lane cannot use this team: {error}"));
    assert!(source.health().await.unwrap().reachable);
    // Every field of the contract's `Capabilities`, spelled out: the struct has no
    // `Default`, so a field added to the contract fails to compile here rather than going
    // unasserted, and the journey below drives each of these against Linear itself.
    assert_eq!(
        source.capabilities(),
        Capabilities {
            projects: Support::Native,
            documents: Support::Native,
            comments: Support::Native,
            assets: Support::Native,
            priority: Support::Native,
            filter_by_priority: Support::Native,
            filter_by_comment_activity: Support::Native,
            filter_by_metadata: Support::Native,
            filter_by_origin: Support::Native,
            reconcile_status: Support::Unsupported,
            complete_by_issue: Support::Unsupported,
            orphan_tasks: Support::Native,
            filter_by_label: Support::Native,
            filter_by_status: Support::Native,
            search_title: Support::Native,
            search_content: Support::Native,
            task_dependencies: DependencySupport::BothDirections,
            project_dependencies: DependencySupport::BothDirections,
            max_page_size: onetaskgraph_linear::MAX_PAGE_SIZE,
        }
    );

    let team_id = linear(&key, TEAM_STATES, json!({"key":team}), "live team lookup")
        .await
        .and_then(|data| {
            data.pointer("/teams/nodes/0/id")
                .and_then(Value::as_str)
                .map(str::to_owned)
                .ok_or_else(|| {
                    format!("LINEAR_WRITE_TEAM={team} names no team this credential can see")
                })
        })
        .unwrap_or_else(|error| {
            panic!("the Linear live lane cannot reach its scratch team: {error}")
        });
    // From the first create on, one guard retires what this invocation created: preparation,
    // the setup after it and the journey all run inside `guard_plugin_invocation`.
    let created = &document_lifecycle::Created::default();
    let lane_endpoint = endpoint.clone();
    let lane_key = key.clone();
    guard_plugin_invocation(
        &lane_endpoint,
        &lane_key,
        &team_key,
        &team_id.clone(),
        scope,
        effective_mode,
        created,
        |standing| async move {
            if ci && document_mode == Mode::Initialize {
                journal.finish().unwrap();
                return;
            }
            journal.journey("capability-and-follow-up");
            let run = LiveRun {
                endpoint,
                key: key.clone(),
                id: Run::current(),
                stamp_micros: now_micros(),
                open_state,
                done_state,
                project_status,
                document_mode,
                standing,
            };
            let id = run.id;
            // `ensure!` keeps the journey's own checks to `Err`, but anything else that panics
            // in it must still reach the cleanup below; the panic is resumed once cleanup ran.
            let panicked = std::sync::Mutex::new(None);
            let result = run_then_cleanup(
                || async {
                    match document_lifecycle::unwinding(drive_every_declared_capability(
                        &run,
                        source.as_ref(),
                        &team_id,
                    ))
                    .await
                    {
                        Ok(outcome) => outcome,
                        Err(panic) => {
                            *panicked.lock().unwrap() = Some(panic);
                            Err("the Linear live journey panicked".into())
                        }
                    }
                },
                || async {
                    // The invocation-owned slots by their exact ids first, then this run's
                    // own: everything it wrote goes whether the journey passed or failed.
                    // Then what an interrupted EARLIER run left, which is a different
                    // decision on different evidence — and which is deliberately here, at
                    // the end, rather than at the start where it used to be. A sweep before
                    // the journey deleted the in-flight issues of any session running beside
                    // this one; a sweep after it recovers exactly the same orphans and can
                    // reach nothing a live run owns.
                    let slots =
                        document_lifecycle::retire(&run.endpoint, &key, scope, created).await;
                    let mine =
                        remove_artifacts(&key, &|prefix, name| is_this_runs(id, prefix, name))
                            .await
                            .and(slots.map(drop));
                    let orphans = sweep_orphans(&key, &Sweep::of(id, now_micros())).await;
                    match (mine, orphans) {
                        (Ok(()), Ok(())) => Ok(()),
                        (Err(mine), Ok(())) => Err(mine),
                        (Ok(()), Err(orphans)) => Err(format!(
                            "residue left by an earlier interrupted run could not be \
                             cleared: {orphans}"
                        )),
                        (Err(mine), Err(orphans)) => Err(format!(
                            "{mine}; additionally, residue left by an earlier interrupted \
                             run could not be cleared: {orphans}"
                        )),
                    }
                },
            )
            .await;
            journal.finish().unwrap();
            if let Some(panic) = panicked.into_inner().unwrap() {
                if let Err(error) = result {
                    eprintln!("{error}");
                }
                std::panic::resume_unwind(panic);
            }
            result.unwrap_or_else(|error| panic!("Linear live capability journey failed: {error}"));
        },
    )
    .await;
}

/// The plugin lane's one invocation cleanup guard: it prepares the standing set and runs
/// `invocation` — the setup after preparation and the journey — over it, so that a panic at
/// any point from the first slot create on, whether inside preparation, straight after it or
/// anywhere before the journey's own cleanup ran, retires every slot `created` records before
/// the panic leaves the lane. A CI set is standing and is never retired here, and once the
/// journey's cleanup has retired the slots the record is empty, so nothing is deleted twice.
#[allow(
    clippy::too_many_arguments,
    reason = "prepare_owned's lane identities plus the invocation; the offline journey passes \
              each one separately to drive this guard as the live lane does"
)]
async fn guard_plugin_invocation<F, Fut>(
    endpoint: &str,
    key: &str,
    team_key: &str,
    team_id: &str,
    scope: Scope<'_>,
    mode: Mode,
    created: &document_lifecycle::Created,
    invocation: F,
) where
    F: FnOnce(Standing) -> Fut,
    Fut: std::future::Future<Output = ()>,
{
    let guarded = document_lifecycle::unwinding(async {
        let standing = document_lifecycle::prepare_owned(
            endpoint,
            key,
            team_key,
            team_id,
            scope,
            mode,
            &[Slot::Filed, Slot::Loose, Slot::FollowUp],
            created,
        )
        .await
        .unwrap_or_else(|e| panic!("{e}"));
        invocation(standing).await;
    })
    .await;
    if let Err(panic) = guarded {
        if let Err(error) = document_lifecycle::retire(endpoint, key, scope, created).await {
            eprintln!("{error}");
        }
        std::panic::resume_unwind(panic);
    }
}

#[path = "document_lifecycle/replay.rs"]
mod document_replay;

fn replay() -> document_replay::Replay {
    document_replay::Replay::start(
        document_lifecycle::journal::Journal::new("plugin", "initialize"),
        [
            (PROBE.to_owned(), PROBE_STORED.to_owned()),
            (MARKDOWN_PROBE.to_owned(), MARKDOWN_PROBE_STORED.to_owned()),
        ]
        .into_iter()
        .collect(),
    )
}
async fn replay_prepare(
    replay: &document_replay::Replay,
    scope: Scope<'_>,
    mode: Mode,
) -> Result<document_lifecycle::Standing, String> {
    document_lifecycle::prepare(
        &replay.endpoint,
        "synthetic",
        "ENG",
        "team",
        scope,
        mode,
        &[Slot::Filed, Slot::Loose, Slot::FollowUp],
    )
    .await
}
async fn replay_drive(
    replay: &document_replay::Replay,
    standing: document_lifecycle::Standing,
    mode: Mode,
    stamp: u64,
) -> Result<(), String> {
    replay_drive_at(&replay.endpoint, &replay.journal, standing, mode, stamp).await
}
async fn replay_drive_at(
    endpoint: &str,
    journal: &document_lifecycle::journal::Journal,
    standing: document_lifecycle::Standing,
    mode: Mode,
    stamp: u64,
) -> Result<(), String> {
    let source = onetaskgraph_linear::Plugin.build(&SourceName::new("live").unwrap(),
        &json!({"endpoint":endpoint,"team":"ENG","status_mapping":{"todo":{"task":"Todo","project":"Planned"},"done":{"task":"Done"}}}),&ReplaySecrets).unwrap();
    let parent = if let Some(parent) = &standing.parent {
        parent.clone()
    } else {
        let data = document_lifecycle::send(endpoint, "synthetic",
            "mutation($input:ProjectCreateInput!){projectCreate(input:$input){success project{id}}}",
            json!({"input":{"name":artifact_title(Run::current(), stamp),"teamIds":["team"]}})).await?;
        data["projectCreate"]["project"]["id"]
            .as_str()
            .ok_or("fresh parent create omitted id")?
            .to_owned()
    };
    let run = LiveRun {
        endpoint: endpoint.to_owned(),
        key: "synthetic".into(),
        id: Run::current(),
        stamp_micros: stamp,
        open_state: "Todo".into(),
        done_state: "Done".into(),
        project_status: "Planned".into(),
        document_mode: mode,
        standing,
    };
    drive_document_paths(&run, source.as_ref(), &NativeId(parent), Some(journal)).await
}

/// One ordinary CI pass through the plugin lane's own invocation guard, recording the
/// standing set it ran over.
async fn replay_ordinary_ci_pass(
    replay: &document_replay::Replay,
    stamp: u64,
    standing_ids: &std::sync::Mutex<Option<BTreeMap<&'static str, String>>>,
) {
    guard_plugin_invocation(
        &replay.endpoint,
        "synthetic",
        "ENG",
        "team",
        Scope::ci("ENG").unwrap(),
        Mode::Ordinary,
        &document_lifecycle::Created::default(),
        |standing| async move {
            *standing_ids.lock().unwrap() = Some(standing.ids.clone());
            replay_drive(replay, standing, Mode::Ordinary, stamp)
                .await
                .unwrap();
        },
    )
    .await;
}

async fn replay_cleanup_documents(replay: &document_replay::Replay) -> usize {
    let query = "query($filter:DocumentFilter!){documents(first:100,filter:$filter){nodes{id title} pageInfo{hasNextPage endCursor}}}";
    let read = || {
        document_lifecycle::send(
            &replay.endpoint,
            "synthetic",
            query,
            json!({"filter":{"title":{"containsIgnoreCase":onetaskgraph_linear::LIVE_ARTIFACT_TITLE_PREFIX}}}),
        )
    };
    let listing = read().await.unwrap();
    let owned = |row: &Value| {
        row["title"].as_str().is_some_and(|title| {
            is_this_runs(
                Run::current(),
                onetaskgraph_linear::LIVE_ARTIFACT_TITLE_PREFIX,
                title,
            )
        })
    };
    for document in listing["documents"]["nodes"]
        .as_array()
        .unwrap()
        .iter()
        .filter(|row| owned(row))
    {
        document_lifecycle::send(
            &replay.endpoint,
            "synthetic",
            onetaskgraph_linear::graphql::DOCUMENT_DELETE,
            json!({"id":document["id"]}),
        )
        .await
        .unwrap();
    }
    let after = read().await.unwrap();
    after["documents"]["nodes"]
        .as_array()
        .unwrap()
        .iter()
        .filter(|row| owned(row))
        .count()
}

/// Both modes run the same capability and follow-up functions as the credentialed lane.
#[tokio::test]
async fn document_modes_replay_the_live_plugin_paths_over_http() {
    let replay = replay();
    let scope = Scope::ci("ENG").unwrap();
    // A default non-CI invocation refuses before any create and names the explicit mode,
    // which initializes its own set and finds it again on recovery.
    let local = Scope::local("ENG", "1-2-900").unwrap();
    assert!(
        replay_prepare(&replay, local, Mode::Ordinary)
            .await
            .err()
            .unwrap()
            .contains("initialize")
    );
    assert_eq!(replay.journal.count(), 0);
    let created = document_lifecycle::Created::default();
    let standing = document_lifecycle::prepare_owned(
        &replay.endpoint,
        "synthetic",
        "ENG",
        "team",
        local,
        Mode::Initialize,
        &[Slot::Filed, Slot::Loose, Slot::FollowUp],
        &created,
    )
    .await
    .unwrap();
    assert_eq!(
        replay.journal.count(),
        3,
        "one owned document per missing plugin slot"
    );
    let again = replay_prepare(&replay, local, Mode::Initialize)
        .await
        .unwrap();
    assert_eq!(standing.ids, again.ids);
    assert_eq!(replay.journal.count(), 3);
    replay_drive(&replay, standing, Mode::Ordinary, now_micros())
        .await
        .unwrap();
    assert_eq!(replay.journal.count(), 3);
    document_lifecycle::retire(&replay.endpoint, "synthetic", local, &created)
        .await
        .unwrap();
    replay.journal.finish().unwrap();
    // The CI set is absent: the first ordinary pass rebuilds it through the lane's own guard,
    // files the creates as a cold rebuild, and then runs its reuse assertions over the set.
    replay.journal.begin("ordinary");
    let stamp = now_micros();
    let rebuilt = std::sync::Mutex::new(None);
    replay_ordinary_ci_pass(&replay, stamp, &rebuilt).await;
    let rebuilt = rebuilt.into_inner().unwrap().unwrap();
    assert_eq!(rebuilt.len(), 4, "a parent and three document slots");
    assert_eq!(
        replay
            .journal
            .count_in(document_lifecycle::journal::COLD_REBUILD),
        3,
        "exactly the three missing documents, filed as a cold rebuild"
    );
    assert_eq!(
        replay.journal.count(),
        3,
        "the reuse assertions create none"
    );
    // A second, warm ordinary pass resets the same retained contents and creates nothing.
    let warm = std::sync::Mutex::new(None);
    replay_ordinary_ci_pass(&replay, stamp + 1, &warm).await;
    assert_eq!(warm.into_inner().unwrap().unwrap(), rebuilt);
    assert_eq!(
        replay.journal.count(),
        3,
        "a warm ordinary pass creates none"
    );
    replay.journal.finish().unwrap();
    replay.journal.begin("fresh");
    let standing = replay_prepare(&replay, scope, Mode::Fresh).await.unwrap();
    replay_drive(&replay, standing, Mode::Fresh, stamp + 2)
        .await
        .unwrap();
    assert_eq!(
        replay.journal.count(),
        3,
        "two document writes and the follow-up document write"
    );
    replay.journal.finish().unwrap();
    // The original filed/loose deletion assertions ran in drive_documents; retire the
    // follow-up using the same documentDelete HTTP boundary as invocation cleanup.
    let fresh_ids: Vec<_> = replay
        .state
        .lock()
        .unwrap()
        .documents
        .iter()
        .filter(|(_, row)| {
            row["title"].as_str().is_some_and(|t| {
                is_this_runs(
                    Run::current(),
                    onetaskgraph_linear::LIVE_ARTIFACT_TITLE_PREFIX,
                    t,
                )
            })
        })
        .map(|(id, _)| id.clone())
        .collect();
    assert_eq!(fresh_ids.len(), 1);
    for id in fresh_ids {
        document_lifecycle::send(
            &replay.endpoint,
            "synthetic",
            onetaskgraph_linear::graphql::DOCUMENT_DELETE,
            json!({"id":id}),
        )
        .await
        .unwrap();
    }
    assert_eq!(
        replay.journal.count(),
        3,
        "deletion never removes successful creations from the journal"
    );
    replay.journal.begin("failure");
    replay.state.lock().unwrap().corrupt_document_create_ack = true;
    let standing = replay_prepare(&replay, scope, Mode::Fresh).await.unwrap();
    let error = replay_drive(&replay, standing, Mode::Fresh, stamp + 3)
        .await
        .unwrap_err();
    assert!(error.contains("visible body"), "{error}");
    assert_eq!(
        replay.journal.count(),
        2,
        "both writes before the assertion failure remain counted"
    );
    let residue = replay_cleanup_documents(&replay).await;
    assert_eq!(
        residue, 0,
        "failed fresh documents retire while standing CI slots survive"
    );
    replay.journal.residue(residue);
    replay.journal.finish().unwrap();
    replay.state.lock().unwrap().corrupt_document_create_ack = false;
    let standing = replay_prepare(&replay, scope, Mode::Ordinary)
        .await
        .unwrap();
    replay_drive(&replay, standing, Mode::Ordinary, stamp + 4)
        .await
        .unwrap();
    assert!(replay.state.lock().unwrap().schema_errors.is_empty());
}

#[tokio::test]
async fn document_lifecycle_replay_refuses_unsafe_ownership_and_recovers_partial_initialization() {
    let replay = replay();
    let scope = Scope::ci("ENG").unwrap();
    replay.state.lock().unwrap().uncertain = true;
    let error = replay_prepare(&replay, scope, Mode::Initialize)
        .await
        .err()
        .unwrap();
    assert!(error.contains("discover"), "{error}");
    assert_eq!(
        replay.journal.count(),
        1,
        "uncertain acknowledgement still records the stored create"
    );
    // The ordinary CI pass resumes that partial initialization as a cold rebuild.
    let recovered = replay_prepare(&replay, scope, Mode::Ordinary)
        .await
        .unwrap();
    assert_eq!(
        replay.journal.count(),
        3,
        "discovery reuses the uncertain first create and fills only missing slots"
    );
    assert_eq!(recovered.ids.len(), 4);
    let again = replay_prepare(&replay, scope, Mode::Ordinary)
        .await
        .unwrap();
    assert_eq!(again.ids, recovered.ids);
    assert_eq!(
        replay.journal.count(),
        3,
        "a warm pass creates no duplicate"
    );
    // A cancelled invocation leaves reusable contents, not missing identities.
    replay_drive(&replay, recovered, Mode::Ordinary, now_micros())
        .await
        .unwrap();
    for defect in ["wrong-team", "unverifiable-team", "ambiguous", "unknown"] {
        let before = {
            let mut state = replay.state.lock().unwrap();
            state.wrong_team = defect == "wrong-team";
            state.unverifiable_team = defect == "unverifiable-team";
            state.ambiguous = defect == "ambiguous";
            if defect == "unknown" {
                state.documents.values_mut().next().unwrap()["title"] =
                    json!("onetaskgraph live cleanup retained-v2 ci ENG filed");
            }
            state.requests.len()
        };
        let error = replay_prepare(&replay, scope, Mode::Ordinary)
            .await
            .err()
            .unwrap();
        assert!(
            error.contains("ownership") || error.contains("membership"),
            "{defect}: {error}"
        );
        let state = replay.state.lock().unwrap();
        assert!(
            state.requests[before..]
                .iter()
                .all(|r| !r["query"].as_str().unwrap().contains("mutation")),
            "{defect} sent a write"
        );
    }
    assert!(replay.state.lock().unwrap().schema_errors.is_empty());
}

/// The transport's own record of a replay: each create and delete mutation it answered.
fn replay_mutations(
    replay: &document_replay::Replay,
    from: usize,
) -> BTreeMap<&'static str, usize> {
    let state = replay.state.lock().unwrap();
    let mut counted = BTreeMap::new();
    for request in &state.requests[from..] {
        let query = request["query"].as_str().unwrap();
        for root in [
            "projectCreate",
            "documentCreate",
            "projectDelete",
            "documentDelete",
        ] {
            if query.contains(&format!("{root}(")) {
                *counted.entry(root).or_default() += 1;
            }
        }
    }
    counted
}

/// A panic straight after each individual slot create of a local initialization — the
/// parent project, then each of the three documents — still retires every slot the
/// invocation created before the panic leaves the lane, and nothing else.
#[tokio::test]
async fn a_panic_after_each_local_slot_create_retires_what_the_invocation_created() {
    let replay = replay();
    let ci = replay_prepare(&replay, Scope::ci("ENG").unwrap(), Mode::Initialize)
        .await
        .unwrap();
    for after in 1..=4 {
        let stamp = format!("1-2-{after}");
        let scope = Scope::local("ENG", &stamp).unwrap();
        let before = replay.state.lock().unwrap().requests.len();
        let creates_before = replay.journal.count();
        let created = document_lifecycle::Created::panicking_after(after);
        let outcome = document_lifecycle::unwinding(document_lifecycle::prepare_owned(
            &replay.endpoint,
            "synthetic",
            "ENG",
            "team",
            scope,
            Mode::Initialize,
            &[Slot::Filed, Slot::Loose, Slot::FollowUp],
            &created,
        ))
        .await;
        let panic = outcome.err().expect("the injected failure panics the lane");
        assert_eq!(
            panic.downcast_ref::<String>().map(String::as_str),
            Some(format!("injected failure after standing create {after}").as_str())
        );
        let sent = replay_mutations(&replay, before);
        let projects = 1;
        let documents = after - projects;
        assert_eq!(
            sent.get("projectCreate").copied().unwrap_or(0),
            projects,
            "after {after}"
        );
        assert_eq!(
            sent.get("documentCreate").copied().unwrap_or(0),
            documents,
            "after {after}"
        );
        assert_eq!(
            sent.get("projectDelete").copied().unwrap_or(0),
            projects,
            "after {after}: the parent created is the parent retired"
        );
        assert_eq!(
            sent.get("documentDelete").copied().unwrap_or(0),
            documents,
            "after {after}: every document created is retired"
        );
        assert_eq!(
            replay.journal.count() - creates_before,
            documents,
            "after {after}: retired documents stay counted as created"
        );
        let state = replay.state.lock().unwrap();
        assert!(
            state
                .documents
                .values()
                .chain(state.projects.values())
                .all(|row| !row["title"]
                    .as_str()
                    .or(row["name"].as_str())
                    .unwrap_or("")
                    .contains(&stamp)),
            "after {after}: nothing of the invocation's set survives"
        );
        assert_eq!(created.len(), 0);
    }
    let survived = replay_prepare(&replay, Scope::ci("ENG").unwrap(), Mode::Ordinary)
        .await
        .unwrap();
    assert_eq!(survived.ids, ci.ids, "the standing CI set is untouched");
    assert!(replay.state.lock().unwrap().schema_errors.is_empty());
}

/// A panic straight after a successful local preparation — before any of the journey's
/// setup — is caught by the plugin lane's own invocation guard, which retires the parent
/// project and all three documents the invocation created; the standing CI set and an
/// unrelated document and project survive, and the creations stay journalled.
#[tokio::test]
async fn a_panic_straight_after_local_preparation_is_retired_by_the_plugin_invocation_guard() {
    let replay = replay();
    let ci = replay_prepare(&replay, Scope::ci("ENG").unwrap(), Mode::Initialize)
        .await
        .unwrap();
    let unrelated_document = document_lifecycle::send(
        &replay.endpoint,
        "synthetic",
        "mutation($input:DocumentCreateInput!){documentCreate(input:$input){success document{id}}}",
        json!({"input":{"title":"Unrelated synthetic document","content":"synthetic","teamId":"team"}}),
    )
    .await
    .unwrap()["documentCreate"]["document"]["id"]
        .as_str()
        .unwrap()
        .to_owned();
    let unrelated_project = document_lifecycle::send(
        &replay.endpoint,
        "synthetic",
        "mutation($input:ProjectCreateInput!){projectCreate(input:$input){success project{id}}}",
        json!({"input":{"name":"Unrelated synthetic project","teamIds":["team"]}}),
    )
    .await
    .unwrap()["projectCreate"]["project"]["id"]
        .as_str()
        .unwrap()
        .to_owned();
    let stamp = "1-2-9";
    let scope = Scope::local("ENG", stamp).unwrap();
    let before = replay.state.lock().unwrap().requests.len();
    let creates_before = replay.journal.count();
    let created = document_lifecycle::Created::default();
    let prepared = std::sync::Mutex::new(None);
    let outcome = document_lifecycle::unwinding(guard_plugin_invocation(
        &replay.endpoint,
        "synthetic",
        "ENG",
        "team",
        scope,
        Mode::Initialize,
        &created,
        |standing| {
            *prepared.lock().unwrap() = Some(standing.ids.clone());
            async {
                panic!("injected failure straight after local preparation");
            }
        },
    ))
    .await;
    let panic = outcome.expect_err("the injected failure still fails the lane");
    assert_eq!(
        panic.downcast_ref::<&str>().copied(),
        Some("injected failure straight after local preparation")
    );
    let prepared = prepared
        .into_inner()
        .unwrap()
        .expect("preparation succeeded first");
    assert_eq!(
        prepared.len(),
        4,
        "the parent and all three local documents were created"
    );
    let sent = replay_mutations(&replay, before);
    assert_eq!(sent.get("projectCreate"), Some(&1));
    assert_eq!(sent.get("documentCreate"), Some(&3));
    assert_eq!(sent.get("projectDelete"), Some(&1), "the parent is retired");
    assert_eq!(
        sent.get("documentDelete"),
        Some(&3),
        "every document is retired"
    );
    assert_eq!(
        replay.journal.count() - creates_before,
        3,
        "retired creations stay journalled"
    );
    {
        let state = replay.state.lock().unwrap();
        for id in prepared.values() {
            assert!(
                !state.documents.contains_key(id) && !state.projects.contains_key(id),
                "{id} survived"
            );
        }
        assert!(state.documents.contains_key(&unrelated_document));
        assert!(state.projects.contains_key(&unrelated_project));
    }
    assert_eq!(created.len(), 0);
    let survived = replay_prepare(&replay, Scope::ci("ENG").unwrap(), Mode::Ordinary)
        .await
        .unwrap();
    assert_eq!(survived.ids, ci.ids, "the standing CI set is untouched");
    assert!(replay.state.lock().unwrap().schema_errors.is_empty());
}

/// An uncertain local create — stored, but acknowledged without its id — is found by its
/// exact identity and retired with the slot created before it; a CI set keeps its slots for
/// the discovery recovery requires.
#[tokio::test]
async fn an_uncertain_local_slot_create_is_discovered_and_retired_before_the_lane_fails() {
    let replay = replay();
    replay.state.lock().unwrap().uncertain = true;
    let created = document_lifecycle::Created::default();
    let error = document_lifecycle::prepare_owned(
        &replay.endpoint,
        "synthetic",
        "ENG",
        "team",
        Scope::local("ENG", "1-2-3").unwrap(),
        Mode::Initialize,
        &[Slot::Filed, Slot::Loose, Slot::FollowUp],
        &created,
    )
    .await
    .err()
    .unwrap();
    assert!(error.contains("discover"), "{error}");
    let sent = replay_mutations(&replay, 0);
    assert_eq!(sent.get("projectCreate"), Some(&1));
    assert_eq!(sent.get("documentCreate"), Some(&1));
    assert_eq!(sent.get("projectDelete"), Some(&1));
    assert_eq!(sent.get("documentDelete"), Some(&1));
    assert_eq!(
        replay.journal.count(),
        1,
        "the retired create stays counted"
    );
    {
        let state = replay.state.lock().unwrap();
        assert!(state.documents.is_empty() && state.projects.is_empty());
    }
    replay.state.lock().unwrap().uncertain = true;
    let before = replay.state.lock().unwrap().requests.len();
    document_lifecycle::prepare_owned(
        &replay.endpoint,
        "synthetic",
        "ENG",
        "team",
        Scope::ci("ENG").unwrap(),
        Mode::Initialize,
        &[Slot::Filed, Slot::Loose, Slot::FollowUp],
        &document_lifecycle::Created::default(),
    )
    .await
    .err()
    .unwrap();
    let sent = replay_mutations(&replay, before);
    assert_eq!(
        sent.get("projectDelete"),
        None,
        "standing CI slots are never retired"
    );
    assert_eq!(
        sent.get("documentDelete"),
        None,
        "standing CI slots are never retired"
    );
    assert!(replay.state.lock().unwrap().schema_errors.is_empty());
}

#[tokio::test]
async fn local_document_sets_cannot_resolve_ci_or_another_invocation() {
    let replay = replay();
    let ci = replay_prepare(&replay, Scope::ci("ENG").unwrap(), Mode::Initialize)
        .await
        .unwrap();
    let first = Scope::local("ENG", "1-2-3").unwrap();
    let second = Scope::local("ENG", "1-4-5").unwrap();
    for scope in [first, second] {
        assert!(
            replay_prepare(&replay, scope, Mode::Ordinary)
                .await
                .err()
                .unwrap()
                .contains("initialize")
        );
    }
    let local = replay_prepare(&replay, first, Mode::Initialize)
        .await
        .unwrap();
    let other = replay_prepare(&replay, second, Mode::Initialize)
        .await
        .unwrap();
    for key in ["filed", "loose", "follow-up", "parent"] {
        assert_ne!(ci.ids[key], local.ids[key]);
        assert_ne!(local.ids[key], other.ids[key]);
    }
    assert_eq!(
        replay.journal.count(),
        9,
        "each independently owned set has three real document creates"
    );
    assert!(replay.state.lock().unwrap().schema_errors.is_empty());
}
#[tokio::test]
async fn cancelled_document_initialization_discovers_its_stored_create_before_recovery() {
    use std::{sync::atomic::Ordering, time::Duration};
    let replay = replay();
    replay.state.lock().unwrap().pause_next_create = true;
    let endpoint = replay.endpoint.clone();
    let initializing = tokio::spawn(async move {
        document_lifecycle::prepare(
            &endpoint,
            "synthetic",
            "ENG",
            "team",
            Scope::ci("ENG").unwrap(),
            Mode::Initialize,
            &[Slot::Filed, Slot::Loose, Slot::FollowUp],
        )
        .await
    });
    tokio::time::timeout(Duration::from_secs(5), async {
        while !replay.paused.load(Ordering::Acquire) {
            tokio::time::sleep(Duration::from_millis(5)).await;
        }
    })
    .await
    .expect("create reached HTTP transport before cancellation");
    initializing.abort();
    assert!(matches!(initializing.await, Err(error) if error.is_cancelled()));
    replay.release.store(true, Ordering::Release);
    tokio::time::timeout(Duration::from_secs(5), async {
        while replay.journal.count() != 1 {
            tokio::time::sleep(Duration::from_millis(5)).await;
        }
    })
    .await
    .expect("forwarding observer records the upstream acknowledgement after cancellation");
    assert_eq!(
        replay.journal.count(),
        1,
        "a committed create remains counted after the caller is cancelled"
    );
    let scope = Scope::ci("ENG").unwrap();
    let restored = replay_prepare(&replay, scope, Mode::Ordinary)
        .await
        .unwrap();
    assert_eq!(
        replay.journal.count(),
        3,
        "recovery discovers the cancelled create and creates only missing identities"
    );
    replay_drive(&replay, restored, Mode::Ordinary, now_micros())
        .await
        .unwrap();
    assert!(replay.state.lock().unwrap().schema_errors.is_empty());
}

/// A child role invoked only by the subprocess seat journey below.
#[tokio::test]
async fn document_writer_child() {
    use std::time::Duration;
    let Ok(role) = env::var("ONETASKGRAPH_LINEAR_WRITER_CHILD") else {
        return;
    };
    let root = std::path::PathBuf::from(env::var_os("ONETASKGRAPH_LINEAR_WRITER_ROOT").unwrap());
    let session = Session::open(
        SESSION_NAME,
        Credential::new("synthetic").unwrap(),
        Exclusivity::OneAtATime,
    );
    if role == "decline" {
        assert!(
            session.is_err(),
            "a concurrent writer unexpectedly acquired the Linear seat"
        );
        println!("declined before HTTP");
        return;
    }
    let _session = session
        .unwrap_or_else(|error| panic!("isolated writer could not acquire its seat: {error}"));
    std::fs::write(root.join("held"), b"held").unwrap();
    tokio::time::timeout(Duration::from_secs(20), async {
        while !root.join("release").exists() {
            tokio::time::sleep(Duration::from_millis(5)).await;
        }
    })
    .await
    .expect("parent releases the writer it started");
    let endpoint = env::var("ONETASKGRAPH_LINEAR_WRITER_ENDPOINT").unwrap();
    let standing = document_lifecycle::prepare(
        &endpoint,
        "synthetic",
        "ENG",
        "team",
        Scope::ci("ENG").unwrap(),
        Mode::Ordinary,
        &[Slot::Filed, Slot::Loose, Slot::FollowUp],
    )
    .await
    .unwrap();
    let journal = document_lifecycle::journal::Journal::new("plugin", "ordinary");
    replay_drive_at(&endpoint, &journal, standing, Mode::Ordinary, now_micros())
        .await
        .unwrap();
}

#[tokio::test]
async fn document_ci_writers_share_the_real_machine_seat_before_http_updates() {
    use std::{
        process::{Child, Command, Stdio},
        time::Duration,
    };
    struct HeldChild(Option<Child>);
    impl Drop for HeldChild {
        fn drop(&mut self) {
            if let Some(child) = self.0.as_mut() {
                let _ = child.kill();
                let _ = child.wait();
            }
        }
    }
    let replay = replay();
    let standing = replay_prepare(&replay, Scope::ci("ENG").unwrap(), Mode::Initialize)
        .await
        .unwrap();
    replay.journal.begin("ordinary");
    let root = env::var_os("ONEPIPELINE_NODE_SCRATCH_DIR")
        .map(std::path::PathBuf::from)
        .unwrap_or_else(env::temp_dir)
        .join(format!(
            "linear-writers-{}-{}",
            std::process::id(),
            now_micros()
        ));
    std::fs::create_dir_all(root.join("seats")).unwrap();
    let command = |role: &str| {
        let mut command = Command::new(env::current_exe().unwrap());
        command
            .args(["--exact", "document_writer_child", "--nocapture"])
            .env("ONETASKGRAPH_LINEAR_WRITER_CHILD", role)
            .env("ONETASKGRAPH_LINEAR_WRITER_ROOT", &root)
            .env("ONETASKGRAPH_LINEAR_WRITER_ENDPOINT", &replay.endpoint)
            .env(
                onetaskgraph_live::SEAT_DIRECTORY_VARIABLE,
                root.join("seats"),
            )
            .env(
                onetaskgraph_live::artifact::REGISTRY_DIRECTORY_VARIABLE,
                root.join("registry"),
            )
            .env_remove("LINEAR_API_KEY")
            .stdout(Stdio::piped())
            .stderr(Stdio::piped());
        command
    };
    let mut first = HeldChild(Some(command("hold").spawn().unwrap()));
    tokio::time::timeout(Duration::from_secs(10), async {
        while !root.join("held").exists() {
            tokio::time::sleep(Duration::from_millis(5)).await;
        }
    })
    .await
    .expect("first child holds its isolated Linear seat");
    let before = replay.state.lock().unwrap().requests.len();
    let declined = command("decline").output().unwrap();
    assert!(
        declined.status.success(),
        "{}",
        String::from_utf8_lossy(&declined.stderr)
    );
    assert!(String::from_utf8_lossy(&declined.stdout).contains("declined before HTTP"));
    assert_eq!(
        replay.state.lock().unwrap().requests.len(),
        before,
        "declined writer sends no HTTP operation"
    );
    std::fs::write(root.join("release"), b"release").unwrap();
    let completed = first.0.take().unwrap().wait_with_output().unwrap();
    assert!(
        completed.status.success(),
        "{}",
        String::from_utf8_lossy(&completed.stdout)
    );
    assert_eq!(replay.journal.count(), 0);
    let requests = replay.state.lock().unwrap().requests[before..].to_vec();
    assert!(
        requests
            .iter()
            .filter(|request| request["query"]
                .as_str()
                .unwrap()
                .contains("documentUpdate("))
            .count()
            >= 3,
        "admitted child runs the actual shared ordinary document paths"
    );
    let after = replay_prepare(&replay, Scope::ci("ENG").unwrap(), Mode::Ordinary)
        .await
        .unwrap();
    assert_eq!(standing.ids, after.ids);
    assert!(replay.state.lock().unwrap().schema_errors.is_empty());
    std::fs::remove_dir_all(root).unwrap();
}

struct ReplaySecrets;
impl SecretResolver for ReplaySecrets {
    fn get(&self, _: &str) -> Option<SecretString> {
        Some(SecretString::from("synthetic"))
    }
}

#[tokio::test]
async fn document_discovery_follows_advancing_http_pages_without_writes() {
    let replay = replay();
    let scope = Scope::ci("ENG").unwrap();
    let initialized = replay_prepare(&replay, scope, Mode::Initialize)
        .await
        .unwrap();
    let before = {
        let mut state = replay.state.lock().unwrap();
        state.discovery_pagination = Some("advance");
        state.requests.len()
    };
    let discovered = replay_prepare(&replay, scope, Mode::Ordinary)
        .await
        .unwrap();
    assert_eq!(discovered.ids, initialized.ids);
    let state = replay.state.lock().unwrap();
    let requests = &state.requests[before..];
    assert!(
        requests
            .iter()
            .all(|request| !request["query"].as_str().unwrap().contains("mutation"))
    );
    let cursors: Vec<_> = requests
        .iter()
        .filter(|request| request["query"].as_str().unwrap().contains("documents("))
        .map(|request| request["variables"]["after"].clone())
        .collect();
    assert_eq!(
        cursors,
        (0..3)
            .flat_map(|_| [Value::Null, json!("1"), json!("2")])
            .collect::<Vec<_>>(),
        "each exact slot discovery reads all three actual stored document pages"
    );
    assert!(state.schema_errors.is_empty(), "{:?}", state.schema_errors);
}

#[tokio::test]
async fn document_discovery_refuses_broken_or_unbounded_http_pagination_before_writes() {
    let replay = replay();
    let scope = Scope::ci("ENG").unwrap();
    replay_prepare(&replay, scope, Mode::Initialize)
        .await
        .unwrap();
    for (fault, expected, pages) in [
        ("missing-cursor", "omitted cursor", 1),
        ("repeated-cursor", "did not advance", 2),
        ("missing-pagination", "omitted pagination", 1),
        ("exhausted", "did not terminate", 50),
    ] {
        let before = {
            let mut state = replay.state.lock().unwrap();
            state.discovery_pagination = Some(fault);
            state.requests.len()
        };
        let error = replay_prepare(&replay, scope, Mode::Ordinary)
            .await
            .err()
            .unwrap();
        assert!(error.contains(expected), "{fault}: {error}");
        let state = replay.state.lock().unwrap();
        let requests = &state.requests[before..];
        assert!(
            requests
                .iter()
                .all(|request| !request["query"].as_str().unwrap().contains("mutation")),
            "{fault} sent a write"
        );
        assert_eq!(
            requests
                .iter()
                .filter(|request| request["query"].as_str().unwrap().contains("documents("))
                .count(),
            pages,
            "{fault}"
        );
        assert!(
            state.schema_errors.is_empty(),
            "{fault}: {:?}",
            state.schema_errors
        );
    }
    assert_eq!(
        replay.journal.count(),
        3,
        "failed ordinary discovery never creates a replacement"
    );
}

#[tokio::test]
async fn document_discovery_requires_well_formed_direct_team_before_project_fallback() {
    let replay = replay();
    let prepare = |mode| {
        document_lifecycle::prepare(
            &replay.endpoint,
            "synthetic",
            "ENG",
            "team",
            Scope::ci("ENG").unwrap(),
            mode,
            &[Slot::Filed],
        )
    };
    let initialized = prepare(Mode::Initialize).await.unwrap();
    for malformed in [
        json!("ENG"),
        json!({}),
        json!({"key":7}),
        json!({"key":"OTHER"}),
    ] {
        let before = {
            let mut state = replay.state.lock().unwrap();
            state.direct_team_override = Some(malformed.clone());
            state.requests.len()
        };
        let error = prepare(Mode::Ordinary).await.err().unwrap();
        assert!(error.contains("membership"), "{malformed}: {error}");
        let state = replay.state.lock().unwrap();
        assert!(
            state.requests[before..]
                .iter()
                .all(|request| !request["query"].as_str().unwrap().contains("mutation")),
            "{malformed} sent a write"
        );
    }
    let before = {
        let mut state = replay.state.lock().unwrap();
        state.direct_team_override = None;
        state.omit_direct_team = true;
        state.requests.len()
    };
    assert!(
        prepare(Mode::Ordinary)
            .await
            .err()
            .unwrap()
            .contains("membership")
    );
    assert!(
        replay.state.lock().unwrap().requests[before..]
            .iter()
            .all(|request| !request["query"].as_str().unwrap().contains("mutation"))
    );
    {
        let mut state = replay.state.lock().unwrap();
        state.omit_direct_team = false;
        state.direct_team_override = Some(Value::Null);
    }
    let recovered = prepare(Mode::Ordinary).await.unwrap();
    assert_eq!(
        recovered.ids, initialized.ids,
        "explicit null uses the verified complete project membership"
    );
    assert_eq!(replay.journal.count(), 1);
}

#[tokio::test]
async fn ordinary_document_run_metadata_reset_is_read_back_and_recovers_after_stale_write() {
    let replay = replay();
    let scope = Scope::ci("ENG").unwrap();
    let first = replay_prepare(&replay, scope, Mode::Initialize)
        .await
        .unwrap();
    replay.journal.begin("ordinary");
    let stamp = now_micros();
    replay_drive(&replay, first, Mode::Ordinary, stamp)
        .await
        .unwrap();
    replay.state.lock().unwrap().freeze_document_run_metadata = true;
    let second = replay_prepare(&replay, scope, Mode::Ordinary)
        .await
        .unwrap();
    let error = replay_drive(&replay, second, Mode::Ordinary, stamp + 1)
        .await
        .unwrap_err();
    assert!(error.contains("reset caller.run"), "{error}");
    replay.state.lock().unwrap().freeze_document_run_metadata = false;
    let recovered = replay_prepare(&replay, scope, Mode::Ordinary)
        .await
        .unwrap();
    replay_drive(&replay, recovered, Mode::Ordinary, stamp + 1)
        .await
        .unwrap();
    assert_eq!(
        replay.journal.count(),
        0,
        "recovery updates the same retained documents"
    );
    assert!(replay.state.lock().unwrap().schema_errors.is_empty());
}

/// The plugin lane's own write of a task naming labels it created, `write_labelled_task`, over
/// HTTP to a replay whose label filter holds one label only from its third lookup and never
/// holds the other: the first is resolved once held and written with its id, and the second
/// ends, once the bound is spent, in the refusal the plugin gives — with no label created and
/// no issue written for it.
#[tokio::test]
async fn a_task_write_naming_a_label_linear_holds_late_resolves_it_and_one_never_held_is_refused() {
    const BOUND: Bound = Bound {
        reads: 4,
        interval: std::time::Duration::from_millis(20),
    };
    let replay = replay();
    let stamp = now_micros();
    let late = artifact_label(Run::current(), stamp);
    let never = artifact_label(Run::current(), stamp + 1);
    {
        let mut state = replay.state.lock().unwrap();
        state.labels.insert(late.clone(), ("label-late".into(), 2));
        state
            .labels
            .insert(never.clone(), ("label-never".into(), u32::MAX));
    }
    let source = onetaskgraph_linear::Plugin
        .build(
            &SourceName::new("live").unwrap(),
            &json!({"endpoint":replay.endpoint,"team":"ENG","status_mapping":{"todo":{"task":"Todo"}}}),
            &ReplaySecrets,
        )
        .unwrap();
    let write = |name: &str, offset: u64| -> ItemWrite<Task> {
        let mut task: Task = serde_json::from_value(json!({
            "id":"authored:labelled","title":artifact_title(Run::current(), stamp + offset),
            "content":"Synthetic labelled task.","status":{"category":"todo","name":"Todo"},
            "labels":[],"project":null,"repositories":[],"metadata":{}
        }))
        .unwrap();
        task.labels = vec![label(name)];
        ItemWrite {
            target: None,
            item: task,
            depends_on: vec![],
        }
    };
    let creates = |replay: &document_replay::Replay| -> Vec<Value> {
        replay
            .state
            .lock()
            .unwrap()
            .requests
            .iter()
            .filter(|request| {
                request["query"]
                    .as_str()
                    .is_some_and(|q| q.contains("issueCreate("))
            })
            .map(|request| request["variables"]["input"]["labelIds"].clone())
            .collect()
    };

    write_labelled_task(BOUND, source.as_ref(), &write(&late, 10))
        .await
        .expect("a label the filter holds within the bound is resolved and written");
    let lookups = |name: &str| replay.state.lock().unwrap().label_lookups[&name.to_lowercase()];
    assert_eq!(
        lookups(&late),
        3,
        "the write asks again until the label is held, and not once more"
    );
    assert_eq!(
        creates(&replay),
        vec![json!(["label-late"])],
        "one issue is written, naming the label once it was resolved"
    );

    let refusal = write_labelled_task(BOUND, source.as_ref(), &write(&never, 11))
        .await
        .expect_err("a label the filter never holds is refused once the bound is spent");
    assert!(
        matches!(&refusal, SourceError::Refused { message }
            if *message == format!("source live cannot resolve label {never:?}: found 0 matches")),
        "the refusal past the bound is the plugin's own: {refusal:?}"
    );
    assert_eq!(
        lookups(&never),
        BOUND.reads,
        "the bound is every lookup made"
    );
    assert_eq!(
        creates(&replay).len(),
        1,
        "no issue is written for a label that was never resolved"
    );
    let state = replay.state.lock().unwrap();
    assert!(
        state.requests.iter().all(|request| {
            let query = request["query"].as_str().unwrap_or_default();
            !query.contains("issueLabel") || query == onetaskgraph_linear::graphql::ISSUE_LABEL
        }),
        "a label is only ever looked up, never created, renamed or removed"
    );
    assert!(state.schema_errors.is_empty(), "{:?}", state.schema_errors);
}

/// A label a live journey created and has not retired, through a cold ordinary CI pass that
/// prepares the standing set and a second pass queued after it: neither pass sends any request
/// that creates, renames or removes a label, and the plugin's lookup still resolves it after
/// both, so neither can have deleted or hidden it. (Residue clearing is driven over the same
/// label in `tests/sweep_gate.rs`.)
#[tokio::test]
async fn standing_set_preparation_and_a_queued_pass_leave_a_live_journeys_label_resolvable() {
    let replay = replay();
    let held = artifact_label(Run::current(), now_micros());
    replay
        .state
        .lock()
        .unwrap()
        .labels
        .insert(held.clone(), ("label-held".into(), 0));
    let standing_ids = std::sync::Mutex::new(None);
    replay_ordinary_ci_pass(&replay, now_micros(), &standing_ids).await;
    let cold = replay.journal.count();
    assert!(cold > 0, "the first pass prepared the standing set cold");
    replay_ordinary_ci_pass(&replay, now_micros(), &standing_ids).await;
    assert_eq!(
        replay.journal.count(),
        cold,
        "the queued pass reused the standing set"
    );
    assert!(
        replay
            .state
            .lock()
            .unwrap()
            .requests
            .iter()
            .all(|request| !request["query"]
                .as_str()
                .unwrap_or_default()
                .contains("issueLabel")),
        "preparation and the passes over the standing set touched no label"
    );
    let source = onetaskgraph_linear::Plugin
        .build(
            &SourceName::new("live").unwrap(),
            &json!({"endpoint":replay.endpoint,"team":"ENG","status_mapping":{"todo":{"task":"Todo"}}}),
            &ReplaySecrets,
        )
        .unwrap();
    let mut task: Task = serde_json::from_value(json!({
        "id":"authored:labelled","title":artifact_title(Run::current(), now_micros()),
        "content":"Synthetic labelled task.","status":{"category":"todo","name":"Todo"},
        "labels":[],"project":null,"repositories":[],"metadata":{}
    }))
    .unwrap();
    task.labels = vec![label(&held)];
    write_labelled_task(
        Bound {
            reads: 1,
            interval: std::time::Duration::ZERO,
        },
        source.as_ref(),
        &ItemWrite {
            target: None,
            item: task,
            depends_on: vec![],
        },
    )
    .await
    .expect("the live journey's label still resolves on the first lookup after both passes");
    assert!(replay.state.lock().unwrap().schema_errors.is_empty());
}