onetaskgraph 0.2.13

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
//! 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::{Sandbox, 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_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"
        );
    }
    // The one thing that did change is the correspondence itself, which is the mechanism
    // rather than a field of the user's: the remote item now records where its last copy
    // came from, so the next edit finds it directly.
    assert_eq!(
        after["metadata"]["onetaskgraph.origin"],
        json!("notes:ENG-1")
    );
}

#[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"
    );
}

#[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}");
}