pigeon-cli 0.4.28

Pigeon: authenticate, sink, and transform personal data from external services.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
use std::fs;

use assert_cmd::Command;
use predicates::prelude::*;
use tempfile::TempDir;

fn pigeon() -> Command {
    Command::cargo_bin("pigeon").unwrap()
}

/// A `pigeon` invocation isolated to a throwaway `PIGEON_CONFIG_DIR`, so
/// tests never read or write the developer's real keyring metadata file.
fn pigeon_in(config_dir: &TempDir) -> Command {
    let mut cmd = pigeon();
    cmd.env("PIGEON_CONFIG_DIR", config_dir.path());
    cmd
}

/// Writes a fake `keyring.toml` entry directly (no `keyring add` needed for
/// the error paths these tests exercise, which fail before ever reaching a
/// secret lookup or a real IMAP/S3 connection). Appends, so multiple calls
/// build up a mixed store. Includes a dummy secret field (ADR-0135: `secret`/
/// `secret_key` have no `#[serde(default)]`, so a real `keyring.toml` entry
/// always carries one).
fn write_identity(config_dir: &TempDir, alias: &str, email: &str) {
    append_keyring_entry(
        config_dir,
        &format!(
            "[[entries]]\nkind = \"email\"\nalias = \"{alias}\"\nemail = \"{email}\"\nprovider = \"gmail\"\nhost = \"imap.gmail.com\"\nport = 993\nsecret = \"fake-secret\"\n"
        ),
    );
}

fn write_bucket_config(config_dir: &TempDir, alias: &str) {
    append_keyring_entry(
        config_dir,
        &format!(
            "[[entries]]\nkind = \"bucket\"\nalias = \"{alias}\"\nendpoint = \"https://nyc3.digitaloceanspaces.com\"\nbucket = \"my-bucket\"\naccess_key_id = \"AKID\"\nsecret_key = \"fake-secret\"\n"
        ),
    );
}

fn append_keyring_entry(config_dir: &TempDir, toml_block: &str) {
    let path = config_dir.path().join("keyring.toml");
    let existing = fs::read_to_string(&path).unwrap_or_default();
    fs::write(path, existing + toml_block).unwrap();
}

/// Writes a bucket-config to an arbitrary `keyring.toml` outside any
/// `PIGEON_CONFIG_DIR`, for the `--keyring-path` tests (ADR-0145). Mirrors
/// `write_bucket_config`'s entry shape; takes a file path rather than a
/// config directory, which is exactly the distinction the flag draws.
///
/// The endpoint is an unroutable loopback port rather than
/// `write_bucket_config`'s plausible-looking URL, so that a test which
/// accidentally got past alias resolution would fail locally instead of
/// making a real network call to a third party. No test here should reach
/// one: rclone's `--retries 5 --low-level-retries 20` turns even a refused
/// connection into minutes of backoff.
fn write_bucket_config_at(keyring_path: &std::path::Path, alias: &str) {
    fs::write(
        keyring_path,
        format!(
            "[[entries]]\nkind = \"bucket\"\nalias = \"{alias}\"\nendpoint = \"http://127.0.0.1:1\"\nbucket = \"my-bucket\"\naccess_key_id = \"AKID\"\nsecret_key = \"fake-secret\"\n"
        ),
    )
    .unwrap();
}

#[test]
fn top_level_help_lists_keyring_and_job_commands() {
    pigeon()
        .arg("--help")
        .assert()
        .success()
        .stdout(predicate::str::contains("keyring"))
        .stdout(predicate::str::contains("job"));
}

#[test]
fn keyring_help_lists_all_subcommands() {
    pigeon()
        .args(["keyring", "--help"])
        .assert()
        .success()
        .stdout(predicate::str::contains("add"))
        .stdout(predicate::str::contains("modify"))
        .stdout(predicate::str::contains("delete"))
        .stdout(predicate::str::contains("list"));
}

#[test]
fn keyring_add_help_lists_email_and_bucket() {
    pigeon()
        .args(["keyring", "add", "--help"])
        .assert()
        .success()
        .stdout(predicate::str::contains("email"))
        .stdout(predicate::str::contains("bucket"));
}

#[test]
fn keyring_add_email_help_lists_provider_and_custom_host_flags() {
    pigeon()
        .args(["keyring", "add", "email", "--help"])
        .assert()
        .success()
        .stdout(predicate::str::contains("--provider"))
        .stdout(predicate::str::contains("--host"))
        .stdout(predicate::str::contains("--port"));
}

#[test]
fn keyring_add_bucket_help_shows_optional_alias() {
    pigeon()
        .args(["keyring", "add", "bucket", "--help"])
        .assert()
        .success()
        .stdout(predicate::str::contains("[ALIAS]"));
}

#[test]
fn keyring_list_on_empty_store_says_so() {
    let config_dir = TempDir::new().unwrap();

    pigeon_in(&config_dir)
        .args(["keyring", "list"])
        .assert()
        .success()
        .stdout(predicate::str::contains("No keyring entries configured."));
}

#[test]
fn log_file_flag_writes_valid_jsonl_with_the_command_name() {
    let config_dir = TempDir::new().unwrap();
    let log_dir = TempDir::new().unwrap();
    let log_file = log_dir.path().join("out.jsonl");

    pigeon_in(&config_dir)
        .args(["--log-file"])
        .arg(&log_file)
        .args(["--no-metrics", "keyring", "list"])
        .assert()
        .success();

    let contents = fs::read_to_string(&log_file).unwrap();
    assert!(!contents.trim().is_empty());

    let mut saw_command_name = false;
    for line in contents.lines() {
        let value: serde_json::Value = serde_json::from_str(line)
            .unwrap_or_else(|err| panic!("invalid JSON line {line:?}: {err}"));
        let text = value.to_string();
        if text.contains("keyring.list") {
            saw_command_name = true;
        }
    }
    assert!(
        saw_command_name,
        "expected at least one log line naming the keyring.list command, got: {contents}"
    );
}

#[test]
fn keyring_list_shows_both_kinds() {
    let config_dir = TempDir::new().unwrap();
    write_identity(&config_dir, "first-last", "first.last@example.com");
    write_bucket_config(&config_dir, "backup");

    pigeon_in(&config_dir)
        .args(["keyring", "list"])
        .assert()
        .success()
        .stdout(predicate::str::contains("email"))
        .stdout(predicate::str::contains("first-last"))
        .stdout(predicate::str::contains("bucket"))
        .stdout(predicate::str::contains("backup"));
}

#[test]
fn keyring_add_email_custom_provider_without_host_fails_fast() {
    let config_dir = TempDir::new().unwrap();

    pigeon_in(&config_dir)
        .args([
            "keyring",
            "add",
            "email",
            "first.last@example.com",
            "--provider",
            "custom",
        ])
        .assert()
        .failure()
        .code(1)
        .stderr(predicate::str::contains("--host is required"));
}

#[test]
fn keyring_add_email_failure_does_not_persist_an_entry() {
    let config_dir = TempDir::new().unwrap();

    // Nothing listens on 127.0.0.1:1 (a privileged, unassigned port), so
    // this deterministically fails at the connection step without ever
    // reaching a real IMAP server.
    pigeon_in(&config_dir)
        .args([
            "keyring",
            "add",
            "email",
            "first.last@example.com",
            "--alias",
            "first-last",
            "--provider",
            "custom",
            "--host",
            "127.0.0.1",
            "--port",
            "1",
        ])
        .write_stdin("fake-secret\n")
        .assert()
        .failure()
        .code(1)
        .stderr(predicate::str::contains("failed to connect"));

    pigeon_in(&config_dir)
        .args(["keyring", "list"])
        .assert()
        .success()
        .stdout(predicate::str::contains("No keyring entries configured."));
}

#[test]
fn keyring_add_email_with_alias_already_used_by_a_bucket_config_is_rejected() {
    let config_dir = TempDir::new().unwrap();
    write_bucket_config(&config_dir, "shared-alias");

    // Proves alias uniqueness is enforced globally, across kinds, per
    // ADR-0022 -- not just within email identities the way it worked before.
    pigeon_in(&config_dir)
        .args([
            "keyring",
            "add",
            "email",
            "first.last@example.com",
            "--alias",
            "shared-alias",
        ])
        .assert()
        .failure()
        .code(1)
        .stderr(predicate::str::contains(
            "an entry named 'shared-alias' already exists",
        ));
}

#[test]
fn keyring_modify_with_unknown_alias_fails_fast() {
    let config_dir = TempDir::new().unwrap();

    pigeon_in(&config_dir)
        .args(["keyring", "modify", "no-such-alias"])
        .assert()
        .failure()
        .code(1)
        .stderr(predicate::str::contains("no entry named 'no-such-alias'"));
}

#[test]
fn keyring_delete_with_unknown_alias_fails_fast() {
    let config_dir = TempDir::new().unwrap();

    pigeon_in(&config_dir)
        .args(["keyring", "delete", "no-such-alias"])
        .assert()
        .failure()
        .code(1)
        .stderr(predicate::str::contains("no entry named 'no-such-alias'"));
}

#[test]
fn keyring_delete_declined_keeps_it() {
    let config_dir = TempDir::new().unwrap();
    write_bucket_config(&config_dir, "backup");

    pigeon_in(&config_dir)
        .args(["keyring", "delete", "backup"])
        .write_stdin("n\n")
        .assert()
        .success()
        .stdout(predicate::str::contains("Cancelled."));

    let contents = fs::read_to_string(config_dir.path().join("keyring.toml")).unwrap();
    assert!(contents.contains("backup"));
}

/// Confirming removes the entry from `keyring.toml` directly (ADR-0135: the
/// secret lives in the same file, so removing the entry removes the secret
/// too -- no separate keychain delete step).
#[test]
fn keyring_delete_confirmed_deletes_it() {
    let config_dir = TempDir::new().unwrap();
    write_bucket_config(&config_dir, "backup");

    pigeon_in(&config_dir)
        .args(["keyring", "delete", "backup"])
        .write_stdin("y\n")
        .assert()
        .success()
        .stdout(predicate::str::contains("Removed 'backup'."));

    let contents = fs::read_to_string(config_dir.path().join("keyring.toml")).unwrap();
    assert!(!contents.contains("backup"));
}

#[test]
fn job_help_lists_run_subcommand() {
    pigeon()
        .args(["job", "--help"])
        .assert()
        .success()
        .stdout(predicate::str::contains("run"));
}

#[test]
fn job_run_help_lists_deduplicate() {
    pigeon()
        .args(["job", "run", "--help"])
        .assert()
        .success()
        .stdout(predicate::str::contains("deduplicate"));
}

#[test]
fn job_run_deduplicate_help_shows_source_bucket_and_concurrency_flags() {
    pigeon()
        .args(["job", "run", "deduplicate", "--help"])
        .assert()
        .success()
        .stdout(predicate::str::contains("--source-bucket"))
        .stdout(predicate::str::contains("--local-output"))
        .stdout(predicate::str::contains("--destination-bucket"))
        .stdout(predicate::str::contains("--concurrency"))
        .stdout(predicate::str::contains("--transfers"))
        .stdout(predicate::str::contains("--checkers"))
        .stdout(predicate::str::contains("--tpslimit"))
        .stdout(predicate::str::contains("--upload-only"))
        .stdout(predicate::str::contains("--report-bucket"))
        .stdout(predicate::str::contains("--non-interactive"))
        // ADR-0136: upload is now one bulk `rclone copy`, tuned by
        // --transfers/--checkers/--tpslimit, not --upload-concurrency.
        .stdout(predicate::str::contains("--upload-concurrency").not())
        // ADR-0082 §0/§1: deduplicate never offers encryption or file-type/
        // zip-expansion selection -- every file is always processed and
        // every zip is always expanded.
        .stdout(predicate::str::contains("--encryption-key").not())
        .stdout(predicate::str::contains("--file-types").not())
        .stdout(predicate::str::contains("--expand-zips").not());
}

#[test]
fn job_run_deduplicate_without_source_bucket_fails_fast_non_interactively() {
    let config_dir = TempDir::new().unwrap();
    let local_output = TempDir::new().unwrap();

    pigeon_in(&config_dir)
        .args([
            "job",
            "run",
            "deduplicate",
            "--local-output",
            local_output.path().to_str().unwrap(),
            "--concurrency",
            "4",
            "--non-interactive",
        ])
        .assert()
        .failure()
        .code(1)
        .stderr(predicate::str::contains(
            "--source-bucket is required when not running interactively",
        ));
}

#[test]
fn job_run_deduplicate_upload_only_without_a_completed_run_fails_fast() {
    let config_dir = TempDir::new().unwrap();
    let local_output = TempDir::new().unwrap();

    // No --source-bucket, no --destination-bucket: the preflight check
    // (ADR-0089) must fail before either would ever be resolved, since this
    // empty --local-output never ran a deduplicate pass at all.
    pigeon_in(&config_dir)
        .args([
            "job",
            "run",
            "deduplicate",
            "--upload-only",
            "--local-output",
            local_output.path().to_str().unwrap(),
            "--non-interactive",
        ])
        .assert()
        .failure()
        .code(1)
        .stderr(predicate::str::contains(
            "no completed deduplicate run found",
        ));
}

#[test]
fn job_run_deduplicate_accepts_a_repeated_source_bucket_flag() {
    // Two --source-bucket occurrences (ADR-0109) -- neither bucket exists,
    // so this just exercises that the repeated flag parses into a Vec and
    // every alias gets validated (the second, unknown one is what trips the
    // failure), not that a real multi-bucket run succeeds end-to-end.
    let config_dir = TempDir::new().unwrap();
    let local_output = TempDir::new().unwrap();

    pigeon_in(&config_dir)
        .args([
            "job",
            "run",
            "deduplicate",
            "--source-bucket",
            "no-such-bucket-a",
            "--source-bucket",
            "no-such-bucket-b",
            "--local-output",
            local_output.path().to_str().unwrap(),
            "--concurrency",
            "4",
            "--non-interactive",
        ])
        .assert()
        .failure()
        .code(1)
        .stderr(predicate::str::contains(
            "no bucket-config named 'no-such-bucket-a'",
        ));
}

#[test]
fn job_run_deduplicate_upload_only_without_destination_bucket_fails_fast() {
    let config_dir = TempDir::new().unwrap();
    let local_output = TempDir::new().unwrap();
    // A completed-looking prior run, so the preflight check passes and
    // --destination-bucket's own resolution is actually reached.
    fs::create_dir_all(local_output.path().join(".staging")).unwrap();
    fs::write(
        local_output.path().join(".staging").join(".processed"),
        b"bucket-a\ta.txt\n",
    )
    .unwrap();
    fs::create_dir_all(local_output.path().join("result")).unwrap();
    fs::write(local_output.path().join("result").join("a.txt"), b"a").unwrap();

    pigeon_in(&config_dir)
        .args([
            "job",
            "run",
            "deduplicate",
            "--upload-only",
            "--local-output",
            local_output.path().to_str().unwrap(),
            "--non-interactive",
        ])
        .assert()
        .failure()
        .code(1)
        .stderr(predicate::str::contains(
            "--destination-bucket is required with --upload-only",
        ));
}

#[test]
fn job_run_deduplicate_with_unknown_bucket_fails_fast() {
    let config_dir = TempDir::new().unwrap();
    let local_output = TempDir::new().unwrap();

    pigeon_in(&config_dir)
        .args([
            "job",
            "run",
            "deduplicate",
            "--source-bucket",
            "no-such-bucket",
            "--local-output",
            local_output.path().to_str().unwrap(),
            "--concurrency",
            "4",
            "--non-interactive",
        ])
        .assert()
        .failure()
        .code(1)
        .stderr(predicate::str::contains(
            "no bucket-config named 'no-such-bucket'",
        ));
}

#[test]
fn job_run_help_lists_rclone() {
    pigeon()
        .args(["job", "run", "--help"])
        .assert()
        .success()
        .stdout(predicate::str::contains("rclone"));
}

#[test]
fn job_run_rclone_help_lists_copy_and_delete() {
    pigeon()
        .args(["job", "run", "rclone", "--help"])
        .assert()
        .success()
        .stdout(predicate::str::contains("copy"))
        .stdout(predicate::str::contains("delete"));
}

#[test]
fn job_run_rclone_copy_help_shows_source_bucket_destination_bucket_and_report_bucket_flags() {
    pigeon()
        .args(["job", "run", "rclone", "copy", "--help"])
        .assert()
        .success()
        .stdout(predicate::str::contains("--source-bucket"))
        .stdout(predicate::str::contains("--destination-bucket"))
        .stdout(predicate::str::contains("--local-output"))
        .stdout(predicate::str::contains("--report-bucket"))
        .stdout(predicate::str::contains("--transfers"))
        .stdout(predicate::str::contains("--checkers"))
        .stdout(predicate::str::contains("--tpslimit"))
        .stdout(predicate::str::contains("--non-interactive"))
        // ADR-0136: this job's rclone performance/retry flags beyond
        // transfers/checkers/tpslimit are fixed, not CLI flags.
        .stdout(predicate::str::contains("--source-path").not())
        .stdout(predicate::str::contains("--concurrency").not())
        .stdout(predicate::str::contains("--encryption-key").not());
}

#[test]
fn job_run_rclone_delete_help_shows_source_bucket_and_report_bucket_flags_but_not_destination_or_transfer_flags()
 {
    pigeon()
        .args(["job", "run", "rclone", "delete", "--help"])
        .assert()
        .success()
        .stdout(predicate::str::contains("--source-bucket"))
        .stdout(predicate::str::contains("--local-output"))
        .stdout(predicate::str::contains("--report-bucket"))
        .stdout(predicate::str::contains("--checkers"))
        .stdout(predicate::str::contains("--non-interactive"))
        // ADR-0110: delete has no destination and no file-transfer tuning
        // -- `rclone purge` moves no file content.
        .stdout(predicate::str::contains("--destination-bucket").not())
        .stdout(predicate::str::contains("--transfers").not())
        .stdout(predicate::str::contains("--tpslimit").not());
}

#[test]
fn job_run_rclone_copy_without_source_bucket_fails_fast_non_interactively() {
    let config_dir = TempDir::new().unwrap();
    let local_output = TempDir::new().unwrap();
    write_bucket_config(&config_dir, "dest");

    pigeon_in(&config_dir)
        .args([
            "job",
            "run",
            "rclone",
            "copy",
            "--destination-bucket",
            "dest",
            "--local-output",
            local_output.path().to_str().unwrap(),
            "--non-interactive",
        ])
        .assert()
        .failure()
        .code(1)
        .stderr(predicate::str::contains(
            "--source-bucket is required when not running interactively",
        ));
}

#[test]
fn job_run_rclone_copy_without_destination_bucket_fails_fast_non_interactively() {
    let config_dir = TempDir::new().unwrap();
    let local_output = TempDir::new().unwrap();
    write_bucket_config(&config_dir, "source");

    pigeon_in(&config_dir)
        .args([
            "job",
            "run",
            "rclone",
            "copy",
            "--source-bucket",
            "source",
            "--local-output",
            local_output.path().to_str().unwrap(),
            "--non-interactive",
        ])
        .assert()
        .failure()
        .code(1)
        .stderr(predicate::str::contains(
            "--destination-bucket is required when not running interactively",
        ));
}

#[test]
fn job_run_rclone_copy_without_rclone_on_path_fails_fast_with_a_clear_error() {
    let config_dir = TempDir::new().unwrap();
    let local_output = TempDir::new().unwrap();
    let empty_path_dir = TempDir::new().unwrap();

    pigeon_in(&config_dir)
        .env("PATH", empty_path_dir.path())
        .args([
            "job",
            "run",
            "rclone",
            "copy",
            "--source-bucket",
            "source",
            "--destination-bucket",
            "dest",
            "--local-output",
            local_output.path().to_str().unwrap(),
            "--non-interactive",
        ])
        .assert()
        .failure()
        .code(1)
        .stderr(predicate::str::contains("was not found on PATH"));
}

#[test]
fn job_run_rclone_delete_without_source_bucket_fails_fast_non_interactively() {
    let config_dir = TempDir::new().unwrap();
    let local_output = TempDir::new().unwrap();

    pigeon_in(&config_dir)
        .args([
            "job",
            "run",
            "rclone",
            "delete",
            "--local-output",
            local_output.path().to_str().unwrap(),
            "--non-interactive",
        ])
        .assert()
        .failure()
        .code(1)
        .stderr(predicate::str::contains(
            "--source-bucket is required when not running interactively",
        ));
}

#[test]
fn job_run_rclone_delete_without_rclone_on_path_fails_fast_with_a_clear_error() {
    let config_dir = TempDir::new().unwrap();
    let local_output = TempDir::new().unwrap();
    let empty_path_dir = TempDir::new().unwrap();

    pigeon_in(&config_dir)
        .env("PATH", empty_path_dir.path())
        .args([
            "job",
            "run",
            "rclone",
            "delete",
            "--source-bucket",
            "source",
            "--local-output",
            local_output.path().to_str().unwrap(),
            "--non-interactive",
        ])
        .assert()
        .failure()
        .code(1)
        .stderr(predicate::str::contains("was not found on PATH"));
}

#[test]
fn job_run_help_lists_transform() {
    pigeon()
        .args(["job", "run", "--help"])
        .assert()
        .success()
        .stdout(predicate::str::contains("transform"));
}

#[test]
fn job_run_transform_help_shows_input_file_type_source_destination_and_rclone_flags() {
    pigeon()
        .args(["job", "run", "transform", "--help"])
        .assert()
        .success()
        .stdout(predicate::str::contains("--input-file-type"))
        .stdout(predicate::str::contains("--source"))
        .stdout(predicate::str::contains("--destination"))
        .stdout(predicate::str::contains("--local-output"))
        .stdout(predicate::str::contains("--concurrency"))
        .stdout(predicate::str::contains("--download-transfers"))
        .stdout(predicate::str::contains("--download-checkers"))
        .stdout(predicate::str::contains("--tpslimit"))
        .stdout(predicate::str::contains("--report-bucket"))
        .stdout(predicate::str::contains("--non-interactive"))
        // ADR-0137: renamed from --source-bucket/--destination-bucket.
        .stdout(predicate::str::contains("--source-bucket").not())
        .stdout(predicate::str::contains("--destination-bucket").not())
        // ADR-0138: the composed form is documented on both flags.
        .stdout(predicate::str::contains("media:mp4/"))
        // ADR-0142: the audio-only input kind is listed.
        .stdout(predicate::str::contains("mp4-audio"))
        // ADR-0136: bucket-config aliases, not raw rclone path strings, and
        // no separate upload phase of the shape --upload-concurrency sizes.
        .stdout(predicate::str::contains("--source-path").not())
        .stdout(predicate::str::contains("--encryption-key").not())
        .stdout(predicate::str::contains("--upload-concurrency").not());
}

#[test]
fn job_run_transform_without_input_file_type_fails_fast_non_interactively() {
    let config_dir = TempDir::new().unwrap();
    let local_output = TempDir::new().unwrap();

    pigeon_in(&config_dir)
        .args([
            "job",
            "run",
            "transform",
            "--source",
            "source",
            "--destination",
            "dest",
            "--local-output",
            local_output.path().to_str().unwrap(),
            "--concurrency",
            "4",
            "--non-interactive",
        ])
        .assert()
        .failure()
        .code(1)
        .stderr(predicate::str::contains(
            "--input-file-type is required when not running interactively",
        ));
}

#[test]
fn job_run_transform_with_invalid_input_file_type_fails_fast() {
    let config_dir = TempDir::new().unwrap();
    let local_output = TempDir::new().unwrap();

    pigeon_in(&config_dir)
        .args([
            "job",
            "run",
            "transform",
            "--input-file-type",
            "gif",
            "--source",
            "source",
            "--destination",
            "dest",
            "--local-output",
            local_output.path().to_str().unwrap(),
            "--concurrency",
            "4",
            "--non-interactive",
        ])
        .assert()
        .failure()
        .code(1)
        .stderr(predicate::str::contains("unknown --input-file-type 'gif'"));
}

#[test]
fn job_run_transform_without_source_fails_fast_non_interactively() {
    let config_dir = TempDir::new().unwrap();
    let local_output = TempDir::new().unwrap();
    write_bucket_config(&config_dir, "destination");

    // ADR-0138 reversed ADR-0137's alias inference: with no --source there
    // is no alias to guess, so the run fails fast rather than defaulting.
    pigeon_in(&config_dir)
        .args([
            "job",
            "run",
            "transform",
            "--input-file-type",
            "png",
            "--destination",
            "destination",
            "--local-output",
            local_output.path().to_str().unwrap(),
            "--concurrency",
            "4",
            "--non-interactive",
        ])
        .assert()
        .failure()
        .code(1)
        .stderr(predicate::str::contains(
            "--source is required when not running interactively",
        ));
}

#[test]
fn job_run_transform_without_destination_fails_fast_non_interactively() {
    let config_dir = TempDir::new().unwrap();
    let local_output = TempDir::new().unwrap();
    write_bucket_config(&config_dir, "source");

    pigeon_in(&config_dir)
        .args([
            "job",
            "run",
            "transform",
            "--input-file-type",
            "png",
            "--source",
            "source",
            "--local-output",
            local_output.path().to_str().unwrap(),
            "--concurrency",
            "4",
            "--non-interactive",
        ])
        .assert()
        .failure()
        .code(1)
        .stderr(predicate::str::contains(
            "--destination is required when not running interactively",
        ));
}

/// The exact regression ADR-0138 fixes: the composed `alias:prefix/` form
/// that ADR-0136 made unexpressible. Resolution must get past both bucket
/// flags (failing later only on the still-unresolved --report-bucket).
#[test]
fn job_run_transform_accepts_the_composed_alias_prefix_form() {
    let config_dir = TempDir::new().unwrap();
    let local_output = TempDir::new().unwrap();
    write_bucket_config(&config_dir, "source");
    write_bucket_config(&config_dir, "destination");

    pigeon_in(&config_dir)
        .args([
            "job",
            "run",
            "transform",
            "--input-file-type",
            "mp4",
            "--source",
            "source:mp4/",
            "--destination",
            "destination:mp4/",
            "--local-output",
            local_output.path().to_str().unwrap(),
            "--concurrency",
            "4",
            "--non-interactive",
        ])
        .assert()
        .failure()
        .code(1)
        .stderr(predicate::str::contains("--source is required").not())
        .stderr(predicate::str::contains("--destination is required").not())
        .stderr(predicate::str::contains("no bucket-config named").not())
        .stderr(predicate::str::contains(
            "--report-bucket is required when not running interactively",
        ));
}

/// One bucket serving as both source and destination, distinguished only
/// by prefix -- impossible under ADR-0137's alias inference, which for a
/// video kind resolved both flags to the same `mp4` alias.
#[test]
fn job_run_transform_accepts_one_bucket_for_both_source_and_destination() {
    let config_dir = TempDir::new().unwrap();
    let local_output = TempDir::new().unwrap();
    write_bucket_config(&config_dir, "media");

    pigeon_in(&config_dir)
        .args([
            "job",
            "run",
            "transform",
            "--input-file-type",
            "mov",
            "--source",
            "media:mov/",
            "--destination",
            "media:mp4/",
            "--local-output",
            local_output.path().to_str().unwrap(),
            "--concurrency",
            "4",
            "--non-interactive",
        ])
        .assert()
        .failure()
        .code(1)
        .stderr(predicate::str::contains("no bucket-config named").not())
        .stderr(predicate::str::contains(
            "--report-bucket is required when not running interactively",
        ));
}

#[test]
fn job_run_transform_with_an_unknown_alias_in_the_composed_form_errors_by_alias_name() {
    let config_dir = TempDir::new().unwrap();
    let local_output = TempDir::new().unwrap();

    pigeon_in(&config_dir)
        .args([
            "job",
            "run",
            "transform",
            "--input-file-type",
            "png",
            "--source",
            "no-such-alias:png/",
            "--local-output",
            local_output.path().to_str().unwrap(),
            "--concurrency",
            "4",
            "--non-interactive",
        ])
        .assert()
        .failure()
        .code(1)
        // The prefix must not leak into the error -- only the alias half
        // failed validation.
        .stderr(predicate::str::contains(
            "no bucket-config named 'no-such-alias'",
        ));
}

#[test]
fn job_run_transform_rejects_a_dot_dot_path_segment_in_a_prefix() {
    let config_dir = TempDir::new().unwrap();
    let local_output = TempDir::new().unwrap();
    write_bucket_config(&config_dir, "source");

    pigeon_in(&config_dir)
        .args([
            "job",
            "run",
            "transform",
            "--input-file-type",
            "png",
            "--source",
            "source:../escape/",
            "--local-output",
            local_output.path().to_str().unwrap(),
            "--concurrency",
            "4",
            "--non-interactive",
        ])
        .assert()
        .failure()
        .code(1)
        .stderr(predicate::str::contains(
            "a '..' path segment is not allowed",
        ));
}

#[test]
fn job_run_transform_without_rclone_or_ffmpeg_on_path_fails_fast_with_a_clear_error() {
    let config_dir = TempDir::new().unwrap();
    let local_output = TempDir::new().unwrap();
    let empty_path_dir = TempDir::new().unwrap();

    pigeon_in(&config_dir)
        .env("PATH", empty_path_dir.path())
        .args([
            "job",
            "run",
            "transform",
            "--input-file-type",
            "png",
            "--source",
            "source",
            "--destination",
            "dest",
            "--local-output",
            local_output.path().to_str().unwrap(),
            "--concurrency",
            "4",
            "--non-interactive",
        ])
        .assert()
        .failure()
        .code(1)
        .stderr(predicate::str::contains("was not found on PATH"));
}

// --- ADR-0145: --keyring-path -------------------------------------------

#[test]
fn top_level_help_shows_the_keyring_path_flag() {
    pigeon()
        .arg("--help")
        .assert()
        .success()
        .stdout(predicate::str::contains("--keyring-path"));
}

#[test]
fn keyring_path_is_global_and_accepted_after_a_job_subcommand() {
    // The whole point of `global = true`: the flag parses *after* the
    // subcommand, which is where an operator naturally types it.
    for args in [
        vec!["job", "run", "transform", "--help"],
        vec!["job", "run", "deduplicate", "--help"],
        vec!["job", "run", "rclone", "copy", "--help"],
        vec!["job", "run", "rclone", "delete", "--help"],
    ] {
        pigeon()
            .args(&args)
            .assert()
            .success()
            .stdout(predicate::str::contains("--keyring-path"));
    }
}

#[test]
fn keyring_path_takes_precedence_over_the_config_dir_env_var() {
    // The env-var keyring HAS the bucket; the --keyring-path one does not.
    // Resolving the alias must therefore fail -- which it only can if the
    // flag beat the env var (ADR-0145 §1).
    let config_dir = TempDir::new().unwrap();
    let alt = TempDir::new().unwrap();
    let local_output = TempDir::new().unwrap();
    write_bucket_config(&config_dir, "src-bucket");
    write_bucket_config_at(&alt.path().join("keyring.toml"), "a-different-bucket");

    pigeon_in(&config_dir)
        .args([
            "job",
            "run",
            "deduplicate",
            "--keyring-path",
            alt.path().join("keyring.toml").to_str().unwrap(),
            "--source-bucket",
            "src-bucket",
            "--local-output",
            local_output.path().to_str().unwrap(),
            "--concurrency",
            "4",
            "--non-interactive",
        ])
        .assert()
        .failure()
        .code(1)
        .stderr(predicate::str::contains(
            "no bucket-config named 'src-bucket'",
        ));
}

#[test]
fn an_explicit_keyring_path_that_does_not_exist_fails_fast_naming_the_path() {
    // Without the guard, `Store::load` treats a missing file as an EMPTY
    // store, so a typo'd path surfaces much later as "no bucket-config
    // named ...", naming neither the real problem nor the path.
    let config_dir = TempDir::new().unwrap();
    let local_output = TempDir::new().unwrap();
    write_bucket_config(&config_dir, "src-bucket");

    pigeon_in(&config_dir)
        .args([
            "job",
            "run",
            "deduplicate",
            "--keyring-path",
            "/no/such/dir/keyring.toml",
            "--source-bucket",
            "src-bucket",
            "--local-output",
            local_output.path().to_str().unwrap(),
            "--non-interactive",
        ])
        .assert()
        .failure()
        .code(1)
        .stderr(predicate::str::contains(
            "--keyring-path /no/such/dir/keyring.toml does not exist",
        ))
        .stderr(predicate::str::contains("no bucket-config named").not());
}

#[test]
fn keyring_list_reads_the_overridden_keyring_path() {
    // `--keyring-path` is global, so it reaches `pigeon keyring` too, not
    // only the job types that motivated it.
    let config_dir = TempDir::new().unwrap();
    let alt = TempDir::new().unwrap();
    write_bucket_config(&config_dir, "in-the-env-dir");
    write_bucket_config_at(&alt.path().join("keyring.toml"), "only-at-the-flag-path");

    pigeon_in(&config_dir)
        .args([
            "keyring",
            "list",
            "--keyring-path",
            alt.path().join("keyring.toml").to_str().unwrap(),
        ])
        .assert()
        .success()
        .stdout(predicate::str::contains("only-at-the-flag-path"))
        .stdout(predicate::str::contains("in-the-env-dir").not());
}

#[test]
fn deduplicate_generates_the_sandboxed_rclone_config_beside_the_keyring() {
    // ADR-0145 §5: `deduplicate` never called `write_sandboxed_config` at
    // all, so it ran against whatever a previous `transform`/`rclone` run
    // happened to leave behind -- or nothing. The generated config must now
    // appear beside the keyring this run was pointed at, and it must appear
    // even though this run goes on to fail, since preflight precedes
    // resolution.
    let config_dir = TempDir::new().unwrap();
    let alt = TempDir::new().unwrap();
    let local_output = TempDir::new().unwrap();
    write_bucket_config_at(&alt.path().join("keyring.toml"), "src-bucket");

    let generated = alt.path().join("rclone.conf");
    assert!(!generated.exists());

    pigeon_in(&config_dir)
        .args([
            "job",
            "run",
            "deduplicate",
            "--keyring-path",
            alt.path().join("keyring.toml").to_str().unwrap(),
            "--source-bucket",
            "no-such-bucket",
            "--local-output",
            local_output.path().to_str().unwrap(),
            "--non-interactive",
        ])
        .assert()
        .failure();

    assert!(
        generated.exists(),
        "deduplicate did not generate rclone.conf"
    );
    let contents = fs::read_to_string(&generated).unwrap();
    assert!(contents.contains("[src-bucket]"), "{contents}");
    assert!(
        !config_dir.path().join("rclone.conf").exists(),
        "the default config dir must be left untouched"
    );
}

// --- `job run email import` (ADR-0146) ---------------------------------
//
// No test reaches a real IMAP server or rclone transfer: every one fails at
// the wizard, before a connection is attempted. rclone's `--retries 5
// --low-level-retries 20` turns even a refused connection into minutes of
// backoff (the test-cost constraint ADR-0145 recorded).

#[test]
fn job_run_help_lists_the_email_group_and_not_the_removed_jobs() {
    // Until ADR-0147 this asserted only that the listing contains
    // "email", which "email-sync" already satisfied -- so it could not
    // actually distinguish the `email` group from its flat siblings. Both
    // halves are load-bearing now.
    pigeon()
        .args(["job", "run", "--help"])
        .assert()
        .success()
        .stdout(predicate::str::contains("email"))
        .stdout(predicate::str::contains("email-sync").not())
        .stdout(predicate::str::contains("email-pull").not());
}

/// Both removed job types must fail as unrecognised subcommands, not
/// merely be absent from the listing (ADR-0147).
#[test]
fn job_run_rejects_the_removed_email_jobs() {
    for removed in ["email-sync", "email-pull"] {
        pigeon()
            .args(["job", "run", removed, "--help"])
            .assert()
            .failure()
            .stderr(predicate::str::contains("unrecognized subcommand"));
    }
}

#[test]
fn job_run_email_help_lists_import() {
    pigeon()
        .args(["job", "run", "email", "--help"])
        .assert()
        .success()
        .stdout(predicate::str::contains("import"));
}

#[test]
fn job_run_email_import_help_shows_its_full_flag_set() {
    pigeon()
        .args(["job", "run", "email", "import", "--help"])
        .assert()
        .success()
        .stdout(predicate::str::contains("--identities"))
        .stdout(predicate::str::contains("--destination"))
        .stdout(predicate::str::contains("--local-output"))
        .stdout(predicate::str::contains("--messages-per-minute"))
        .stdout(predicate::str::contains("--batch-size"))
        .stdout(predicate::str::contains("--max-connections"))
        .stdout(predicate::str::contains("--push-concurrency"))
        .stdout(predicate::str::contains("--report-bucket"))
        .stdout(predicate::str::contains("--non-interactive"));
}

/// Pins ADR-0146 §1's scoping decisions, the way ADR-0081's own
/// `--encryption-key` test pinned the since-removed `email-pull`'s. Each
/// absence is deliberate
/// and each would be easy to add back by accident:
/// `--encryption-key` is permanently out of scope; `--upload-only` is
/// meaningless when delivery is inline; `--concurrency` would imply it
/// governs throughput when `--messages-per-minute` does; and `--tpslimit`
/// and friends do not apply to `rclone copyto`.
#[test]
fn job_run_email_import_help_omits_every_deliberately_absent_flag() {
    pigeon()
        .args(["job", "run", "email", "import", "--help"])
        .assert()
        .success()
        .stdout(predicate::str::contains("--encryption-key").not())
        .stdout(predicate::str::contains("--upload-only").not())
        .stdout(predicate::str::contains("--concurrency").not())
        .stdout(predicate::str::contains("--tpslimit").not())
        .stdout(predicate::str::contains("--transfers").not())
        .stdout(predicate::str::contains("--checkers").not());
}

/// `--push-concurrency` ends in "concurrency", so the negative assertion
/// above has to be checking for the standalone `--concurrency` flag rather
/// than a substring that `--push-concurrency` would satisfy.
#[test]
fn job_run_email_import_help_still_shows_push_concurrency() {
    pigeon()
        .args(["job", "run", "email", "import", "--help"])
        .assert()
        .success()
        .stdout(predicate::str::contains("--push-concurrency"));
}

#[test]
fn job_run_email_import_without_identities_fails_fast_non_interactively() {
    let config_dir = TempDir::new().unwrap();
    let local_output = TempDir::new().unwrap();
    write_bucket_config(&config_dir, "dest");

    pigeon_in(&config_dir)
        .args([
            "job",
            "run",
            "email",
            "import",
            "--destination",
            "dest",
            "--local-output",
            local_output.path().to_str().unwrap(),
            "--report-bucket",
            "dest",
            "--non-interactive",
        ])
        .assert()
        .failure()
        .code(1)
        .stderr(predicate::str::contains(
            "--identities is required when not running interactively",
        ));
}

/// `--destination` is mandatory, unlike the sibling email jobs'
/// `--remote-output`, which silently resolves to "don't upload"
/// (ADR-0146 §1): a job whose only purpose is delivery must not be able to
/// run without somewhere to deliver to.
#[test]
fn job_run_email_import_without_a_destination_fails_fast_non_interactively() {
    let config_dir = TempDir::new().unwrap();
    let local_output = TempDir::new().unwrap();
    write_identity(&config_dir, "first-last", "first.last@example.com");
    write_bucket_config(&config_dir, "dest");

    pigeon_in(&config_dir)
        .args([
            "job",
            "run",
            "email",
            "import",
            "--identities",
            "first-last",
            "--local-output",
            local_output.path().to_str().unwrap(),
            "--report-bucket",
            "dest",
            "--non-interactive",
        ])
        .assert()
        .failure()
        .code(1)
        .stderr(predicate::str::contains(
            "--destination is required when not running interactively",
        ));
}

#[test]
fn job_run_email_import_requires_a_report_bucket_non_interactively() {
    let config_dir = TempDir::new().unwrap();
    let local_output = TempDir::new().unwrap();
    write_identity(&config_dir, "first-last", "first.last@example.com");
    write_bucket_config(&config_dir, "dest");

    pigeon_in(&config_dir)
        .args([
            "job",
            "run",
            "email",
            "import",
            "--identities",
            "first-last",
            "--destination",
            "dest",
            "--local-output",
            local_output.path().to_str().unwrap(),
            "--non-interactive",
        ])
        .assert()
        .failure()
        .code(1)
        .stderr(predicate::str::contains(
            "--report-bucket is required when not running interactively",
        ));
}

#[test]
fn job_run_email_import_with_an_unknown_identity_fails() {
    let config_dir = TempDir::new().unwrap();
    let local_output = TempDir::new().unwrap();
    write_bucket_config(&config_dir, "dest");

    pigeon_in(&config_dir)
        .args([
            "job",
            "run",
            "email",
            "import",
            "--identities",
            "nope",
            "--destination",
            "dest",
            "--local-output",
            local_output.path().to_str().unwrap(),
            "--report-bucket",
            "dest",
            "--non-interactive",
        ])
        .assert()
        .failure()
        .code(1)
        .stderr(predicate::str::contains("no identity with alias 'nope'"));
}

#[test]
fn job_run_email_import_with_an_unknown_destination_alias_fails() {
    let config_dir = TempDir::new().unwrap();
    let local_output = TempDir::new().unwrap();
    write_identity(&config_dir, "first-last", "first.last@example.com");
    write_bucket_config(&config_dir, "dest");

    pigeon_in(&config_dir)
        .args([
            "job",
            "run",
            "email",
            "import",
            "--identities",
            "first-last",
            "--destination",
            "nope:eml/",
            "--local-output",
            local_output.path().to_str().unwrap(),
            "--report-bucket",
            "dest",
            "--non-interactive",
        ])
        .assert()
        .failure()
        .code(1)
        .stderr(predicate::str::contains("no bucket-config named 'nope'"));
}

/// ADR-0138's prefix validation reaches this job's `--destination` too: a
/// `..` segment would be taken literally by rclone, writing outside the
/// configured prefix.
#[test]
fn job_run_email_import_rejects_a_parent_directory_segment_in_the_destination_prefix() {
    let config_dir = TempDir::new().unwrap();
    let local_output = TempDir::new().unwrap();
    write_identity(&config_dir, "first-last", "first.last@example.com");
    write_bucket_config(&config_dir, "dest");

    pigeon_in(&config_dir)
        .args([
            "job",
            "run",
            "email",
            "import",
            "--identities",
            "first-last",
            "--destination",
            "dest:../escape/",
            "--local-output",
            local_output.path().to_str().unwrap(),
            "--report-bucket",
            "dest",
            "--non-interactive",
        ])
        .assert()
        .failure()
        .code(1)
        .stderr(predicate::str::contains(
            "a '..' path segment is not allowed",
        ));
}

/// The first email job to depend on `rclone` (ADR-0146 §9): both siblings
/// are `minio`-only, so this preflight is new behavior for an email job and
/// must fail before any IMAP credential is touched.
#[test]
fn job_run_email_import_without_rclone_on_path_fails_fast_with_a_clear_error() {
    let config_dir = TempDir::new().unwrap();
    let local_output = TempDir::new().unwrap();
    let empty_path_dir = TempDir::new().unwrap();
    write_identity(&config_dir, "first-last", "first.last@example.com");
    write_bucket_config(&config_dir, "dest");

    pigeon_in(&config_dir)
        .env("PATH", empty_path_dir.path())
        .args([
            "job",
            "run",
            "email",
            "import",
            "--identities",
            "first-last",
            "--destination",
            "dest",
            "--local-output",
            local_output.path().to_str().unwrap(),
            "--report-bucket",
            "dest",
            "--non-interactive",
        ])
        .assert()
        .failure()
        .code(1)
        .stderr(predicate::str::contains("was not found on PATH"));
}

/// ADR-0147 §2: a leftover `kind = "encryption-key"` entry must fail with a
/// message naming both the file and the block to delete. Asserted at the
/// CLI level and not only in `Store::load`'s own unit tests because the
/// failure path locks the operator out of *every* keyring command --
/// including the `list`/`delete` they would otherwise use to clean it up --
/// so what reaches stderr is the only remediation they get.
#[test]
fn keyring_list_explains_how_to_remove_a_leftover_encryption_key_entry() {
    let config_dir = TempDir::new().unwrap();
    append_keyring_entry(
        &config_dir,
        "[[entries]]\nkind = \"encryption-key\"\nalias = \"primary\"\n\
         created_at = \"2026-09-24T00:00:00Z\"\nkey_hex = \"0\"\n",
    );

    pigeon_in(&config_dir)
        .args(["keyring", "list"])
        .assert()
        .failure()
        .code(1)
        .stderr(predicate::str::contains("encryption-key"))
        .stderr(predicate::str::contains("ADR-0147"))
        .stderr(predicate::str::contains("[[entries]]"))
        .stderr(predicate::str::contains("keyring.toml"));
}

/// The companion to the above: a stale `encryption_key_alias` on a *bucket*
/// entry is a different compatibility story. Nothing in the crate uses
/// `deny_unknown_fields`, so serde ignores it and no migration is needed.
#[test]
fn keyring_list_ignores_a_stale_encryption_key_alias_on_a_bucket_entry() {
    let config_dir = TempDir::new().unwrap();
    append_keyring_entry(
        &config_dir,
        "[[entries]]\nkind = \"bucket\"\nalias = \"backup\"\n\
         endpoint = \"https://nyc3.digitaloceanspaces.com\"\nbucket = \"my-bucket\"\n\
         access_key_id = \"AKID\"\nsecret_key = \"fake-secret\"\n\
         encryption_key_alias = \"primary\"\n",
    );

    pigeon_in(&config_dir)
        .args(["keyring", "list"])
        .assert()
        .success()
        .stdout(predicate::str::contains("backup"));
}

/// ADR-0147 removed the `encryption-key` kind, so `keyring add` offers
/// exactly two.
#[test]
fn keyring_add_help_lists_only_email_and_bucket() {
    pigeon()
        .args(["keyring", "add", "--help"])
        .assert()
        .success()
        .stdout(predicate::str::contains("email"))
        .stdout(predicate::str::contains("bucket"))
        .stdout(predicate::str::contains("encryption-key").not());
}