onetaskgraph 0.2.21

One interface over the ticketing systems your work lives in.
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
//! The copy verb, driven the way a user drives it.
//!
//! The round trip is the point of the whole verb, so it is proven rather than asserted:
//! a task is copied out of a destination into a folder of Markdown, the Markdown is
//! edited the way a person edits it, and the copy back updates the item it came from
//! instead of creating a second one — with every field the edit did not touch
//! byte-for-byte what it was.
//!
//! Every test here spawns the compiled binary as a subprocess and asserts on its exit
//! code, stdout and stderr. The same verb driven as a *library* call, which is the
//! consumer a command-line-only copy would strand, is proven in
//! `crates/onetaskgraph-core/tests/copy.rs`.

use std::process::Output;

use serde_json::{Value, json};

use crate::common::{SOURCE_BOUNDARIES, Sandbox, SourceBoundary, stderr, stdout};
use crate::fixtures::{
    LINEAR_REFUSED_WRITE, ROWS, SOURCE, document, empty_folder,
    github_projects_failing_a_field_write_and_its_cleanup,
    github_projects_failing_a_field_write_once, github_projects_failing_to_file_and_its_cleanup,
    github_projects_failing_to_file_once, github_projects_reading_one_item_behind,
    github_projects_with_board, linear_block, linear_empty_workspace,
    linear_failing_a_relation_write_once, qualified,
};

/// The folder every copy journey copies into, configured beside the source under test.
const NOTES: &str = "notes";

fn run(sandbox: &Sandbox, arguments: &[&str]) -> Output {
    sandbox
        .command()
        .args(arguments)
        .assert()
        .get_output()
        .clone()
}

/// Standard output of a run that had to succeed, quoting stderr when it did not.
fn ok(sandbox: &Sandbox, arguments: &[&str]) -> String {
    let output = run(sandbox, arguments);
    assert_eq!(
        output.status.code(),
        Some(0),
        "`onetaskgraph {}` exited {:?}\n{}",
        arguments.join(" "),
        output.status.code(),
        stderr(&output)
    );
    stdout(&output)
}

/// Standard error of a run that had to fail with `code`.
fn refused(sandbox: &Sandbox, arguments: &[&str], code: i32) -> String {
    let output = run(sandbox, arguments);
    assert_eq!(
        output.status.code(),
        Some(code),
        "`onetaskgraph {}` was expected to exit {code}\n{}{}",
        arguments.join(" "),
        stdout(&output),
        stderr(&output)
    );
    stderr(&output)
}

/// One item of a `--json` copy report, as a comparable triple.
fn reported(rendered: &str) -> Vec<(String, Value, String)> {
    let report: Value = serde_json::from_str(rendered).expect("a copy emits JSON");
    report["items"]
        .as_array()
        .expect("a copy report carries items")
        .iter()
        .map(|item| {
            (
                item["source"].as_str().expect("a source id").to_owned(),
                item["destination"].clone(),
                item["action"].as_str().expect("an action").to_owned(),
            )
        })
        .collect()
}

/// One item of a `<verb> show --json` response.
fn shown(sandbox: &Sandbox, verb: &str, id: &str) -> Value {
    let rendered = ok(sandbox, &[verb, "show", id, "--json"]);
    let response: Value = serde_json::from_str(&rendered).expect("show emits JSON");
    response["items"][0]["item"].clone()
}

/// Two Markdown folders, the first holding one task and the second empty, and the root
/// of the first.
///
/// This is the user's own flow in miniature: a folder standing in for the system their
/// team works out of, and a folder they author and edit in.
fn folders(sandbox: &Sandbox) -> std::path::PathBuf {
    let root = sandbox.subdirectory("remote");
    let tasks = root.join("tasks");
    std::fs::create_dir_all(&tasks).expect("the remote task folder");
    std::fs::write(
        tasks.join("ENG-1.md"),
        "---\ntitle: Rate-limit the sync loop\nstatus: doing\n\
         labels: [{id: L-1, name: bug}]\n\
         metadata: {caller.count: 3, caller.shape: {nested: [1, true, null]}}\n\
         repositories: [github.com/nickderobertis/onetaskgraph]\n---\nthe body\n",
    )
    .expect("the remote task");
    sandbox.project_document(&document(&json!({
        "remote": {"plugin": "local-md", "config": {
            "root": root,
            "status_mapping": {"todo": "todo", "doing": "in-progress", "shipped": "done"},
        }},
        NOTES: {"plugin": "local-md", "config": empty_folder(sandbox, NOTES)},
    })));
    root
}

#[test]
fn linear_is_a_permanent_task_destination_with_typed_metadata_and_repository_origins() {
    let sandbox = Sandbox::new();
    let root = sandbox.subdirectory("linear-task-source");
    std::fs::create_dir_all(root.join("tasks")).unwrap();
    std::fs::write(root.join("tasks/A.md"), "---\ntitle: Authored locally\nstatus: Todo\nlabels: [{id: local-bug, name: bug}]\nmetadata: {object: {a: 1}, array: [1, true], string: text, number: 3.5, boolean: true, null: null}\nrepositories: [github.com/acme/work]\n---\nvisible body\n").unwrap();
    sandbox.project_document(&document(&json!({
        "authored": {"plugin":"local-md","config":{"root":root,"status_mapping":{"Todo":"todo"}}},
        "linear": {"plugin":"linear","config":linear_block(&sandbox)},
    })));

    let first = reported(&ok(
        &sandbox,
        &["task", "copy", "authored:A", "--to", "linear", "--json"],
    ));
    assert_eq!(first.len(), 1);
    assert_eq!(first[0].2, "created");
    let destination = first[0].1.as_str().unwrap().to_owned();
    let item = shown(&sandbox, "task", &destination);
    assert_eq!(item["title"], "Authored locally");
    assert_eq!(item["content"], "visible body");
    assert_eq!(item["status"]["name"], "Todo");
    assert_eq!(item["labels"][0]["name"], "bug");
    assert_eq!(item["repositories"], json!(["github.com/acme/work"]));
    for key in ["object", "array", "string", "number", "boolean", "null"] {
        let source = shown(&sandbox, "task", "authored:A");
        assert_eq!(
            item["metadata"][key], source["metadata"][key],
            "metadata key {key}"
        );
    }
    let second = reported(&ok(
        &sandbox,
        &["task", "copy", "authored:A", "--to", "linear", "--json"],
    ));
    assert_eq!(second[0].1, destination);
    assert!(matches!(second[0].2.as_str(), "updated" | "unchanged"));
}

#[test]
fn linear_project_and_task_copies_write_native_relations_and_record_only_cross_source_edges() {
    let sandbox = Sandbox::new();
    let root = sandbox.subdirectory("linear-graph-source");
    std::fs::create_dir_all(root.join("tasks")).unwrap();
    std::fs::create_dir_all(root.join("projects")).unwrap();
    for (path, title, dependencies) in [
        ("tasks/FAR.md", "Far task", ""),
        (
            "tasks/NEAR.md",
            "Near task",
            "depends_on: [FAR, {id: \"elsewhere:P-9\", item: project}]\n",
        ),
        ("tasks/CHILD.md", "Project child", "project: NEAR\n"),
        ("projects/FAR.md", "Far project", ""),
        (
            "projects/NEAR.md",
            "Near project",
            "labels: [{id: local-roadmap, name: roadmap}]\nmetadata: {caller.project: {enabled: true}}\nrepositories: [github.com/acme/project]\ndepends_on: [FAR, {id: \"elsewhere:T-9\", item: task}]\n",
        ),
    ] {
        std::fs::write(
            root.join(path),
            format!("---\ntitle: {title}\nstatus: Todo\n{dependencies}---\nbody\n"),
        )
        .unwrap();
    }
    sandbox.project_document(&document(&json!({
        "authored": {"plugin":"local-md","config":{"root":root,"status_mapping":{"Todo":"todo"}}},
        "linear": {"plugin":"linear","config":linear_block(&sandbox)},
    })));
    let task_far = reported(&ok(
        &sandbox,
        &["task", "copy", "authored:FAR", "--to", "linear", "--json"],
    ))[0]
        .1
        .as_str()
        .unwrap()
        .to_owned();
    let task_near = reported(&ok(
        &sandbox,
        &["task", "copy", "authored:NEAR", "--to", "linear", "--json"],
    ))[0]
        .1
        .as_str()
        .unwrap()
        .to_owned();
    let project_far = reported(&ok(
        &sandbox,
        &[
            "project",
            "copy",
            "authored:FAR",
            "--to",
            "linear",
            "--no-tasks",
            "--json",
        ],
    ))[0]
        .1
        .as_str()
        .unwrap()
        .to_owned();
    let project_report = reported(&ok(
        &sandbox,
        &[
            "project",
            "copy",
            "authored:NEAR",
            "--to",
            "linear",
            "--json",
        ],
    ));
    assert_eq!(
        project_report.len(),
        2,
        "the project copy includes its task"
    );
    let project_near = project_report[0].1.as_str().unwrap().to_owned();
    let written_project = shown(&sandbox, "project", &project_near);
    assert_eq!(written_project["content"], "body");
    assert_eq!(written_project["status"]["name"], "Todo");
    assert_eq!(written_project["labels"][0]["name"], "roadmap");
    assert_eq!(
        written_project["metadata"]["caller.project"]["enabled"],
        true
    );
    assert_eq!(
        written_project["repositories"],
        json!(["github.com/acme/project"])
    );
    let child = shown(&sandbox, "task", project_report[1].1.as_str().unwrap());
    assert_eq!(child["project"], project_near.split_once(':').unwrap().1);
    let repeated = reported(&ok(
        &sandbox,
        &[
            "project",
            "copy",
            "authored:NEAR",
            "--to",
            "linear",
            "--json",
        ],
    ));
    assert_eq!(
        repeated.iter().map(|item| &item.1).collect::<Vec<_>>(),
        project_report
            .iter()
            .map(|item| &item.1)
            .collect::<Vec<_>>()
    );

    let edges = |verb: &str, id: &str, reverse: bool| {
        let mut args = vec![verb, "deps", id, "--json"];
        if reverse {
            args.splice(3..3, ["--direction", "depended-on-by"]);
        }
        serde_json::from_str::<Value>(&ok(&sandbox, &args)).unwrap()["items"]
            .as_array()
            .unwrap()
            .clone()
    };
    let task_forward = edges("task", &task_near, false);
    assert_eq!(
        task_forward.len(),
        2,
        "the repeated write does not duplicate relations"
    );
    assert!(
        task_forward.iter().any(|edge| edge["to"]["id"] == task_far),
        "{task_forward:#?}"
    );
    assert!(
        task_forward
            .iter()
            .any(|edge| edge["to"]["id"] == "elsewhere:P-9")
    );
    assert!(
        edges("task", &task_far, true)
            .iter()
            .any(|edge| edge["from"]["id"] == task_near)
    );
    let project_forward = edges("project", &project_near, false);
    assert_eq!(
        project_forward.len(),
        2,
        "the repeated project write replaces its relation set"
    );
    assert!(
        project_forward
            .iter()
            .any(|edge| edge["to"]["id"] == project_far)
    );
    assert!(
        project_forward
            .iter()
            .any(|edge| edge["to"]["id"] == "elsewhere:T-9")
    );
    assert!(
        edges("project", &project_far, true)
            .iter()
            .any(|edge| edge["from"]["id"] == project_near)
    );

    for (verb, id) in [("task", task_near.clone()), ("project", project_near)] {
        let item = shown(&sandbox, verb, &id);
        let recorded = item["metadata"]["onetaskgraph.depends_on"]
            .as_array()
            .unwrap();
        assert_eq!(recorded.len(), 1, "only the cross-source edge is recorded");
        assert!(
            recorded[0]["id"]
                .as_str()
                .unwrap()
                .starts_with("elsewhere:")
        );
    }
    let near_file = root.join("tasks/NEAR.md");
    let edited = std::fs::read_to_string(&near_file).unwrap().replace(
        "[FAR, {id: \"elsewhere:P-9\", item: project}]",
        &format!("[{{id: \"{project_far}\", item: project}}]"),
    );
    std::fs::write(&near_file, edited).unwrap();
    ok(
        &sandbox,
        &["task", "copy", "authored:NEAR", "--to", "linear"],
    );
    let replaced = edges("task", &task_near, false);
    assert_eq!(replaced.len(), 1);
    assert_eq!(replaced[0]["to"]["id"], project_far);
    let recorded = shown(&sandbox, "task", &task_near)["metadata"]["onetaskgraph.depends_on"]
        .as_array()
        .unwrap()
        .clone();
    assert_eq!(
        recorded[0]["kind"], "project",
        "a same-source cross-kind far end uses the fallback because an issue relation cannot name a project"
    );
}

#[test]
fn a_round_trip_edit_updates_the_item_it_came_from_rather_than_duplicating_it() {
    let sandbox = Sandbox::new();
    folders(&sandbox);

    // Out of the destination and into Markdown.
    let copied = ok(&sandbox, &["task", "copy", "remote:ENG-1", "--to", NOTES]);
    assert_eq!(
        copied.split_whitespace().collect::<Vec<_>>(),
        ["remote:ENG-1", "notes:ENG-1", "created"]
    );
    let before = shown(&sandbox, "task", "remote:ENG-1");

    // Edited the way a person edits it: one field, in the file.
    let file = sandbox.project().join(NOTES).join("tasks/ENG-1.md");
    let text = std::fs::read_to_string(&file).expect("the copied Markdown is there");
    assert!(
        text.contains("onetaskgraph.origin: remote:ENG-1"),
        "the copy records where it came from:\n{text}"
    );
    std::fs::write(
        &file,
        text.replace(
            "title: Rate-limit the sync loop",
            "title: Rate-limit the sync loop, carefully",
        ),
    )
    .expect("the edit lands");

    let back = ok(
        &sandbox,
        &["task", "copy", "notes:ENG-1", "--to", "remote", "--json"],
    );
    assert_eq!(
        reported(&back),
        vec![(
            "notes:ENG-1".to_owned(),
            json!("remote:ENG-1"),
            "updated".to_owned()
        )]
    );

    // Exactly one item where there was one before: the copy back updated, and the
    // folder holds no second document.
    assert_eq!(
        ok(&sandbox, &["task", "list", "--source", "remote"])
            .lines()
            .filter(|line| !line.trim().is_empty())
            .count(),
        1
    );

    let after = shown(&sandbox, "task", "remote:ENG-1");
    assert_eq!(
        after["title"],
        json!("Rate-limit the sync loop, carefully"),
        "the edited field changed"
    );
    // And every field the edit did not touch is byte-for-byte what it was.
    for field in [
        "id",
        "content",
        "status",
        "labels",
        "project",
        "repositories",
        "url",
        "created_at",
        "updated_at",
    ] {
        assert_eq!(
            after[field], before[field],
            "{field} survived the round trip"
        );
    }
    for key in ["caller.count", "caller.shape"] {
        assert_eq!(
            after["metadata"][key], before["metadata"][key],
            "{key} survived the round trip"
        );
    }
    // Including the correspondence itself: the copy back found this item by following the
    // edited file's own origin, so it is the original and its provenance is its own. This
    // one was authored here and has none, and the copy back leaves it with none.
    assert_eq!(
        after["metadata"]["onetaskgraph.origin"],
        Value::Null,
        "a copy back does not stamp the original with the id of the copy that came from it"
    );
}

/// Three Markdown folders in the shape a settlement write-back has: the store a plan is
/// authored in, the store it is copied onto, and a run-owned scratch store the settled run
/// is projected back out of.
///
/// The middle one is the destination of both copies, and that is the whole of the
/// arrangement: a forward copy reaches it by searching, a copy-back reaches it by
/// following the scratch item's own origin, and only one of the two may write the origin.
fn authoring_board_and_scratch(sandbox: &Sandbox) -> std::path::PathBuf {
    let authoring = sandbox.subdirectory("authoring");
    let tasks = authoring.join("tasks");
    std::fs::create_dir_all(&tasks).expect("the authoring task folder");
    std::fs::write(
        tasks.join("plan-x.md"),
        "---\ntitle: Plan X\nstatus: todo\nmetadata: {caller.stage: authored}\n---\nthe plan\n",
    )
    .expect("the authored plan");
    let documents = authoring.join("documents");
    std::fs::create_dir_all(&documents).expect("the authoring document folder");
    std::fs::write(
        documents.join("brief-x.md"),
        "---\ntitle: Brief X\nmetadata: {caller.stage: authored}\n---\nthe brief\n",
    )
    .expect("the authored brief");
    sandbox.project_document(&document(&json!({
        "authoring": {"plugin": "local-md", "config": {
            "root": authoring,
            "status_mapping": {"todo": "todo", "doing": "in-progress", "shipped": "done"},
        }},
        "plans": {"plugin": "local-md", "config": empty_folder(sandbox, "plans")},
        "run": {"plugin": "local-md", "config": empty_folder(sandbox, "run")},
    })));
    authoring
}

/// The metadata one Markdown file records at a key, or `Value::Null` when it records none.
fn recorded_origin(sandbox: &Sandbox, source: &str, verb: &str, id: &str) -> Value {
    shown(sandbox, verb, &format!("{source}:{id}"))["metadata"]["onetaskgraph.origin"].clone()
}

#[test]
fn a_copy_back_leaves_the_destinations_own_origin_so_the_next_copy_still_finds_it() {
    // The defect this closes, driven end to end: a copy-back stamped the destination with
    // the id of the copy that came *out* of it, and the next ordinary copy from the store
    // the item was authored in then matched nothing and created a second item beside it.
    let sandbox = Sandbox::new();
    authoring_board_and_scratch(&sandbox);

    let forward = ok(
        &sandbox,
        &[
            "task",
            "copy",
            "authoring:plan-x",
            "--to",
            "plans",
            "--json",
        ],
    );
    assert_eq!(
        reported(&forward),
        vec![(
            "authoring:plan-x".to_owned(),
            json!("plans:plan-x"),
            "created".to_owned()
        )]
    );
    assert_eq!(
        recorded_origin(&sandbox, "plans", "task", "plan-x"),
        json!("authoring:plan-x"),
        "a forward copy records where it came from"
    );

    // A run projects the plan out to a scratch store of its own, settles it, and copies
    // the settled item back. The scratch item's origin names the board, so the copy-back
    // reaches the board item by following it.
    ok(
        &sandbox,
        &["task", "copy", "plans:plan-x", "--to", "run", "--json"],
    );
    let scratch = sandbox.project().join("run").join("tasks/plan-x.md");
    let text = std::fs::read_to_string(&scratch).expect("the scratch copy is there");
    assert!(
        text.contains("onetaskgraph.origin: plans:plan-x"),
        "the scratch copy knows which board item it came from:\n{text}"
    );
    std::fs::write(&scratch, text.replace("status: todo", "status: shipped"))
        .expect("the run settles the plan");

    let back = ok(
        &sandbox,
        &["task", "copy", "run:plan-x", "--to", "plans", "--json"],
    );
    assert_eq!(
        reported(&back),
        vec![(
            "run:plan-x".to_owned(),
            json!("plans:plan-x"),
            "updated".to_owned()
        )]
    );
    assert_eq!(
        shown(&sandbox, "task", "plans:plan-x")["status"]["category"],
        json!("done"),
        "the settled status landed"
    );
    assert_eq!(
        recorded_origin(&sandbox, "plans", "task", "plan-x"),
        json!("authoring:plan-x"),
        "and the board item still says where it itself came from"
    );

    // Projecting the same settled run again writes nothing: preserving the origin is not
    // a change, so a repeat settlement is not a write.
    let repeated = ok(
        &sandbox,
        &["task", "copy", "run:plan-x", "--to", "plans", "--json"],
    );
    assert_eq!(
        reported(&repeated),
        vec![(
            "run:plan-x".to_owned(),
            json!("plans:plan-x"),
            "unchanged".to_owned()
        )]
    );

    // And the plan is still readable back the way it was written: an ordinary copy from
    // the store it was authored in updates the one item rather than creating a second.
    let again = ok(
        &sandbox,
        &[
            "task",
            "copy",
            "authoring:plan-x",
            "--to",
            "plans",
            "--json",
        ],
    );
    assert_eq!(
        reported(&again),
        vec![(
            "authoring:plan-x".to_owned(),
            json!("plans:plan-x"),
            "updated".to_owned()
        )]
    );
    assert_eq!(
        ok(&sandbox, &["task", "list", "--source", "plans"])
            .lines()
            .filter(|line| !line.trim().is_empty())
            .count(),
        1,
        "exactly one item where there was one before"
    );
}

#[test]
fn a_document_copy_back_leaves_the_destinations_own_origin_the_same_way() {
    // A document is not work and takes part in no graph, but it is copied by the same
    // rules and carries the same reserved key — so a settled run projecting a document
    // back must not cost that document its correspondence either.
    let sandbox = Sandbox::new();
    authoring_board_and_scratch(&sandbox);

    ok(
        &sandbox,
        &[
            "document",
            "copy",
            "authoring:brief-x",
            "--to",
            "plans",
            "--json",
        ],
    );
    assert_eq!(
        recorded_origin(&sandbox, "plans", "document", "brief-x"),
        json!("authoring:brief-x"),
        "a forward copy records where it came from"
    );

    ok(
        &sandbox,
        &["document", "copy", "plans:brief-x", "--to", "run", "--json"],
    );
    let scratch = sandbox.project().join("run").join("documents/brief-x.md");
    let text = std::fs::read_to_string(&scratch).expect("the scratch copy is there");
    assert!(
        text.contains("onetaskgraph.origin: plans:brief-x"),
        "the scratch copy knows which document it came from:\n{text}"
    );
    std::fs::write(&scratch, text.replace("the brief", "the settled brief"))
        .expect("the run settles the brief");

    let back = ok(
        &sandbox,
        &["document", "copy", "run:brief-x", "--to", "plans", "--json"],
    );
    assert_eq!(
        reported(&back),
        vec![(
            "run:brief-x".to_owned(),
            json!("plans:brief-x"),
            "updated".to_owned()
        )]
    );
    assert_eq!(
        shown(&sandbox, "document", "plans:brief-x")["content"],
        json!("the settled brief"),
        "the settled body landed"
    );
    assert_eq!(
        recorded_origin(&sandbox, "plans", "document", "brief-x"),
        json!("authoring:brief-x"),
        "and the document still says where it itself came from"
    );

    // Projecting the same settled run again is not a write.
    let repeated = ok(
        &sandbox,
        &["document", "copy", "run:brief-x", "--to", "plans", "--json"],
    );
    assert_eq!(
        reported(&repeated),
        vec![(
            "run:brief-x".to_owned(),
            json!("plans:brief-x"),
            "unchanged".to_owned()
        )]
    );

    // And the document is still readable back the way it was written.
    let again = ok(
        &sandbox,
        &[
            "document",
            "copy",
            "authoring:brief-x",
            "--to",
            "plans",
            "--json",
        ],
    );
    assert_eq!(
        reported(&again),
        vec![(
            "authoring:brief-x".to_owned(),
            json!("plans:brief-x"),
            "updated".to_owned()
        )]
    );
    assert_eq!(
        ok(&sandbox, &["document", "list", "--source", "plans"])
            .lines()
            .filter(|line| !line.trim().is_empty())
            .count(),
        1,
        "exactly one document where there was one before"
    );
}

#[test]
fn a_copy_back_of_a_project_keeps_every_origin_and_orphans_nothing_the_source_holds() {
    // The same rule where a whole project is projected and settled: each task is matched
    // independently, so each has its own origin to lose, and a task whose origin the
    // copy-back preserved must not then read as one the source no longer holds.
    let sandbox = Sandbox::new();
    let authoring = sandbox.subdirectory("authoring");
    for (kind, id, front) in [
        ("projects", "P-1", "title: Engine\nstatus: doing"),
        ("tasks", "T-1", "title: Alpha\nstatus: todo\nproject: P-1"),
        ("tasks", "T-2", "title: Beta\nstatus: todo\nproject: P-1"),
    ] {
        let path = authoring.join(kind).join(format!("{id}.md"));
        std::fs::create_dir_all(path.parent().expect("a parent")).expect("the folder");
        std::fs::write(path, format!("---\n{front}\n---\nbody\n")).expect("the document");
    }
    sandbox.project_document(&document(&json!({
        "authoring": {"plugin": "local-md", "config": {
            "root": authoring,
            "status_mapping": {"todo": "todo", "doing": "in-progress", "shipped": "done"},
        }},
        "plans": {"plugin": "local-md", "config": empty_folder(&sandbox, "plans")},
        "run": {"plugin": "local-md", "config": empty_folder(&sandbox, "run")},
    })));

    ok(
        &sandbox,
        &[
            "project",
            "copy",
            "authoring:P-1",
            "--to",
            "plans",
            "--json",
        ],
    );
    ok(
        &sandbox,
        &["project", "copy", "plans:P-1", "--to", "run", "--json"],
    );
    let settled = sandbox.project().join("run").join("tasks/T-1.md");
    let text = std::fs::read_to_string(&settled).expect("the scratch copy is there");
    std::fs::write(&settled, text.replace("status: todo", "status: shipped"))
        .expect("the run settles a task");

    let back = reported(&ok(
        &sandbox,
        &["project", "copy", "run:P-1", "--to", "plans", "--json"],
    ));
    assert!(
        back.iter().all(|(_, _, action)| action != "orphaned"),
        "nothing the scratch store holds is reported as gone from it: {back:?}"
    );
    for (verb, id) in [("project", "P-1"), ("task", "T-1"), ("task", "T-2")] {
        assert_eq!(
            recorded_origin(&sandbox, "plans", verb, id),
            json!(format!("authoring:{id}")),
            "{verb} {id} still says where it itself came from"
        );
    }

    // Copying the project from the store it was authored in matches every item again:
    // nothing is created, and no task the authoring store still holds is orphaned.
    let again = reported(&ok(
        &sandbox,
        &[
            "project",
            "copy",
            "authoring:P-1",
            "--to",
            "plans",
            "--json",
        ],
    ));
    assert!(
        again
            .iter()
            .all(|(_, _, action)| action == "updated" || action == "unchanged"),
        "every item was matched rather than created or orphaned: {again:?}"
    );
    assert_eq!(
        ok(&sandbox, &["task", "list", "--source", "plans"])
            .lines()
            .filter(|line| !line.trim().is_empty())
            .count(),
        2,
        "the two tasks that were there, and no duplicates"
    );
}

#[test]
fn every_source_kind_can_be_copied_into_a_folder_of_markdown_with_its_fields_intact() {
    // A journey written once and run against every configured source kind, so no plugin
    // is proven by a suite of its own writing. The destination is a Markdown folder
    // because that is the one every source can be copied *into* today, and it is what the
    // user's own flow authors and edits in.
    for row in ROWS {
        let sandbox = Sandbox::new();
        sandbox.project_document(&row.document_with_folder(&sandbox, NOTES));
        let from = qualified(SOURCE, "T-1");

        let planned = ok(&sandbox, &["task", "copy", &from, "--to", NOTES, "--json"]);
        assert_eq!(
            reported(&planned),
            vec![(from.clone(), json!("notes:T-1"), "created".to_owned())],
            "{}",
            row.name
        );

        let source = shown(&sandbox, "task", &from);
        let copied = shown(&sandbox, "task", "notes:T-1");
        for field in ["title", "content", "status", "labels", "repositories"] {
            assert_eq!(copied[field], source[field], "{}: {field}", row.name);
        }
        // Value and JSON type alike, for every key the caller owns.
        for key in ["onepipeline.turn_budget", "caller.flags"] {
            assert_eq!(
                copied["metadata"][key], source["metadata"][key],
                "{}: {key}",
                row.name
            );
        }
        assert_eq!(
            copied["metadata"]["onetaskgraph.origin"],
            json!(from),
            "{}",
            row.name
        );
        // `url` is the destination's own and is never written.
        assert_eq!(copied["url"], Value::Null, "{}", row.name);

        // A second copy of the same item updates that one and creates nothing.
        let again = ok(&sandbox, &["task", "copy", &from, "--to", NOTES, "--json"]);
        assert_eq!(
            reported(&again),
            vec![(from.clone(), json!("notes:T-1"), "unchanged".to_owned())],
            "{}",
            row.name
        );
        assert_eq!(
            ok(&sandbox, &["task", "list", "--source", NOTES])
                .lines()
                .filter(|line| !line.trim().is_empty())
                .count(),
            1,
            "{}",
            row.name
        );
    }
}

/// The GitHub board every journey below copies into, beside the folder it copies from.
fn board_with_plans(sandbox: &Sandbox, folder: &str) -> crate::fixtures::GitHubBoardFields {
    let (config, board) = github_projects_with_board(sandbox);
    sandbox.project_document(&document(&json!({
        folder: {"plugin":"local-md","config":{
            "root": sandbox.subdirectory(folder),
            "status_mapping": {"Todo":"todo","Doing":"in-progress","Shipped":"done",
                               "Idea":"draft"}}},
        "board": {"plugin":"github-projects","config":config}
    })));
    board
}

#[test]
fn a_project_and_its_tasks_copy_into_a_board_without_touching_the_board_itself() {
    // The defect this replaces: the source resolved to one board id and treated it as the
    // project, so copying a project into it renamed a real user's board. A board is a
    // container of projects now — a project lands as an issue and its tasks land as that
    // issue's sub-issues — and the board's own fields are never written by anything here.
    let sandbox = Sandbox::new();
    let root = sandbox.subdirectory("plans");
    std::fs::create_dir_all(root.join("projects")).unwrap();
    std::fs::create_dir_all(root.join("tasks")).unwrap();
    std::fs::write(root.join("projects/P-1.md"), "---\ntitle: Published roadmap\nstatus: Doing\nmetadata: {caller.approved: true, caller.shape: {nested: [1, true, null]}}\n---\nThe permanent plan\n").unwrap();
    std::fs::write(
        root.join("tasks/A.md"),
        "---\ntitle: First step\nstatus: Todo\nproject: P-1\n---\ndo this first\n",
    )
    .unwrap();
    std::fs::write(
        root.join("tasks/B.md"),
        "---\ntitle: Second step\nstatus: Todo\nproject: P-1\n---\nthen this\n",
    )
    .unwrap();
    let board = board_with_plans(&sandbox, "plans");
    let before = board.own();
    assert_eq!(
        before,
        json!({"title":"Fixture board",
               "shortDescription":"the board a person set up",
               "readme":"# Fixture board\n\nA person wrote this."}),
        "the board this copy lands on is a person's, with a title and a readme of its own"
    );

    let copied = ok(
        &sandbox,
        &["project", "copy", "plans:P-1", "--to", "board", "--json"],
    );
    let reported = reported(&copied);
    assert_eq!(
        reported
            .iter()
            .map(|(source, _, action)| (source.as_str(), action.as_str()))
            .collect::<Vec<_>>(),
        vec![
            ("plans:P-1", "created"),
            ("plans:A", "created"),
            ("plans:B", "created"),
        ]
    );
    let project = reported[0].1.as_str().expect("a created project id");

    let written = shown(&sandbox, "project", project);
    assert_eq!(written["title"], "Published roadmap");
    assert_eq!(written["content"], "The permanent plan");
    assert_eq!(written["status"]["category"], "in-progress");
    assert_eq!(written["metadata"]["caller.approved"], true);
    assert_eq!(
        written["metadata"]["caller.shape"],
        json!({"nested":[1,true,null]}),
        "unbounded caller JSON survives with its types intact"
    );

    let listed = ok(&sandbox, &["task", "list", "--source", "board"]);
    for title in ["First step", "Second step"] {
        assert!(listed.contains(title), "{listed}");
    }
    let filed = shown(&sandbox, "task", reported[1].1.as_str().unwrap());
    assert_eq!(
        filed["project"].as_str(),
        project.strip_prefix("board:"),
        "a project's tasks are that issue's sub-issues"
    );
    assert_eq!(filed["status"]["name"], "Todo");

    assert_eq!(
        board.own(),
        before,
        "the board's own title, shortDescription and readme are never written"
    );
}

#[test]
fn a_project_whose_goal_outgrows_a_board_description_still_copies() {
    // Why the metadata slot moved out of `shortDescription`: that field is capped at 300
    // characters, and the metadata comment spent about 110 of them before any content, so
    // a project carrying an ordinary goal statement could not be copied at all.
    let sandbox = Sandbox::new();
    let root = sandbox.subdirectory("plans");
    std::fs::create_dir_all(root.join("projects")).unwrap();
    let goal =
        "This plan exists so that the whole harness can author its work on a board. ".repeat(6);
    assert!(goal.len() > 300, "the goal must outgrow the old slot");
    std::fs::write(
        root.join("projects/P-1.md"),
        format!("---\ntitle: Long goal\nstatus: Todo\nmetadata: {{onepipeline.steps: [{goal:?}]}}\n---\n{goal}\n"),
    )
    .unwrap();
    board_with_plans(&sandbox, "plans");

    let copied = ok(
        &sandbox,
        &[
            "project",
            "copy",
            "plans:P-1",
            "--to",
            "board",
            "--no-tasks",
            "--json",
        ],
    );
    let id = reported(&copied)[0].1.as_str().expect("an id").to_owned();
    let written = shown(&sandbox, "project", &id);
    assert_eq!(written["content"], goal.trim_end());
    assert_eq!(written["metadata"]["onepipeline.steps"], json!([goal]));
}

#[test]
fn a_board_that_fails_between_creating_an_issue_and_filing_it_says_so_and_recovers() {
    // Landing an item on a board is two calls — `createIssue`, then
    // `addProjectV2ItemById` — so GitHub can fail between them, and what happens then is
    // a journey rather than a reading of the code: the copy exits non-zero saying what
    // GitHub said, the board holds nothing it was not already holding, and the retry
    // lands exactly one item rather than two.
    let sandbox = Sandbox::new();
    let root = sandbox.subdirectory("plans");
    std::fs::create_dir_all(root.join("tasks")).unwrap();
    std::fs::write(
        root.join("tasks/A.md"),
        "---\ntitle: First step\nstatus: Todo\n---\ndo this first\n",
    )
    .unwrap();
    sandbox.project_document(&document(&json!({
        "plans": {"plugin":"local-md","config":{
            "root": root, "status_mapping": {"Todo":"todo"}}},
        "board": {"plugin":"github-projects",
                  "config": github_projects_failing_to_file_once(&sandbox)}
    })));

    let said = refused(&sandbox, &["task", "copy", "plans:A", "--to", "board"], 1);
    assert!(
        said.contains("Something went wrong while executing your query"),
        "the failure GitHub reported is what the caller is told: {said}"
    );
    let listed = ok(&sandbox, &["task", "list", "--source", "board"]);
    assert!(
        !listed.contains("First step"),
        "an issue that was never filed is on no board: {listed}"
    );

    let copied = ok(
        &sandbox,
        &["task", "copy", "plans:A", "--to", "board", "--json"],
    );
    let landed = reported(&copied);
    assert_eq!(landed.len(), 1, "{copied}");
    assert_eq!(
        landed[0].1,
        json!("board:ISSUE-2"),
        "the issue the failed attempt created is on no board, so nothing can match it and \
         the retry creates its own — the orphan stays in the repository: {copied}"
    );
    let listed = ok(&sandbox, &["task", "list", "--source", "board"]);
    assert_eq!(
        listed.matches("First step").count(),
        1,
        "the retry lands one item where the failed attempt landed none: {listed}"
    );
}

#[test]
fn a_dependency_naming_a_board_item_as_the_wrong_kind_is_refused_before_anything_lands() {
    // The board holds the far end itself, so it is the board that says which kind `P-2`
    // is — a project. An edge naming it a task would be stored as a relationship at a
    // level it is not at, and the refusal comes before the issue is created.
    let sandbox = Sandbox::new();
    let root = sandbox.subdirectory("plans");
    std::fs::create_dir_all(root.join("tasks")).unwrap();
    std::fs::write(
        root.join("tasks/A.md"),
        "---\ntitle: First step\nstatus: Todo\n\
         depends_on: [{id: \"board:P-2\", item: task}]\n---\ndo this first\n",
    )
    .unwrap();
    board_with_plans(&sandbox, "plans");

    let said = refused(&sandbox, &["task", "copy", "plans:A", "--to", "board"], 1);
    for expected in ["P-2", "project", "task"] {
        assert!(said.contains(expected), "{expected} is named: {said}");
    }
    let listed = ok(&sandbox, &["task", "list", "--source", "board"]);
    assert!(
        !listed.contains("First step"),
        "nothing was created before the refusal: {listed}"
    );
}

#[test]
fn a_field_write_that_fails_after_an_issue_is_filed_takes_the_issue_back() {
    // The later half of the same sequence: the issue exists and is on the board, and the
    // board field that would let the next copy find it is what did not land.
    //
    // That state used to be left behind, and `--match-by title` was the escape a person
    // had to know to reach for. It is not left behind any more: creating an item here is
    // several calls, GitHub can fail at any of them, and a write that refused must not
    // leave an item nobody asked for — so the source takes back the issue it created and
    // the plain retry is a clean one. The escape itself is unaffected and is proven where
    // it belongs, over a correspondence a *person* removed.
    let sandbox = Sandbox::new();
    let root = sandbox.subdirectory("plans");
    std::fs::create_dir_all(root.join("tasks")).unwrap();
    std::fs::write(
        root.join("tasks/A.md"),
        "---\ntitle: First step\nstatus: Doing\n---\ndo this first\n",
    )
    .unwrap();
    sandbox.project_document(&document(&json!({
        "plans": {"plugin":"local-md","config":{
            "root": root, "status_mapping": {"Doing":"in-progress"}}},
        "board": {"plugin":"github-projects",
                  "config": github_projects_failing_a_field_write_once(&sandbox)}
    })));

    let said = refused(&sandbox, &["task", "copy", "plans:A", "--to", "board"], 1);
    assert!(
        said.contains("Something went wrong while executing your query"),
        "the failure GitHub reported is what the caller is told: {said}"
    );
    let listed = ok(&sandbox, &["task", "list", "--source", "board"]);
    assert_eq!(
        listed.matches("First step").count(),
        0,
        "the issue the failed write created is not left on the board: {listed}"
    );

    // The failure is spent, so the plain retry — no escape, no flag — creates the one
    // issue this plan owes, with the status the failed attempt could not write.
    let copied = ok(
        &sandbox,
        &["task", "copy", "plans:A", "--to", "board", "--json"],
    );
    let landed = reported(&copied);
    assert_eq!(landed.len(), 1, "{copied}");
    assert_eq!(landed[0].2, "created", "{copied}");
    let finished = shown(&sandbox, "task", landed[0].1.as_str().expect("an id"));
    assert_eq!(
        finished["status"]["category"], "in-progress",
        "the status the failed attempt could not write is what the retry lands"
    );
    let listed = ok(&sandbox, &["task", "list", "--source", "board"]);
    assert_eq!(
        listed.matches("First step").count(),
        1,
        "and one plan is one issue rather than two: {listed}"
    );
}

#[test]
fn a_status_this_integration_cannot_hold_is_refused_naming_it_and_the_source() {
    // `draft` is an ordinary status everywhere else. This source refuses it, and says why:
    // a GitHub draft issue cannot have sub-issues, and a project's tasks are sub-issues.
    let sandbox = Sandbox::new();
    let root = sandbox.subdirectory("plans");
    std::fs::create_dir_all(root.join("tasks")).unwrap();
    std::fs::write(
        root.join("tasks/A.md"),
        "---\ntitle: Not yet committed\nstatus: Idea\n---\nan idea\n",
    )
    .unwrap();
    board_with_plans(&sandbox, "plans");

    assert_eq!(
        shown(&sandbox, "task", "plans:A")["status"]["category"],
        "draft",
        "draft is an ordinary accepted status in the source it came from"
    );
    let complaint = refused(&sandbox, &["task", "copy", "plans:A", "--to", "board"], 1);
    assert!(complaint.contains("draft"), "{complaint}");
    assert!(complaint.contains("board"), "{complaint}");
    assert!(complaint.contains("sub-issue"), "{complaint}");
}

#[test]
fn a_copy_into_a_board_settles_instead_of_reporting_a_change_on_every_run() {
    // Writing `done` closes the issue, and writing a non-terminal status over a closed one
    // has to reopen it. Without that the item reads back `Unknown` and this loop never
    // reaches `unchanged` — a copy would report a change forever.
    let sandbox = Sandbox::new();
    let root = sandbox.subdirectory("plans");
    std::fs::create_dir_all(root.join("tasks")).unwrap();
    let write_status = |status: &str| {
        std::fs::write(
            root.join("tasks/A.md"),
            format!("---\ntitle: One step\nstatus: {status}\n---\ndo this\n"),
        )
        .unwrap();
    };
    write_status("Todo");
    board_with_plans(&sandbox, "plans");

    let copy = |sandbox: &Sandbox| {
        reported(&ok(
            sandbox,
            &["task", "copy", "plans:A", "--to", "board", "--json"],
        ))
    };
    let created = copy(&sandbox);
    assert_eq!(created[0].2, "created");
    let id = created[0].1.as_str().expect("an id").to_owned();
    assert_eq!(copy(&sandbox)[0].2, "unchanged");

    write_status("Shipped");
    assert_eq!(copy(&sandbox)[0].2, "updated");
    assert_eq!(shown(&sandbox, "task", &id)["status"]["category"], "done");
    assert_eq!(
        copy(&sandbox)[0].2,
        "unchanged",
        "a closed issue reads back as the status that closed it"
    );

    write_status("Todo");
    assert_eq!(copy(&sandbox)[0].2, "updated");
    let reopened = shown(&sandbox, "task", &id);
    assert_eq!(
        reopened["status"],
        json!({"category":"todo","name":"Todo"}),
        "a non-terminal status reopens the issue rather than leaving it Unknown"
    );
    assert_eq!(copy(&sandbox)[0].2, "unchanged");
}

#[test]
fn github_projects_is_a_permanent_destination_whose_created_items_are_issues() {
    let sandbox = Sandbox::new();
    let root = sandbox.subdirectory("authored");
    std::fs::create_dir_all(root.join("tasks")).unwrap();
    std::fs::write(root.join("tasks/PLAN-1.md"), "---\ntitle: Publish the plan\nstatus: Todo\nmetadata: {caller.count: 3, caller.shape: {nested: [1, true, null]}}\nrepositories: [github.com/nickderobertis/onetaskgraph]\ndepends_on: [PLAN-2, {id: 'elsewhere:T-9', item: task}]\n---\nshare this plan\n").unwrap();
    std::fs::write(
        root.join("tasks/PLAN-2.md"),
        "---\ntitle: Supporting plan\nstatus: Todo\n---\nsupport it\n",
    )
    .unwrap();
    board_with_plans(&sandbox, "authored");

    let first = ok(
        &sandbox,
        &[
            "task",
            "copy",
            "authored:PLAN-1",
            "authored:PLAN-2",
            "--to",
            "board",
            "--json",
        ],
    );
    let first = reported(&first);
    assert_eq!(
        first
            .iter()
            .map(|(source, _, action)| (source.as_str(), action.as_str()))
            .collect::<Vec<_>>(),
        vec![
            ("authored:PLAN-1", "created"),
            ("authored:PLAN-2", "created"),
        ]
    );
    let one = first[0].1.as_str().expect("an id").to_owned();
    let two = first[1].1.as_str().expect("an id").to_owned();

    let copied = shown(&sandbox, "task", &one);
    assert_eq!(copied["title"], "Publish the plan");
    assert_eq!(copied["content"], "share this plan");
    assert_eq!(copied["status"]["name"], "Todo");
    assert_eq!(copied["metadata"]["caller.count"], 3);
    assert_eq!(
        copied["metadata"]["caller.shape"],
        json!({"nested":[1,true,null]})
    );
    assert_eq!(
        copied["repositories"],
        json!(["github.com/nickderobertis/onetaskgraph"]),
        "a list that is exactly the issue's own repository is derived rather than recorded"
    );

    let dependencies: Value =
        serde_json::from_str(&ok(&sandbox, &["task", "deps", &one, "--json"])).unwrap();
    assert_eq!(
        dependencies["items"]
            .as_array()
            .unwrap()
            .iter()
            .map(|edge| edge["to"].clone())
            .collect::<Vec<_>>(),
        vec![
            json!({"id":two,"kind":"task"}),
            json!({"id":"elsewhere:T-9","kind":"task"})
        ],
        "the far end inside the copied set is native and the one elsewhere is recorded"
    );

    let second = ok(
        &sandbox,
        &["task", "copy", "authored:PLAN-1", "--to", "board", "--json"],
    );
    // Copying PLAN-1 alone is not the same copy: PLAN-2 is no longer in the copied set, so
    // its edge is rewritten to name the source it is still in. That is a real change, and
    // the point here is that it lands on the item already there rather than beside it.
    assert_eq!(
        reported(&second),
        vec![("authored:PLAN-1".into(), json!(one), "updated".into())]
    );
    assert_eq!(
        ok(&sandbox, &["task", "list", "--source", "board"])
            .lines()
            .count(),
        6,
        "a second copy of the same item updates it rather than duplicating it"
    );
}

/// One authored document beside the board, in a source that has documents.
///
/// A folder of Markdown declares it holds none and the board's own documents are what this
/// journey copies *into*, so the source here is an `in-memory` one holding exactly one
/// document — carrying no labels, because items this destination creates carry none and a
/// write that named one would be refused for a reason this journey is not about.
///
/// `boundary` reaches the *board* alone. It is the destination and so the thing under
/// test, and putting the authored side behind a pipe too would double the journey's cost
/// to prove a transport the shared table already drives.
fn authored_document_beside(sandbox: &Sandbox, boundary: SourceBoundary) {
    let (config, _board) = github_projects_with_board(sandbox);
    sandbox.project_document(&document(&json!({
        "authored": {"plugin":"in-memory","config":{
            "capabilities": {"documents": "native"},
            "documents": [{
                "id": "HARNESS-1",
                "title": "Harness plan",
                "content": "the plan a manager reviews",
                "project": null,
                "labels": [],
                "metadata": {"caller.flags": [true, null],
                             "caller.shape": {"nested": [1, true, null]},
                             "onepipeline.turn_budget": 12},
                "repositories": ["github.com/nickderobertis/onetaskgraph"]
            }]}},
        "board": boundary.source_with_secrets(
            "github-projects",
            config,
            &["GITHUB_PROJECTS_FIXTURE_TOKEN"],
        )
    })));
}

#[test]
fn a_document_copies_into_a_github_board_as_an_issue_and_reads_back_unchanged() {
    // The round trip a board has to support before a design document can live on one: the
    // copy lands as an issue titled the way this board spells a document, a *later*
    // invocation reads it back with every field and every caller key intact, and a second
    // copy matches the one already there rather than adding a duplicate.
    //
    // Driven at both boundaries, because journey 19 asks every journey for it and because
    // this is the one that *writes*: the title this source rewrites on the way in and back
    // off on the way out crosses the pipe in both directions, and caller JSON has to keep
    // its types through a transport as well as through an issue body.
    for boundary in SOURCE_BOUNDARIES {
        let sandbox = Sandbox::new();
        authored_document_beside(&sandbox, boundary);

        let created = reported(&ok(
            &sandbox,
            &[
                "document",
                "copy",
                "authored:HARNESS-1",
                "--to",
                "board",
                "--json",
            ],
        ));
        assert_eq!(created.len(), 1, "{boundary:?}: {created:?}");
        assert_eq!(created[0].2, "created", "{boundary:?}: {created:?}");
        let landed_id = created[0].1.as_str().expect("a qualified id").to_owned();

        // A later invocation, against the board the first one wrote.
        let landed = shown(&sandbox, "document", &landed_id);
        let source = shown(&sandbox, "document", "authored:HARNESS-1");
        for field in ["title", "content", "repositories"] {
            assert_eq!(
                landed[field], source[field],
                "{boundary:?}: the board holds {field} as the source reported it"
            );
        }
        assert_eq!(
            landed["title"], "Harness plan",
            "{boundary:?}: the title that comes back out is the title that went in, prefix \
             and all removed"
        );
        for key in ["caller.flags", "caller.shape", "onepipeline.turn_budget"] {
            assert_eq!(
                landed["metadata"][key], source["metadata"][key],
                "{boundary:?}: the board holds the metadata key {key} with its JSON type intact"
            );
        }
        assert_eq!(
            landed["location"]["url"],
            json!(format!(
                "https://example.invalid/{}",
                landed_id.strip_prefix("board:").expect("a board id")
            )),
            "{boundary:?}: and says where it is, as a link a reader can open: {landed}"
        );

        // It is a document of that board and nothing else, which is only true if the prefix
        // really landed on the issue: a title without it reads back as a task.
        assert_eq!(
            ok(&sandbox, &["task", "list", "--source", "board"])
                .lines()
                .filter(|line| !line.trim().is_empty())
                .count(),
            4,
            "{boundary:?}: the copy added no task"
        );
        assert_eq!(
            ok(&sandbox, &["project", "list", "--source", "board"])
                .lines()
                .filter(|line| !line.trim().is_empty())
                .count(),
            2,
            "{boundary:?}: and no project"
        );

        let again = reported(&ok(
            &sandbox,
            &[
                "document",
                "copy",
                "authored:HARNESS-1",
                "--to",
                "board",
                "--json",
            ],
        ));
        assert_eq!(again[0].1, json!(landed_id), "{boundary:?}: {again:?}");
        assert!(
            matches!(again[0].2.as_str(), "updated" | "unchanged"),
            "{boundary:?}: a second copy is not a second create: {again:?}"
        );
        assert_eq!(
            ok(&sandbox, &["document", "list", "--source", "board"])
                .lines()
                .filter(|line| !line.trim().is_empty())
                .count(),
            4,
            "{boundary:?}: the board's own three documents and exactly one copied one"
        );
    }
}

#[test]
fn copying_an_issue_back_updates_fields_and_replaces_a_native_dependency() {
    let sandbox = Sandbox::new();
    let github = ROWS
        .iter()
        .find(|row| row.plugin == "github-projects")
        .unwrap();
    sandbox.project_document(&github.document_with_folder(&sandbox, NOTES));
    ok(&sandbox, &["task", "copy", "work:T-1", "--to", NOTES]);
    let file = sandbox.project().join(NOTES).join("tasks/T-1.md");
    std::fs::write(&file, "---\ntitle: Alpha engine revised\nstatus: Todo\nlabels: [{id: L-1, name: bug}, {id: L-3, name: core}]\nmetadata: {onetaskgraph.origin: 'work:T-1'}\nrepositories: [github.com/nickderobertis/onetaskgraph]\ndepends_on: [{id: 'work:T-3', item: task}]\n---\nthe engine core\n").unwrap();
    let copied = ok(
        &sandbox,
        &["task", "copy", "notes:T-1", "--to", "work", "--json"],
    );
    assert_eq!(
        reported(&copied),
        vec![("notes:T-1".into(), json!("work:T-1"), "updated".into())]
    );
}

#[test]
fn several_ids_in_one_command_are_one_copied_set_whose_edges_are_recreated() {
    // The ids named together *are* the set: an edge between two of them is recreated at
    // the destination, which one command per id could not do — the far end's own
    // destination id is not known until the copy that creates it has run.
    let row = &ROWS[0];
    let sandbox = Sandbox::new();
    sandbox.project_document(&row.document_with_folder(&sandbox, NOTES));
    let first = qualified(SOURCE, "T-1");
    let second = qualified(SOURCE, "T-2");

    let copied = ok(
        &sandbox,
        &["task", "copy", &first, &second, "--to", NOTES, "--json"],
    );
    assert_eq!(
        reported(&copied),
        vec![
            (first.clone(), json!("notes:T-1"), "created".to_owned()),
            (second.clone(), json!("notes:T-2"), "created".to_owned()),
        ]
    );

    let edges = ok(&sandbox, &["task", "deps", "notes:T-1", "--json"]);
    let edges: Value = serde_json::from_str(&edges).expect("deps emits JSON");
    let ends: Vec<&str> = edges["items"]
        .as_array()
        .expect("an array of edges")
        .iter()
        .map(|edge| edge["to"]["id"].as_str().expect("a qualified id"))
        .collect();
    assert!(
        ends.contains(&"notes:T-2"),
        "the far end inside the copied set is the destination's own id: {ends:?}"
    );
    assert!(
        ends.contains(&"elsewhere:P-9"),
        "a far end already naming another source is left exactly as it is: {ends:?}"
    );
}

#[test]
fn a_dry_run_reads_everything_writes_nothing_and_says_what_it_would_have_done() {
    let sandbox = Sandbox::new();
    folders(&sandbox);

    let planned = ok(
        &sandbox,
        &[
            "task",
            "copy",
            "remote:ENG-1",
            "--to",
            NOTES,
            "--dry-run",
            "--json",
        ],
    );
    assert_eq!(
        reported(&planned),
        vec![("remote:ENG-1".to_owned(), Value::Null, "created".to_owned())],
        "a dry run that would create has no destination id, because nothing was created"
    );
    assert!(
        !sandbox.project().join(NOTES).join("tasks").exists(),
        "a dry run writes nothing"
    );

    // And once something is there, a dry run over it names the id it would update.
    ok(&sandbox, &["task", "copy", "remote:ENG-1", "--to", NOTES]);
    let file = sandbox.project().join(NOTES).join("tasks/ENG-1.md");
    let before = std::fs::read(&file).expect("the copied Markdown is there");
    std::fs::write(
        &file,
        String::from_utf8(before.clone())
            .expect("UTF-8")
            .replace("title: Rate-limit", "title: Edited rate-limit"),
    )
    .expect("the edit lands");
    let edited = std::fs::read(&file).expect("the edited Markdown is there");

    let planned = ok(
        &sandbox,
        &[
            "task",
            "copy",
            "remote:ENG-1",
            "--to",
            NOTES,
            "--dry-run",
            "--json",
        ],
    );
    assert_eq!(
        reported(&planned),
        vec![(
            "remote:ENG-1".to_owned(),
            json!("notes:ENG-1"),
            "updated".to_owned()
        )]
    );
    assert_eq!(
        std::fs::read(&file).expect("the Markdown is still there"),
        edited,
        "a dry run over an item it would update still writes nothing"
    );
}

#[test]
fn a_destination_configured_with_no_write_side_exits_non_zero_naming_it_and_its_plugin() {
    let sandbox = Sandbox::new();
    sandbox.project_document(&document(&json!({
        SOURCE: {"plugin": "in-memory", "config": {"tasks": [
            {"id": "T-1", "title": "Alpha", "status": {"category": "todo", "name": "Todo"},
             "labels": []}
        ]}},
        "sealed": {"plugin": "in-memory", "config": {
            "capabilities": {"writes": "unsupported"}
        }},
    })));

    let said = refused(
        &sandbox,
        &["task", "copy", &qualified(SOURCE, "T-1"), "--to", "sealed"],
        1,
    );
    assert!(said.contains("source sealed cannot be written"), "{said}");
    assert!(said.contains("its plugin is in-memory"), "{said}");
    assert!(said.contains("sources list"), "{said}");
}

#[test]
fn a_destination_that_cannot_carry_a_key_refuses_the_write_naming_the_source_and_the_keys() {
    let sandbox = Sandbox::new();
    sandbox.project_document(&document(&json!({
        SOURCE: {"plugin": "in-memory", "config": {"tasks": [
            {"id": "T-1", "title": "Alpha", "status": {"category": "todo", "name": "Todo"},
             "labels": [], "metadata": {"caller.flags": [true, null], "caller.count": 3}}
        ]}},
        "picky": {"plugin": "in-memory", "config": {
            "capabilities": {"unwritable_metadata_keys": ["caller.flags", "caller.count"]}
        }},
    })));

    let said = refused(
        &sandbox,
        &["task", "copy", &qualified(SOURCE, "T-1"), "--to", "picky"],
        1,
    );
    assert!(said.contains("source picky could not do it"), "{said}");
    assert!(said.contains("caller.count, caller.flags"), "{said}");
    assert!(
        !said.contains("dropped"),
        "the keys are named rather than dropped: {said}"
    );
}

#[test]
fn a_stale_origin_refuses_and_recreate_falls_through_to_matching_by_origin_instead() {
    let sandbox = Sandbox::new();
    let remote = folders(&sandbox);
    ok(&sandbox, &["task", "copy", "remote:ENG-1", "--to", NOTES]);

    // Somebody deletes the counterpart at the destination on purpose.
    std::fs::remove_file(remote.join("tasks/ENG-1.md")).expect("the remote document goes away");

    let said = refused(
        &sandbox,
        &["task", "copy", "notes:ENG-1", "--to", "remote"],
        1,
    );
    assert!(
        said.contains("notes:ENG-1 was copied from remote:ENG-1"),
        "{said}"
    );
    assert!(said.contains("--recreate"), "{said}");

    let created = ok(
        &sandbox,
        &[
            "task",
            "copy",
            "notes:ENG-1",
            "--to",
            "remote",
            "--recreate",
            "--json",
        ],
    );
    assert_eq!(
        reported(&created),
        vec![(
            "notes:ENG-1".to_owned(),
            json!("remote:ENG-1"),
            "created".to_owned()
        )]
    );
}

#[test]
fn an_origin_a_person_removed_creates_until_match_by_re_establishes_the_correspondence() {
    let sandbox = Sandbox::new();
    folders(&sandbox);
    ok(&sandbox, &["task", "copy", "remote:ENG-1", "--to", NOTES]);

    // A person edits the Markdown and deletes the key: neither rule can find the
    // counterpart any more, so the next copy creates a second document.
    let file = sandbox.project().join(NOTES).join("tasks/ENG-1.md");
    let text = std::fs::read_to_string(&file).expect("the copied Markdown is there");
    std::fs::write(
        &file,
        text.replace("  onetaskgraph.origin: remote:ENG-1\n", ""),
    )
    .expect("the edit lands");

    let duplicated = ok(
        &sandbox,
        &["task", "copy", "remote:ENG-1", "--to", NOTES, "--json"],
    );
    assert_eq!(
        reported(&duplicated),
        vec![(
            "remote:ENG-1".to_owned(),
            json!("notes:ENG-1-2"),
            "created".to_owned()
        )]
    );

    // The caller-named escape re-establishes it without hand-editing ids.
    std::fs::remove_file(sandbox.project().join(NOTES).join("tasks/ENG-1-2.md"))
        .expect("the duplicate goes away");
    let matched = ok(
        &sandbox,
        &[
            "task",
            "copy",
            "remote:ENG-1",
            "--to",
            NOTES,
            "--match-by",
            "title",
            "--json",
        ],
    );
    assert_eq!(
        reported(&matched),
        vec![(
            "remote:ENG-1".to_owned(),
            json!("notes:ENG-1"),
            "updated".to_owned()
        )]
    );
}

#[test]
fn copying_a_project_carries_its_tasks_and_reports_one_the_source_no_longer_holds() {
    let sandbox = Sandbox::new();
    let root = sandbox.subdirectory("remote");
    for (kind, id, front) in [
        (
            "projects",
            "P-1",
            "title: Engine\nstatus: doing\ndepends_on: [{id: T-1, item: task}]",
        ),
        ("tasks", "T-1", "title: Alpha\nstatus: todo\nproject: P-1"),
        ("tasks", "T-2", "title: Beta\nstatus: todo\nproject: P-1"),
    ] {
        let path = root.join(kind).join(format!("{id}.md"));
        std::fs::create_dir_all(path.parent().expect("a parent")).expect("the folder");
        std::fs::write(path, format!("---\n{front}\n---\nbody\n")).expect("the document");
    }
    sandbox.project_document(&document(&json!({
        "remote": {"plugin": "local-md", "config": {
            "root": root,
            "status_mapping": {"todo": "todo", "doing": "in-progress"},
        }},
        NOTES: {"plugin": "local-md", "config": empty_folder(&sandbox, NOTES)},
    })));

    // A dry run of a project the destination does not hold yet still reads every task in
    // it and reports what each would have got — there is simply no destination id for any
    // of them, because nothing was written and the project they would be filed under does
    // not exist.
    let planned = ok(
        &sandbox,
        &[
            "project",
            "copy",
            "remote:P-1",
            "--to",
            NOTES,
            "--dry-run",
            "--json",
        ],
    );
    assert_eq!(
        reported(&planned),
        vec![
            ("remote:P-1".to_owned(), Value::Null, "created".to_owned()),
            ("remote:T-1".to_owned(), Value::Null, "created".to_owned()),
            ("remote:T-2".to_owned(), Value::Null, "created".to_owned()),
        ]
    );
    assert!(
        !sandbox.project().join(NOTES).join("tasks").exists()
            && !sandbox.project().join(NOTES).join("projects").exists(),
        "a dry run writes nothing"
    );

    let copied = ok(
        &sandbox,
        &["project", "copy", "remote:P-1", "--to", NOTES, "--json"],
    );
    assert_eq!(
        reported(&copied),
        vec![
            (
                "remote:P-1".to_owned(),
                json!("notes:P-1"),
                "created".to_owned()
            ),
            (
                "remote:T-1".to_owned(),
                json!("notes:T-1"),
                "created".to_owned()
            ),
            (
                "remote:T-2".to_owned(),
                json!("notes:T-2"),
                "created".to_owned()
            ),
        ]
    );
    // Each copied task is filed under the destination project rather than the source's.
    assert_eq!(
        shown(&sandbox, "task", "notes:T-1")["project"],
        json!("P-1")
    );
    let dependencies: Value =
        serde_json::from_str(&ok(&sandbox, &["project", "deps", "notes:P-1", "--json"]))
            .expect("project dependencies emit JSON");
    assert!(
        dependencies["items"]
            .as_array()
            .expect("dependency items")
            .contains(&json!({
                "from": {"id": "notes:P-1", "kind": "project"},
                "to": {"id": "notes:T-1", "kind": "task"},
                "kind": "blocks"
            })),
        "the copied project edge is recreated between destination items: {dependencies:#}"
    );

    // A second copy matches each task independently and duplicates nothing.
    let again = ok(
        &sandbox,
        &["project", "copy", "remote:P-1", "--to", NOTES, "--json"],
    );
    assert!(
        reported(&again)
            .iter()
            .all(|(_, _, action)| action == "unchanged"),
        "{again}"
    );

    // A destination item the source no longer holds is left alone and reported.
    std::fs::remove_file(root.join("tasks/T-2.md")).expect("the source drops a task");
    let orphaned = ok(
        &sandbox,
        &["project", "copy", "remote:P-1", "--to", NOTES, "--json"],
    );
    assert!(
        reported(&orphaned).contains(&(
            "remote:T-2".to_owned(),
            json!("notes:T-2"),
            "orphaned".to_owned()
        )),
        "{orphaned}"
    );
    assert_eq!(shown(&sandbox, "task", "notes:T-2")["title"], json!("Beta"));

    let alone = ok(
        &sandbox,
        &[
            "project",
            "copy",
            "remote:P-1",
            "--to",
            NOTES,
            "--no-tasks",
            "--json",
        ],
    );
    assert_eq!(reported(&alone).len(), 1);
}

#[test]
fn a_copy_that_cannot_run_at_all_exits_non_zero_with_a_suggested_next_action() {
    let sandbox = Sandbox::new();
    folders(&sandbox);

    for (arguments, expected) in [
        (
            vec!["task", "copy", "remote:absent", "--to", NOTES],
            "no item with the id remote:absent",
        ),
        (
            vec!["task", "copy", "remote:ENG-1", "--to", "nowhere"],
            "no source named \"nowhere\" is configured",
        ),
        (
            vec!["task", "copy", "ENG-1", "--to", NOTES],
            "is not a qualified id",
        ),
        (
            vec!["task", "copy", "remote:ENG-1", "--to", "NOT A NAME"],
            "--to NOT A NAME",
        ),
    ] {
        let said = refused(&sandbox, &arguments, 1);
        assert!(said.contains(expected), "{arguments:?}: {said}");
        assert!(said.contains("next:"), "{arguments:?}: {said}");
    }
}

/// A folder holding one project and two tasks in it, the second blocking the first.
///
/// The shape a plan is authored in: `A` cannot start until `B` is done, and both are part
/// of one project. Copying it is what needs the far end of that edge — an item the same
/// run is creating — to be findable at the destination.
fn plans_with_a_dependency(sandbox: &Sandbox) -> std::path::PathBuf {
    let root = sandbox.subdirectory("plans");
    std::fs::create_dir_all(root.join("projects")).unwrap();
    std::fs::create_dir_all(root.join("tasks")).unwrap();
    std::fs::write(
        root.join("projects/P-1.md"),
        "---\ntitle: Published roadmap\nstatus: Doing\n---\nThe permanent plan\n",
    )
    .unwrap();
    std::fs::write(
        root.join("tasks/A.md"),
        "---\ntitle: First step\nstatus: Todo\nproject: P-1\n\
         depends_on: [B]\n---\ndo this after B\n",
    )
    .unwrap();
    std::fs::write(
        root.join("tasks/B.md"),
        "---\ntitle: Second step\nstatus: Todo\nproject: P-1\n---\nthen this\n",
    )
    .unwrap();
    root
}

#[test]
fn a_copy_resolves_a_dependency_on_an_item_it_created_in_the_same_run() {
    // The defect: three runs of one project copy each created some items and then refused,
    // naming "GitHub dependency item <node-id> was not found" — an item that same run had
    // just created. GitHub's board read is eventually consistent, so the far end of an edge
    // written moments after its creation was routinely absent from the read that looked it
    // up. The board this runs against never shows the item most recently filed on it, which
    // is that hazard with the timing taken out of it.
    let sandbox = Sandbox::new();
    plans_with_a_dependency(&sandbox);
    sandbox.project_document(&document(&json!({
        "plans": {"plugin":"local-md","config":{
            "root": sandbox.subdirectory("plans"),
            "status_mapping": {"Todo":"todo","Doing":"in-progress","Shipped":"done"}}},
        "board": {"plugin":"github-projects",
                  "config": github_projects_reading_one_item_behind(&sandbox)}
    })));

    let output = run(
        &sandbox,
        &["project", "copy", "plans:P-1", "--to", "board", "--json"],
    );
    let said = stderr(&output);
    assert!(
        !said.contains("was not found"),
        "no item this run created is reported as missing: {said}"
    );
    assert_eq!(output.status.code(), Some(0), "{said}");

    let landed = reported(&stdout(&output));
    assert_eq!(
        landed
            .iter()
            .map(|(source, _, action)| (source.as_str(), action.as_str()))
            .collect::<Vec<_>>(),
        vec![
            ("plans:P-1", "created"),
            ("plans:A", "created"),
            ("plans:B", "created"),
        ]
    );

    // The edge is really there, read back through the binary's own dependency verb, and it
    // names the destination's item rather than the id it had at its source.
    let first = landed[1].1.as_str().expect("a created task id");
    let second = landed[2].1.as_str().expect("a created task id");
    let edges = ok(&sandbox, &["task", "deps", first]);
    assert!(
        edges.contains(second),
        "{first} depends on {second} at the destination:\n{edges}"
    );
    assert!(
        !edges.contains("plans:B"),
        "the far end is the destination's own item, not the id it had at its source:\n{edges}"
    );
}

#[test]
fn a_copy_that_cannot_finish_leaves_the_board_as_it_found_it() {
    // A copy is either complete or it never happened. Half of one has to be run again, and
    // the re-run is the mutation burst that trips GitHub's secondary rate limiter — which
    // then refuses even reads for the next fifty minutes. So the copy undoes the items it
    // created and the retry starts from the board it started from.
    //
    // The board here fails the first field write onto an item it has already filed: the
    // issue exists and is on the board when the refusal arrives, which is exactly the state
    // that used to be left behind.
    let sandbox = Sandbox::new();
    plans_with_a_dependency(&sandbox);
    sandbox.project_document(&document(&json!({
        "plans": {"plugin":"local-md","config":{
            "root": sandbox.subdirectory("plans"),
            "status_mapping": {"Todo":"todo","Doing":"in-progress","Shipped":"done"}}},
        "board": {"plugin":"github-projects",
                  "config": github_projects_failing_a_field_write_once(&sandbox)}
    })));

    let said = refused(
        &sandbox,
        &["project", "copy", "plans:P-1", "--to", "board"],
        1,
    );
    assert!(
        said.contains("Something went wrong while executing your query"),
        "the failure GitHub reported is what the caller is told: {said}"
    );
    assert!(
        !said.contains("could not be undone"),
        "this board takes its items back, so the copy must not report otherwise: {said}"
    );

    // Nothing of that copy is on the board: not the project written first, and not the
    // task whose creation landed before the refusal.
    let projects = ok(&sandbox, &["project", "list", "--source", "board"]);
    assert!(
        !projects.contains("Published roadmap"),
        "the destination holds none of that copy's items:\n{projects}"
    );
    let tasks = ok(&sandbox, &["task", "list", "--source", "board"]);
    for title in ["First step", "Second step"] {
        assert!(
            !tasks.contains(title),
            "the destination holds none of that copy's items:\n{tasks}"
        );
    }

    // And the retry is a clean one: the failure is spent, so the same copy now completes.
    let again = ok(
        &sandbox,
        &["project", "copy", "plans:P-1", "--to", "board", "--json"],
    );
    assert_eq!(
        reported(&again)
            .iter()
            .map(|(source, _, action)| (source.as_str(), action.as_str()))
            .collect::<Vec<_>>(),
        vec![
            ("plans:P-1", "created"),
            ("plans:A", "created"),
            ("plans:B", "created"),
        ]
    );
}

#[test]
fn a_copy_into_linear_that_cannot_finish_leaves_the_workspace_as_it_found_it() {
    // The same rule as the board above, against the other hosted destination this
    // repository ships: a copy is either complete or it never happened. Linear could not
    // take a project back until `projectDelete` was pinned, so a project copy that failed
    // part way left the project it had created behind — which is the state this asserts
    // is gone.
    //
    // The workspace here fails the relation between two issues it has already created, so
    // the refusal arrives with the project and both of its tasks landed: every kind of
    // item this copy can create is there to be taken back.
    let sandbox = Sandbox::new();
    plans_with_a_dependency(&sandbox);
    sandbox.project_document(&document(&json!({
        "plans": {"plugin":"local-md","config":{
            "root": sandbox.subdirectory("plans"),
            "status_mapping": {"Todo":"todo","Doing":"in-progress","Shipped":"done"}}},
        "work": {"plugin":"linear","config":linear_failing_a_relation_write_once(&sandbox)}
    })));

    let said = refused(
        &sandbox,
        &["project", "copy", "plans:P-1", "--to", "work"],
        1,
    );
    assert!(
        said.contains(LINEAR_REFUSED_WRITE),
        "the failure Linear reported is what the caller is told: {said}"
    );
    assert!(
        !said.contains("could not be undone"),
        "this workspace takes its items back, so the copy must not report otherwise: {said}"
    );

    // Nothing of that copy is in the workspace: not the project written first, and not
    // either task whose creation landed before the refusal.
    let projects = ok(&sandbox, &["project", "list", "--source", "work"]);
    assert!(
        !projects.contains("Published roadmap"),
        "the destination holds none of that copy's items:\n{projects}"
    );
    let tasks = ok(&sandbox, &["task", "list", "--source", "work"]);
    for title in ["First step", "Second step"] {
        assert!(
            !tasks.contains(title),
            "the destination holds none of that copy's items:\n{tasks}"
        );
    }

    // And the retry is a clean one: the failure is spent, so the same copy now completes.
    let again = ok(
        &sandbox,
        &["project", "copy", "plans:P-1", "--to", "work", "--json"],
    );
    assert_eq!(
        reported(&again)
            .iter()
            .map(|(source, _, action)| (source.as_str(), action.as_str()))
            .collect::<Vec<_>>(),
        vec![
            ("plans:P-1", "created"),
            ("plans:A", "created"),
            ("plans:B", "created"),
        ]
    );
}

#[test]
fn a_cleanup_that_also_fails_reports_the_write_that_failed_rather_than_the_tidy_up() {
    // Filing an item on a board is several calls, so a failure after the first leaves an
    // issue this run created and nobody asked for — which the source takes back. GitHub can
    // refuse that removal too, and what the caller is owed then is *why the copy stopped*.
    // The tidy-up's own failure is about an item they never asked to exist; reporting it
    // instead would leave them reading a deletion error for a copy they made.
    //
    // This board refuses the field write and then refuses the removal, so both failures are
    // real and the copy has to choose which one to say.
    let sandbox = Sandbox::new();
    let root = sandbox.subdirectory("plans");
    std::fs::create_dir_all(root.join("tasks")).unwrap();
    std::fs::write(
        root.join("tasks/A.md"),
        "---\ntitle: First step\nstatus: Doing\n---\ndo this first\n",
    )
    .unwrap();
    sandbox.project_document(&document(&json!({
        "plans": {"plugin":"local-md","config":{
            "root": root, "status_mapping": {"Doing":"in-progress"}}},
        "board": {"plugin":"github-projects",
                  "config": github_projects_failing_a_field_write_and_its_cleanup(&sandbox)}
    })));

    let said = refused(&sandbox, &["task", "copy", "plans:A", "--to", "board"], 1);
    assert!(
        said.contains("updateProjectV2ItemFieldValue"),
        "the failure that stopped the copy is what the caller is told: {said}"
    );
    assert!(
        !said.contains("deleteIssue"),
        "and not the failure of the tidy-up that followed it: {said}"
    );

    // The item the removal could not take back really is still there — the refusal above is
    // the whole of what the caller gets, so this is the state they are left in.
    let listed = ok(&sandbox, &["task", "list", "--source", "board"]);
    assert_eq!(
        listed.matches("First step").count(),
        1,
        "the removal failed, so the item it could not take back is on the board: {listed}"
    );

    // Both failures are spent, so the copy the caller runs next matches that item by title
    // rather than filing a second one for the same plan.
    let again = ok(
        &sandbox,
        &[
            "task",
            "copy",
            "plans:A",
            "--to",
            "board",
            "--match-by",
            "title",
            "--json",
        ],
    );
    let landed = reported(&again);
    assert_eq!(landed.len(), 1, "{again}");
    assert_eq!(landed[0].2, "updated", "{again}");
    let listed = ok(&sandbox, &["task", "list", "--source", "board"]);
    assert_eq!(
        listed.matches("First step").count(),
        1,
        "and one plan is one issue rather than two: {listed}"
    );
}

#[test]
fn a_creation_whose_filing_and_cleanup_both_fail_still_reports_the_filing() {
    // The earlier half of the same sequence: `createIssue` lands, filing it on the board
    // does not, and the removal that would take the created issue back is refused as well.
    // The caller is told why the copy stopped — an issue they never asked to exist failing
    // to be removed is not something they can act on, and reporting it would replace the
    // reason with a consequence.
    let sandbox = Sandbox::new();
    let root = sandbox.subdirectory("plans");
    std::fs::create_dir_all(root.join("tasks")).unwrap();
    std::fs::write(
        root.join("tasks/A.md"),
        "---\ntitle: First step\nstatus: Doing\n---\ndo this first\n",
    )
    .unwrap();
    sandbox.project_document(&document(&json!({
        "plans": {"plugin":"local-md","config":{
            "root": root, "status_mapping": {"Doing":"in-progress"}}},
        "board": {"plugin":"github-projects",
                  "config": github_projects_failing_to_file_and_its_cleanup(&sandbox)}
    })));

    let said = refused(&sandbox, &["task", "copy", "plans:A", "--to", "board"], 1);
    assert!(
        said.contains("addProjectV2ItemById"),
        "the failure that stopped the copy is what the caller is told: {said}"
    );
    assert!(
        !said.contains("deleteIssue"),
        "and not the failure of the tidy-up that followed it: {said}"
    );

    // The issue never reached the board, so nothing there answers for this plan — and the
    // retry, with both failures spent, files exactly one.
    let listed = ok(&sandbox, &["task", "list", "--source", "board"]);
    assert_eq!(listed.matches("First step").count(), 0, "{listed}");
    let again = ok(
        &sandbox,
        &["task", "copy", "plans:A", "--to", "board", "--json"],
    );
    assert_eq!(reported(&again)[0].2, "created", "{again}");
    let listed = ok(&sandbox, &["task", "list", "--source", "board"]);
    assert_eq!(listed.matches("First step").count(), 1, "{listed}");
}

/// The document-bearing destination the document copy journeys copy into.
const STORE: &str = "store";

/// Every row whose source holds documents; the rest assert the refusal below.
///
/// The copy *round trip* out of every one of these rows — created, read back, and matched
/// rather than duplicated on a second copy — needs a destination that outlives one
/// invocation, so it lives in `document_store.rs` beside the peer that provides one for
/// any source. What stays here is the pair of refusals, which write nothing and so need no
/// destination to read back, and the round trip out of the one row whose own plugin is a
/// destination that outlives an invocation.
fn documentary_rows() -> impl Iterator<Item = &'static crate::fixtures::Row> {
    ROWS.iter()
        .filter(|row| row.declared().documents.is_native())
}

#[test]
fn a_document_copy_into_a_source_that_has_none_is_refused_naming_it_and_its_plugin() {
    // Refused from the declaration rather than from a failed write, so nothing is read
    // first — the same shape the write-support refusal already has.
    for row in documentary_rows() {
        let sandbox = Sandbox::new();
        sandbox.project_document(&row.document_with_documentless(&sandbox, NOTES));

        let complaint = refused(
            &sandbox,
            &["document", "copy", &qualified(SOURCE, "D-1"), "--to", NOTES],
            1,
        );
        assert!(
            complaint.contains(NOTES) && complaint.contains("in-memory"),
            "{}: the refusal names the source and its plugin:\n{complaint}",
            row.name
        );
        assert!(
            complaint.contains("has no documents"),
            "{}: and says what is wrong with it:\n{complaint}",
            row.name
        );
    }
}

#[test]
fn a_document_copy_out_of_a_source_that_has_none_is_refused_naming_it_and_its_plugin() {
    for row in ROWS
        .iter()
        .filter(|row| !row.declared().documents.is_native())
    {
        let sandbox = Sandbox::new();
        sandbox.project_document(&row.document_with_store(&sandbox, STORE));

        let complaint = refused(
            &sandbox,
            &["document", "copy", &qualified(SOURCE, "D-1"), "--to", STORE],
            1,
        );
        assert!(
            complaint.contains(SOURCE) && complaint.contains(row.plugin),
            "{}: the refusal names the source and its plugin:\n{complaint}",
            row.name
        );
        assert!(
            complaint.contains("has no documents"),
            "{}: and says what is wrong with it:\n{complaint}",
            row.name
        );
    }
}

/// The Markdown folder these document journeys read out of, at one boundary or the other.
///
/// Both sources are the same plugin, and both go behind the boundary under test: a copy is
/// a read and a write, so putting only one side over the pipe would leave half the seam
/// driven by the in-process source.
fn markdown_pair(sandbox: &Sandbox, boundary: SourceBoundary) -> String {
    document(&json!({
        SOURCE: boundary.source("local-md", crate::fixtures::local_md_config(sandbox)),
        NOTES: boundary.source("local-md", empty_folder(sandbox, NOTES)),
    }))
}

/// Where the Markdown folder `name` holds the entity `id` of kind `verb`.
fn markdown_path(sandbox: &Sandbox, name: &str, verb: &str, id: &str) -> String {
    let path = sandbox
        .subdirectory(name)
        .join(format!("{verb}s"))
        .join(format!("{id}.md"));
    std::fs::canonicalize(&path)
        .unwrap_or_else(|error| panic!("{}: {error}", path.display()))
        .to_string_lossy()
        .into_owned()
}

#[test]
fn a_document_copies_into_a_folder_of_markdown_and_the_next_invocation_reads_it_all_back() {
    // A folder of Markdown outlives the invocation that wrote it, so this is the whole
    // round trip through the command line a user types: list, show, copy, and then a
    // *separate* run that reads back what landed. Driven at both boundaries, because a
    // plugin a process away must answer exactly what the in-process one does.
    for boundary in SOURCE_BOUNDARIES {
        let sandbox = Sandbox::new();
        sandbox.project_document(&markdown_pair(&sandbox, boundary));

        let listing = ok(&sandbox, &["document", "list", "--source", SOURCE]);
        for id in ["D-1", "D-2", "D-3"] {
            assert!(
                listing.contains(&qualified(SOURCE, id)),
                "{boundary:?}: the folder lists {id}:\n{listing}"
            );
        }
        assert!(
            listing.contains("Alpha design") && listing.contains("Loose note"),
            "{boundary:?}: a document list carries each title:\n{listing}"
        );

        // Shown, and where each of the three kinds is is the path of the file behind it.
        for (verb, id) in [("document", "D-1"), ("task", "T-1"), ("project", "P-1")] {
            let shown = ok(&sandbox, &[verb, "show", &qualified(SOURCE, id), "--json"]);
            let response: Value = serde_json::from_str(&shown).expect("a show emits JSON");
            assert_eq!(
                response["items"][0]["item"]["location"],
                json!({"path": markdown_path(&sandbox, "local-md", verb, id)}),
                "{boundary:?}: `{verb} show {id}` reports the file behind it:\n{shown}"
            );
        }

        let held = shown(&sandbox, "document", &qualified(SOURCE, "D-1"));

        let created = reported(&ok(
            &sandbox,
            &[
                "document",
                "copy",
                &qualified(SOURCE, "D-1"),
                "--to",
                NOTES,
                "--json",
            ],
        ));
        assert_eq!(
            created,
            vec![(
                qualified(SOURCE, "D-1"),
                json!(qualified(NOTES, "D-1")),
                "created".to_owned()
            )],
            "{boundary:?}"
        );
        // One file, under `documents/` and nowhere else.
        assert!(
            sandbox
                .subdirectory(NOTES)
                .join("documents/D-1.md")
                .is_file(),
            "{boundary:?}: the copy landed as one file under documents/"
        );

        // And a *later* invocation reads back every field the copy carried, with its JSON
        // types intact.
        let landed = shown(&sandbox, "document", &qualified(NOTES, "D-1"));
        for field in ["title", "content", "labels", "project", "repositories"] {
            assert_eq!(
                landed[field], held[field],
                "{boundary:?}: the folder holds {field} as the source reported it"
            );
        }
        for key in ["onepipeline.turn_budget", "caller.flags"] {
            assert_eq!(
                landed["metadata"][key], held["metadata"][key],
                "{boundary:?}: the folder holds the metadata key {key} with its JSON type intact"
            );
        }
        assert_eq!(
            landed["metadata"]["onetaskgraph.origin"],
            json!(qualified(SOURCE, "D-1")),
            "{boundary:?}: and the origin the copy recorded"
        );

        // The three a copy never writes, and so the only three a reader finds different:
        // the location is this folder's own file, and the URL and the times are absent
        // because this destination has none of its own to report.
        assert_eq!(
            landed["location"],
            json!({"path": markdown_path(&sandbox, NOTES, "document", "D-1")}),
            "{boundary:?}: the destination reports where *it* holds the document"
        );
        assert_ne!(
            landed["location"], held["location"],
            "{boundary:?}: which is not where the source held it"
        );
        for own in ["url", "created_at", "updated_at"] {
            assert_eq!(
                landed[own],
                json!(null),
                "{boundary:?}: {own} is the destination's own and was never written"
            );
        }

        // A second copy updates the one already there rather than adding a duplicate.
        let again = reported(&ok(
            &sandbox,
            &[
                "document",
                "copy",
                &qualified(SOURCE, "D-1"),
                "--to",
                NOTES,
                "--json",
            ],
        ));
        assert_eq!(
            again[0].1,
            json!(qualified(NOTES, "D-1")),
            "{boundary:?}: the second copy found the first one's document"
        );
        assert!(
            matches!(again[0].2.as_str(), "updated" | "unchanged"),
            "{boundary:?}: a second copy is not a second create: {:?}",
            again[0]
        );
        let listed = ok(&sandbox, &["document", "list", "--source", NOTES]);
        assert_eq!(
            listed
                .lines()
                .filter(|line| !line.trim().is_empty())
                .count(),
            1,
            "{boundary:?}: exactly one where there was one before:\n{listed}"
        );
    }
}

/// One `linear` source at `boundary`, carrying the credential name across the pipe.
///
/// `SourceBoundary::source` cannot do this for every plugin and must not try: §3.1 clears
/// a spawned plugin's environment, so a hosted source sees only the credentials its own
/// configuration *names*, and a source with no credential names none. This one has one.
fn linear_at(boundary: SourceBoundary, config: Value) -> Value {
    match boundary {
        SourceBoundary::Direct => json!({"plugin": "linear", "config": config}),
        SourceBoundary::Subprocess => json!({
            "plugin": "subprocess",
            "config": {
                "command": env!("CARGO_BIN_EXE_onetaskgraph-source"),
                "secrets": ["LINEAR_API_KEY"],
                "settings": {"kind": "linear", "config": config},
            },
        }),
    }
}

#[test]
fn a_document_copies_into_a_linear_workspace_and_the_next_invocation_reads_it_all_back() {
    // The whole round trip against Linear's own document type, through the command line a
    // user types: list, show, copy, and then a *separate* run that reads back what landed.
    // The responder holds its workspace in this process, so a destination written by one
    // invocation really is still there for the next one — which is what makes this a round
    // trip rather than an assertion about what a copy would have written.
    //
    // Driven at both boundaries, because a plugin a process away must answer exactly what
    // the in-process one does, and the credential has to cross that pipe for it to.
    for boundary in SOURCE_BOUNDARIES {
        let sandbox = Sandbox::new();
        sandbox.project_document(&document(&json!({
            SOURCE: linear_at(boundary, linear_block(&sandbox)),
            NOTES: linear_at(boundary, linear_empty_workspace(&sandbox)),
        })));

        let listing = ok(&sandbox, &["document", "list", "--source", SOURCE]);
        for id in ["D-1", "D-2", "D-3"] {
            assert!(
                listing.contains(&qualified(SOURCE, id)),
                "{boundary:?}: the workspace lists {id}:\n{listing}"
            );
        }
        assert!(
            listing.contains("Alpha design") && listing.contains("Loose note"),
            "{boundary:?}: a document list carries each title:\n{listing}"
        );

        // Shown, and where each of the three kinds is is a link a reader can open — never
        // a path, which is what a source over a remote service has none of.
        for (verb, id) in [("document", "D-1"), ("task", "T-1"), ("project", "P-1")] {
            let held = shown(&sandbox, verb, &qualified(SOURCE, id));
            let location = &held["location"];
            assert!(
                location["url"].as_str().is_some_and(|url| !url.is_empty()),
                "{boundary:?}: `{verb} show {id}` reports a link:\n{location}"
            );
            assert!(
                location.get("path").is_none(),
                "{boundary:?}: and only a link:\n{location}"
            );
        }

        let held = shown(&sandbox, "document", &qualified(SOURCE, "D-1"));

        let created = reported(&ok(
            &sandbox,
            &[
                "document",
                "copy",
                &qualified(SOURCE, "D-1"),
                "--to",
                NOTES,
                "--json",
            ],
        ));
        assert_eq!(created.len(), 1, "{boundary:?}: one document, one write");
        assert_eq!(created[0].0, qualified(SOURCE, "D-1"), "{boundary:?}");
        assert_eq!(created[0].2, "created", "{boundary:?}");
        let landed_id = created[0].1.as_str().expect("a destination id").to_owned();

        // And a *later* invocation reads back every field the copy carried, out of this
        // source's own trailing slot, with its JSON types intact.
        let landed = shown(&sandbox, "document", &landed_id);
        for field in ["title", "content", "project", "repositories"] {
            assert_eq!(
                landed[field], held[field],
                "{boundary:?}: the workspace holds {field} as the source reported it"
            );
        }
        for key in ["onepipeline.turn_budget", "caller.flags"] {
            assert_eq!(
                landed["metadata"][key], held["metadata"][key],
                "{boundary:?}: and the metadata key {key} with its JSON type intact"
            );
        }
        assert_eq!(
            landed["metadata"]["onetaskgraph.origin"],
            json!(qualified(SOURCE, "D-1")),
            "{boundary:?}: and the origin the copy recorded"
        );
        // The visible body is the text a person wrote: the slot the metadata above came
        // out of is not in it.
        assert!(
            !landed["content"]
                .as_str()
                .expect("a body")
                .contains("onetaskgraph.metadata"),
            "{boundary:?}: the slot is taken off the visible body:\n{}",
            landed["content"]
        );
        // Where the destination holds it is the destination's own page, not the source's.
        assert!(
            landed["location"]["url"]
                .as_str()
                .is_some_and(|url| !url.is_empty()),
            "{boundary:?}: the destination says where *it* holds the document"
        );
        assert_ne!(
            landed["location"], held["location"],
            "{boundary:?}: which is not where the source held it"
        );

        // A second copy updates the one already there rather than adding a duplicate.
        let again = reported(&ok(
            &sandbox,
            &[
                "document",
                "copy",
                &qualified(SOURCE, "D-1"),
                "--to",
                NOTES,
                "--json",
            ],
        ));
        assert_eq!(
            again[0].1,
            json!(landed_id),
            "{boundary:?}: the second copy found the first one's document"
        );
        assert!(
            matches!(again[0].2.as_str(), "updated" | "unchanged"),
            "{boundary:?}: a second copy is not a second create: {:?}",
            again[0]
        );
        let listed = ok(&sandbox, &["document", "list", "--source", NOTES]);
        assert_eq!(
            listed
                .lines()
                .filter(|line| !line.trim().is_empty())
                .count(),
            1,
            "{boundary:?}: exactly one where there was one before:\n{listed}"
        );
    }
}