vissue-cli 0.3.0

vissue command line: plain-text issue tracking over per-project orgmode files
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
//! Command-line behaviour, exercised through the built binary.

use std::fs;
use std::path::Path;
use std::process::Command;

#[cfg(not(unix))]
#[test]
fn serve_is_unix_only() {
    let out = Command::new(env!("CARGO_BIN_EXE_vissue"))
        .arg("serve")
        .output()
        .expect("run vissue");
    assert!(!out.status.success());
    assert!(
        String::from_utf8_lossy(&out.stderr).contains("Unix-only"),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );
}

fn fixture_root() -> std::path::PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/fixture_vault")
}

fn vissue(args: &[&str]) -> std::process::Output {
    Command::new(env!("CARGO_BIN_EXE_vissue"))
        .args(["--root", fixture_root().to_str().unwrap()])
        .args(args)
        .output()
        .expect("run vissue")
}

fn stdout(out: &std::process::Output) -> String {
    String::from_utf8(out.stdout.clone()).unwrap()
}

#[test]
fn projects_lists_the_fixture_projects() {
    let out = vissue(&["projects"]);
    assert!(out.status.success());
    assert_eq!(stdout(&out), "atlas\nbeacon\n");
}

#[test]
fn count_and_list_accept_both_project_flags() {
    assert_eq!(stdout(&vissue(&["count", "-P", "atlas"])), "4\n");
    assert_eq!(stdout(&vissue(&["count", "-p", "atlas"])), "4\n");
    assert_eq!(stdout(&vissue(&["count", "--project", "atlas"])), "4\n");
    let listed = stdout(&vissue(&["list", "-P", "atlas"]));
    assert_eq!(listed.lines().count(), 4, "{listed}");
    assert!(listed.contains("atlas-1a2b"), "{listed}");
}

#[test]
fn export_emits_one_json_object_per_line() {
    let out = vissue(&["export", "-P", "beacon"]);
    assert!(out.status.success());
    let text = stdout(&out);
    assert_eq!(text.lines().count(), 2, "{text}");
    for line in text.lines() {
        let row: serde_json::Value = serde_json::from_str(line).unwrap();
        assert_eq!(row["project"], "beacon");
    }
}

#[test]
fn check_exits_zero_on_the_fixture() {
    let out = vissue(&["check"]);
    assert!(
        out.status.success(),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );
    assert!(stdout(&out).contains("0 error(s), 0 warning(s)"));
}

/// A report written into a body quotes org, and quoted org is not a definition.
///
/// The loop this guards is the ordinary one: an agent is handed an issue,
/// works, and writes its report back with `append`. Reports quote the heading
/// they were given, ids and all. If a quoted `:ID:` counted, a `:PARENT:` that
/// points nowhere would resolve against the mention and `check` would go quiet
/// on the one class of damage it exists to catch.
#[test]
fn an_id_quoted_in_a_report_does_not_resolve_a_broken_parent() {
    let dir = tempfile::tempdir().unwrap();
    fs::create_dir_all(dir.path().join("Software")).unwrap();
    let own = |args: &[&str]| -> std::process::Output {
        let mut argv = vec!["--root", dir.path().to_str().unwrap()];
        argv.extend_from_slice(args);
        Command::new(env!("CARGO_BIN_EXE_vissue"))
            .args(argv)
            .output()
            .unwrap()
    };

    own(&["create", "-p", "atlas", "The child", "-q"]);
    let issues = dir.path().join("Software/atlas/issues.org");
    let planted = fs::read_to_string(&issues)
        .unwrap()
        .replace(":CREATED:", ":PARENT:     ghost-9999\n:CREATED:");
    fs::write(&issues, planted).unwrap();

    let broken = own(&["check"]);
    assert!(
        !broken.status.success() && stdout(&broken).contains("ghost-9999"),
        "a parent that names nothing is an error: {}",
        stdout(&broken)
    );

    let host = stdout(&own(&["create", "-p", "atlas", "The report", "-q"]))
        .trim()
        .to_string();
    own(&[
        "append",
        &host,
        "--text",
        "The heading I was handed reads:\n:PROPERTIES:\n:ID: ghost-9999\n:END:\n",
    ]);

    let after = own(&["check"]);
    assert!(
        !after.status.success() && stdout(&after).contains("ghost-9999"),
        "quoting the id in a report silenced the check: {}",
        stdout(&after)
    );
}

#[test]
fn show_json_returns_an_object() {
    let out = vissue(&["show", "atlas-2c3d", "--json"]);
    assert!(out.status.success());
    let row: serde_json::Value = serde_json::from_str(&stdout(&out)).unwrap();
    assert_eq!(row["id"], "atlas-2c3d");
    assert_eq!(row["parent"], "atlas-1a2b");
}

#[test]
fn mirror_writes_a_file_and_reports_the_path() {
    let dir = tempfile::tempdir().unwrap();
    let target = dir.path().join("nested/mirror.org");
    let out = vissue(&["mirror", "-P", "atlas", "--out", target.to_str().unwrap()]);
    assert!(
        out.status.success(),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );
    assert!(stdout(&out).starts_with("wrote "));
    let text = fs::read_to_string(&target).unwrap();
    assert!(
        text.contains("# MIRROR: generated by `vissue mirror`"),
        "{text}"
    );
    assert!(text.contains("* atlas"), "{text}");
    assert!(!text.contains("* beacon"), "{text}");
}

#[test]
fn mirror_writes_to_stdout_on_a_dash() {
    let out = vissue(&["mirror", "--out", "-", "--format", "markdown"]);
    assert!(out.status.success());
    let text = stdout(&out);
    assert!(text.starts_with("# vissue mirror"), "{text}");
    assert!(text.contains("## atlas"), "{text}");
    assert!(text.contains("## beacon"), "{text}");
}

#[test]
fn an_unknown_mirror_format_fails_loudly() {
    let out = vissue(&["mirror", "--out", "-", "--format", "pdf"]);
    assert!(!out.status.success());
    assert!(String::from_utf8_lossy(&out.stderr).contains("unknown format"));
}

#[test]
fn whoami_prints_the_identity_a_claim_would_record() {
    let out = vissue(&["whoami"]);
    assert!(
        out.status.success(),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );
    let text = stdout(&out);
    assert!(!text.trim().is_empty(), "no identity printed");
}

#[test]
fn tui_help_names_offline() {
    let out = vissue(&["tui", "--help"]);
    assert!(
        out.status.success(),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );
    let text = stdout(&out);
    assert!(text.contains("--offline"), "{text}");
    assert!(text.contains("Never attach"), "{text}");
}

#[test]
fn hud_help_names_rofi_and_iced() {
    let out = vissue(&["hud", "--help"]);
    assert!(
        out.status.success(),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );
    let text = stdout(&out);
    assert!(text.contains("--mode"), "{text}");
    assert!(text.contains("rofi"), "{text}");
    assert!(text.contains("--rofi"), "{text}");
    assert!(text.contains("--iced"), "{text}");
    assert!(text.contains("--toggle"), "{text}");
}

#[test]
fn iced_hud_without_binary_exits_127() {
    let out = Command::new(env!("CARGO_BIN_EXE_vissue"))
        .args(["--root", fixture_root().to_str().unwrap(), "hud"])
        .env("VISSUE_HUD_BIN", "/nonexistent/vissue-hud")
        .env("PATH", "/nonexistent")
        .output()
        .expect("run vissue hud --iced");
    assert_eq!(out.status.code(), Some(127));
    let err = String::from_utf8_lossy(&out.stderr);
    assert!(err.contains("cargo install vissue-hud"), "{err}");
}

#[test]
fn hud_missing_override_bin_exits_127() {
    let out = Command::new(env!("CARGO_BIN_EXE_vissue"))
        .args(["--root", fixture_root().to_str().unwrap(), "hud", "--iced"])
        .env("VISSUE_HUD_BIN", "/nonexistent/vissue-hud")
        .output()
        .expect("run vissue hud --iced");
    assert_eq!(out.status.code(), Some(127));
    let err = String::from_utf8_lossy(&out.stderr);
    assert!(err.contains("cargo install vissue-hud"), "{err}");
}

#[cfg(not(unix))]
#[test]
fn tui_without_offline_is_unix_only() {
    let out = vissue(&["tui"]);
    assert!(!out.status.success());
    assert!(
        String::from_utf8_lossy(&out.stderr).contains("Unix-only"),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );
}

#[cfg(not(unix))]
#[test]
fn hud_without_offline_is_unix_only() {
    let out = vissue(&["hud"]);
    assert!(!out.status.success());
    assert!(
        String::from_utf8_lossy(&out.stderr).contains("Unix-only"),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );
}

#[test]
fn identity_reports_the_resolved_binary_root_and_prefix() {
    // `identity` answers the wrapper's old question, "which binary and which
    // tracker", and is distinct from `whoami`, which names the claimant.
    let text = stdout(&vissue(&["identity"]));
    assert!(text.contains("prefix: Software"), "{text}");
    assert!(text.contains("prefix=Software"), "{text}");
    assert!(text.contains("fixture_vault"), "{text}");
    assert!(text.contains("binary:"), "{text}");
}

#[test]
fn the_environment_can_name_the_claiming_identity() {
    let out = Command::new(env!("CARGO_BIN_EXE_vissue"))
        .args(["--root", fixture_root().to_str().unwrap()])
        .env("VISSUE_AGENT", "grind-worker-3")
        .arg("whoami")
        .output()
        .expect("run vissue");
    assert_eq!(
        String::from_utf8(out.stdout).unwrap().trim(),
        "grind-worker-3"
    );
}

#[test]
fn a_create_and_update_cycle_works_in_a_temporary_root() {
    let dir = tempfile::tempdir().unwrap();
    let root = dir.path().to_str().unwrap();
    let run = |args: &[&str]| {
        Command::new(env!("CARGO_BIN_EXE_vissue"))
            .args(["--root", root])
            .args(args)
            .output()
            .expect("run vissue")
    };

    let created = run(&["create", "-P", "demo", "--quiet", "first task"]);
    assert!(
        created.status.success(),
        "{}",
        String::from_utf8_lossy(&created.stderr)
    );
    let id = String::from_utf8(created.stdout)
        .unwrap()
        .trim()
        .to_string();
    assert!(id.starts_with("demo-"), "{id}");

    let updated = run(&["update", &id, "--state", "STARTED"]);
    assert!(updated.status.success());
    assert!(String::from_utf8_lossy(&updated.stdout).contains("state TODO -> STARTED"));

    let shown = run(&["show", &id]);
    assert!(String::from_utf8_lossy(&shown.stdout).contains("State:    STARTED"));
    assert_eq!(
        String::from_utf8_lossy(&run(&["count", "--ready"]).stdout),
        "1\n"
    );
}

#[test]
fn the_root_may_come_from_the_environment() {
    let out = Command::new(env!("CARGO_BIN_EXE_vissue"))
        .env("VISSUE_ROOT", fixture_root())
        .arg("projects")
        .output()
        .expect("run vissue");
    assert_eq!(String::from_utf8(out.stdout).unwrap(), "atlas\nbeacon\n");
}

#[test]
fn the_shared_issue_root_environment_is_supported() {
    let out = Command::new(env!("CARGO_BIN_EXE_vissue"))
        .env_remove("VISSUE_ROOT")
        .env("ISSUE_ROOT", fixture_root())
        .arg("projects")
        .output()
        .expect("run vissue");
    assert_eq!(String::from_utf8(out.stdout).unwrap(), "atlas\nbeacon\n");
}

#[test]
fn the_read_only_command_surface_dispatches_against_the_fixture() {
    let cases: &[(&[&str], &str)] = &[
        (&["list", "--json"], "\"id\": \"atlas-3e4f\""),
        (
            &["show", "atlas-1a2b"],
            "Title:    Parse the manifest header",
        ),
        (&["ready", "--json"], "\"id\": \"atlas-1a2b\""),
        (&["claims"], "fixture-agent"),
        (&["agenda", "--days", "5000"], "beacon-5j6k"),
        (&["hygiene", "--stale-days", "1"], "stale_claims=1"),
        (&["waiting-on", "atlas-1a2b"], "atlas-3e4f"),
        (
            &["body-excerpt", "atlas-1a2b"],
            "* STARTED [#A] Parse the manifest header",
        ),
        (&["search", "parser"], "atlas-1a2b"),
        (&["children", "atlas-1a2b"], "atlas-2c3d"),
        (&["ancestors", "atlas-3e4f", "--depth", "3"], "1 atlas-1a2b"),
        (&["impact", "atlas-1a2b", "--depth", "3"], "1 atlas-3e4f"),
        (
            &["related", "atlas-1a2b", "--format", "org"],
            "[[id:atlas-2c3d]",
        ),
        (&["stale", "--days", "1"], "beacon-5j6k"),
        (&["count", "--state", "TODO"], "2\n"),
        (
            &["tree", "atlas-1a2b", "--format", "dot"],
            "digraph vissue_tree",
        ),
        (&["cycles"], "no cycles"),
        (&["graph", "--project", "atlas"], "digraph vissue_graph"),
        (&["backlinks", "atlas-1a2b"], "atlas-2c3d"),
        (&["roadmap", "--project", "atlas"], "## atlas"),
        (&["digest", "--json"], "\"issues\": 6"),
    ];

    for (args, expected) in cases {
        let out = vissue(args);
        assert!(
            out.status.success(),
            "command {args:?} failed: {}",
            String::from_utf8_lossy(&out.stderr)
        );
        let text = stdout(&out);
        assert!(
            text.contains(expected),
            "command {args:?} did not contain {expected:?}: {text}"
        );
    }

    // `gen` and `events` read a log the fixture does not carry in git, so
    // anything that writes one -- a `vissue ping` in a checkout, an earlier
    // test -- would decide the answer. They are asked of a tracker this test
    // owns instead.
    let dir = tempfile::tempdir().unwrap();
    fs::create_dir_all(dir.path().join("Software")).unwrap();
    let own = |args: &[&str]| -> std::process::Output {
        let mut argv = vec!["--root", dir.path().to_str().unwrap()];
        argv.extend_from_slice(args);
        Command::new(env!("CARGO_BIN_EXE_vissue"))
            .args(argv)
            .output()
            .unwrap()
    };
    assert_eq!(stdout(&own(&["gen"])), "0\n");
    assert!(
        stdout(&own(&["events", "--since", "0"])).contains("generation=0 since=0 count=0"),
        "{}",
        stdout(&own(&["events", "--since", "0"]))
    );
}

/// `vissue export | head` closes the pipe once it has enough. The output has
/// to be larger than a pipe buffer for the writer to still be writing when
/// that happens, so this builds a corpus rather than using the fixture.
#[test]
fn a_reader_that_closes_the_pipe_is_not_a_failure() {
    use std::io::Read as _;
    use std::process::Stdio;

    let dir = tempfile::tempdir().unwrap();
    let root = dir.path().to_str().unwrap().to_string();
    for i in 0..400 {
        let out = Command::new(env!("CARGO_BIN_EXE_vissue"))
            .args(["--root", &root, "q", "-p", "demo"])
            .arg(format!(
                "issue {i} with a title long enough that four hundred of them exceed a pipe buffer"
            ))
            .output()
            .expect("run vissue");
        assert!(out.status.success());
    }

    let mut child = Command::new(env!("CARGO_BIN_EXE_vissue"))
        .args(["--root", &root, "export"])
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .expect("run vissue");

    // Read one line, then drop the pipe while the writer is mid-corpus.
    let mut stdout = child.stdout.take().unwrap();
    let mut first = [0u8; 64];
    stdout.read_exact(&mut first).unwrap();
    drop(stdout);

    let out = child.wait_with_output().expect("wait for vissue");
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(out.status.success(), "exited {:?}: {stderr}", out.status);
    assert!(stderr.is_empty(), "{stderr}");
}

/// The one command that replaces reading the file by hand.
///
/// Recovering an issue's text used to mean parsing `path:start-end` out of
/// `show` and running `sed` over the org file, because `show` printed the
/// range and stopped.
#[test]
fn show_org_writes_the_whole_heading() {
    let out = vissue(&["show", "--org", "atlas-1a2b"]);
    assert!(
        out.status.success(),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );
    let text = stdout(&out);
    assert!(text.starts_with("* STARTED [#A]"), "{text}");
    assert!(text.contains(":ID:         atlas-1a2b"), "{text}");
    assert!(
        text.contains(":LOGBOOK:"),
        "the notes travel with it: {text}"
    );
    assert!(
        text.contains("Scope: read the header block"),
        "the body travels with it: {text}"
    );
    // Nothing but the heading, so the output can be redirected into a file.
    assert!(!text.contains("File:"), "{text}");
    assert!(!text.contains("excerpt"), "{text}");
}

#[test]
fn show_prints_the_body_and_json_carries_it() {
    let text = stdout(&vissue(&["show", "atlas-2c3d"]));
    assert!(text.contains("Body:"), "{text}");
    assert!(text.contains("Scope: one row per parsed record"), "{text}");

    let row: serde_json::Value =
        serde_json::from_str(&stdout(&vissue(&["show", "atlas-2c3d", "--json"]))).unwrap();
    assert!(
        row["body"]
            .as_str()
            .unwrap()
            .contains("one row per parsed record"),
        "{row}"
    );
}

#[test]
fn show_org_and_json_are_not_asked_for_together() {
    let out = vissue(&["show", "--org", "--json", "atlas-1a2b"]);
    assert!(!out.status.success(), "{}", stdout(&out));
}

/// Recording a worker's report, the return half of handing work out.
#[test]
fn append_reads_a_file_and_stdin() {
    let dir = tempfile::tempdir().unwrap();
    let root = dir.path();
    std::fs::create_dir_all(root.join("Software")).unwrap();
    let mk = |args: &[&str]| -> std::process::Output {
        let mut argv = vec!["--root", root.to_str().unwrap()];
        argv.extend_from_slice(args);
        Command::new(env!("CARGO_BIN_EXE_vissue"))
            .args(argv)
            .output()
            .unwrap()
    };
    let id = String::from_utf8_lossy(
        &mk(&["create", "-p", "atlas", "--quiet", "Streaming exporter"]).stdout,
    )
    .trim()
    .to_string();

    let report = dir.path().join("SUMMARY.md");
    std::fs::write(&report, "## What changed\n\n* took a Read\n").unwrap();
    let out = mk(&["append", &id, "--file", report.to_str().unwrap()]);
    assert!(
        out.status.success(),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );

    let shown = String::from_utf8_lossy(&mk(&["show", &id]).stdout).to_string();
    assert!(shown.contains("## What changed"), "{shown}");
    assert!(shown.contains("took a Read"), "{shown}");

    // --text is the same thing without a file.
    assert!(mk(&["append", &id, "--text", "second pass"])
        .status
        .success());
    let shown = String::from_utf8_lossy(&mk(&["show", &id]).stdout).to_string();
    assert!(shown.contains("second pass"), "{shown}");

    // The tracker still reads back cleanly after markdown went in.
    let check = mk(&["check"]);
    assert!(
        check.status.success(),
        "{}",
        String::from_utf8_lossy(&check.stdout)
    );

    // Neither source given is an error, not an empty append.
    assert!(!mk(&["append", &id]).status.success());
}

/// `vissue keys` in its three shapes, against a chosen overlay.
///
/// The overlay path comes from the environment, so each case runs in its own
/// process with its own value rather than reassigning one the whole suite
/// shares.
#[test]
fn keys_prints_the_catalog_and_checks_an_overlay() {
    let dir = tempfile::tempdir().unwrap();
    let keys = |overlay: Option<&str>, args: &[&str]| -> std::process::Output {
        let mut cmd = Command::new(env!("CARGO_BIN_EXE_vissue"));
        cmd.args(["--root", fixture_root().to_str().unwrap(), "keys"]);
        cmd.args(args);
        match overlay {
            Some(path) => cmd.env("VISSUE_KEYS", path),
            None => cmd.env_remove("VISSUE_KEYS"),
        };
        cmd.output().unwrap()
    };

    // The catalog names every action with the chord that is live for it.
    let table = keys(None, &[]);
    assert!(table.status.success());
    let text = stdout(&table);
    for action in ["list.down", "issue.claim", "board.help"] {
        assert!(text.contains(action), "{action} missing: {text}");
    }

    let taken = keys(None, &["--occupancy"]);
    assert!(taken.status.success());
    assert!(stdout(&taken).contains('\t'), "{}", stdout(&taken));

    // A sound overlay checks out, and the rebound chord is what shows.
    let good = dir.path().join("good.toml");
    fs::write(&good, "[board]\n\"list.down\" = \"e\"\n").unwrap();
    let checked = keys(Some(good.to_str().unwrap()), &["--check"]);
    assert!(
        checked.status.success(),
        "{}",
        String::from_utf8_lossy(&checked.stderr)
    );
    assert!(stdout(&checked).trim() == "ok", "{}", stdout(&checked));
    let listed = stdout(&keys(Some(good.to_str().unwrap()), &[]));
    let row = listed
        .lines()
        .find(|l| l.contains("list.down"))
        .unwrap_or_else(|| panic!("no list.down row: {listed}"));
    assert_eq!(
        row.split_whitespace().last(),
        Some("e"),
        "the rebound chord is not shown: {row}"
    );

    // A conflicting one fails the check and says why.
    let bad = dir.path().join("bad.toml");
    fs::write(&bad, "[board]\n\"list.down\" = \"enter\"\n").unwrap();
    let refused = keys(Some(bad.to_str().unwrap()), &["--check"]);
    assert!(!refused.status.success());
    assert!(
        String::from_utf8_lossy(&refused.stderr).contains("reserved"),
        "{}",
        String::from_utf8_lossy(&refused.stderr)
    );
}

/// `hud --iced` hands the board the tracker it was pointed at.
///
/// The binary is replaced by a script that records its arguments, so what is
/// checked is the command line the CLI builds rather than a window.
#[test]
fn the_iced_hud_is_given_the_root_prefix_and_flags() {
    use std::os::unix::fs::PermissionsExt;

    let dir = tempfile::tempdir().unwrap();
    let record = dir.path().join("argv");
    let fake = dir.path().join("fake-hud");
    // Staged and renamed: a file written here and exec'd immediately can hit
    // ETXTBSY when another test thread forks while the descriptor is open.
    let staging = fake.with_extension("staging");
    fs::write(
        &staging,
        format!("#!/bin/sh\nprintf '%s\\n' \"$@\" > {}\n", record.display()),
    )
    .unwrap();
    let mut perm = fs::metadata(&staging).unwrap().permissions();
    perm.set_mode(0o755);
    fs::set_permissions(&staging, perm).unwrap();
    fs::rename(&staging, &fake).unwrap();

    let out = Command::new(env!("CARGO_BIN_EXE_vissue"))
        .args([
            "--root",
            fixture_root().to_str().unwrap(),
            "hud",
            "--iced",
            "--offline",
            "--toggle",
        ])
        .env("VISSUE_HUD_BIN", &fake)
        .output()
        .unwrap();
    assert!(
        out.status.success(),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );

    let argv = fs::read_to_string(&record).unwrap();
    let args: Vec<&str> = argv.lines().collect();
    assert!(args.contains(&"--root"), "{args:?}");
    assert!(args.contains(&"--prefix"), "{args:?}");
    assert!(args.contains(&"--offline"), "{args:?}");
    assert!(args.contains(&"--toggle"), "{args:?}");
    assert!(
        args.iter().any(|a| a.contains("fixture_vault")),
        "the board was not pointed at this tracker: {args:?}"
    );
}

#[test]
fn a_body_can_be_piped_in() {
    use std::io::Write;
    use std::process::Stdio;

    let dir = tempfile::tempdir().unwrap();
    std::fs::create_dir_all(dir.path().join("Software")).unwrap();
    let mut child = Command::new(env!("CARGO_BIN_EXE_vissue"))
        .args([
            "--root",
            dir.path().to_str().unwrap(),
            "create",
            "-p",
            "atlas",
            "--quiet",
            "--body-file",
            "-",
            "Read from a pipe",
        ])
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .spawn()
        .unwrap();
    child
        .stdin
        .take()
        .unwrap()
        .write_all(b"the body came down the pipe\n")
        .unwrap();
    let out = child.wait_with_output().unwrap();
    assert!(out.status.success());
    let id = String::from_utf8_lossy(&out.stdout).trim().to_string();

    let shown = Command::new(env!("CARGO_BIN_EXE_vissue"))
        .args(["--root", dir.path().to_str().unwrap(), "show", &id])
        .output()
        .unwrap();
    assert!(
        String::from_utf8_lossy(&shown.stdout).contains("the body came down the pipe"),
        "{}",
        String::from_utf8_lossy(&shown.stdout)
    );
}

/// The reference documents every subcommand the binary offers.
///
/// The command table is what a reader consults to find out what vissue can
/// do, so a verb missing from it is a verb that effectively does not exist.
/// Reading `--help` rather than a second list keeps the two together.
#[test]
fn the_reference_lists_every_subcommand() {
    let help = stdout(&vissue(&["--help"]));
    let mut in_commands = false;
    let mut commands: Vec<String> = Vec::new();
    for line in help.lines() {
        if line.starts_with("Commands:") {
            in_commands = true;
            continue;
        }
        if in_commands && line.starts_with("Options:") {
            break;
        }
        if !in_commands {
            continue;
        }
        // Subcommand rows are indented; continuation lines of a long
        // description are indented further and carry no verb.
        let trimmed = line.trim_start();
        if trimmed.is_empty() || line.len() - trimmed.len() > 4 {
            continue;
        }
        if let Some(name) = trimmed.split_whitespace().next() {
            if name != "help" {
                commands.push(name.to_string());
            }
        }
    }
    assert!(commands.len() > 20, "no subcommands parsed: {commands:?}");

    let reference = fs::read_to_string(
        Path::new(env!("CARGO_MANIFEST_DIR")).join("../../docs/orgmode/reference.org"),
    )
    .expect("reference");
    let missing: Vec<&String> = commands
        .iter()
        .filter(|name| !reference.contains(&format!("={name}=")))
        .collect();
    assert!(
        missing.is_empty(),
        "not in docs/orgmode/reference.org: {missing:?}"
    );
}

/// The change stream a poller lives on: `gen`, `wait`, `events`.
///
/// A tool that watches a tracker asks for the generation, blocks until it
/// moves, then reads what happened. The contract is in the exit code, so a
/// `wait` that returned the wrong one would send a poller into a spin or
/// leave it asleep through a change, and neither shows up as an error.
#[test]
fn the_change_stream_reports_and_blocks_the_way_a_poller_needs() {
    use std::time::Instant;

    let dir = tempfile::tempdir().unwrap();
    let root = dir.path();
    fs::create_dir_all(root.join("Software")).unwrap();
    let run = |args: &[&str]| -> std::process::Output {
        let mut argv = vec!["--root", root.to_str().unwrap()];
        argv.extend_from_slice(args);
        Command::new(env!("CARGO_BIN_EXE_vissue"))
            .args(argv)
            .output()
            .unwrap()
    };
    let gen_now = |run: &dyn Fn(&[&str]) -> std::process::Output| -> u64 {
        stdout(&run(&["gen"])).trim().parse().expect("a generation")
    };

    // An untouched tracker sits at zero and has nothing to report.
    assert_eq!(gen_now(&run), 0);
    let empty = stdout(&run(&["events", "--since", "0"]));
    assert!(empty.contains("count=0"), "{empty}");

    let id = stdout(&run(&["create", "-p", "atlas", "--quiet", "watch me"]))
        .trim()
        .to_string();
    let after_create = gen_now(&run);
    assert!(after_create > 0, "a write did not move the generation");

    // Already moved past --last: return at once rather than wait out the
    // timeout, or a poller that fell behind never catches up.
    let started = Instant::now();
    let caught_up = run(&["wait", "--last", "0", "--timeout-ms", "5000"]);
    assert!(
        caught_up.status.success(),
        "wait reported no change though the generation had moved"
    );
    assert!(
        started.elapsed() < std::time::Duration::from_secs(3),
        "wait sat out the timeout on a generation that had already moved"
    );
    assert_eq!(
        stdout(&caught_up).trim(),
        after_create.to_string(),
        "wait did not print the generation it woke at"
    );

    // Nothing changing is exit 2, which is how a poller tells a quiet
    // interval from a change it missed.
    let quiet = run(&[
        "wait",
        "--last",
        &after_create.to_string(),
        "--timeout-ms",
        "700",
    ]);
    assert_eq!(quiet.status.code(), Some(2), "{}", stdout(&quiet));

    // A write from another process wakes it.
    let mut poker = Command::new("sh")
        .arg("-c")
        .arg(format!(
            "sleep 1; {} --root {} note {id} poke >/dev/null 2>&1",
            env!("CARGO_BIN_EXE_vissue"),
            root.to_str().unwrap()
        ))
        .spawn()
        .unwrap();
    let woken = run(&[
        "wait",
        "--last",
        &after_create.to_string(),
        "--timeout-ms",
        "15000",
    ]);
    let _ = poker.wait();
    assert!(
        woken.status.success(),
        "wait slept through another process's write"
    );

    // The log says what happened, in both shapes it offers.
    let events = stdout(&run(&["events", "--since", "0"]));
    assert!(events.contains("issues_write"), "{events}");
    assert!(events.contains("atlas"), "{events}");
    let json = events
        .split("---json---")
        .nth(1)
        .unwrap_or_else(|| panic!("no json block: {events}"));
    let parsed: serde_json::Value = serde_json::from_str(json.trim()).expect("events JSON");
    let recorded = parsed["events"].as_array().expect("an events array");
    assert!(recorded.len() >= 2, "{parsed}");
    assert_eq!(recorded[0]["kind"], "issues_write", "{parsed}");
    assert_eq!(recorded[0]["project"], "atlas", "{parsed}");

    // Asking from the far end returns nothing rather than repeating.
    let tail = stdout(&run(&["events", "--since", &gen_now(&run).to_string()]));
    assert!(tail.contains("count=0"), "{tail}");
}

/// `mirror --check` answers by exit code, the part a script reads.
///
/// The core comparison is tested elsewhere. What a caller depends on is the
/// mapping onto an exit status: a stale copy that exits 0 is a shared backlog
/// everyone trusts and nobody regenerates.
#[test]
fn mirror_check_reports_freshness_in_its_exit_code() {
    let dir = tempfile::tempdir().unwrap();
    let root = dir.path();
    fs::create_dir_all(root.join("Software")).unwrap();
    let run = |args: &[&str]| -> std::process::Output {
        let mut argv = vec!["--root", root.to_str().unwrap()];
        argv.extend_from_slice(args);
        Command::new(env!("CARGO_BIN_EXE_vissue"))
            .args(argv)
            .output()
            .unwrap()
    };

    let id = stdout(&run(&["create", "-p", "atlas", "--quiet", "first"]))
        .trim()
        .to_string();
    run(&["create", "-p", "beacon", "--quiet", "second"]);

    let mirror = root.join("mirror.org");
    let written = run(&["mirror", "--out", mirror.to_str().unwrap()]);
    assert!(written.status.success(), "{}", stdout(&written));

    let fresh = run(&["mirror", "--check", mirror.to_str().unwrap()]);
    assert!(fresh.status.success(), "a new mirror read as stale");
    assert!(stdout(&fresh).contains("fresh:"), "{}", stdout(&fresh));

    // One note is enough to make the copy out of date.
    run(&["note", &id, "moved on"]);
    let stale = run(&["mirror", "--check", mirror.to_str().unwrap()]);
    assert_eq!(stale.status.code(), Some(1), "{}", stdout(&stale));
    let report = stdout(&stale);
    assert!(report.contains("stale:"), "{report}");
    // It names which project moved, so a regeneration is not a guess.
    assert!(report.contains("moved: atlas"), "{report}");

    // Regenerating settles it.
    run(&["mirror", "--out", mirror.to_str().unwrap()]);
    assert!(
        run(&["mirror", "--check", mirror.to_str().unwrap()])
            .status
            .success(),
        "a regenerated mirror still read as stale"
    );

    // A file that was never a mirror is stale rather than fresh: treating an
    // unstamped file as current is the failure worth avoiding.
    let prose = root.join("notes.org");
    fs::write(&prose, "just prose\n").unwrap();
    let unstamped = run(&["mirror", "--check", prose.to_str().unwrap()]);
    assert_eq!(unstamped.status.code(), Some(1), "{}", stdout(&unstamped));
    assert!(
        stdout(&unstamped).contains("no SYNC stamp"),
        "{}",
        stdout(&unstamped)
    );

    // So is one that is not there at all.
    let absent = run(&[
        "mirror",
        "--check",
        root.join("absent.org").to_str().unwrap(),
    ]);
    assert_eq!(absent.status.code(), Some(1));

    // A mirror of one project is checked against what it covered, not the
    // whole tracker, or it would read as stale the moment anything else moved.
    let atlas_only = root.join("atlas.org");
    run(&[
        "mirror",
        "-p",
        "atlas",
        "--out",
        atlas_only.to_str().unwrap(),
    ]);

    let beacon_id = stdout(&run(&["list", "-P", "beacon"]))
        .split_whitespace()
        .next()
        .expect("a beacon issue")
        .to_string();
    let elsewhere = run(&["note", &beacon_id, "elsewhere"]);
    assert!(
        elsewhere.status.success(),
        "the note that makes this test mean anything failed: {}",
        String::from_utf8_lossy(&elsewhere.stderr)
    );
    // The whole-tracker mirror does go stale, making the
    // atlas-only one staying fresh a scope check rather than a no-op.
    assert_eq!(
        run(&["mirror", "--check", mirror.to_str().unwrap()])
            .status
            .code(),
        Some(1),
        "the beacon note did not move the tracker at all"
    );
    assert!(
        run(&["mirror", "--check", atlas_only.to_str().unwrap()])
            .status
            .success(),
        "a change in another project staled an atlas-only mirror"
    );
}

/// Naming a project that does not exist creates it, and case folds.
///
/// This is what lets a tracker grow without a setup step, and it is also
/// why a typo files work somewhere real but unwatched, so it is worth
/// stating in a test as well as in the reference.
#[test]
fn a_project_comes_into_being_when_something_is_filed_there() {
    let dir = tempfile::tempdir().unwrap();
    let root = dir.path();
    fs::create_dir_all(root.join("Software")).unwrap();
    let run = |args: &[&str]| -> std::process::Output {
        let mut argv = vec!["--root", root.to_str().unwrap()];
        argv.extend_from_slice(args);
        Command::new(env!("CARGO_BIN_EXE_vissue"))
            .args(argv)
            .output()
            .unwrap()
    };
    let projects = |run: &dyn Fn(&[&str]) -> std::process::Output| -> Vec<String> {
        stdout(&run(&["projects"]))
            .lines()
            .map(str::to_string)
            .collect()
    };

    let id = stdout(&run(&["create", "-p", "atlas", "--quiet", "one"]))
        .trim()
        .to_string();
    assert_eq!(projects(&run), ["atlas"]);

    // A different case reaches the project that is already there rather
    // than making a second one beside it.
    let folded = run(&["create", "-p", "Atlas", "--quiet", "two"]);
    assert!(folded.status.success(), "{}", stdout(&folded));
    assert!(
        stdout(&folded).trim().starts_with("atlas-"),
        "{}",
        stdout(&folded)
    );
    assert_eq!(
        projects(&run),
        ["atlas"],
        "a case variant split the project"
    );

    // An unknown name is filed rather than refused, by create and by refile.
    let elsewhere = run(&["create", "-p", "brandnew", "--quiet", "three"]);
    assert!(elsewhere.status.success());
    assert!(projects(&run).contains(&"brandnew".to_string()));

    let moved = run(&["refile", &id, "--to", "somewhere-else"]);
    assert!(moved.status.success(), "{}", stdout(&moved));
    assert!(projects(&run).contains(&"somewhere-else".to_string()));
    // The id does not follow the project, so edges pointing at it still hold.
    let detail: serde_json::Value =
        serde_json::from_str(&stdout(&run(&["show", &id, "--json"]))).unwrap();
    assert_eq!(detail["id"], id.as_str());
    assert_eq!(detail["project"], "somewhere-else");

    // Two projects differing only by case are refused rather than guessed at.
    for name in ["Beacon", "beacon"] {
        let path = root.join("Software").join(name);
        fs::create_dir_all(&path).unwrap();
        fs::write(path.join("issues.org"), "#+TITLE: x\n").unwrap();
    }
    let ambiguous = run(&["create", "-p", "BEACON", "--quiet", "which one"]);
    assert!(!ambiguous.status.success(), "{}", stdout(&ambiguous));
    let err = String::from_utf8_lossy(&ambiguous.stderr);
    assert!(err.contains("ambiguous"), "{err}");
    assert!(err.contains("Beacon") && err.contains("beacon"), "{err}");
}

/// The blocker graph stays acyclic, and a corrupt one degrades safely.
///
/// `ready` is what a dispatcher takes work from, and it is defined by
/// walking blocker edges. A ring in that graph could spin it or make it
/// answer with work nobody can start, so the tracker refuses to write one
/// and survives finding one that was written by hand.
#[test]
fn a_blocker_ring_is_refused_and_a_planted_one_does_not_spin() {
    let dir = tempfile::tempdir().unwrap();
    let root = dir.path();
    fs::create_dir_all(root.join("Software")).unwrap();
    let run = |args: &[&str]| -> std::process::Output {
        let mut argv = vec!["--root", root.to_str().unwrap()];
        argv.extend_from_slice(args);
        Command::new(env!("CARGO_BIN_EXE_vissue"))
            .args(argv)
            .output()
            .unwrap()
    };
    let mk = |title: &str| {
        stdout(&run(&["create", "-p", "atlas", "--quiet", title]))
            .trim()
            .to_string()
    };

    let (a, b, c) = (mk("A"), mk("B"), mk("C"));

    // A legal chain: C waits on B waits on A, so only A is ready.
    assert!(run(&["update", &b, "--block", &a]).status.success());
    assert!(run(&["update", &c, "--block", &b]).status.success());
    assert!(stdout(&run(&["cycles"])).contains("no cycles"));
    let ready = stdout(&run(&["ready"]));
    assert_eq!(ready.lines().count(), 1, "{ready}");
    assert!(
        ready.contains(&a),
        "the root of the chain is the ready one: {ready}"
    );

    // Closing the ring is refused, and says what it would have made.
    let ring = run(&["update", &a, "--block", &c]);
    assert_eq!(ring.status.code(), Some(1), "{}", stdout(&ring));
    let err = String::from_utf8_lossy(&ring.stderr);
    assert!(err.contains("blocker cycle"), "{err}");

    // So is an issue blocking itself, and it reads differently.
    let own = run(&["update", &a, "--block", &a]);
    assert_eq!(own.status.code(), Some(1), "{}", stdout(&own));
    let err = String::from_utf8_lossy(&own.stderr);
    assert!(err.contains("cannot block itself"), "{err}");

    // Neither refusal left anything behind.
    assert!(stdout(&run(&["cycles"])).contains("no cycles"));
    assert!(run(&["check"]).status.success());

    // A ring written straight into the file, which nothing can prevent.
    let path = root.join("Software/atlas/issues.org");
    let text = fs::read_to_string(&path).unwrap();
    fs::write(
        &path,
        text.replace(
            &format!(":ID:         {a}\n"),
            &format!(":ID:         {a}\n:BLOCKED_BY: {c}\n"),
        ),
    )
    .unwrap();

    // The ring is named, not counted, so it can be repaired.
    let found = stdout(&run(&["cycles"]));
    for id in [&a, &b, &c] {
        assert!(found.contains(id.as_str()), "{found}");
    }
    // check refuses the corpus.
    let checked = run(&["check"]);
    assert_eq!(checked.status.code(), Some(1), "{}", stdout(&checked));

    // And the dispatcher gets nothing rather than a spin or phantom work.
    let ready = run(&["ready"]);
    assert!(
        ready.status.success(),
        "ready failed outright: {}",
        String::from_utf8_lossy(&ready.stderr)
    );
    assert!(
        stdout(&ready).trim().is_empty(),
        "a ring offered work anyway: {}",
        stdout(&ready)
    );
}

/// Concurrent writers do not lose each other's work.
///
/// Every mutation is a read-modify-write of a whole `issues.org`, so two
/// processes that overlap without the advisory lock will each write a file
/// built from what they read before the other landed. The loser's issue is
/// gone, and nothing reports it: the tracker stays valid, just smaller.
///
/// Separate processes rather than threads, because that is the case the lock
/// exists for and the only one an in-process mutex cannot cover.
#[test]
fn concurrent_writers_all_land() {
    use std::process::Stdio;

    let dir = tempfile::tempdir().unwrap();
    let root = dir.path();
    fs::create_dir_all(root.join("Software")).unwrap();

    const WRITERS: usize = 12;
    let mut kids = Vec::with_capacity(WRITERS);
    for i in 0..WRITERS {
        kids.push(
            Command::new(env!("CARGO_BIN_EXE_vissue"))
                .args([
                    "--root",
                    root.to_str().unwrap(),
                    "create",
                    "-p",
                    "atlas",
                    "--quiet",
                    &format!("writer {i}"),
                ])
                .stdout(Stdio::null())
                .stderr(Stdio::piped())
                .spawn()
                .unwrap(),
        );
    }
    for (i, kid) in kids.into_iter().enumerate() {
        let out = kid.wait_with_output().unwrap();
        assert!(
            out.status.success(),
            "writer {i} failed: {}",
            String::from_utf8_lossy(&out.stderr)
        );
    }

    let run = |args: &[&str]| -> std::process::Output {
        let mut argv = vec!["--root", root.to_str().unwrap()];
        argv.extend_from_slice(args);
        Command::new(env!("CARGO_BIN_EXE_vissue"))
            .args(argv)
            .output()
            .unwrap()
    };

    // Every writer reported success, so every issue has to be there.
    let count: usize = stdout(&run(&["count"])).trim().parse().expect("a count");
    assert_eq!(count, WRITERS, "a write was lost: {count} of {WRITERS}");

    // Each one by title, so a count that happens to match cannot hide a
    // duplicate standing in for a loser.
    let listed = stdout(&run(&["list"]));
    for i in 0..WRITERS {
        assert!(
            listed.contains(&format!("writer {i}")),
            "writer {i} is missing: {listed}"
        );
    }

    // The file a race leaves behind is usually still valid, and that is what
    // makes the loss quiet. Check anyway.
    assert!(
        run(&["check"]).status.success(),
        "{}",
        stdout(&run(&["check"]))
    );
}