aboutsummaryrefslogtreecommitdiff
path: root/internal/engine/apply_test.go
blob: c832e3a36a8d4db53345c79b23085036a36a9113 (plain) (blame)
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
// SPDX-License-Identifier: GPL-3.0-or-later

package engine

import (
	"context"
	"os"
	"path"
	"path/filepath"
	"strings"
	"testing"
	"time"

	"git.labunix.xyz/krino/internal/apply"
	"git.labunix.xyz/krino/internal/journal"
	"git.labunix.xyz/krino/internal/plan"
	"git.labunix.xyz/krino/internal/trash"
)

// applyFixture builds a directory with two files and a rule moving pdfs into
// Work, then plans it. It returns the home, the plan and an open journal.
//
// This uses writeConfig, which takes a main-file body and a dirs map keyed
// by name (see TestLoadRejectsUnsuppliedCaptures's comment in
// engine_test.go for the same shape used elsewhere in this package): the
// real config language (docs/design.md §4.2-4.3) requires `(path ...)` and
// `(rule ...)` in a directory file reached through `(include ...)`, not in
// the main file directly.
func applyFixture(t *testing.T) (string, *Engine, *DirPlan, *journal.Writer, string) {
	t.Helper()
	h := sandbox(t)
	dl := filepath.Join(h, "dl")
	for name, body := range map[string]string{"a.pdf": "one", "b.txt": "two"} {
		if err := os.MkdirAll(dl, 0o755); err != nil {
			t.Fatal(err)
		}
		if err := os.WriteFile(filepath.Join(dl, name), []byte(body), 0o644); err != nil {
			t.Fatal(err)
		}
		old := time.Now().Add(-time.Hour)
		os.Chtimes(filepath.Join(dl, name), old, old)
	}
	main := writeConfig(t, h, `(include "dl")`, map[string]string{
		"dl": `(path "~/dl")` + "\n" + `(rule "pdfs" (when (type pdf)) (move "Work"))`,
	})
	e, errs := Load(main)
	if len(errs) > 0 {
		t.Fatal(errs)
	}
	dp, err := e.Plan(context.Background(), e.Dirs[0], plan.NewClaims())
	if err != nil {
		t.Fatal(err)
	}
	j, err := journal.Open(filepath.Join(h, ".local", "state", "krino", "krino.log"))
	if err != nil {
		t.Fatal(err)
	}
	t.Cleanup(func() { j.Close() })
	return h, e, dp, j, journal.NewRunID(time.Now())
}

func TestApplyMovesApprovedAndDeclinesTheRest(t *testing.T) {
	h, e, dp, j, run := applyFixture(t)
	res, err := e.Apply(context.Background(), dp, map[string]bool{"a.pdf": true}, j, run)
	if err != nil {
		t.Fatal(err)
	}
	if res.Applied != 1 || res.Failed != 0 {
		t.Errorf("result = %+v; want one applied, none failed", res)
	}
	if _, err := os.Stat(filepath.Join(h, "dl", "Work", "a.pdf")); err != nil {
		t.Errorf("the approved file did not move: %v", err)
	}
	if _, err := os.Stat(filepath.Join(h, "dl", "a.pdf")); !os.IsNotExist(err) {
		t.Error("the original survived the move")
	}
	if _, err := os.Stat(filepath.Join(h, "dl", "b.txt")); err != nil {
		t.Error("a file that matched no rule was touched")
	}
}

func TestApplyLogsRunBoundariesAndSteps(t *testing.T) {
	h, e, dp, j, run := applyFixture(t)
	if _, err := e.Apply(context.Background(), dp, map[string]bool{"a.pdf": true}, j, run); err != nil {
		t.Fatal(err)
	}
	j.Close()

	entries, err := journal.Entries(filepath.Join(h, ".local", "state", "krino", "krino.log"), run)
	if err != nil {
		t.Fatal(err)
	}
	if len(entries) < 3 {
		t.Fatalf("logged %d entries, want run-start, at least one step and run-end", len(entries))
	}
	if entries[0].Action != "run-start" || entries[len(entries)-1].Action != "run-end" {
		t.Errorf("boundaries = %q .. %q", entries[0].Action, entries[len(entries)-1].Action)
	}
	var moved *journal.Entry
	for i := range entries {
		if entries[i].Action == "move" {
			moved = &entries[i]
		}
	}
	if moved == nil {
		t.Fatal("no move entry was logged")
	}
	if moved.Status != "ok" || moved.File != "a.pdf" || moved.Rule != "pdfs" {
		t.Errorf("move entry = %+v", *moved)
	}
	if moved.Size != int64(len("one")) {
		t.Errorf("Size = %d; want the size at Dst after the step", moved.Size)
	}
	if !strings.HasSuffix(moved.Dst, filepath.Join("Work", "a.pdf")) {
		t.Errorf("Dst = %q", moved.Dst)
	}
}

func TestPlanUndoReversesLastStepFirst(t *testing.T) {
	h, e, dp, j, run := applyFixture(t)
	if _, err := e.Apply(context.Background(), dp, map[string]bool{"a.pdf": true}, j, run); err != nil {
		t.Fatal(err)
	}
	j.Close()

	up, err := e.PlanUndo(run)
	if err != nil {
		t.Fatal(err)
	}
	if len(up.Files) != 1 {
		t.Fatalf("undo plan covers %d files, want 1", len(up.Files))
	}
	f := up.Files[0]
	if f.Refused != "" {
		t.Fatalf("undo refused: %s", f.Refused)
	}
	if len(f.Steps) == 0 || f.Steps[0].Action != "undo-move" {
		t.Fatalf("steps = %+v; want undo-move first", f.Steps)
	}
	if f.Steps[0].Dst != filepath.Join(h, "dl", "a.pdf") {
		t.Errorf("undo-move puts the file at %q, want its original path", f.Steps[0].Dst)
	}
}

// TestPlanUndoRefusesWholeFileWhenOneStepCannotBeReversed: spec §10 - no file
// is left half undone, so one refused step refuses the file.
func TestPlanUndoRefusesWholeFileWhenOneStepCannotBeReversed(t *testing.T) {
	h, e, dp, j, run := applyFixture(t)
	if _, err := e.Apply(context.Background(), dp, map[string]bool{"a.pdf": true}, j, run); err != nil {
		t.Fatal(err)
	}
	j.Close()
	// Someone edited the moved file, so the reversal is no longer safe.
	moved := filepath.Join(h, "dl", "Work", "a.pdf")
	if err := os.WriteFile(moved, []byte("edited since the run"), 0o644); err != nil {
		t.Fatal(err)
	}

	up, err := e.PlanUndo(run)
	if err != nil {
		t.Fatal(err)
	}
	f := up.Files[0]
	if f.Refused == "" {
		t.Fatal("undo did not refuse a file that changed since the run")
	}
	if !strings.Contains(f.Refused, "changed") {
		t.Errorf("Refused = %q; want it to say the file changed", f.Refused)
	}
}

func TestPlanUndoRefusesPermanentDelete(t *testing.T) {
	h := sandbox(t)
	dl := filepath.Join(h, "dl")
	os.MkdirAll(dl, 0o755)
	os.WriteFile(filepath.Join(dl, "old.iso"), []byte("gone"), 0o644)
	old := time.Now().Add(-time.Hour)
	os.Chtimes(filepath.Join(dl, "old.iso"), old, old)
	main := writeConfig(t, h, `(include "dl")`, map[string]string{
		"dl": `(path "~/dl")` + "\n" + `(rule "purge" (when (type iso)) (delete permanent))`,
	})
	e, errs := Load(main)
	if len(errs) > 0 {
		t.Fatal(errs)
	}
	dp, err := e.Plan(context.Background(), e.Dirs[0], plan.NewClaims())
	if err != nil {
		t.Fatal(err)
	}
	j, _ := journal.Open(filepath.Join(h, ".local", "state", "krino", "krino.log"))
	run := journal.NewRunID(time.Now())
	if _, err := e.Apply(context.Background(), dp, map[string]bool{"old.iso": true}, j, run); err != nil {
		t.Fatal(err)
	}
	j.Close()

	up, err := e.PlanUndo(run)
	if err != nil {
		t.Fatal(err)
	}
	if up.Files[0].Refused == "" || !strings.Contains(up.Files[0].Refused, "permanent") {
		t.Errorf("Refused = %q; want it to name the permanent delete", up.Files[0].Refused)
	}
}

// TestPlanUndoDropsDeclinedFileButKeepsPermanentDelete: a file the
// ORIGINAL forward run declined (spec §9: its steps are still logged,
// status "declined") has no "ok" entries at all, so planUndoFile's
// last-to-first walk skips every one of them and returns an UndoFile with
// Steps == nil and Refused == "" - a file that was never touched, not a
// reversible one. Without the guard against that, PlanUndo would append
// that empty UndoFile anyway, and undoActionableCount (cmd/krino) counts
// every Refused == "" file as "to reverse" regardless of whether it has
// any steps - inflating the header's count while the table renders no row
// for it and the final tally comes up one short, silently, at exit 0.
//
// The two halves live in one test, deliberately: a fix that dropped every
// zero-step UndoFile instead of the correct
// "len(Steps) == 0 && Refused == \"\"" condition would also drop a
// permanently deleted file (zero steps, but Refused IS set - spec §10
// requires it to stay visible with its reason) - so both conditions live
// in the same test, and a future "simplification" that breaks either one
// fails this one test immediately.
func TestPlanUndoDropsDeclinedFileButKeepsPermanentDelete(t *testing.T) {
	h := sandbox(t)
	dl := filepath.Join(h, "dl")
	if err := os.MkdirAll(dl, 0o755); err != nil {
		t.Fatal(err)
	}
	files := map[string]string{"moved.pdf": "one", "declined.pdf": "two", "old.iso": "gone"}
	old := time.Now().Add(-time.Hour)
	for name, body := range files {
		p := filepath.Join(dl, name)
		if err := os.WriteFile(p, []byte(body), 0o644); err != nil {
			t.Fatal(err)
		}
		if err := os.Chtimes(p, old, old); err != nil {
			t.Fatal(err)
		}
	}
	main := writeConfig(t, h, `(include "dl")`, map[string]string{
		"dl": `(path "~/dl")` + "\n" +
			`(rule "pdfs" (when (type pdf)) (move "Work"))` + "\n" +
			`(rule "purge" (when (type iso)) (delete permanent))`,
	})
	e, errs := Load(main)
	if len(errs) > 0 {
		t.Fatal(errs)
	}
	dp, err := e.Plan(context.Background(), e.Dirs[0], plan.NewClaims())
	if err != nil {
		t.Fatal(err)
	}
	j, err := journal.Open(filepath.Join(h, ".local", "state", "krino", "krino.log"))
	if err != nil {
		t.Fatal(err)
	}
	run := journal.NewRunID(time.Now())
	// declined.pdf is deliberately left out of approved: spec §9 still logs
	// its step, status "declined" - it was never touched.
	if _, err := e.Apply(context.Background(), dp, map[string]bool{"moved.pdf": true, "old.iso": true}, j, run); err != nil {
		t.Fatal(err)
	}
	j.Close()

	up, err := e.PlanUndo(run)
	if err != nil {
		t.Fatal(err)
	}

	byFile := map[string]UndoFile{}
	for _, f := range up.Files {
		byFile[f.File] = f
	}

	if _, ok := byFile["declined.pdf"]; ok {
		t.Errorf("a file with no \"ok\" entries (declined in the original run) must not appear in the undo plan at all: %+v", up.Files)
	}
	if got := byFile["moved.pdf"]; len(got.Steps) == 0 {
		t.Errorf("the actually-reversed file lost its steps: %+v", got)
	}
	permDel, ok := byFile["old.iso"]
	if !ok {
		t.Fatal("the permanently deleted file was dropped too - a zero-step file is not always an untouched one, and this one must stay visible with its refusal reason")
	}
	if permDel.Refused == "" || !strings.Contains(permDel.Refused, "permanent") {
		t.Errorf("Refused = %q; want it to still name the permanent delete", permDel.Refused)
	}
	if len(up.Files) != 2 {
		t.Errorf("undo plan has %d files, want exactly 2 (moved.pdf and old.iso); declined.pdf must be omitted, not merely empty: %+v", len(up.Files), up.Files)
	}
}

// TestPlanUndoAcceptsIntactRun: journal.Entries returning a nil error for a
// run whose run-start and run-end both parsed cleanly is the signal that
// the chain is intact, and PlanUndo must build a usable plan from it
// rather than refuse.
func TestPlanUndoAcceptsIntactRun(t *testing.T) {
	h, e, dp, j, run := applyFixture(t)
	if _, err := e.Apply(context.Background(), dp, map[string]bool{"a.pdf": true}, j, run); err != nil {
		t.Fatal(err)
	}
	j.Close()

	logPath := filepath.Join(h, ".local", "state", "krino", "krino.log")
	entries, err := journal.Entries(logPath, run)
	if err != nil {
		t.Fatalf("Entries refused a fully intact run: %v", err)
	}
	if entries[len(entries)-1].Action != "run-end" {
		t.Fatalf("fixture run is not intact: last action %q", entries[len(entries)-1].Action)
	}

	up, err := e.PlanUndo(run)
	if err != nil {
		t.Fatalf("PlanUndo refused an intact run: %v", err)
	}
	if len(up.Files) != 1 || up.Files[0].Refused != "" {
		t.Fatalf("intact run did not yield a usable undo plan: %+v", up)
	}
}

// TestPlanUndoAcceptsCrashedRun: a run-start with no run-end (the process
// died mid-run) must still yield a usable undo plan, per Entries' documented
// window-to-EOF behaviour. A refusal here would mean PlanUndo's assumption
// and Entries' actual behaviour have drifted apart.
func TestPlanUndoAcceptsCrashedRun(t *testing.T) {
	h, e, dp, j, run := applyFixture(t)
	if _, err := e.Apply(context.Background(), dp, map[string]bool{"a.pdf": true}, j, run); err != nil {
		t.Fatal(err)
	}
	j.Close()

	logPath := filepath.Join(h, ".local", "state", "krino", "krino.log")
	data, err := os.ReadFile(logPath)
	if err != nil {
		t.Fatal(err)
	}
	lines := strings.Split(strings.TrimRight(string(data), "\n"), "\n")
	if !strings.Contains(lines[len(lines)-1], "\trun-end\t") {
		t.Fatalf("fixture's last line is not run-end: %q", lines[len(lines)-1])
	}
	// Simulate a crash: the process died before writing run-end.
	truncated := strings.Join(lines[:len(lines)-1], "\n") + "\n"
	if err := os.WriteFile(logPath, []byte(truncated), 0o644); err != nil {
		t.Fatal(err)
	}

	entries, err := journal.Entries(logPath, run)
	if err != nil {
		t.Fatalf("Entries refused a crashed-but-clean run: %v", err)
	}
	if len(entries) == 0 {
		t.Fatal("no entries survived truncation")
	}

	up, err := e.PlanUndo(run)
	if err != nil {
		t.Fatalf("PlanUndo refused a crashed run: %v", err)
	}
	if len(up.Files) != 1 || up.Files[0].Refused != "" {
		t.Fatalf("crashed run did not yield a usable undo plan: %+v", up)
	}
}

// TestApplyDeclinesLogEachStepAndTouchNothing: a chain that is not named in
// approved is left completely alone, but still logged (spec §9: "declined
// files are [logged]"), one entry per step, status "declined".
func TestApplyDeclinesLogEachStepAndTouchNothing(t *testing.T) {
	h, e, dp, j, run := applyFixture(t)
	res, err := e.Apply(context.Background(), dp, map[string]bool{}, j, run)
	if err != nil {
		t.Fatal(err)
	}
	if res.Declined != 1 || res.Applied != 0 {
		t.Errorf("result = %+v; want one declined, none applied", res)
	}
	if _, err := os.Stat(filepath.Join(h, "dl", "a.pdf")); err != nil {
		t.Errorf("a declined file was touched: %v", err)
	}
	j.Close()

	entries, err := journal.Entries(filepath.Join(h, ".local", "state", "krino", "krino.log"), run)
	if err != nil {
		t.Fatal(err)
	}
	var declined *journal.Entry
	for i := range entries {
		if entries[i].Status == "declined" {
			declined = &entries[i]
		}
	}
	if declined == nil {
		t.Fatal("no declined entry was logged")
	}
	if declined.Action != "move" || declined.File != "a.pdf" {
		t.Errorf("declined entry = %+v", *declined)
	}
}

// TestApplyChecksContextBetweenFilesNotWithinOne: Ctrl-C finishes the
// current file's chain, logs it, and stops before the next one - spec §11.
// The context is already cancelled before Apply is even called, so the
// boundary check must fire before the first (only actionable) file, proving
// cancellation is honoured rather than ignored.
func TestApplyChecksContextBetweenFilesNotWithinOne(t *testing.T) {
	h, e, dp, j, run := applyFixture(t)
	ctx, cancel := context.WithCancel(context.Background())
	cancel()
	res, err := e.Apply(ctx, dp, map[string]bool{"a.pdf": true}, j, run)
	if err == nil {
		t.Fatal("Apply did not report the cancellation")
	}
	if len(res.Files) != 0 || res.Applied != 0 {
		t.Errorf("result = %+v; want nothing done once already cancelled", res)
	}
	if _, err := os.Stat(filepath.Join(h, "dl", "a.pdf")); err != nil {
		t.Error("a cancelled Apply touched a file")
	}
}

// TestApplyUndoRestoresMovedFile: the smallest possible round trip through
// ApplyUndo.
func TestApplyUndoRestoresMovedFile(t *testing.T) {
	h, e, dp, j, run := applyFixture(t)
	if _, err := e.Apply(context.Background(), dp, map[string]bool{"a.pdf": true}, j, run); err != nil {
		t.Fatal(err)
	}
	j.Close()

	up, err := e.PlanUndo(run)
	if err != nil {
		t.Fatal(err)
	}
	if up.Files[0].Refused != "" {
		t.Fatalf("undo refused: %s", up.Files[0].Refused)
	}

	logPath := filepath.Join(h, ".local", "state", "krino", "krino.log")
	j2, err := journal.Open(logPath)
	if err != nil {
		t.Fatal(err)
	}
	defer j2.Close()
	undoRun := journal.NewRunID(time.Now())
	res, err := e.ApplyUndo(context.Background(), up, j2, undoRun)
	if err != nil {
		t.Fatal(err)
	}
	if res.Applied != 1 || res.Failed != 0 {
		t.Errorf("undo result = %+v; want one applied, none failed", res)
	}
	if _, err := os.Stat(filepath.Join(h, "dl", "a.pdf")); err != nil {
		t.Errorf("undo did not restore the file: %v", err)
	}
	if _, err := os.Stat(filepath.Join(h, "dl", "Work", "a.pdf")); !os.IsNotExist(err) {
		t.Error("undo left a copy at the moved-to location")
	}
}

// TestApplyUndoNamesItsFiles: every file in an undo result says which file
// it is, reversed or declined, so a front end showing a row per file can
// put each outcome on the right row (GUI design §4). The log is the only
// source of that name, so Rel and Name are all an undo result can carry.
func TestApplyUndoNamesItsFiles(t *testing.T) {
	h, e, dp, j, run := applyFixture(t)
	if _, err := e.Apply(context.Background(), dp, map[string]bool{"a.pdf": true}, j, run); err != nil {
		t.Fatal(err)
	}
	j.Close()

	j2, err := journal.Open(filepath.Join(h, ".local", "state", "krino", "krino.log"))
	if err != nil {
		t.Fatal(err)
	}
	defer j2.Close()

	// Declined first - nothing is reversed, so the run is still undoable -
	// then reversed for real. Both paths must name the file.
	for _, declined := range []bool{true, false} {
		up, err := e.PlanUndo(run)
		if err != nil {
			t.Fatal(err)
		}
		if len(up.Files) != 1 || up.Files[0].Refused != "" {
			t.Fatalf("undo plan = %+v", up.Files)
		}
		up.Files[0].Declined = declined
		res, err := e.ApplyUndo(context.Background(), up, j2, journal.NewRunID(time.Now()))
		if err != nil {
			t.Fatal(err)
		}
		if len(res.Files) != 1 {
			t.Fatalf("declined=%v: result files = %+v, want one", declined, res.Files)
		}
		fr := res.Files[0]
		if fr.File.Rel != "a.pdf" || fr.File.Name != path.Base("a.pdf") {
			t.Errorf("declined=%v: file = %+v, want a.pdf", declined, fr.File)
		}
	}
}

// TestApplyUndoSkipsRefusedFiles: rule 4 enforced at execution time too - a
// refused file must come back from ApplyUndo untouched.
func TestApplyUndoSkipsRefusedFiles(t *testing.T) {
	h, e, dp, j, run := applyFixture(t)
	if _, err := e.Apply(context.Background(), dp, map[string]bool{"a.pdf": true}, j, run); err != nil {
		t.Fatal(err)
	}
	j.Close()
	moved := filepath.Join(h, "dl", "Work", "a.pdf")
	if err := os.WriteFile(moved, []byte("edited since the run"), 0o644); err != nil {
		t.Fatal(err)
	}

	up, err := e.PlanUndo(run)
	if err != nil {
		t.Fatal(err)
	}
	if up.Files[0].Refused == "" {
		t.Fatal("expected the file to be refused")
	}

	logPath := filepath.Join(h, ".local", "state", "krino", "krino.log")
	j2, err := journal.Open(logPath)
	if err != nil {
		t.Fatal(err)
	}
	defer j2.Close()
	res, err := e.ApplyUndo(context.Background(), up, j2, journal.NewRunID(time.Now()))
	if err != nil {
		t.Fatal(err)
	}
	if res.Declined != 1 || res.Applied != 0 {
		t.Errorf("undo result = %+v; want the refused file declined, nothing applied", res)
	}
	if got, err := os.ReadFile(moved); err != nil || string(got) != "edited since the run" {
		t.Errorf("a refused file was touched: content=%q err=%v", got, err)
	}
}

// TestApplyUndoLogsDeclinedFile: a file the front end's own review chose
// not to reverse (Refused
// empty, Declined set by the caller - PlanUndo itself never sets it) must
// still be logged, spec §9's "declined files are logged even though nothing
// happens to them" extended to undo. The file must come back untouched, the
// run must still get its run-start/run-end boundaries even though nothing
// was actually reversed, and the logged entry's status must read "declined",
// never "refused" - which spec §9/§10 give a different meaning (the world
// changed under us).
func TestApplyUndoLogsDeclinedFile(t *testing.T) {
	h, e, dp, j, run := applyFixture(t)
	if _, err := e.Apply(context.Background(), dp, map[string]bool{"a.pdf": true}, j, run); err != nil {
		t.Fatal(err)
	}
	j.Close()

	up, err := e.PlanUndo(run)
	if err != nil {
		t.Fatal(err)
	}
	if up.Files[0].Refused != "" {
		t.Fatalf("expected the file to be reversible, got refused: %s", up.Files[0].Refused)
	}
	up.Files[0].Declined = true

	logPath := filepath.Join(h, ".local", "state", "krino", "krino.log")
	j2, err := journal.Open(logPath)
	if err != nil {
		t.Fatal(err)
	}
	defer j2.Close()
	undoRun := journal.NewRunID(time.Now())
	res, err := e.ApplyUndo(context.Background(), up, j2, undoRun)
	if err != nil {
		t.Fatal(err)
	}
	if res.Declined != 1 || res.Applied != 0 {
		t.Errorf("undo result = %+v; want the declined file counted, nothing applied", res)
	}
	if _, err := os.Stat(filepath.Join(h, "dl", "Work", "a.pdf")); err != nil {
		t.Errorf("the declined file was moved: %v", err)
	}
	if _, err := os.Stat(filepath.Join(h, "dl", "a.pdf")); !os.IsNotExist(err) {
		t.Error("the declined file's reversal ran anyway")
	}

	entries, err := journal.Entries(logPath, undoRun)
	if err != nil {
		t.Fatal(err)
	}
	if entries[0].Action != "run-start" || entries[len(entries)-1].Action != "run-end" {
		t.Errorf("boundaries = %q .. %q; a run with only a declined file must still get both", entries[0].Action, entries[len(entries)-1].Action)
	}
	// a.pdf's chain moved it into a directory Apply had to create (spec
	// §10: last-original-step-first means undo-move is logged before its
	// own undo-mkdir), so more than one entry carries File "a.pdf" -
	// every one of them must read "declined", and the first must be the
	// file's own undo-move.
	var fileEntries []journal.Entry
	for _, en := range entries {
		if en.File == "a.pdf" {
			fileEntries = append(fileEntries, en)
		}
	}
	if len(fileEntries) == 0 {
		t.Fatal("no entry was logged for the declined file")
	}
	if fileEntries[0].Action != "undo-move" {
		t.Errorf("first step's action = %q, want the file's own undo-move", fileEntries[0].Action)
	}
	for _, en := range fileEntries {
		if en.Status != "declined" {
			t.Errorf("entry %+v: status = %q, want %q (never \"refused\", which means something else)", en, en.Status, "declined")
		}
	}
}

// TestApplyUndoDecliningEveryFileDoesNotMarkOriginalRunUndone: reproduced
// via pty as `1 moved (undone)` with the file still filed. The mechanism is
// journal.Runs' own (see TestRunsDoesNotMarkUndoneWhenEveryFileWasDeclined
// for that unit-level pin); this is the same defect exercised end to end
// through a real forward run, a real declined undo, and e.Runs() itself -
// the exact call `krino log` makes - rather than a hand-built log.
func TestApplyUndoDecliningEveryFileDoesNotMarkOriginalRunUndone(t *testing.T) {
	h, e, dp, j, run := applyFixture(t)
	if _, err := e.Apply(context.Background(), dp, map[string]bool{"a.pdf": true}, j, run); err != nil {
		t.Fatal(err)
	}
	j.Close()

	up, err := e.PlanUndo(run)
	if err != nil {
		t.Fatal(err)
	}
	if up.Files[0].Refused != "" {
		t.Fatalf("expected the file to be reversible, got refused: %s", up.Files[0].Refused)
	}
	up.Files[0].Declined = true // the front end's own review declined it

	logPath := filepath.Join(h, ".local", "state", "krino", "krino.log")
	j2, err := journal.Open(logPath)
	if err != nil {
		t.Fatal(err)
	}
	undoRun := journal.NewRunID(time.Now())
	res, err := e.ApplyUndo(context.Background(), up, j2, undoRun)
	if err != nil {
		t.Fatal(err)
	}
	j2.Close()
	if res.Declined != 1 || res.Applied != 0 {
		t.Fatalf("undo result = %+v; want the declined file counted, nothing applied", res)
	}
	if _, err := os.Stat(filepath.Join(h, "dl", "Work", "a.pdf")); err != nil {
		t.Fatalf("the declined file was moved: %v", err)
	}

	runs, err := e.Runs(0)
	if err != nil {
		t.Fatal(err)
	}
	byID := map[string]bool{}
	for _, r := range runs {
		byID[r.ID] = r.Undone
	}
	if byID[run] {
		t.Errorf("original run %q marked Undone, but every file's reversal was declined and nothing moved", run)
	}
	if byID[undoRun] {
		t.Errorf("the undo run %q itself must never read as Undone", undoRun)
	}
}

func TestRunsDelegatesToJournal(t *testing.T) {
	_, e, dp, j, run := applyFixture(t)
	if _, err := e.Apply(context.Background(), dp, map[string]bool{"a.pdf": true}, j, run); err != nil {
		t.Fatal(err)
	}
	j.Close()

	runs, err := e.Runs(0)
	if err != nil {
		t.Fatal(err)
	}
	if len(runs) != 1 || runs[0].ID != run {
		t.Errorf("runs = %+v, want one run %q", runs, run)
	}
}

// TestApplyLogsTrashEntryNameInDetail: the trash entry name must be logged
// explicitly (Detail), not left to be re-derived from Dst's basename -
// Dst's shape is internal/apply's contract, not undo's, and the two must
// not be secretly coupled.
func TestApplyLogsTrashEntryNameInDetail(t *testing.T) {
	h := sandbox(t)
	dl := filepath.Join(h, "dl")
	if err := os.MkdirAll(dl, 0o755); err != nil {
		t.Fatal(err)
	}
	if err := os.WriteFile(filepath.Join(dl, "old.log"), []byte("stale"), 0o644); err != nil {
		t.Fatal(err)
	}
	old := time.Now().Add(-time.Hour)
	os.Chtimes(filepath.Join(dl, "old.log"), old, old)
	main := writeConfig(t, h, `(include "dl")`, map[string]string{
		"dl": `(path "~/dl")` + "\n" + `(rule "trash-logs" (when (type log)) (delete))`,
	})
	e, errs := Load(main)
	if len(errs) > 0 {
		t.Fatal(errs)
	}
	dp, err := e.Plan(context.Background(), e.Dirs[0], plan.NewClaims())
	if err != nil {
		t.Fatal(err)
	}
	logPath := filepath.Join(h, ".local", "state", "krino", "krino.log")
	j, err := journal.Open(logPath)
	if err != nil {
		t.Fatal(err)
	}
	run := journal.NewRunID(time.Now())
	if _, err := e.Apply(context.Background(), dp, map[string]bool{"old.log": true}, j, run); err != nil {
		t.Fatal(err)
	}
	j.Close()

	entries, err := journal.Entries(logPath, run)
	if err != nil {
		t.Fatal(err)
	}
	var trashEntry *journal.Entry
	for i := range entries {
		if entries[i].Action == "trash" {
			trashEntry = &entries[i]
		}
	}
	if trashEntry == nil {
		t.Fatal("no trash entry was logged")
	}
	if trashEntry.Detail == "" {
		t.Fatal("trash entry's Detail does not carry the trash entry name")
	}

	up, err := e.PlanUndo(run)
	if err != nil {
		t.Fatal(err)
	}
	if up.Files[0].Refused != "" {
		t.Fatalf("undo refused: %s", up.Files[0].Refused)
	}
	j2, err := journal.Open(logPath)
	if err != nil {
		t.Fatal(err)
	}
	defer j2.Close()
	res, err := e.ApplyUndo(context.Background(), up, j2, journal.NewRunID(time.Now()))
	if err != nil {
		t.Fatal(err)
	}
	if res.Applied != 1 {
		t.Errorf("undo result = %+v; want the trashed file restored", res)
	}
	if _, err := os.Stat(filepath.Join(h, "dl", "old.log")); err != nil {
		t.Errorf("undo did not restore the trashed file: %v", err)
	}
}

// TestRunUndoStepTrashReadsEntryNameFromDetailNotDst: Src is deliberately a
// path whose basename names no real trash entry; only Original.Detail
// names the real one. If runUndoStep ever goes back to deriving the name
// from Dst (or Src), this fails.
func TestRunUndoStepTrashReadsEntryNameFromDetailNotDst(t *testing.T) {
	h := sandbox(t)
	dl := filepath.Join(h, "dl")
	if err := os.MkdirAll(dl, 0o755); err != nil {
		t.Fatal(err)
	}
	target := filepath.Join(dl, "gone.txt")
	if err := os.WriteFile(target, []byte("data"), 0o644); err != nil {
		t.Fatal(err)
	}
	entry, err := trash.Put(target)
	if err != nil {
		t.Fatal(err)
	}

	// Original is what the run logged for the trash step: the entry name in
	// Detail, and the entry's own path, size and mtime (checked again at
	// execution time).
	entryPath := filepath.Join(trash.Dir(), "files", entry)
	fi, err := os.Stat(entryPath)
	if err != nil {
		t.Fatal(err)
	}
	step := UndoStep{
		Action:   "undo-trash",
		Src:      "/this/path/does/not/exist/files/wrong-name",
		Dst:      target,
		Original: journal.Entry{Action: "trash", Src: target, Dst: entryPath, Size: fi.Size(), ModTime: fi.ModTime(), Detail: entry},
	}
	sr := runUndoStep(step)
	if sr.Status != "ok" {
		t.Fatalf("runUndoStep = %+v; want ok, using Original.Detail's entry name", sr)
	}
	if _, err := os.Stat(target); err != nil {
		t.Errorf("file was not restored: %v", err)
	}
}

// TestPlanUndoRefusesFileModifiedWithinSameSecond: the journal now records
// ModTime with sub-second precision (RFC3339Nano), so a
// file rewritten within the same whole second as the run must still be
// detected as changed - a .Unix()-granularity comparison would miss this
// and undo would silently move the edited file back over the user's data.
func TestPlanUndoRefusesFileModifiedWithinSameSecond(t *testing.T) {
	h, e, dp, j, run := applyFixture(t)
	if _, err := e.Apply(context.Background(), dp, map[string]bool{"a.pdf": true}, j, run); err != nil {
		t.Fatal(err)
	}
	j.Close()

	moved := filepath.Join(h, "dl", "Work", "a.pdf")
	fi, err := os.Stat(moved)
	if err != nil {
		t.Fatal(err)
	}
	sec := fi.ModTime().Truncate(time.Second)
	nudge := 100 * time.Millisecond
	if sec.Add(nudge).Equal(fi.ModTime()) {
		nudge = 700 * time.Millisecond // guaranteed different sub-second offset
	}
	nudged := sec.Add(nudge)
	if err := os.Chtimes(moved, nudged, nudged); err != nil {
		t.Fatal(err)
	}

	up, err := e.PlanUndo(run)
	if err != nil {
		t.Fatal(err)
	}
	if up.Files[0].Refused == "" {
		t.Fatal("undo did not refuse a file whose mtime changed within the same second")
	}
}

// TestUndoFileStopsAfterFailedFileAffectingStep: a failed undo-move must
// stop the rest of that file's reversal - continuing
// would leave it half undone (spec §10), even though the later step
// (undo-copy) would, in isolation, have succeeded.
func TestUndoFileStopsAfterFailedFileAffectingStep(t *testing.T) {
	h := sandbox(t)
	keep := filepath.Join(h, "keep.txt")
	if err := os.WriteFile(keep, []byte("do not trash me"), 0o644); err != nil {
		t.Fatal(err)
	}
	j, err := journal.Open(filepath.Join(h, "state", "krino.log"))
	if err != nil {
		t.Fatal(err)
	}
	defer j.Close()
	e := &Engine{Now: time.Now}

	uf := UndoFile{
		File: "f", Dir: "d",
		Steps: []UndoStep{
			// Src does not exist, so the rename underneath fails.
			{Action: "undo-move", Src: filepath.Join(h, "no-such-source"), Dst: filepath.Join(h, "sub", "dst.txt")},
			{Action: "undo-copy", Src: keep},
		},
	}
	fr, err := e.undoFile(uf, j, "run1")
	if err != nil {
		t.Fatal(err)
	}
	if fr.Steps[0].Status != "failed" {
		t.Fatalf("step 0 = %+v, want failed", fr.Steps[0])
	}
	if fr.Steps[1].Status != "skipped" {
		t.Fatalf("step 1 = %+v, want skipped after the file-affecting failure", fr.Steps[1])
	}
	if _, err := os.Stat(keep); err != nil {
		t.Errorf("the skipped undo-copy still touched its file: %v", err)
	}
}

// TestUndoFileContinuesPastFailedMkdir: a failed undo-mkdir (directory not
// empty) must NOT stop the rest of the file's reversal, unlike every other
// action.
func TestUndoFileContinuesPastFailedMkdir(t *testing.T) {
	h := sandbox(t)
	nonEmpty := filepath.Join(h, "nonempty")
	if err := os.MkdirAll(nonEmpty, 0o755); err != nil {
		t.Fatal(err)
	}
	if err := os.WriteFile(filepath.Join(nonEmpty, "still-here.txt"), []byte("x"), 0o644); err != nil {
		t.Fatal(err)
	}
	keep := filepath.Join(h, "keep.txt")
	if err := os.WriteFile(keep, []byte("trash me, that's fine"), 0o644); err != nil {
		t.Fatal(err)
	}
	j, err := journal.Open(filepath.Join(h, "state", "krino.log"))
	if err != nil {
		t.Fatal(err)
	}
	defer j.Close()
	e := &Engine{Now: time.Now}

	keepInfo, err := os.Stat(keep)
	if err != nil {
		t.Fatal(err)
	}
	uf := UndoFile{
		File: "f", Dir: "d",
		Steps: []UndoStep{
			{Action: "undo-mkdir", Src: nonEmpty},
			{Action: "undo-copy", Src: keep, Original: journal.Entry{Action: "copy", Dst: keep, Size: keepInfo.Size(), ModTime: keepInfo.ModTime()}},
		},
	}
	fr, err := e.undoFile(uf, j, "run2")
	if err != nil {
		t.Fatal(err)
	}
	if fr.Steps[0].Status != "failed" {
		t.Fatalf("step 0 = %+v, want failed (not empty)", fr.Steps[0])
	}
	if fr.Steps[1].Status != "ok" {
		t.Fatalf("step 1 = %+v, want ok - a failed undo-mkdir must not stop the rest of the file", fr.Steps[1])
	}
	if _, err := os.Stat(keep); !os.IsNotExist(err) {
		t.Error("undo-copy after the failed mkdir did not run")
	}
}

// TestApplyUndoRefusesWhenDestinationReappearsBeforeExecution: spec §10
// says an undo plan is shown and approved like any other, so there is a
// real, human-length window between PlanUndo's
// refuseIfSrcExists check and ApplyUndo actually running - long enough for
// something else to create a file at the reversal's destination in between.
// undo-move/undo-rename must re-check at execution time rather than let a
// bare os.Rename silently replace it and report the step "ok".
func TestApplyUndoRefusesWhenDestinationReappearsBeforeExecution(t *testing.T) {
	h, e, dp, j, run := applyFixture(t)
	if _, err := e.Apply(context.Background(), dp, map[string]bool{"a.pdf": true}, j, run); err != nil {
		t.Fatal(err)
	}
	j.Close()

	up, err := e.PlanUndo(run)
	if err != nil {
		t.Fatal(err)
	}
	if up.Files[0].Refused != "" {
		t.Fatalf("undo refused at planning time: %s", up.Files[0].Refused)
	}

	// The window spec §10 describes: something creates a file at the
	// reversal's destination after planning, before execution.
	reappeared := filepath.Join(h, "dl", "a.pdf")
	if err := os.WriteFile(reappeared, []byte("someone else's file"), 0o644); err != nil {
		t.Fatal(err)
	}

	logPath := filepath.Join(h, ".local", "state", "krino", "krino.log")
	j2, err := journal.Open(logPath)
	if err != nil {
		t.Fatal(err)
	}
	defer j2.Close()
	res, err := e.ApplyUndo(context.Background(), up, j2, journal.NewRunID(time.Now()))
	if err != nil {
		t.Fatal(err)
	}
	if res.Failed != 1 || res.Applied != 0 {
		t.Errorf("undo result = %+v; want the step to fail rather than silently overwrite", res)
	}
	if got, err := os.ReadFile(reappeared); err != nil || string(got) != "someone else's file" {
		t.Errorf("the reappeared file was overwritten: content=%q err=%v", got, err)
	}
	moved := filepath.Join(h, "dl", "Work", "a.pdf")
	if got, err := os.ReadFile(moved); err != nil || string(got) != "one" {
		t.Errorf("the moved file did not stay where it was: content=%q err=%v", got, err)
	}
}

// TestApplyUndoDoesNotCountFailedMkdirAsFailed: a file whose only failure
// is an undo-mkdir (a shared directory not yet empty) must not flip
// ApplyResult.Failed - ApplyResult maps to krino undo's exit code, and
// this specific refusal is tidiness, not a hazard.
func TestApplyUndoDoesNotCountFailedMkdirAsFailed(t *testing.T) {
	h := sandbox(t)
	dir := filepath.Join(h, "Work")
	if err := os.MkdirAll(dir, 0o755); err != nil {
		t.Fatal(err)
	}
	dst := filepath.Join(dir, "a.pdf")
	if err := os.WriteFile(dst, []byte("moved"), 0o644); err != nil {
		t.Fatal(err)
	}
	// A sibling file still occupies the directory, so its undo-mkdir must
	// fail with "not empty" once undo-move has already vacated dst.
	if err := os.WriteFile(filepath.Join(dir, "sibling.pdf"), []byte("still here"), 0o644); err != nil {
		t.Fatal(err)
	}
	src := filepath.Join(h, "a.pdf")

	j, err := journal.Open(filepath.Join(h, "state", "krino.log"))
	if err != nil {
		t.Fatal(err)
	}
	defer j.Close()
	e := &Engine{Now: time.Now}

	dstInfo, err := os.Stat(dst)
	if err != nil {
		t.Fatal(err)
	}
	up := &UndoPlan{Run: "r", Files: []UndoFile{
		{File: "a.pdf", Dir: "d", Steps: []UndoStep{
			{Action: "undo-move", Src: dst, Dst: src, Original: journal.Entry{Action: "move", Src: src, Dst: dst, Size: dstInfo.Size(), ModTime: dstInfo.ModTime()}},
			{Action: "undo-mkdir", Src: dir},
		}},
	}}
	res, err := e.ApplyUndo(context.Background(), up, j, "run1")
	if err != nil {
		t.Fatal(err)
	}
	if res.Applied != 1 {
		t.Errorf("Applied = %d, want 1 (the move succeeded)", res.Applied)
	}
	if res.Failed != 0 {
		t.Errorf("Failed = %d, want 0 - a failed undo-mkdir alone must not count as a failure", res.Failed)
	}
}

// overwriteFixture builds a directory where a forward move under
// (on-conflict overwrite) will displace a pre-existing file at its
// destination: dl/incoming.pdf moves to dl/Work/incoming.pdf, which already
// holds a different file (the "victim") the move must trash first. This is
// the one shape that makes a step's Displaces and another step's Dst name
// the exact same path (internal/plan/conflict.go's resolveConflict,
// deliberately).
func overwriteFixture(t *testing.T) (string, *Engine, *DirPlan, *journal.Writer, string) {
	t.Helper()
	h := sandbox(t)
	dl := filepath.Join(h, "dl")
	work := filepath.Join(dl, "Work")
	if err := os.MkdirAll(work, 0o755); err != nil {
		t.Fatal(err)
	}
	old := time.Now().Add(-time.Hour)

	incoming := filepath.Join(dl, "incoming.pdf")
	if err := os.WriteFile(incoming, []byte("incoming content"), 0o644); err != nil {
		t.Fatal(err)
	}
	if err := os.Chtimes(incoming, old, old); err != nil {
		t.Fatal(err)
	}
	victim := filepath.Join(work, "incoming.pdf")
	if err := os.WriteFile(victim, []byte("original victim content"), 0o644); err != nil {
		t.Fatal(err)
	}
	if err := os.Chtimes(victim, old, old); err != nil {
		t.Fatal(err)
	}

	main := writeConfig(t, h, `(include "dl")`, map[string]string{
		"dl": `(path "~/dl")` + "\n" + `(on-conflict overwrite)` + "\n" + `(rule "pdfs" (when (type pdf)) (move "Work"))`,
	})
	e, errs := Load(main)
	if len(errs) > 0 {
		t.Fatal(errs)
	}
	dp, err := e.Plan(context.Background(), e.Dirs[0], plan.NewClaims())
	if err != nil {
		t.Fatal(err)
	}
	j, err := journal.Open(filepath.Join(h, ".local", "state", "krino", "krino.log"))
	if err != nil {
		t.Fatal(err)
	}
	t.Cleanup(func() { j.Close() })
	return h, e, dp, j, journal.NewRunID(time.Now())
}

// TestApplyUndoReversesOverwriteRoundTrip: `krino undo` could not reverse a
// run that used (on-conflict overwrite) at all, by construction.
// reverseStep's planning-time occupancy check judged the displace reversal
// against the world exactly as it stood before any reversal had run, while
// the move-back that frees the contested path is ordered to execute first
// (reversal is last-original-step-first), so the displace reversal was
// refused every time and, being file-affecting, aborted the whole file's
// reversal - including the otherwise-safe move-back. This is the first
// coverage of undo-displace anywhere in the repo (grep undo-displace
// across every prior test returns nothing), and it is built from a REAL
// forward run through overwriteFixture's real displacing apply: a
// hand-assembled journal.Entry is exactly what would let a narrower,
// wrong fix pass while still being wrong.
func TestApplyUndoReversesOverwriteRoundTrip(t *testing.T) {
	h, e, dp, j, run := overwriteFixture(t)
	if _, err := e.Apply(context.Background(), dp, map[string]bool{"incoming.pdf": true}, j, run); err != nil {
		t.Fatal(err)
	}
	j.Close()

	dest := filepath.Join(h, "dl", "Work", "incoming.pdf")
	if got, err := os.ReadFile(dest); err != nil || string(got) != "incoming content" {
		t.Fatalf("forward run did not land as expected: content=%q err=%v", got, err)
	}

	up, err := e.PlanUndo(run)
	if err != nil {
		t.Fatal(err)
	}
	if len(up.Files) != 1 {
		t.Fatalf("undo plan covers %d files, want 1", len(up.Files))
	}
	if up.Files[0].Refused != "" {
		t.Fatalf("undo refused an (on-conflict overwrite) round trip that should be fully reversible: %s", up.Files[0].Refused)
	}
	var sawDisplace bool
	for _, s := range up.Files[0].Steps {
		if s.Action == "undo-displace" {
			sawDisplace = true
			if s.Refused != "" {
				t.Errorf("undo-displace step itself refused: %s", s.Refused)
			}
		}
	}
	if !sawDisplace {
		t.Fatal("no undo-displace step in the plan; the fixture did not exercise the displace path")
	}

	logPath := filepath.Join(h, ".local", "state", "krino", "krino.log")
	j2, err := journal.Open(logPath)
	if err != nil {
		t.Fatal(err)
	}
	defer j2.Close()
	res, err := e.ApplyUndo(context.Background(), up, j2, journal.NewRunID(time.Now()))
	if err != nil {
		t.Fatal(err)
	}
	if res.Applied != 1 || res.Failed != 0 || res.Declined != 0 {
		t.Fatalf("undo result = %+v; want the one file fully reversed", res)
	}

	orig := filepath.Join(h, "dl", "incoming.pdf")
	if got, err := os.ReadFile(orig); err != nil || string(got) != "incoming content" {
		t.Errorf("the incoming file did not come back to its original path: content=%q err=%v", got, err)
	}
	if got, err := os.ReadFile(dest); err != nil || string(got) != "original victim content" {
		t.Errorf("the displaced original was not restored from the Trash: content=%q err=%v", got, err)
	}
}

// TestApplyUndoStillRefusesGenuineOccupant: the projection must only excuse
// a path an earlier step of THIS SAME chain is about to vacate, never turn
// every occupancy refusal into a pass. Here something outside the chain
// entirely - not the
// displaced original, not the incoming file itself - now occupies the
// path the move-back needs, and no step of this file's reversal will ever
// free it.
func TestApplyUndoStillRefusesGenuineOccupant(t *testing.T) {
	h, e, dp, j, run := overwriteFixture(t)
	if _, err := e.Apply(context.Background(), dp, map[string]bool{"incoming.pdf": true}, j, run); err != nil {
		t.Fatal(err)
	}
	j.Close()

	reappeared := filepath.Join(h, "dl", "incoming.pdf")
	if err := os.WriteFile(reappeared, []byte("someone else's file"), 0o644); err != nil {
		t.Fatal(err)
	}

	up, err := e.PlanUndo(run)
	if err != nil {
		t.Fatal(err)
	}
	if up.Files[0].Refused == "" {
		t.Fatal("undo did not refuse a path genuinely occupied by something outside this file's own chain")
	}
	if !strings.Contains(up.Files[0].Refused, "already exists") {
		t.Errorf("Refused = %q, want it to say the path already exists", up.Files[0].Refused)
	}
	if got, err := os.ReadFile(reappeared); err != nil || string(got) != "someone else's file" {
		t.Errorf("the genuine occupant was disturbed just by planning: content=%q err=%v", got, err)
	}
}

// TestTallyFileCountsAnAllSkippedFileAsDeclined: a file every one of whose
// steps came back "skipped" - the shape an approved all-skipped chain used
// to take - set none of ok/failed/declined
// in tallyFile, so it fell out of the outcome tally entirely: "0 applied ·
// 0 failed · 0 declined" for a file the user was asked about and approved.
// tallyFile must land every file it is given in exactly one bucket; nothing
// ran and nothing failed, so it belongs in Declined.
func TestTallyFileCountsAnAllSkippedFileAsDeclined(t *testing.T) {
	result := &ApplyResult{}
	steps := []apply.StepResult{
		{Status: "skipped", Detail: "target exists"},
	}
	tallyFile(result, steps, nil)
	if result.Applied != 0 || result.Failed != 0 || result.Declined != 1 {
		t.Errorf("result = %+v, want the all-skipped file counted once, as declined", result)
	}
}

// TestTallyFileCountsMixedOutcomesOnceEach pins the existing "not mutually
// exclusive" contract alongside the new all-skipped fallback: a file with
// one ok, one failed and one declined step must still count toward all
// three (unchanged behaviour), and the fallback added for the all-skipped
// case must never fire when any real status is present.
func TestTallyFileCountsMixedOutcomesOnceEach(t *testing.T) {
	result := &ApplyResult{}
	steps := []apply.StepResult{
		{Status: "ok"},
		{Status: "failed"},
		{Status: "declined"},
	}
	tallyFile(result, steps, nil)
	if result.Applied != 1 || result.Failed != 1 || result.Declined != 1 {
		t.Errorf("result = %+v, want one of each", result)
	}
}

// sharedDestUndoFixture builds a downloads directory with three pdf files
// (a.pdf, b.pdf, c.pdf) and a single rule moving all of them into dest,
// applies the move, and returns the sandbox home, the loaded engine, the
// journal's path and the forward run's ID.
//
// All three files landing on one destination that this one run creates is
// the shape that exercises the run-wide directory retry: whichever file's
// chain first creates dest carries its undo-mkdir step(s), and that file's
// own reversal typically runs while its siblings still occupy dest -
// refusing the removal correctly, at first. dest may name a nested path
// ("Work/Sub"): apply.mkdirAllTracked then records every directory the
// move had to create, outermost first, and every one of them still lands
// on that same first file's chain.
//
// TestApplyUndoRemovesSharedDirectoryAfterEveryFileReverses and
// TestApplyUndoRetryLogsBothMkdirEntriesAndStillMarksOriginalRunUndone
// used to duplicate this setup verbatim; TestApplyUndoRetryRemovesNestedDirectoriesDeepestFirst
// needed the identical shape with only dest varying, which is what named the
// parameter rather than hard-coding "Filed" here.
func sharedDestUndoFixture(t *testing.T, dest string) (h string, e *Engine, logPath string, run string) {
	t.Helper()
	h = sandbox(t)
	dl := filepath.Join(h, "dl")
	if err := os.MkdirAll(dl, 0o755); err != nil {
		t.Fatal(err)
	}
	// Three files that all move into ONE created destination: only the file
	// whose chain first creates it ever carries the undo-mkdir step, and
	// that step is attempted while its siblings are still inside.
	for _, n := range []string{"a.pdf", "b.pdf", "c.pdf"} {
		if err := os.WriteFile(filepath.Join(dl, n), []byte(n), 0o640); err != nil {
			t.Fatal(err)
		}
	}
	main := writeConfig(t, h, `(include "dl")`, map[string]string{"dl": `
(path "~/dl")
(min-age 0s)
(rule "pdfs" (when (type pdf)) (move "` + dest + `"))
`})
	loaded, errs := Load(main)
	if len(errs) > 0 {
		t.Fatal(errs)
	}
	e = loaded
	dp, err := e.Plan(context.Background(), e.Dirs[0], plan.NewClaims())
	if err != nil {
		t.Fatal(err)
	}
	approved := map[string]bool{}
	for _, c := range dp.Chains {
		approved[c.File.Rel] = true
	}
	logPath = filepath.Join(h, ".local", "state", "krino", "krino.log")
	j, err := journal.Open(logPath)
	if err != nil {
		t.Fatal(err)
	}
	run = journal.NewRunID(time.Now())
	if _, err := e.Apply(context.Background(), dp, approved, j, run); err != nil {
		t.Fatal(err)
	}
	j.Close()
	return h, e, logPath, run
}

func TestApplyUndoRemovesSharedDirectoryAfterEveryFileReverses(t *testing.T) {
	h, e, logPath, run := sharedDestUndoFixture(t, "Filed")
	dl := filepath.Join(h, "dl")
	filed := filepath.Join(dl, "Filed")
	if _, err := os.Stat(filed); err != nil {
		t.Fatalf("apply did not create the directory: %v", err)
	}

	up, err := e.PlanUndo(run)
	if err != nil {
		t.Fatal(err)
	}
	j2, err := journal.Open(logPath)
	if err != nil {
		t.Fatal(err)
	}
	res, err := e.ApplyUndo(context.Background(), up, j2, journal.NewRunID(time.Now()))
	if err != nil {
		t.Fatal(err)
	}
	j2.Close()
	if res.Failed != 0 {
		t.Fatalf("undo reported %d failures: %+v", res.Failed, res)
	}
	if _, err := os.Stat(filed); !os.IsNotExist(err) {
		t.Errorf("undo left the created directory behind: %v", err)
	}
	for _, n := range []string{"a.pdf", "b.pdf", "c.pdf"} {
		if _, err := os.Stat(filepath.Join(dl, n)); err != nil {
			t.Errorf("%s did not come back: %v", n, err)
		}
	}
}

// TestApplyUndoRetryRemovesNestedDirectoriesDeepestFirst: retryDirRemovals
// must retry deepest path first. All three
// files move into Work/Sub, so Apply's single mkdirAllTracked call creates
// both Work and Work/Sub on the FIRST file's own chain (outermost first),
// which means that one file's reversal carries two undo-mkdir steps, one for
// each directory - and both are refused on that file's own turn, since the
// other two files still sit in Work/Sub at that point.
//
// Retried deepest first, Work/Sub empties out and is removed, and Work -
// now itself empty - is removed right after. Retried shallowest first
// instead, Work is tried while Work/Sub (now empty, but not yet removed)
// still sits inside it, so Work is refused as non-empty and never retried
// again in this run; Work/Sub is then removed, leaving the outer Work
// directory behind. So end state alone - no directory left over - already
// distinguishes correct (deepest-first) ordering from inverted or dropped
// ordering; unlike the flat-destination tests above, where only one
// directory ever entered `retries`, this is the case built to tell the two
// apart.
func TestApplyUndoRetryRemovesNestedDirectoriesDeepestFirst(t *testing.T) {
	h, e, logPath, run := sharedDestUndoFixture(t, "Work/Sub")
	dl := filepath.Join(h, "dl")
	work := filepath.Join(dl, "Work")
	sub := filepath.Join(work, "Sub")
	if _, err := os.Stat(sub); err != nil {
		t.Fatalf("apply did not create the nested directory: %v", err)
	}

	up, err := e.PlanUndo(run)
	if err != nil {
		t.Fatal(err)
	}
	j2, err := journal.Open(logPath)
	if err != nil {
		t.Fatal(err)
	}
	res, err := e.ApplyUndo(context.Background(), up, j2, journal.NewRunID(time.Now()))
	if err != nil {
		t.Fatal(err)
	}
	j2.Close()
	if res.Failed != 0 {
		t.Fatalf("undo reported %d failures: %+v", res.Failed, res)
	}
	if _, err := os.Stat(sub); !os.IsNotExist(err) {
		t.Errorf("undo left the nested directory behind: %v", err)
	}
	if _, err := os.Stat(work); !os.IsNotExist(err) {
		t.Errorf("undo left the outer directory behind - retryDirRemovals is not retrying deepest path first: %v", err)
	}
	for _, n := range []string{"a.pdf", "b.pdf", "c.pdf"} {
		if _, err := os.Stat(filepath.Join(dl, n)); err != nil {
			t.Errorf("%s did not come back: %v", n, err)
		}
	}
}

// TestApplyUndoRetryLogsBothMkdirEntriesAndStillMarksOriginalRunUndone:
// when retryDirRemovals succeeds in removing a directory, it appends an
// ADDITIONAL journal entry for it - the original "failed" undo-mkdir entry,
// recorded on whichever file's chain first created the directory, is never
// rewritten or removed - and, because that entry's Action is still
// "undo-mkdir" like the first, journal.ranAnyUndoStep continues to exclude
// it from what marks a run "(undone)" (this must not change whether a run
// shows as (undone); the test confirms that rather than assuming it).
func TestApplyUndoRetryLogsBothMkdirEntriesAndStillMarksOriginalRunUndone(t *testing.T) {
	_, e, logPath, run := sharedDestUndoFixture(t, "Filed")

	up, err := e.PlanUndo(run)
	if err != nil {
		t.Fatal(err)
	}
	j2, err := journal.Open(logPath)
	if err != nil {
		t.Fatal(err)
	}
	undoRun := journal.NewRunID(time.Now())
	res, err := e.ApplyUndo(context.Background(), up, j2, undoRun)
	if err != nil {
		t.Fatal(err)
	}
	j2.Close()
	if res.Failed != 0 {
		t.Fatalf("undo reported %d failures: %+v", res.Failed, res)
	}

	entries, err := journal.Entries(logPath, undoRun)
	if err != nil {
		t.Fatal(err)
	}
	var failed, ok *journal.Entry
	var mkdirCount int
	for i := range entries {
		en := &entries[i]
		if en.Action != "undo-mkdir" {
			continue
		}
		mkdirCount++
		switch en.Status {
		case "failed":
			failed = en
		case "ok":
			ok = en
		}
	}
	if mkdirCount != 2 {
		t.Fatalf("undo-mkdir entries = %d, want exactly 2 (the original refusal plus the retry's addition): %+v", mkdirCount, entries)
	}
	if failed == nil {
		t.Fatal("the original refused undo-mkdir entry is missing - it must never be rewritten or removed")
	}
	if ok == nil {
		t.Fatal("no successful undo-mkdir entry was appended for the retry")
	}
	if failed.Src != ok.Src {
		t.Errorf("failed.Src = %q, ok.Src = %q; want the same directory", failed.Src, ok.Src)
	}
	if failed.File != ok.File {
		t.Errorf("failed.File = %q, ok.File = %q; want the retry entry to carry the file that owned the original undo-mkdir", failed.File, ok.File)
	}
	if failed.Dir != ok.Dir {
		t.Errorf("failed.Dir = %q, ok.Dir = %q; want the same directory name", failed.Dir, ok.Dir)
	}

	runs, err := e.Runs(0)
	if err != nil {
		t.Fatal(err)
	}
	byID := map[string]bool{}
	for _, r := range runs {
		byID[r.ID] = r.Undone
	}
	if !byID[run] {
		t.Errorf("original run %q not marked Undone, though every file came back", run)
	}
	if byID[undoRun] {
		t.Errorf("the undo run %q itself must never read as Undone", undoRun)
	}
}

// TestPermanentDeleteStillRestoresWhatItDisplaced: a chain that overwrites
// and then permanently deletes trashes a file the user owned to make room.
// That file is a different file, and §7.4 promises of it: "move the
// existing target to Trash first (logged, so undo restores it)". Walking
// the file's entries used to stop dead at the permanent delete, so the
// displace was never reached and the user's file stayed in the Trash with
// krino reporting the run fully undone.
func TestPermanentDeleteStillRestoresWhatItDisplaced(t *testing.T) {
	// A real trash entry, so the reversal is offered rather than refused
	// for a reason that has nothing to do with this test.
	h := sandbox(t)
	entry := filepath.Join(trash.Dir(), "files", "a.pdf")
	if err := os.MkdirAll(filepath.Dir(entry), 0o755); err != nil {
		t.Fatal(err)
	}
	if err := os.WriteFile(entry, []byte("the file that was in the way"), 0o644); err != nil {
		t.Fatal(err)
	}
	fi, err := os.Lstat(entry)
	if err != nil {
		t.Fatal(err)
	}
	displaced := filepath.Join(h, "archive", "a.pdf")
	info := filepath.Join(trash.Dir(), "info", "a.pdf.trashinfo")
	if err := os.MkdirAll(filepath.Dir(info), 0o755); err != nil {
		t.Fatal(err)
	}
	if err := os.WriteFile(info, []byte("[Trash Info]\nPath="+displaced+"\nDeletionDate=2026-09-17T00:00:00\n"), 0o644); err != nil {
		t.Fatal(err)
	}
	ents := []journal.Entry{
		// Chronological, as the log has them: the displace first, then the
		// move that needed the name, then the permanent delete.
		{Action: "displace", Status: "ok", File: "a.pdf", Dir: "dl", Step: 1,
			Src: displaced, Dst: entry, Detail: "a.pdf",
			Size: fi.Size(), ModTime: fi.ModTime()},
		{Action: "move", Status: "ok", File: "a.pdf", Dir: "dl", Step: 1,
			Src: filepath.Join(h, "dl", "a.pdf"), Dst: displaced},
		{Action: "delete", Status: "ok", File: "a.pdf", Dir: "dl", Step: 2,
			Src: displaced},
	}
	uf := planUndoFile("dl", "a.pdf", ents, map[journal.ReversedKey]int{})
	if uf.Refused == "" {
		t.Error("the permanently deleted file is no longer refused")
	}

	rest, ok := displacedUndoFile("dl", ents, map[journal.ReversedKey]int{})
	if !ok {
		t.Fatal("the displaced file was not offered for reversal at all")
	}
	if rest.Refused != "" {
		t.Errorf("the displaced file is refused: %q", rest.Refused)
	}
	if len(rest.Steps) != 1 || rest.Steps[0].Action != "undo-displace" {
		t.Fatalf("steps = %+v; want one undo-displace", rest.Steps)
	}
	if rest.Steps[0].Dst != displaced {
		t.Errorf("the reversal puts the file at %q, want %q", rest.Steps[0].Dst, displaced)
	}
	if rest.File != displaced {
		t.Errorf("the offered file is %q, want the displaced file %q", rest.File, displaced)
	}
}

// TestDisplacedFileIsNotOfferedTwice: when the chain's own file is
// reversible, the displace is reversed as one of its steps, as before -
// the separate offer exists only for the file that cannot be reversed.
func TestDisplacedFileIsNotOfferedTwice(t *testing.T) {
	ents := []journal.Entry{
		{Action: "displace", Status: "ok", File: "a.pdf", Dir: "dl", Step: 1,
			Src: "/archive/a.pdf", Dst: "/trash/files/a.pdf", Detail: "a.pdf"},
		{Action: "move", Status: "ok", File: "a.pdf", Dir: "dl", Step: 1,
			Src: "/dl/a.pdf", Dst: "/archive/a.pdf"},
	}
	if _, ok := displacedUndoFile("dl", ents, map[journal.ReversedKey]int{}); ok {
		t.Error("a reversible chain's displace was offered a second time on its own")
	}
}