logmv 0.7.1

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

// ---------------------------------------------------------------------------
// T5: AC1, AC3, AC5, AC10, AC11
// Move happy path with relative src+dst (cwd = temp dir), positional <LOG>,
// with two K V pairs. After success: src gone, dst exists with content; log
// created with exactly one JSON line: act="move", absolute src/dst, the two
// pairs present after the canonical keys in order as strings; stdout empty;
// exit 0.
// ---------------------------------------------------------------------------
#[test]
fn t5_move_happy_path_relative_paths_with_pairs() {
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("src.txt");
    fs::write(&src, b"hello").unwrap();
    let log = dir.path().join("move.log");

    Command::cargo_bin("logmv")
        .unwrap()
        .current_dir(dir.path())
        .args([
            log.to_str().unwrap(), // LOG (absolute, first positional)
            "src.txt",             // SRC (relative)
            "dst.txt",             // DST (relative)
            "by",
            "cc", // K V pair 1
            "ac",
            "p", // K V pair 2
        ])
        .assert()
        .success()
        .stdout(predicate::str::is_empty());

    // src must be gone.
    assert!(!src.exists(), "src must be gone after move");

    // dst must exist with original content.
    let dst = dir.path().join("dst.txt");
    assert!(dst.exists(), "dst must exist after move");
    assert_eq!(fs::read(&dst).unwrap(), b"hello");

    // log must exist with exactly one line.
    let log_content = fs::read_to_string(&log).unwrap();
    let lines: Vec<&str> = log_content.lines().collect();
    assert_eq!(lines.len(), 1, "log must have exactly one line");

    // Line must parse as valid JSON.
    let entry: serde_json::Value =
        serde_json::from_str(lines[0]).expect("log line must be valid JSON");

    assert_eq!(entry["act"], "move");

    // src and dst recorded as absolute paths.
    let logged_src = entry["src"].as_str().unwrap();
    let logged_dst = entry["dst"].as_str().unwrap();
    assert!(
        logged_src.starts_with('/'),
        "logged src must be absolute, got: {logged_src}"
    );
    assert!(
        logged_dst.starts_with('/'),
        "logged dst must be absolute, got: {logged_dst}"
    );

    // ts must be present and parse as ISO-8601.
    let ts_str = entry["ts"].as_str().expect("ts field must be present");
    chrono::DateTime::parse_from_rfc3339(ts_str).expect("ts must be valid ISO-8601 with offset");

    // Pairs must appear after canonical keys, in order, as strings.
    let obj = entry.as_object().unwrap();
    let keys: Vec<&str> = obj.keys().map(|k| k.as_str()).collect();
    assert_eq!(
        &keys[..4],
        &["ts", "act", "src", "dst"],
        "first four keys must be canonical in order, got: {keys:?}"
    );
    assert_eq!(
        &keys[4..],
        &["by", "ac"],
        "pairs must follow in given order, got: {keys:?}"
    );
    assert_eq!(entry["by"].as_str().unwrap(), "cc");
    assert_eq!(entry["ac"].as_str().unwrap(), "p");
}

// ---------------------------------------------------------------------------
// T6: AC2, AC5  [never-unlink invariant]
// Trash happy path (inject HOME seam), no pairs. Source gone, content
// recoverable in $HOME/.Trash (never unlinked); log line act="trash", dst=canonical
// landing path (like move); and the line carries ONLY the four canonical keys; exit 0.
// ---------------------------------------------------------------------------
#[test]
fn t6_trash_happy_path_never_unlinks_no_pairs() {
    let dir = tempfile::tempdir().unwrap();
    let home_tmp = tempfile::tempdir().unwrap(); // inject $HOME seam
    let trash_root = home_tmp.path().join(".Trash");
    fs::create_dir(&trash_root).unwrap();
    let src = dir.path().join("precious.txt");
    fs::write(&src, b"irreplaceable").unwrap();
    let log = dir.path().join("trash.log");

    Command::cargo_bin("logmv")
        .unwrap()
        .env("HOME", home_tmp.path())
        .args([
            log.to_str().unwrap(), // LOG (first positional)
            "--trash",
            src.to_str().unwrap(),
        ])
        .assert()
        .success()
        .stdout(predicate::str::is_empty());

    // Source must be gone from original location.
    assert!(!src.exists(), "source must be gone after trash");

    // Content must be recoverable in $HOME/.Trash (never unlinked).
    let trashed = trash_root.join("precious.txt");
    assert!(trashed.exists(), "content must be in trash dir");
    assert_eq!(
        fs::read(&trashed).unwrap(),
        b"irreplaceable",
        "trashed content must be intact"
    );

    // Log line checks.
    let log_content = fs::read_to_string(&log).unwrap();
    let entry: serde_json::Value =
        serde_json::from_str(log_content.trim()).expect("log line must be valid JSON");
    assert_eq!(entry["act"], "trash");
    let expected_dst = std::fs::canonicalize(&trash_root)
        .unwrap()
        .join("precious.txt");
    let expected_dst_str = expected_dst.to_str().unwrap();
    let dst_val = entry["dst"].as_str().expect("dst must be a string");
    assert!(
        dst_val.starts_with('/'),
        "dst must be absolute, got: {dst_val}"
    );
    assert_eq!(
        dst_val, expected_dst_str,
        "dst must be the canonical landing path"
    );

    // ts must be present and parse.
    let ts_str = entry["ts"].as_str().expect("ts must be present");
    chrono::DateTime::parse_from_rfc3339(ts_str).expect("ts must be valid ISO-8601 with offset");

    // With no pairs, the line must carry ONLY the four canonical keys.
    let obj = entry.as_object().unwrap();
    assert_eq!(
        obj.len(),
        4,
        "no-pairs line must have exactly 4 keys, got: {:?}",
        obj.keys().collect::<Vec<_>>()
    );
}

// ---------------------------------------------------------------------------
// T7: AC7, AC11  [never-overwrite / no-data-loss invariant]
// Move where dst pre-exists with distinct content → exit non-zero, stderr
// non-empty, src intact, dst content unchanged, no log written, stdout empty.
// ---------------------------------------------------------------------------
#[test]
fn t7_never_overwrite_move_refuses() {
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("src.txt");
    let dst = dir.path().join("dst.txt");
    fs::write(&src, b"source content").unwrap();
    fs::write(&dst, b"existing content").unwrap();
    let log = dir.path().join("log.jsonl");

    Command::cargo_bin("logmv")
        .unwrap()
        .args([
            log.to_str().unwrap(),
            src.to_str().unwrap(),
            dst.to_str().unwrap(),
        ])
        .assert()
        .failure()
        .stdout(predicate::str::is_empty())
        .stderr(predicate::str::is_empty().not());

    // src must be intact.
    assert!(src.exists(), "src must be intact after refusal");

    // dst content must be unchanged.
    assert_eq!(
        fs::read(&dst).unwrap(),
        b"existing content",
        "dst content must be unchanged"
    );

    // No log must have been written.
    assert!(!log.exists(), "no log file must be created on refusal");
}

// ---------------------------------------------------------------------------
// T8: AC7  [never-overwrite invariant, trash collision]
// Trash where $HOME/.Trash already holds the same name → disambiguating suffix
// applied; both files survive under distinct names, neither clobbered.
// ---------------------------------------------------------------------------
#[test]
fn t8_trash_collision_disambiguates() {
    let dir = tempfile::tempdir().unwrap();
    let home_tmp = tempfile::tempdir().unwrap(); // inject $HOME seam
    let trash_root = home_tmp.path().join(".Trash");
    fs::create_dir(&trash_root).unwrap();
    let src = dir.path().join("file.txt");
    fs::write(&src, b"new content").unwrap();
    // Pre-seed $HOME/.Trash with the same name.
    let existing = trash_root.join("file.txt");
    fs::write(&existing, b"old content").unwrap();
    let log = dir.path().join("log.jsonl");

    Command::cargo_bin("logmv")
        .unwrap()
        .env("HOME", home_tmp.path())
        .args([log.to_str().unwrap(), "--trash", src.to_str().unwrap()])
        .assert()
        .success();

    // Source must be gone.
    assert!(!src.exists(), "source must be gone after trash");

    // Old content must survive unchanged.
    assert_eq!(
        fs::read(&existing).unwrap(),
        b"old content",
        "pre-existing trash file must not be clobbered"
    );

    // Trash dir must contain exactly 2 files (original + disambiguated).
    let entries: Vec<_> = fs::read_dir(&trash_root)
        .unwrap()
        .filter_map(|e| e.ok())
        .collect();
    assert_eq!(
        entries.len(),
        2,
        "trash dir must have 2 files (original + disambiguated), got {}",
        entries.len()
    );

    // Log must record the disambiguated landing path (AC3).
    let log_content = fs::read_to_string(&log).unwrap();
    let lines: Vec<&str> = log_content.lines().filter(|l| !l.is_empty()).collect();
    assert_eq!(lines.len(), 1, "log must have exactly one line");
    let entry: serde_json::Value =
        serde_json::from_str(lines[0]).expect("log line must be valid JSON");
    assert_eq!(entry["act"], "trash");
    let expected_dst = std::fs::canonicalize(&trash_root)
        .unwrap()
        .join("file-1.txt");
    let expected_dst_str = expected_dst.to_str().unwrap();
    let dst_val = entry["dst"].as_str().expect("dst must be a string");
    assert!(
        dst_val.starts_with('/'),
        "dst must be absolute, got: {dst_val}"
    );
    assert!(
        dst_val.ends_with("/file-1.txt"),
        "dst must end with /file-1.txt (disambiguated suffix), got: {dst_val}"
    );
    assert_eq!(
        dst_val, expected_dst_str,
        "dst must be the canonical landing path for the disambiguated file"
    );
}

// ---------------------------------------------------------------------------
// T9: AC9, AC11  [no-silent-drift invariant]
// Move succeeds but log append fails (<LOG> points at a directory → EISDIR).
// Exit non-zero, loud stderr; dst exists and src gone (move happened);
// stdout empty.
// ---------------------------------------------------------------------------
#[test]
fn t9_drift_window_loud_error() {
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("src.txt");
    fs::write(&src, b"content").unwrap();
    let dst = dir.path().join("dst.txt");
    // Make <LOG> point at a directory → EISDIR on append.
    let log_as_dir = dir.path().join("logdir");
    fs::create_dir(&log_as_dir).unwrap();

    Command::cargo_bin("logmv")
        .unwrap()
        .args([
            log_as_dir.to_str().unwrap(), // LOG → directory → EISDIR
            src.to_str().unwrap(),
            dst.to_str().unwrap(),
        ])
        .assert()
        .failure()
        .stdout(predicate::str::is_empty())
        .stderr(predicate::str::is_empty().not());

    // Move must have happened (not rolled back).
    assert!(!src.exists(), "src must be gone (move was not rolled back)");
    assert!(
        dst.exists(),
        "dst must exist (move happened before log failed)"
    );
}

// ---------------------------------------------------------------------------
// T10: AC10  [no-clobber-of-log invariant]
// Pre-seed log with one valid line; run → log has exactly 2 lines; original
// line is byte-identical and first; new line is appended (not truncated).
// ---------------------------------------------------------------------------
#[test]
fn t10_append_preserves_history() {
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("src.txt");
    fs::write(&src, b"content").unwrap();
    let dst = dir.path().join("dst.txt");
    let log = dir.path().join("log.jsonl");

    // Pre-seed the log with one valid 4-key entry (new contract schema).
    let existing_line =
        r#"{"ts":"2024-01-01T00:00:00+00:00","act":"move","src":"/old/src","dst":"/old/dst"}"#;
    fs::write(&log, format!("{existing_line}\n")).unwrap();

    Command::cargo_bin("logmv")
        .unwrap()
        .args([
            log.to_str().unwrap(),
            src.to_str().unwrap(),
            dst.to_str().unwrap(),
        ])
        .assert()
        .success();

    let log_content = fs::read_to_string(&log).unwrap();
    let lines: Vec<&str> = log_content.lines().filter(|l| !l.is_empty()).collect();

    assert_eq!(lines.len(), 2, "log must have exactly 2 lines after append");

    // Original line byte-identical and first.
    assert_eq!(
        lines[0], existing_line,
        "original log line must be byte-identical and first"
    );

    // New line parses as valid JSON.
    let _: serde_json::Value =
        serde_json::from_str(lines[1]).expect("new log line must be valid JSON");
}

// ---------------------------------------------------------------------------
// T11: AC4
// Missing <LOG>: invoke with no positional log (logmv --trash <src>, no other
// args) → exit non-zero, stderr non-empty; src untouched (no action without
// a log target).
// ---------------------------------------------------------------------------
#[test]
fn t11_missing_log_is_usage_error() {
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("src.txt");
    fs::write(&src, b"content").unwrap();

    Command::cargo_bin("logmv")
        .unwrap()
        .args(["--trash", src.to_str().unwrap()])
        // deliberately omit LOG positional
        .assert()
        .failure()
        .stderr(predicate::str::is_empty().not());

    // src must not have been moved.
    assert!(src.exists(), "src must not be moved when LOG is missing");
}

// ---------------------------------------------------------------------------
// T_oddarg: AC12  [input-rule, no-move-no-log invariant]
// Odd trailing args (logmv <LOG> <SRC> <DST> K: dangling key with no value)
// → exit non-zero, stderr non-empty; src NOT moved, no log written,
// stdout empty.
// ---------------------------------------------------------------------------
#[test]
fn t_oddarg_dangling_key_is_usage_error() {
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("src.txt");
    fs::write(&src, b"content").unwrap();
    let dst = dir.path().join("dst.txt");
    let log = dir.path().join("log.jsonl");

    Command::cargo_bin("logmv")
        .unwrap()
        .args([
            log.to_str().unwrap(),
            src.to_str().unwrap(),
            dst.to_str().unwrap(),
            "dangling_key", // one K with no V: odd trailing args
        ])
        .assert()
        .failure()
        .stdout(predicate::str::is_empty())
        .stderr(predicate::str::is_empty().not());

    // src must NOT have been moved.
    assert!(src.exists(), "src must not be moved on odd-arg error");
    // No log must have been written.
    assert!(!log.exists(), "no log must be written on odd-arg error");
}

// ---------------------------------------------------------------------------
// T_collide_i: AC13  [canonical-unspoofable, no-move-no-log invariant]
// Metadata key collides with a canonical key (logmv <LOG> <SRC> <DST> ts X)
// → exit non-zero, stderr non-empty; src NOT moved, no log written.
// ---------------------------------------------------------------------------
#[test]
fn t_collide_i_canonical_key_collision_refuses() {
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("src.txt");
    fs::write(&src, b"content").unwrap();
    let dst = dir.path().join("dst.txt");
    let log = dir.path().join("log.jsonl");

    Command::cargo_bin("logmv")
        .unwrap()
        .args([
            log.to_str().unwrap(),
            src.to_str().unwrap(),
            dst.to_str().unwrap(),
            "ts",
            "spoofed", // collision: "ts" is a canonical key
        ])
        .assert()
        .failure()
        .stderr(predicate::str::is_empty().not());

    // src must NOT have been moved.
    assert!(
        src.exists(),
        "src must not be moved on canonical-key collision"
    );
    // No log must have been written.
    assert!(
        !log.exists(),
        "no log must be written on canonical-key collision"
    );
}

// ===========================================================================
// Task 0002: new integration tests (12)
// All disposition: write (new behavior, all red until implementation lands)
// ===========================================================================

// ---------------------------------------------------------------------------
// t_into_dir_move: AC1
// DST is an existing directory → SRC moves to DST/basename(SRC).
// Log line: act="move", dst = absolute path of the file inside DST (not DST
// itself), src = absolute path of SRC. Exit 0.
// ---------------------------------------------------------------------------
#[test]
fn t_into_dir_move() {
    let tmp = tempfile::tempdir().unwrap();
    let src_file = tmp.path().join("file.txt");
    fs::write(&src_file, b"hello into-dir").unwrap();
    let dest_dir = tmp.path().join("dest");
    fs::create_dir(&dest_dir).unwrap();
    let log = tmp.path().join("move.log");

    Command::cargo_bin("logmv")
        .unwrap()
        .args([
            log.to_str().unwrap(),
            src_file.to_str().unwrap(),
            dest_dir.to_str().unwrap(),
        ])
        .assert()
        .success()
        .stdout(predicate::str::is_empty());

    // SRC gone.
    assert!(!src_file.exists(), "src must be gone after into-dir move");

    // DST/basename(SRC) exists with original content.
    let dst_file = dest_dir.join("file.txt");
    assert!(
        dst_file.exists(),
        "dest/file.txt must exist after into-dir move"
    );
    assert_eq!(fs::read(&dst_file).unwrap(), b"hello into-dir");

    // Exactly one log line.
    let log_content = fs::read_to_string(&log).unwrap();
    let lines: Vec<&str> = log_content.lines().filter(|l| !l.is_empty()).collect();
    assert_eq!(lines.len(), 1, "log must have exactly one line");

    let entry: serde_json::Value =
        serde_json::from_str(lines[0]).expect("log line must be valid JSON");
    assert_eq!(entry["act"], "move");

    // dst must be the file inside dest, not dest itself.
    let logged_dst = entry["dst"].as_str().unwrap();
    assert!(
        logged_dst.ends_with("/file.txt"),
        "logged dst must be the resolved file path inside dest, got: {logged_dst}"
    );
    assert_ne!(
        logged_dst,
        dest_dir.to_str().unwrap(),
        "logged dst must not be the dest dir itself"
    );

    // ts parses as RFC3339.
    let ts_str = entry["ts"].as_str().expect("ts must be present");
    chrono::DateTime::parse_from_rfc3339(ts_str).expect("ts must be valid ISO-8601 with offset");
}

// ---------------------------------------------------------------------------
// t_into_dir_collision: AC3
// DST is an existing directory and DST/basename(SRC) already exists →
// refuse, exit non-zero, no move, no log; SRC and existing file both intact.
// ---------------------------------------------------------------------------
#[test]
fn t_into_dir_collision() {
    let tmp = tempfile::tempdir().unwrap();
    let src_file = tmp.path().join("file.txt");
    fs::write(&src_file, b"source content").unwrap();
    let dest_dir = tmp.path().join("dest");
    fs::create_dir(&dest_dir).unwrap();
    let existing = dest_dir.join("file.txt");
    fs::write(&existing, b"existing content").unwrap();
    let log = tmp.path().join("move.log");

    Command::cargo_bin("logmv")
        .unwrap()
        .args([
            log.to_str().unwrap(),
            src_file.to_str().unwrap(),
            dest_dir.to_str().unwrap(),
        ])
        .assert()
        .failure()
        // Refusal must name the RESOLVED path dest/file.txt, not just dest.
        // Current code names dest (the dir); new code must name dest/file.txt.
        .stderr(predicate::str::contains("file.txt"));

    // SRC intact.
    assert!(
        src_file.exists(),
        "src must be intact after into-dir collision"
    );
    // Pre-existing dest/file.txt content unchanged.
    assert_eq!(
        fs::read(&existing).unwrap(),
        b"existing content",
        "dest/file.txt must be unchanged"
    );
    // No log written (refused before mutation).
    assert!(
        !log.exists(),
        "no log must be written on into-dir collision"
    );
}

// ---------------------------------------------------------------------------
// t_mkdir_creates_and_logs: AC4 + AC6
// Arrange: file.txt; target a/b/c/file.txt where a exists but a/b, a/b/c
// are missing. --mkdir creates the chain, logs parent→child before the move.
// Assert: a/b and a/b/c created; a untouched; move done; log order =
// mkdir(dst=abs a/b), mkdir(dst=abs a/b/c), move.
// ---------------------------------------------------------------------------
#[test]
fn t_mkdir_creates_and_logs() {
    let tmp = tempfile::tempdir().unwrap();
    let src_file = tmp.path().join("file.txt");
    fs::write(&src_file, b"mkdir-log content").unwrap();
    // a/ exists; a/b and a/b/c are missing.
    let a_dir = tmp.path().join("a");
    fs::create_dir(&a_dir).unwrap();
    let target = tmp.path().join("a/b/c/file.txt");
    let log = tmp.path().join("move.log");

    Command::cargo_bin("logmv")
        .unwrap()
        .args([
            log.to_str().unwrap(),
            "--mkdir",
            src_file.to_str().unwrap(),
            target.to_str().unwrap(),
        ])
        .assert()
        .success()
        .stdout(predicate::str::is_empty());

    // a/b and a/b/c created.
    assert!(tmp.path().join("a/b").is_dir(), "a/b must be created");
    assert!(tmp.path().join("a/b/c").is_dir(), "a/b/c must be created");

    // a/ still exists (untouched).
    assert!(a_dir.is_dir(), "a must still exist");

    // Move done.
    assert!(!src_file.exists(), "src must be gone after --mkdir move");
    assert!(target.exists(), "target file must exist after --mkdir move");

    // Log: mkdir(a/b), mkdir(a/b/c), move; exactly 3 lines.
    let log_content = fs::read_to_string(&log).unwrap();
    let lines: Vec<&str> = log_content.lines().filter(|l| !l.is_empty()).collect();
    assert_eq!(lines.len(), 3, "log must have 3 lines: 2 mkdir + 1 move");

    let e0: serde_json::Value = serde_json::from_str(lines[0]).expect("line 0 must be valid JSON");
    let e1: serde_json::Value = serde_json::from_str(lines[1]).expect("line 1 must be valid JSON");
    let e2: serde_json::Value = serde_json::from_str(lines[2]).expect("line 2 must be valid JSON");

    // First two lines: mkdir in parent→child order.
    assert_eq!(e0["act"], "mkdir", "line 0 must be mkdir");
    assert_eq!(e0["src"], "-", "mkdir src must be '-'");
    assert!(
        e0["dst"].as_str().unwrap().ends_with("/a/b"),
        "line 0 mkdir dst must be abs a/b, got: {}",
        e0["dst"]
    );

    assert_eq!(e1["act"], "mkdir", "line 1 must be mkdir");
    assert_eq!(e1["src"], "-", "mkdir src must be '-'");
    assert!(
        e1["dst"].as_str().unwrap().ends_with("/a/b/c"),
        "line 1 mkdir dst must be abs a/b/c, got: {}",
        e1["dst"]
    );

    // Third line: move.
    assert_eq!(e2["act"], "move", "line 2 must be move");

    // ts parses on all lines.
    for (i, e) in [&e0, &e1, &e2].iter().enumerate() {
        let ts_str = e["ts"]
            .as_str()
            .unwrap_or_else(|| panic!("line {i} must have ts"));
        chrono::DateTime::parse_from_rfc3339(ts_str)
            .unwrap_or_else(|_| panic!("line {i} ts must be valid RFC3339"));
    }
}

// ---------------------------------------------------------------------------
// t_mkdir_noop_when_chain_present: AC6
// Arrange: file.txt, fully-existing a/b/. --mkdir with fully-present chain
// produces zero mkdir lines; exactly one log line (act="move").
// ---------------------------------------------------------------------------
#[test]
fn t_mkdir_noop_when_chain_present() {
    let tmp = tempfile::tempdir().unwrap();
    let src_file = tmp.path().join("file.txt");
    fs::write(&src_file, b"noop content").unwrap();
    // a/b/ fully present.
    let ab_dir = tmp.path().join("a/b");
    fs::create_dir_all(&ab_dir).unwrap();
    let target = tmp.path().join("a/b/dst.txt");
    let log = tmp.path().join("move.log");

    Command::cargo_bin("logmv")
        .unwrap()
        .args([
            log.to_str().unwrap(),
            "--mkdir",
            src_file.to_str().unwrap(),
            target.to_str().unwrap(),
        ])
        .assert()
        .success()
        .stdout(predicate::str::is_empty());

    // Move done.
    assert!(!src_file.exists(), "src must be gone");
    assert!(target.exists(), "target must exist");

    // Exactly one log line, act="move", no mkdir lines.
    let log_content = fs::read_to_string(&log).unwrap();
    let lines: Vec<&str> = log_content.lines().filter(|l| !l.is_empty()).collect();
    assert_eq!(
        lines.len(),
        1,
        "log must have exactly one line (zero mkdir lines)"
    );

    let entry: serde_json::Value =
        serde_json::from_str(lines[0]).expect("log line must be valid JSON");
    assert_eq!(entry["act"], "move", "the sole log line must be act=move");
}

// ---------------------------------------------------------------------------
// t_mkdir_create_failure_reports_creation: AC2 + AC3
// Arrange: src.txt; a regular FILE at blocker occupies a target path
// component, so create_dir_all(blocker/sub) fails ENOTDIR before any mkdir
// line is logged. LOG does not exist yet.
// Assert: exit non-zero, stderr non-empty; blocker/sub NOT created; blocker
// still a regular file; src.txt intact; dst.txt absent; LOG not created;
// stderr does not contain "append" (creation failed before any append; a
// create failure must not claim an append failed).
// ---------------------------------------------------------------------------
#[test]
fn t_mkdir_create_failure_reports_creation() {
    let tmp = tempfile::tempdir().unwrap();
    let src_file = tmp.path().join("src.txt");
    fs::write(&src_file, b"create-failure content").unwrap();
    // blocker is a regular file, not a directory: create_dir_all(blocker/sub)
    // must fail ENOTDIR.
    let blocker = tmp.path().join("blocker");
    fs::write(&blocker, b"i am a file, not a dir").unwrap();
    let target = tmp.path().join("blocker/sub/dst.txt");
    let log = tmp.path().join("move.log");

    Command::cargo_bin("logmv")
        .unwrap()
        .args([
            log.to_str().unwrap(),
            "--mkdir",
            src_file.to_str().unwrap(),
            target.to_str().unwrap(),
        ])
        .assert()
        .failure()
        .stderr(predicate::str::is_empty().not())
        .stderr(predicate::str::contains("append").not());

    // blocker/sub must not exist; blocker remains a regular file.
    assert!(
        !tmp.path().join("blocker/sub").exists(),
        "blocker/sub must not be created on create failure"
    );
    assert!(blocker.is_file(), "blocker must still be a regular file");
    // src intact; dst absent.
    assert!(src_file.exists(), "src must be intact");
    assert!(!target.exists(), "dst.txt must not exist");
    // No log written.
    assert!(!log.exists(), "no log must be written on create failure");
}

// ---------------------------------------------------------------------------
// t_mkdir_append_failure_reports_created: AC2 + AC3
// Arrange: src.txt; newdir is MISSING so create_dir_all succeeds; LOG path
// is itself a DIRECTORY, so appending the mkdir line fails EISDIR after
// newdir has already been created.
// Assert: exit non-zero, stderr non-empty; newdir EXISTS as a directory
// (created before the append failed: the discriminator vs the create-
// failure test); src.txt intact; newdir/dst.txt absent; stderr does not
// contain "creation" (creation succeeded; only the append failed).
// ---------------------------------------------------------------------------
#[test]
fn t_mkdir_append_failure_reports_created() {
    let tmp = tempfile::tempdir().unwrap();
    let src_file = tmp.path().join("src.txt");
    fs::write(&src_file, b"append-failure content").unwrap();
    // newdir does not exist yet; the mkdir chain must create it.
    let new_dir = tmp.path().join("newdir");
    let target = new_dir.join("dst.txt");
    // logdir is a directory, not a file: appending to it must fail EISDIR.
    let log_dir = tmp.path().join("logdir");
    fs::create_dir(&log_dir).unwrap();

    Command::cargo_bin("logmv")
        .unwrap()
        .args([
            log_dir.to_str().unwrap(),
            "--mkdir",
            src_file.to_str().unwrap(),
            target.to_str().unwrap(),
        ])
        .assert()
        .failure()
        .stderr(predicate::str::is_empty().not())
        .stderr(predicate::str::contains("creation").not());

    // newdir must exist: it was created before the log append failed.
    assert!(new_dir.is_dir(), "newdir must have been created");
    // src intact; dst absent.
    assert!(src_file.exists(), "src must be intact");
    assert!(!target.exists(), "newdir/dst.txt must not exist");
}

// ---------------------------------------------------------------------------
// t_no_mkdir_missing_parent_errors: AC5
// Arrange: file.txt; target a/b/file.txt with a/b missing; no --mkdir flag.
// Assert: exit non-zero, stderr non-empty; a/b NOT created; file.txt intact;
// no log. (Locks the flag-off boundary.)
// Regression guard (green-green): AC5 "today's behavior preserved" -- missing
// parent without --mkdir must still error; locks the mkdir flag-off boundary.
// ---------------------------------------------------------------------------
#[test]
fn t_no_mkdir_missing_parent_errors() {
    let tmp = tempfile::tempdir().unwrap();
    let src_file = tmp.path().join("file.txt");
    fs::write(&src_file, b"content").unwrap();
    // a/b does NOT exist.
    let target = tmp.path().join("a/b/file.txt");
    let log = tmp.path().join("move.log");

    Command::cargo_bin("logmv")
        .unwrap()
        .args([
            log.to_str().unwrap(),
            src_file.to_str().unwrap(),
            target.to_str().unwrap(),
        ])
        .assert()
        .failure()
        .stderr(predicate::str::is_empty().not());

    // a/b must NOT have been created.
    assert!(
        !tmp.path().join("a/b").exists(),
        "a/b must not be created without --mkdir"
    );
    // file.txt intact.
    assert!(src_file.exists(), "src must be intact");
    // No log.
    assert!(!log.exists(), "no log must be written");
}

// ---------------------------------------------------------------------------
// t_trailing_slash_mkdir_creates_dir: Q3 (AC1 + AC4)
// Trailing slash on DST signals directory intent even when DST is non-existent.
// --mkdir creates DST as a directory and moves SRC into it as
// DST/basename(SRC): NOT a file named DST.
// Assert: newdir created as a directory; newdir/file.txt exists (not a file
// named newdir); log has one mkdir line (dst=abs newdir) then move line
// whose dst=abs newdir/file.txt.
// ---------------------------------------------------------------------------
#[test]
fn t_trailing_slash_mkdir_creates_dir() {
    let tmp = tempfile::tempdir().unwrap();
    let src_file = tmp.path().join("file.txt");
    fs::write(&src_file, b"trailing-slash content").unwrap();
    // DST with trailing slash: construct string explicitly to preserve the slash.
    let dst_arg = format!("{}/newdir/", tmp.path().to_str().unwrap());
    let log = tmp.path().join("move.log");

    Command::cargo_bin("logmv")
        .unwrap()
        .args([
            log.to_str().unwrap(),
            "--mkdir",
            src_file.to_str().unwrap(),
            &dst_arg,
        ])
        .assert()
        .success()
        .stdout(predicate::str::is_empty());

    // newdir created as a directory (not a file).
    let newdir = tmp.path().join("newdir");
    assert!(newdir.is_dir(), "newdir must be created as a directory");

    // SRC moved into newdir as newdir/file.txt.
    assert!(!src_file.exists(), "src must be gone");
    let dst_file = newdir.join("file.txt");
    assert!(dst_file.exists(), "newdir/file.txt must exist");
    assert_eq!(fs::read(&dst_file).unwrap(), b"trailing-slash content");

    // Log: one mkdir line then one move line.
    let log_content = fs::read_to_string(&log).unwrap();
    let lines: Vec<&str> = log_content.lines().filter(|l| !l.is_empty()).collect();
    assert_eq!(lines.len(), 2, "log must have 2 lines: 1 mkdir + 1 move");

    let e0: serde_json::Value = serde_json::from_str(lines[0]).expect("line 0 must be valid JSON");
    let e1: serde_json::Value = serde_json::from_str(lines[1]).expect("line 1 must be valid JSON");

    assert_eq!(e0["act"], "mkdir", "line 0 must be mkdir");
    assert_eq!(e0["src"], "-");
    assert!(
        e0["dst"].as_str().unwrap().ends_with("/newdir"),
        "mkdir dst must be abs newdir, got: {}",
        e0["dst"]
    );

    assert_eq!(e1["act"], "move", "line 1 must be move");
    assert!(
        e1["dst"].as_str().unwrap().ends_with("/newdir/file.txt"),
        "move dst must be abs newdir/file.txt, got: {}",
        e1["dst"]
    );
}

// ---------------------------------------------------------------------------
// t_rmdir_cascade_and_logs: AC7 + AC8
// Arrange: keep/a/b/file.txt (b holds only file.txt, a holds only b).
// keep/ also holds other.txt (non-empty boundary). dest is existing dir out/.
// Act: logmv LOG --rmdir keep/a/b/file.txt out
// Assert: keep/a/b and keep/a removed; keep remains (cascade stopped at
// non-empty keep); out/file.txt exists; log order = move, rmdir(keep/a/b),
// rmdir(keep/a): child→parent, each dst="-".
// ---------------------------------------------------------------------------
#[test]
fn t_rmdir_cascade_and_logs() {
    let tmp = tempfile::tempdir().unwrap();
    // keep/other.txt makes keep/ non-empty after cascade.
    let keep_dir = tmp.path().join("keep");
    fs::create_dir_all(tmp.path().join("keep/a/b")).unwrap();
    fs::write(tmp.path().join("keep/other.txt"), b"anchor").unwrap();
    let src_file = tmp.path().join("keep/a/b/file.txt");
    fs::write(&src_file, b"cascade content").unwrap();
    // out/ is an existing dir (into-dir target).
    let out_dir = tmp.path().join("out");
    fs::create_dir(&out_dir).unwrap();
    let log = tmp.path().join("move.log");

    Command::cargo_bin("logmv")
        .unwrap()
        .args([
            log.to_str().unwrap(),
            "--rmdir",
            src_file.to_str().unwrap(),
            out_dir.to_str().unwrap(),
        ])
        .assert()
        .success()
        .stdout(predicate::str::is_empty());

    // keep/a/b and keep/a removed.
    assert!(
        !tmp.path().join("keep/a/b").exists(),
        "keep/a/b must be removed"
    );
    assert!(
        !tmp.path().join("keep/a").exists(),
        "keep/a must be removed"
    );

    // keep/ still exists (non-empty boundary).
    assert!(keep_dir.is_dir(), "keep must still exist (was non-empty)");

    // out/file.txt exists (into-dir move).
    let dst_file = out_dir.join("file.txt");
    assert!(dst_file.exists(), "out/file.txt must exist after move");
    assert_eq!(fs::read(&dst_file).unwrap(), b"cascade content");

    // Log: move, rmdir(keep/a/b), rmdir(keep/a); 3 lines.
    let log_content = fs::read_to_string(&log).unwrap();
    let lines: Vec<&str> = log_content.lines().filter(|l| !l.is_empty()).collect();
    assert_eq!(lines.len(), 3, "log must have 3 lines: move + 2 rmdir");

    let e0: serde_json::Value = serde_json::from_str(lines[0]).expect("line 0 must be valid JSON");
    let e1: serde_json::Value = serde_json::from_str(lines[1]).expect("line 1 must be valid JSON");
    let e2: serde_json::Value = serde_json::from_str(lines[2]).expect("line 2 must be valid JSON");

    // First line: move.
    assert_eq!(e0["act"], "move", "line 0 must be move");

    // Second line: rmdir keep/a/b (child).
    assert_eq!(e1["act"], "rmdir", "line 1 must be rmdir");
    assert_eq!(e1["dst"], "-", "rmdir dst must be '-'");
    assert!(
        e1["src"].as_str().unwrap().ends_with("/keep/a/b"),
        "line 1 rmdir src must be abs keep/a/b, got: {}",
        e1["src"]
    );

    // Third line: rmdir keep/a (parent).
    assert_eq!(e2["act"], "rmdir", "line 2 must be rmdir");
    assert_eq!(e2["dst"], "-", "rmdir dst must be '-'");
    assert!(
        e2["src"].as_str().unwrap().ends_with("/keep/a"),
        "line 2 rmdir src must be abs keep/a, got: {}",
        e2["src"]
    );
}

// ---------------------------------------------------------------------------
// t_rmdir_truly_empty_only_dsstore: AC9
// Arrange: dir/file.txt and dir/.DS_Store. Dest existing dir out/.
// Act: logmv LOG --rmdir dir/file.txt out
// Assert: dir still exists (holds .DS_Store); out/file.txt exists;
// log has the move line and zero rmdir lines.
// ---------------------------------------------------------------------------
#[test]
fn t_rmdir_truly_empty_only_dsstore() {
    let tmp = tempfile::tempdir().unwrap();
    let src_dir = tmp.path().join("dir");
    fs::create_dir(&src_dir).unwrap();
    let src_file = src_dir.join("file.txt");
    fs::write(&src_file, b"dsstore content").unwrap();
    // .DS_Store makes the dir non-empty even after file.txt is moved.
    fs::write(src_dir.join(".DS_Store"), b"store").unwrap();
    let out_dir = tmp.path().join("out");
    fs::create_dir(&out_dir).unwrap();
    let log = tmp.path().join("move.log");

    Command::cargo_bin("logmv")
        .unwrap()
        .args([
            log.to_str().unwrap(),
            "--rmdir",
            src_file.to_str().unwrap(),
            out_dir.to_str().unwrap(),
        ])
        .assert()
        .success()
        .stdout(predicate::str::is_empty());

    // dir still exists (holds .DS_Store → not truly empty).
    assert!(src_dir.is_dir(), "dir must still exist (had .DS_Store)");

    // out/file.txt exists.
    let dst_file = out_dir.join("file.txt");
    assert!(dst_file.exists(), "out/file.txt must exist");

    // Log: exactly one line (the move), zero rmdir lines.
    let log_content = fs::read_to_string(&log).unwrap();
    let lines: Vec<&str> = log_content.lines().filter(|l| !l.is_empty()).collect();
    assert_eq!(
        lines.len(),
        1,
        "log must have exactly 1 line (no rmdir for .DS_Store dir)"
    );

    let entry: serde_json::Value =
        serde_json::from_str(lines[0]).expect("log line must be valid JSON");
    assert_eq!(entry["act"], "move", "the sole log line must be act=move");
}

// ---------------------------------------------------------------------------
// t_rmdir_with_trash: AC10
// Arrange: dir/only.txt (sole entry of dir); inject $HOME seam.
// Act: logmv LOG --rmdir --trash dir/only.txt (HOME=$HOME/.Trash used)
// Assert: content recoverable in $HOME/.Trash (never unlinked); dir removed;
// log = trash line (dst: canonical landing path, .../only.txt) then one rmdir line (src=abs dir, dst="-").
// ---------------------------------------------------------------------------
#[test]
fn t_rmdir_with_trash() {
    let tmp = tempfile::tempdir().unwrap();
    let src_dir = tmp.path().join("dir");
    fs::create_dir(&src_dir).unwrap();
    let src_file = src_dir.join("only.txt");
    fs::write(&src_file, b"trash cascade content").unwrap();
    let home_tmp = tempfile::tempdir().unwrap(); // inject $HOME seam
    let trash_root = home_tmp.path().join(".Trash");
    fs::create_dir(&trash_root).unwrap();
    let log = tmp.path().join("move.log");

    Command::cargo_bin("logmv")
        .unwrap()
        .env("HOME", home_tmp.path())
        .args([
            log.to_str().unwrap(),
            "--rmdir",
            "--trash",
            src_file.to_str().unwrap(),
        ])
        .assert()
        .success()
        .stdout(predicate::str::is_empty());

    // Content recoverable in $HOME/.Trash (never unlinked).
    let trashed = trash_root.join("only.txt");
    assert!(trashed.exists(), "content must be in trash dir");
    assert_eq!(fs::read(&trashed).unwrap(), b"trash cascade content");

    // dir removed (was empty after trash).
    assert!(
        !src_dir.exists(),
        "dir must be removed after --rmdir with --trash"
    );

    // Log: trash line then rmdir line; 2 lines total.
    let log_content = fs::read_to_string(&log).unwrap();
    let lines: Vec<&str> = log_content.lines().filter(|l| !l.is_empty()).collect();
    assert_eq!(lines.len(), 2, "log must have 2 lines: trash + rmdir");

    let e0: serde_json::Value = serde_json::from_str(lines[0]).expect("line 0 must be valid JSON");
    let e1: serde_json::Value = serde_json::from_str(lines[1]).expect("line 1 must be valid JSON");

    assert_eq!(e0["act"], "trash", "line 0 must be trash");
    let expected_dst = std::fs::canonicalize(&trash_root).unwrap().join("only.txt");
    let expected_dst_str = expected_dst.to_str().unwrap();
    let dst_val = e0["dst"].as_str().expect("dst must be a string");
    assert!(
        dst_val.starts_with('/'),
        "dst must be absolute, got: {dst_val}"
    );
    assert_eq!(
        dst_val, expected_dst_str,
        "dst must be the canonical landing path"
    );

    assert_eq!(e1["act"], "rmdir", "line 1 must be rmdir");
    assert_eq!(e1["dst"], "-", "rmdir dst must be '-'");
    assert!(
        e1["src"].as_str().unwrap().ends_with("/dir"),
        "rmdir src must be abs dir, got: {}",
        e1["src"]
    );
}

// ---------------------------------------------------------------------------
// t_mkdir_isolation_doomed_move: AC11 (mkdir half)
// Arrange: file.txt; target a/b/file.txt with a/b missing; --mkdir PLUS
// a colliding metadata pair ts X.
// Assert: exit non-zero; a/b NOT created (mkdir refused before mutation by
// early pair-collision check); file.txt intact; no log.
// ---------------------------------------------------------------------------
#[test]
fn t_mkdir_isolation_doomed_move() {
    let tmp = tempfile::tempdir().unwrap();
    let src_file = tmp.path().join("file.txt");
    fs::write(&src_file, b"content").unwrap();
    let target = tmp.path().join("a/b/file.txt");
    let log = tmp.path().join("move.log");

    Command::cargo_bin("logmv")
        .unwrap()
        .args([
            log.to_str().unwrap(),
            "--mkdir",
            src_file.to_str().unwrap(),
            target.to_str().unwrap(),
            "ts",
            "X", // canonical-key collision: must refuse before any mkdir
        ])
        .assert()
        .failure()
        // Must be the canonical-key collision error, not the clap odd-args error.
        // Real error: "metadata key collides with canonical key: ts"
        .stderr(predicate::str::contains("collides"));

    // a/b must NOT have been created (doomed move creates zero dirs).
    assert!(
        !tmp.path().join("a/b").exists(),
        "a/b must not be created for a doomed move"
    );
    // file.txt intact.
    assert!(src_file.exists(), "src must be intact");
    // No log.
    assert!(!log.exists(), "no log must be written for a doomed move");
}

// ---------------------------------------------------------------------------
// t_rmdir_not_run_when_move_log_fails: AC11 (rmdir half)
// Reuses T9's EISDIR drift trick: move physically succeeds but the log append
// fails (LOG is a directory). --rmdir must NOT run when the move's log append
// fails. Red discriminator: dst.txt IS created (move happened) while keep/a
// STILL EXISTS (rmdir skipped). Under current arg-parse death dst.txt is never
// created, making the dst.exists() assertion the decisive red signal.
// ---------------------------------------------------------------------------
#[test]
fn t_rmdir_not_run_when_move_log_fails() {
    let tmp = tempfile::tempdir().unwrap();
    // keep/a/file.txt: a holds only that file (will be empty after move).
    fs::create_dir_all(tmp.path().join("keep/a")).unwrap();
    let src_file = tmp.path().join("keep/a/file.txt");
    fs::write(&src_file, b"drift content").unwrap();
    // Plain non-existent destination (not a dir).
    let dst = tmp.path().join("dst.txt");
    // LOG is a directory: causes EISDIR on append, after the rename succeeds.
    let log_as_dir = tmp.path().join("logdir");
    fs::create_dir(&log_as_dir).unwrap();

    Command::cargo_bin("logmv")
        .unwrap()
        .args([
            log_as_dir.to_str().unwrap(),
            "--rmdir",
            src_file.to_str().unwrap(),
            dst.to_str().unwrap(),
        ])
        .assert()
        .failure()
        .stderr(predicate::str::is_empty().not());

    // Move physically happened: dst.txt exists with the moved content.
    assert!(
        dst.exists(),
        "dst must exist: move happened before log failed"
    );
    assert_eq!(fs::read(&dst).unwrap(), b"drift content");
    // src is gone (rename was atomic).
    assert!(!src_file.exists(), "src must be gone after rename");
    // keep/a STILL EXISTS: rmdir was correctly skipped (move log append failed).
    assert!(
        tmp.path().join("keep/a").is_dir(),
        "keep/a must still exist: --rmdir must not run when log append fails"
    );
}

// ---------------------------------------------------------------------------
// t_full_sequence_order_schema: AC12
// Arrange: src/x/file.txt (x empties after move, src holds only x).
// Dest chain dst/y/z/ missing entirely.
// Act: logmv LOG --mkdir --rmdir src/x/file.txt dst/y/z/file.txt
// Assert: full log line sequence in exact order:
//   mkdir(src="-", dst=abs dst/), mkdir(dst=abs dst/y/), mkdir(dst=abs dst/y/z/),
//   move, rmdir(src=abs src/x/, dst="-"), rmdir(src=abs src/, dst="-").
// Every line parses as compact JSON on ts/act/src/dst schema.
// Move done, dirs created/removed as expected.
// ---------------------------------------------------------------------------
#[test]
fn t_full_sequence_order_schema() {
    let tmp = tempfile::tempdir().unwrap();
    // src/x/file.txt: x holds only file.txt; src holds only x.
    let src_base = tmp.path().join("src");
    let x_dir = src_base.join("x");
    fs::create_dir_all(&x_dir).unwrap();
    let src_file = x_dir.join("file.txt");
    fs::write(&src_file, b"full sequence content").unwrap();
    // dst/y/z/ does NOT exist.
    let target = tmp.path().join("dst/y/z/file.txt");
    let log = tmp.path().join("move.log");

    Command::cargo_bin("logmv")
        .unwrap()
        .args([
            log.to_str().unwrap(),
            "--mkdir",
            "--rmdir",
            src_file.to_str().unwrap(),
            target.to_str().unwrap(),
        ])
        .assert()
        .success()
        .stdout(predicate::str::is_empty());

    // Move done.
    assert!(!src_file.exists(), "src file must be gone");
    assert!(target.exists(), "target file must exist");
    assert_eq!(fs::read(&target).unwrap(), b"full sequence content");

    // Dirs created (dst chain).
    assert!(tmp.path().join("dst").is_dir());
    assert!(tmp.path().join("dst/y").is_dir());
    assert!(tmp.path().join("dst/y/z").is_dir());

    // Dirs removed (src chain cascaded).
    assert!(!x_dir.exists(), "src/x must be removed");
    assert!(!src_base.exists(), "src must be removed");

    // Log: read all lines.
    let log_content = fs::read_to_string(&log).unwrap();
    let lines: Vec<&str> = log_content.lines().filter(|l| !l.is_empty()).collect();
    // 3 mkdir + 1 move + 2 rmdir = 6 lines.
    assert_eq!(
        lines.len(),
        6,
        "log must have 6 lines (3 mkdir + move + 2 rmdir)"
    );

    let entries: Vec<serde_json::Value> = lines
        .iter()
        .enumerate()
        .map(|(i, l)| {
            serde_json::from_str(l).unwrap_or_else(|e| panic!("line {i} must be valid JSON: {e}"))
        })
        .collect();

    // Every line has ts/act/src/dst as first four keys.
    for (i, entry) in entries.iter().enumerate() {
        let obj = entry.as_object().unwrap();
        let keys: Vec<&str> = obj.keys().map(|k| k.as_str()).collect();
        assert_eq!(
            &keys[..4],
            &["ts", "act", "src", "dst"],
            "line {i} must have canonical keys first, got: {keys:?}"
        );
        // ts parses.
        chrono::DateTime::parse_from_rfc3339(entry["ts"].as_str().unwrap())
            .unwrap_or_else(|_| panic!("line {i} ts must be valid RFC3339"));
    }

    // Lines 0-2: mkdir in parent→child order.
    assert_eq!(entries[0]["act"], "mkdir");
    assert_eq!(entries[0]["src"], "-");
    assert!(
        entries[0]["dst"].as_str().unwrap().ends_with("/dst"),
        "line 0 mkdir dst must be abs dst/, got: {}",
        entries[0]["dst"]
    );

    assert_eq!(entries[1]["act"], "mkdir");
    assert_eq!(entries[1]["src"], "-");
    assert!(
        entries[1]["dst"].as_str().unwrap().ends_with("/dst/y"),
        "line 1 mkdir dst must be abs dst/y, got: {}",
        entries[1]["dst"]
    );

    assert_eq!(entries[2]["act"], "mkdir");
    assert_eq!(entries[2]["src"], "-");
    assert!(
        entries[2]["dst"].as_str().unwrap().ends_with("/dst/y/z"),
        "line 2 mkdir dst must be abs dst/y/z, got: {}",
        entries[2]["dst"]
    );

    // Line 3: move.
    assert_eq!(entries[3]["act"], "move");
    assert!(
        entries[3]["src"]
            .as_str()
            .unwrap()
            .ends_with("/src/x/file.txt"),
        "move src got: {}",
        entries[3]["src"]
    );
    assert!(
        entries[3]["dst"]
            .as_str()
            .unwrap()
            .ends_with("/dst/y/z/file.txt"),
        "move dst got: {}",
        entries[3]["dst"]
    );

    // Lines 4-5: rmdir in child→parent order.
    assert_eq!(entries[4]["act"], "rmdir");
    assert_eq!(entries[4]["dst"], "-");
    assert!(
        entries[4]["src"].as_str().unwrap().ends_with("/src/x"),
        "line 4 rmdir src must be abs src/x, got: {}",
        entries[4]["src"]
    );

    assert_eq!(entries[5]["act"], "rmdir");
    assert_eq!(entries[5]["dst"], "-");
    assert!(
        entries[5]["src"].as_str().unwrap().ends_with("/src"),
        "line 5 rmdir src must be abs src, got: {}",
        entries[5]["src"]
    );
}

// ---------------------------------------------------------------------------
// T11: AC1, AC4  [never-overwrite invariant, dangling-symlink move dest]
// Move onto a dangling-symlink destination must be refused (no-clobber): the
// atomic primitive checks the directory entry itself (symlink not followed),
// unlike the old `.exists()` check which follows the link and sees "nothing".
// ---------------------------------------------------------------------------
#[test]
fn t_move_refuses_dangling_symlink_dest() {
    let tmp = tempfile::tempdir().unwrap();
    let src = tmp.path().join("src.txt");
    fs::write(&src, b"source content").unwrap();
    let dst = tmp.path().join("dst.txt");
    // Dangling symlink: target need not exist.
    std::os::unix::fs::symlink(tmp.path().join("does-not-exist"), &dst).unwrap();
    let log = tmp.path().join("log.jsonl");

    Command::cargo_bin("logmv")
        .unwrap()
        .args([
            log.to_str().unwrap(),
            src.to_str().unwrap(),
            dst.to_str().unwrap(),
        ])
        .assert()
        .failure()
        .stdout(predicate::str::is_empty())
        .stderr(predicate::str::is_empty().not());

    // src must be intact.
    assert!(src.exists(), "src must be intact after refusal");
    assert_eq!(
        fs::read(&src).unwrap(),
        b"source content",
        "src content must be unchanged"
    );

    // dst must still be a dangling symlink, not replaced.
    assert!(
        fs::symlink_metadata(&dst).unwrap().file_type().is_symlink(),
        "dst symlink must not be clobbered"
    );

    // No log must have been written.
    assert!(!log.exists(), "no log file must be created on refusal");
}

// ---------------------------------------------------------------------------
// T12: AC1, AC4  [never-overwrite invariant, dangling-symlink trash collision]
// Trash where the trash-dir name is a dangling symlink must disambiguate
// rather than clobbering the symlink: the atomic primitive checks the
// directory entry itself (symlink not followed).
// ---------------------------------------------------------------------------
#[test]
fn t_trash_disambiguates_around_dangling_symlink() {
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("file.txt");
    fs::write(&src, b"new content").unwrap();
    let home_tmp = tempfile::tempdir().unwrap();
    let trash_root = home_tmp.path().join(".Trash");
    fs::create_dir(&trash_root).unwrap();
    // Pre-seed the colliding name as a dangling symlink.
    std::os::unix::fs::symlink(home_tmp.path().join("nope"), trash_root.join("file.txt")).unwrap();
    let log = dir.path().join("log.jsonl");

    Command::cargo_bin("logmv")
        .unwrap()
        .env("HOME", home_tmp.path())
        .args([log.to_str().unwrap(), "--trash", src.to_str().unwrap()])
        .assert()
        .success()
        .stdout(predicate::str::is_empty());

    // Source must be gone.
    assert!(!src.exists(), "source must be gone after trash");

    // Pre-existing dangling symlink must not be clobbered.
    assert!(
        fs::symlink_metadata(trash_root.join("file.txt"))
            .unwrap()
            .file_type()
            .is_symlink(),
        "pre-existing dangling symlink must not be clobbered"
    );

    // Trashed content must land at the disambiguated name.
    assert_eq!(
        fs::read(trash_root.join("file-1.txt")).unwrap(),
        b"new content",
        "trashed content must land at disambiguated name"
    );

    // Log must record the disambiguated landing path.
    let log_content = fs::read_to_string(&log).unwrap();
    let lines: Vec<&str> = log_content.lines().filter(|l| !l.is_empty()).collect();
    assert_eq!(lines.len(), 1, "log must have exactly one line");
    let entry: serde_json::Value =
        serde_json::from_str(lines[0]).expect("log line must be valid JSON");
    assert_eq!(entry["act"], "trash");
    let expected_dst = std::fs::canonicalize(&trash_root)
        .unwrap()
        .join("file-1.txt");
    let expected_dst_str = expected_dst.to_str().unwrap();
    let dst_val = entry["dst"].as_str().expect("dst must be a string");
    assert!(
        dst_val.starts_with('/'),
        "dst must be absolute, got: {dst_val}"
    );
    assert!(
        dst_val.ends_with("/file-1.txt"),
        "dst must end with /file-1.txt (disambiguated suffix), got: {dst_val}"
    );
    assert_eq!(
        dst_val, expected_dst_str,
        "dst must be the canonical landing path for the disambiguated file"
    );
}

// ---------------------------------------------------------------------------
// t_trash_rejects_empty_home: AC1; AC2 (empty case)
// Empty HOME ("") with a pre-existing cwd-relative .Trash (the buggy target)
// must be rejected before any rename: exit non-zero, stderr non-empty; src
// intact and unchanged; nothing landed in cwd-relative .Trash; no log written.
// ---------------------------------------------------------------------------
#[test]
fn t_trash_rejects_empty_home() {
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("precious.txt");
    fs::write(&src, b"irreplaceable").unwrap();
    // Pre-create the buggy target so current code would silently succeed.
    fs::create_dir(dir.path().join(".Trash")).unwrap();
    let log = dir.path().join("trash.log");

    Command::cargo_bin("logmv")
        .unwrap()
        .current_dir(dir.path())
        .env("HOME", "")
        .args([log.to_str().unwrap(), "--trash", src.to_str().unwrap()])
        .assert()
        .failure()
        .stderr(predicate::str::is_empty().not());

    // Source must be intact on rejection.
    assert!(src.exists(), "source must be intact on rejection");
    assert_eq!(fs::read(&src).unwrap(), b"irreplaceable");

    // File must NOT be trashed into cwd-relative .Trash.
    assert!(
        !dir.path().join(".Trash").join("precious.txt").exists(),
        "file must NOT be trashed into cwd-relative .Trash"
    );

    // No log written on pre-rename rejection.
    assert!(!log.exists(), "no log written on pre-rename rejection");
}

// ---------------------------------------------------------------------------
// t_trash_rejects_relative_home: AC1; AC2 (relative case)
// Relative HOME ("relhome") with a pre-existing cwd-relative relhome/.Trash
// (the buggy target) must be rejected before any rename: exit non-zero,
// stderr non-empty; src intact and unchanged; nothing landed in the
// cwd-relative relhome/.Trash; no log written.
// ---------------------------------------------------------------------------
#[test]
fn t_trash_rejects_relative_home() {
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("precious.txt");
    fs::write(&src, b"irreplaceable").unwrap();
    // Pre-create the buggy target so current code would silently succeed.
    fs::create_dir_all(dir.path().join("relhome").join(".Trash")).unwrap();
    let log = dir.path().join("trash.log");

    Command::cargo_bin("logmv")
        .unwrap()
        .current_dir(dir.path())
        .env("HOME", "relhome")
        .args([log.to_str().unwrap(), "--trash", src.to_str().unwrap()])
        .assert()
        .failure()
        .stderr(predicate::str::is_empty().not());

    // Source must be intact on rejection.
    assert!(src.exists(), "source must be intact on rejection");
    assert_eq!(fs::read(&src).unwrap(), b"irreplaceable");

    // File must NOT be trashed into cwd-relative relhome/.Trash.
    assert!(
        !dir.path()
            .join("relhome")
            .join(".Trash")
            .join("precious.txt")
            .exists(),
        "file must NOT be trashed into cwd-relative relhome/.Trash"
    );

    // No log written on pre-rename rejection.
    assert!(!log.exists(), "no log written on pre-rename rejection");
}

// ---------------------------------------------------------------------------
// t_flag_after_positionals_rejected: AC1/AC3
// Move mode: a --mkdir token appearing after SRC/DST positionals lands in the
// trailing metadata slab. It must be rejected, not silently logged as a junk
// pair: exit non-zero, stderr non-empty, no log file written, SRC intact, no
// dst created.
// ---------------------------------------------------------------------------
#[test]
fn t_flag_after_positionals_rejected() {
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("src.txt");
    fs::write(&src, b"hello").unwrap();
    let dst = dir.path().join("dst.txt");
    let log = dir.path().join("move.log");

    Command::cargo_bin("logmv")
        .unwrap()
        .current_dir(dir.path())
        .args([
            log.to_str().unwrap(),
            "src.txt",
            "dst.txt",
            "--mkdir",
            "somevalue",
        ])
        .assert()
        .failure()
        .stderr(predicate::str::is_empty().not());

    // No log written: the junk pair must never reach the frozen log contract.
    assert!(
        !log.exists(),
        "no log file must be created when a --flag token appears after positionals"
    );

    // src must be intact: the guard must fire before any rename.
    assert!(src.exists(), "src must be intact after rejection");
    assert_eq!(fs::read(&src).unwrap(), b"hello");

    // dst must not have been created.
    assert!(!dst.exists(), "dst must not be created after rejection");
}

// ---------------------------------------------------------------------------
// t_trash_flag_after_positionals_rejected: AC1
// Trash mode: a --mkdir token appearing after the trash positionals lands in
// the metadata slab (pair_up(&rest)). Must be rejected before any rename: exit
// non-zero, stderr non-empty, no log written, source intact at its origin, and
// nothing landed in $HOME/.Trash. HOME is seeded to a tempdir so a red run
// never touches the real ~/.Trash.
// ---------------------------------------------------------------------------
#[test]
fn t_trash_flag_after_positionals_rejected() {
    let dir = tempfile::tempdir().unwrap();
    let home_tmp = tempfile::tempdir().unwrap(); // inject $HOME seam
    let trash_root = home_tmp.path().join(".Trash");
    fs::create_dir(&trash_root).unwrap();
    let p = dir.path().join("precious.txt");
    fs::write(&p, b"irreplaceable").unwrap();
    let log = dir.path().join("trash.log");

    Command::cargo_bin("logmv")
        .unwrap()
        .env("HOME", home_tmp.path())
        .args([
            log.to_str().unwrap(),
            "--trash",
            p.to_str().unwrap(),
            "a",
            "b",
            "--mkdir",
            "c",
        ])
        .assert()
        .failure()
        .stderr(predicate::str::is_empty().not());

    // No log written on rejection.
    assert!(
        !log.exists(),
        "no log file must be created when a --flag token appears after trash positionals"
    );

    // Source must be intact at its origin.
    assert!(p.exists(), "source must be intact after rejection");
    assert_eq!(fs::read(&p).unwrap(), b"irreplaceable");

    // Nothing must have landed in $HOME/.Trash.
    assert!(
        !trash_root.join("precious.txt").exists(),
        "file must NOT be trashed into $HOME/.Trash on rejection"
    );
}

// ---------------------------------------------------------------------------
// t_hyphen_metadata_key_supported: AC2/AC3
// Boundary lock: a mid-hyphen metadata key (created-by) that does NOT start
// with -- must remain a supported, ordinary K/V pair. Passes today and after
// the guard lands; its purpose is to fail if a future guard over-rejects any
// hyphen instead of only a leading --.
// ---------------------------------------------------------------------------
#[test]
fn t_hyphen_metadata_key_supported() {
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("src.txt");
    fs::write(&src, b"hello").unwrap();
    let log = dir.path().join("move.log");

    Command::cargo_bin("logmv")
        .unwrap()
        .current_dir(dir.path())
        .args([
            log.to_str().unwrap(),
            "src.txt",
            "dst.txt",
            "created-by",
            "alice",
        ])
        .assert()
        .success();

    // src must be gone.
    assert!(!src.exists(), "src must be gone after move");

    // dst must exist.
    let dst = dir.path().join("dst.txt");
    assert!(dst.exists(), "dst must exist after move");

    // log must have exactly one line.
    let log_content = fs::read_to_string(&log).unwrap();
    let lines: Vec<&str> = log_content.lines().collect();
    assert_eq!(lines.len(), 1, "log must have exactly one line");

    let entry: serde_json::Value =
        serde_json::from_str(lines[0]).expect("log line must be valid JSON");
    let obj = entry.as_object().unwrap();
    let keys: Vec<&str> = obj.keys().map(|k| k.as_str()).collect();
    assert_eq!(
        &keys[..4],
        &["ts", "act", "src", "dst"],
        "first four keys must be canonical in order, got: {keys:?}"
    );
    assert_eq!(
        &keys[4..],
        &["created-by"],
        "mid-hyphen key must follow canonical keys, got: {keys:?}"
    );
    assert_eq!(entry["created-by"].as_str().unwrap(), "alice");
}