ebman 0.37.0

k9s-style TUI for AWS Elastic Beanstalk
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
//! Rule for every mutating path — `deny_write`, read-only,
//! the freeze window, and the tables that pin which commands write.
//!
//! Split out of the 9,515-line `app/tests.rs`. Bodies moved
//! unchanged apart from one rewrite: `super::` meant `crate::app` in
//! the flat file and would mean `crate::app::tests` here, so every
//! explicit `super::` path was re-anchored (rustfmt reflowed some
//! lines as a result, since the new path is longer).

use super::super::*;
#[allow(unused_imports)]
use super::support::*;

#[test]
fn action_destructive_covers_terminate_and_ssm_run() {
    // Terminate has been destructive since 0.6; SsmRun added in
    // 0.17.3 — operator-explicit shell exec across instances is
    // treat-as-write and the modal renders red so the visual cue
    // matches the intent.
    assert!(Action::Terminate.destructive());
    assert!(Action::SsmRun.destructive());
    // Every other variant stays non-destructive. Exhaustive list
    // (0.17.4 — code-review flagged the previous Capacity/Clone/
    // Upgrade/Abort/Config*/TerminateInstance gap) so a future
    // accidental destructive() flip is caught here.
    assert!(!Action::Rebuild.destructive());
    assert!(!Action::RestartAppServer.destructive());
    assert!(!Action::SwapCnames.destructive());
    assert!(!Action::Deploy.destructive());
    assert!(!Action::UpgradePlatform.destructive());
    assert!(!Action::Clone.destructive());
    assert!(!Action::Scale.destructive());
    assert!(!Action::Capacity.destructive());
    assert!(!Action::AbortUpdate.destructive());
    assert!(!Action::ConfigSave.destructive());
    assert!(!Action::ConfigDelete.destructive());
    assert!(!Action::ConfigApply.destructive());
    assert!(!Action::TerminateInstance.destructive());
}

#[test]
fn deny_write_refuses_in_demo_mode_even_when_not_read_only() {
    let mut app = test_app();
    app.demo_mode = true;
    // Sanity: not in read-only mode otherwise.
    assert!(!app.read_only);
    let denied = app.deny_write("any-env", "rebuild");
    assert!(denied, "demo mode must deny writes");
    let err = app
        .error_message
        .as_deref()
        .expect("demo-mode deny_write should set error_message");
    assert!(
        err.contains("demo mode"),
        "expected demo-mode reason in toast, got: {err}"
    );
    // No safety pin → no "would also refuse" suffix.
    assert!(
        !err.contains("would also refuse"),
        "no pin configured → no compose suffix, got: {err}"
    );
}

#[test]
fn deny_write_demo_mode_composes_pin_reason_in_toast() {
    // Operators iterating on `safety_envs` in `--demo` to validate
    // their config wording should see BOTH the demo refusal AND
    // the pin reason — without this they'd have to exit demo to
    // confirm the pin is wired (0.17.4 review finding).
    let mut app = test_app();
    app.demo_mode = true;
    app.cfg.safety_envs.insert("prod-eu-1".into(), true);
    let denied = app.deny_write("prod-eu-1", "rebuild");
    assert!(denied);
    let err = app.error_message.as_deref().unwrap();
    assert!(err.contains("demo mode"), "got: {err}");
    assert!(
        err.contains("would also refuse"),
        "expected pin compose suffix, got: {err}"
    );
    assert!(
        err.contains("safety.envs.prod-eu-1"),
        "expected pin source in suffix, got: {err}"
    );
}

#[test]
fn deny_write_allows_writes_when_not_demo_and_not_read_only() {
    let mut app = test_app();
    // demo_mode is false by default in test_app.
    let denied = app.deny_write("any-env", "rebuild");
    assert!(!denied, "non-demo non-readonly path must allow writes");
    assert!(
        app.error_message.is_none(),
        "no error toast on allowed write, got: {:?}",
        app.error_message
    );
}

#[tokio::test]
async fn rollback_to_label_opens_confirm_for_named_label() {
    // `:rollback --to LABEL` skips the snapshot+event-scan
    // detection and routes straight to the deploy confirm. Pins
    // that the operator's explicit choice wins over any captured
    // snapshot.
    let mut app = test_app();
    app.environments = vec![mk_env("prod", "shop", "Web", "Red")];
    app.rebuild_view();
    app.table_state.select(Some(0));
    // Snapshot exists with a DIFFERENT label; --to must override.
    app.deploy_snapshots.insert(
        "prod".into(),
        DeploySnapshot {
            previous_version_label: "build-snap".into(),
            taken_at: chrono::Utc::now(),
        },
    );
    app.execute_command("rollback --to build-820");
    // Confirm modal opened with the operator-named label.
    match &app.action_flow {
        Some(ActionFlow::Confirm(modal)) => {
            assert_eq!(modal.params.deploy_version.as_deref(), Some("build-820"));
            // No watchdog when --auto-rollback wasn't passed.
            assert!(modal.params.auto_rollback_secs.is_none());
        }
        _ => panic!("expected confirm modal open"),
    }
}

#[tokio::test]
async fn freeze_deploys_blocks_writes_with_reason_surfaced() {
    // Shared freeze-marker path; see `freeze::MARKER_LOCK`.
    let _marker_guard = crate::freeze::MARKER_LOCK
        .lock()
        .unwrap_or_else(|e| e.into_inner());
    // Operator dispatches `:freeze-deploys incident #1234` →
    // every destructive action refuses, with the reason
    // surfaced in the toast. Same gate as the read-only pins
    // but more visible (the reason is operator-supplied).
    let mut app = test_app();
    app.execute_command("freeze-deploys incident #1234");
    assert!(app.deploy_freeze.is_some(), "freeze should be set");
    assert!(
        app.is_read_only_for("any-env"),
        "freeze must block every env"
    );
    let reason = app.read_only_reason("any-env").unwrap_or_default();
    assert!(
        reason.contains("deploys frozen") && reason.contains("incident #1234"),
        "expected reason to surface, got: {reason}"
    );
}

#[tokio::test]
async fn freeze_deploys_with_no_reason_still_blocks() {
    // Shared freeze-marker path; see `freeze::MARKER_LOCK`.
    let _marker_guard = crate::freeze::MARKER_LOCK
        .lock()
        .unwrap_or_else(|e| e.into_inner());
    // Reason is optional — empty-reason freeze still blocks
    // but the toast wording shifts.
    let mut app = test_app();
    app.execute_command("freeze-deploys");
    assert!(app.deploy_freeze.is_some());
    let reason = app.read_only_reason("env").unwrap_or_default();
    assert!(
        reason.contains("deploys frozen") && !reason.contains(": "),
        "no-reason wording shouldn't include `: <reason>`, got: {reason}"
    );
}

#[tokio::test]
async fn thaw_deploys_clears_the_freeze() {
    // Shared freeze-marker path; see `freeze::MARKER_LOCK`.
    let _marker_guard = crate::freeze::MARKER_LOCK
        .lock()
        .unwrap_or_else(|e| e.into_inner());
    let mut app = test_app();
    app.execute_command("freeze-deploys testing");
    assert!(app.deploy_freeze.is_some());
    app.execute_command("thaw-deploys");
    assert!(app.deploy_freeze.is_none(), "thaw should clear freeze");
    assert!(
        !app.is_read_only_for("env"),
        "thaw must restore writes (no other locks set in this test)"
    );
}

#[tokio::test]
async fn freeze_overrides_per_env_pin_in_read_only_reason() {
    // Shared freeze-marker path; see `freeze::MARKER_LOCK`.
    let _marker_guard = crate::freeze::MARKER_LOCK
        .lock()
        .unwrap_or_else(|e| e.into_inner());
    // When BOTH a freeze AND a per-env safety pin are active,
    // the freeze reason wins in the toast — it's the more-
    // recent operator gesture and the more informative message.
    let mut app = test_app();
    app.cfg.safety_envs.insert("prod".into(), true);
    app.execute_command("freeze-deploys incident");
    let reason = app.read_only_reason("prod").unwrap_or_default();
    assert!(
        reason.contains("deploys frozen"),
        "freeze reason must win over per-env pin, got: {reason}"
    );
}

#[tokio::test]
async fn incident_start_freezes_and_end_thaws() {
    // Shared freeze-marker path; see `freeze::MARKER_LOCK`.
    let _marker_guard = crate::freeze::MARKER_LOCK
        .lock()
        .unwrap_or_else(|e| e.into_inner());
    let mut app = test_app();
    app.execute_command("incident START \"checkout 5xx spike\"");
    assert!(app.incident.is_some(), "incident should be active");
    assert!(app.deploy_freeze.is_some(), "START must set the freeze");
    assert!(
        app.is_read_only_for("any-env"),
        "incident freeze blocks every env"
    );
    let reason = app.read_only_reason("any-env").unwrap_or_default();
    assert!(
        reason.contains("incident: checkout 5xx spike"),
        "freeze reason carries the headline, got: {reason}"
    );
    app.execute_command("incident END");
    assert!(app.incident.is_none(), "END clears the incident");
    assert!(app.deploy_freeze.is_none(), "END thaws deploys");
    let status = app.status_message.clone().unwrap_or_default();
    assert!(
        status.contains("incident closed") && status.contains("checkout 5xx spike"),
        "END summary names the incident, got: {status}"
    );
}

#[tokio::test]
async fn promote_env_opens_deploy_confirm_on_target_with_sources_version() {
    // `:promote-env staging prod` takes staging's current
    // version_label, opens the deploy confirm on PROD (not the
    // selected env), and threads the label as deploy_version.
    let mut app = test_app();
    let mut staging = mk_env("staging", "shop", "Web", "Green");
    staging.version_label = "build-900".into();
    let mut prod = mk_env("prod", "shop", "Web", "Green");
    prod.version_label = "build-820".into();
    app.environments = vec![staging, prod];
    app.rebuild_view();
    // Cursor is on staging — the modal must still target prod
    // because the command names target explicitly, not via the
    // table cursor.
    app.table_state.select(Some(0));
    app.execute_command("promote-env staging prod");
    match &app.action_flow {
        Some(ActionFlow::Confirm(modal)) => {
            assert_eq!(modal.target_env, "prod");
            assert_eq!(modal.params.deploy_version.as_deref(), Some("build-900"));
            assert!(matches!(modal.action, Action::Deploy));
        }
        _ => panic!("expected confirm modal open on target"),
    }
}

#[tokio::test]
async fn handle_confirm_modal_lint_stuffs_issues_into_modal() {
    // After spawn_confirm_lint emits its message, the handler
    // clears the loading flag and stores the issues vec.
    // Modal renders Warn+ as inline warnings on the next draw.
    let mut app = test_app();
    app.environments = vec![mk_env("prod", "shop", "Web", "Green")];
    app.rebuild_view();
    app.table_state.select(Some(0));
    app.execute_command("deploy build-900");
    // Empty issues — handler still clears the loading flag.
    app.handle_msg(AppMsg::ConfirmModalLint {
        gen: app.generation,
        env_name: "prod".into(),
        issues: vec![],
    });
    match &app.action_flow {
        Some(ActionFlow::Confirm(modal)) => {
            assert!(!modal.loading_lint, "loading flag should clear");
            assert_eq!(modal.lint_issues.as_ref().map(|v| v.len()), Some(0));
        }
        _ => panic!("expected confirm modal open"),
    }
}

#[tokio::test]
async fn handle_confirm_modal_lint_drops_stale_target_results() {
    // If the operator opens a deploy on prod, closes it, then
    // opens a deploy on staging, the in-flight prod lint result
    // shouldn't land on the staging modal. Handler guards on
    // `modal.target_env == env_name`.
    let mut app = test_app();
    app.environments = vec![
        mk_env("prod", "shop", "Web", "Green"),
        mk_env("staging", "shop", "Web", "Green"),
    ];
    app.rebuild_view();
    // Open modal on staging.
    app.table_state.select(Some(1));
    app.execute_command("deploy build-900");
    // Late-arriving lint result for prod — should be dropped.
    app.handle_msg(AppMsg::ConfirmModalLint {
        gen: app.generation,
        env_name: "prod".into(),
        issues: vec![crate::lint::Issue {
            rule_id: "EBL001".into(),
            severity: crate::lint::Severity::Warn,
            env_name: Some("prod".into()),
            title: "stale".into(),
            detail: "stale".into(),
            suggestion: None,
            fields: Default::default(),
        }],
    });
    match &app.action_flow {
        Some(ActionFlow::Confirm(modal)) => {
            // loading_lint should still be true (we never
            // applied the stale result).
            assert!(
                modal.loading_lint,
                "loading flag must stay true on stale result"
            );
            assert!(
                modal.lint_issues.is_none(),
                "stale result must not populate"
            );
        }
        _ => panic!("expected confirm modal open"),
    }
}

#[tokio::test]
async fn is_read_only_for_layers_global_env_and_account() {
    // Global toggle wins over everything — even an env not in the
    // pin map.
    let mut app = test_app();
    app.read_only = true;
    assert!(app.is_read_only_for("any-env"));
    assert!(app.read_only_reason("any-env").unwrap().contains("global"));

    // Global off + per-env pin → that one env is locked, others
    // aren't.
    let mut app = test_app();
    app.cfg.safety_envs.insert("uflexi-prod".into(), true);
    app.cfg.safety_envs.insert("uflexi-staging".into(), false);
    assert!(app.is_read_only_for("uflexi-prod"));
    assert!(!app.is_read_only_for("uflexi-staging"));
    assert!(!app.is_read_only_for("uflexi-dev"));
    assert!(app
        .read_only_reason("uflexi-prod")
        .unwrap()
        .contains("safety.envs.uflexi-prod"));

    // Global off + per-account pin → every env in that profile is
    // locked.
    let mut app = test_app();
    app.context.profile = Some("prod-acct".into());
    app.cfg.safety_accounts.insert("prod-acct".into(), true);
    assert!(app.is_read_only_for("any-env"));
    assert!(app
        .read_only_reason("any-env")
        .unwrap()
        .contains("safety.accounts.prod-acct"));
    // Switching profile away clears the lock.
    app.context.profile = Some("dev-acct".into());
    assert!(!app.is_read_only_for("any-env"));

    // Nothing pinned → unlocked + reason is None.
    let app = test_app();
    assert!(!app.is_read_only_for("any-env"));
    assert!(app.read_only_reason("any-env").is_none());
}

#[tokio::test]
async fn deny_write_batch_refuses_when_any_selected_env_is_pinned() {
    // Regression: pre-fix, cmd_batch_* gated only on the global
    // `read_only` flag, so a per-env safety pin (safety.envs.X) was
    // silently bypassed for batch ops. deny_write_batch must refuse
    // the whole batch if ANY selected env is pinned.
    let mut app = test_app();
    app.cfg.safety_envs.insert("prod-web".into(), true);
    let selection = vec!["staging-web".to_string(), "prod-web".to_string()];
    assert!(
        app.deny_write_batch(&selection, "batch action"),
        "a pinned env in the selection must refuse the batch"
    );
    let msg = app.error_message.clone().unwrap();
    // Names the locked env + the safety.envs source.
    assert!(msg.contains("prod-web"), "got: {msg}");
    assert!(msg.contains("safety.envs.prod-web"), "got: {msg}");
    // Refuse-all: the unpinned env is NOT quietly let through.
    assert!(msg.contains("1 of 2"), "got: {msg}");
}

#[tokio::test]
async fn deny_write_batch_allows_when_no_env_pinned() {
    let mut app = test_app();
    app.cfg.safety_envs.insert("other-env".into(), true); // not in selection
    let selection = vec!["staging-web".to_string(), "dev-web".to_string()];
    assert!(
        !app.deny_write_batch(&selection, "batch action"),
        "no selected env pinned → batch proceeds"
    );
    assert!(app.error_message.is_none());
}

#[tokio::test]
async fn deny_write_batch_global_flag_uses_fleet_message_not_per_env_list() {
    // The env-independent gates (global read-only / freeze / demo)
    // should still produce their familiar whole-fleet toast rather
    // than enumerating envs.
    let mut app = test_app();
    app.read_only = true;
    let selection = vec!["a".to_string(), "b".to_string()];
    assert!(app.deny_write_batch(&selection, "batch action"));
    let msg = app.error_message.clone().unwrap();
    assert!(msg.contains("read-only mode"), "got: {msg}");
    // Not the per-env "N of M …" shape.
    assert!(!msg.contains(" of "), "got: {msg}");
}

#[tokio::test]
async fn render_greens_type_to_confirm_only_on_exact_match() {
    // Styled-harness demo: the type-to-confirm field turns green only
    // when the typed text exactly matches the target env name.
    let mut app = test_app();
    // Red env behind the modal so the only green on screen can come
    // from the modal's match indicator, not a table health dot.
    app.environments = vec![mk_env("prod", "uflexi", "Web", "Red")];
    app.rebuild_view();
    app.mode = Mode::Action;
    let mut modal = mk_modal(Action::Terminate, "prod");
    modal.kind = ConfirmKind::TypeName;

    // Differential count so constant green chrome (header) doesn't
    // confound the check: the exact match must add green cells (the
    // typed field + enter hint) over the partial-match baseline.
    let theme = app.theme.clone();
    modal.typed = "pro".into();
    app.action_flow = Some(ActionFlow::Confirm(modal.clone()));
    let no_match_green = count_fg(&render_buf(&mut app, 120, 30), theme.health_green);

    modal.typed = "prod".into();
    app.action_flow = Some(ActionFlow::Confirm(modal));
    let matched_green = count_fg(&render_buf(&mut app, 120, 30), theme.health_green);

    assert!(
        matched_green > no_match_green,
        "exact type-to-confirm match should paint more green than a partial match \
             (matched={matched_green}, no_match={no_match_green})"
    );
}

#[tokio::test]
async fn every_write_command_is_refused_in_read_only_mode() {
    for cmd in WRITE_COMMANDS.iter().chain(APPLICATION_SCOPED_WRITES) {
        let mut app = read_only_app_with_env();
        app.execute_command(cmd);
        let err = app.error_message.as_deref().unwrap_or_default();
        assert!(
            err.contains("read-only mode"),
            ":{cmd} was not refused by the safety gate — got {err:?}\n\
             (a write that doesn't reach `deny_write` ignores --deny-write \
             and safety.envs.*.read_only)"
        );
    }
}

#[tokio::test]
async fn an_application_scoped_write_still_honours_the_global_toggle() {
    // It can't match a per-env pin — there's no single env — so the
    // global toggle is the only thing standing in front of it.
    for cmd in APPLICATION_SCOPED_WRITES {
        let mut app = read_only_app_with_env();
        app.execute_command(cmd);
        let err = app.error_message.as_deref().unwrap_or_default();
        assert!(err.contains("read-only mode"), ":{cmd} — got {err:?}");
    }
}

#[tokio::test]
async fn every_write_command_is_refused_by_a_per_env_safety_pin() {
    // The global toggle and the per-env pin are separate paths through
    // `is_read_only_for`; a command could honour one and not the other.
    for cmd in WRITE_COMMANDS {
        let mut app = read_only_app_with_env();
        app.read_only = false;
        app.cfg.safety_envs.insert("api-prod".into(), true);
        app.execute_command(cmd);
        let err = app.error_message.as_deref().unwrap_or_default();
        assert!(
            err.contains("safety.envs"),
            ":{cmd} ignored the per-env safety pin — got {err:?}"
        );
    }
}

#[tokio::test]
async fn every_batch_write_is_refused_in_read_only_mode() {
    for cmd in BATCH_WRITE_COMMANDS {
        let mut app = read_only_app_with_env();
        // Bulk ops act on the space-multi-selected set.
        app.multi_selected = ["api-prod".to_string()].into_iter().collect();
        app.execute_command(cmd);
        let err = app.error_message.as_deref().unwrap_or_default();
        assert!(
            err.contains("read-only"),
            ":{cmd} was not refused by the batch safety gate — got {err:?}"
        );
    }
}

#[tokio::test]
async fn every_batch_write_is_refused_when_one_member_is_pinned() {
    // The point of `deny_write_batch`: a batch is refused if ANY member
    // is pinned, not just if all of them are. A batch that skipped the
    // pinned env and wrote to the rest would be worse than refusing.
    for cmd in BATCH_WRITE_COMMANDS {
        let mut app = read_only_app_with_env();
        app.environments = vec![
            mk_env("api-prod", "uflexi", "Web", "Green"),
            mk_env("api-staging", "uflexi", "Web", "Green"),
        ];
        app.rebuild_view();
        app.table_state.select(Some(0));
        app.read_only = false;
        // Only ONE of the two is pinned.
        app.cfg.safety_envs.insert("api-prod".into(), true);
        app.multi_selected = ["api-prod".to_string(), "api-staging".to_string()]
            .into_iter()
            .collect();
        app.execute_command(cmd);
        let err = app.error_message.as_deref().unwrap_or_default();
        assert!(
            err.contains("safety.envs"),
            ":{cmd} wrote to a batch containing a pinned env — got {err:?}"
        );
    }
}

// --- the destructive commands actually route --------------------------
//
// From the 131-command dispatch sweep: each of these could be turned
// into a no-op and the whole suite stayed green. The safety tests pin
// the 29 declared WRITE_COMMANDS, but those are the option-setting ones
// that gate inside their own handler. The confirm-modal actions —
// restart, rebuild, terminate, stop, start — were pinned by nothing, so
// a broken or renamed dispatch arm would silently do nothing at all.

#[tokio::test]
async fn the_confirm_modal_commands_arm_the_right_action() {
    for (cmd, expected) in [
        ("restart", Action::RestartAppServer),
        ("rebuild", Action::Rebuild),
        ("stop", Action::Scale),
        ("start", Action::Scale),
    ] {
        let mut app = test_app();
        app.environments = vec![mk_env("api-prod", "uflexi", "Web", "Green")];
        app.view.invalidate();
        app.rebuild_view();
        app.table_state.select(Some(0));

        app.execute_command(cmd);

        let Some(ActionFlow::Confirm(modal)) = app.action_flow.as_ref() else {
            panic!(
                ":{cmd} armed no confirm modal at all (error: {:?})",
                app.error_message
            );
        };
        assert_eq!(modal.action, expected, ":{cmd} armed the wrong action");
        assert_eq!(
            modal.target_env, "api-prod",
            ":{cmd} aimed at the wrong env"
        );
        assert_eq!(app.mode, Mode::Action, ":{cmd} left the mode behind");
    }
}

#[tokio::test]
async fn terminate_routes_to_the_strict_typed_name_guard() {
    // Terminate deliberately does NOT use the Y/N confirm the others
    // do — it goes through the action menu so the operator has to type
    // the env name. That difference is the whole safety story for the
    // one irreversible action, and nothing pinned it.
    let mut app = test_app();
    app.environments = vec![mk_env("api-prod", "uflexi", "Web", "Green")];
    app.view.invalidate();
    app.rebuild_view();
    app.table_state.select(Some(0));

    app.execute_command("terminate");

    let Some(ActionFlow::Confirm(modal)) = app.action_flow.as_ref() else {
        panic!(
            ":terminate armed no confirm at all (error: {:?})",
            app.error_message
        );
    };
    assert_eq!(modal.action, Action::Terminate);
    assert_eq!(modal.target_env, "api-prod");
    assert_eq!(
        modal.kind,
        ConfirmKind::TypeName,
        ":terminate must demand the typed env name, not a Y/N"
    );
}

#[tokio::test]
async fn destructive_commands_still_refuse_under_deny_write() {
    // The routing tests above arm a modal; this pins that the same
    // route still refuses when writes are denied. Without it, a fix to
    // routing could quietly bypass the gate and both other tests would
    // still pass.
    for cmd in ["restart", "rebuild", "terminate", "stop", "start"] {
        let mut app = read_only_app_with_env();
        app.execute_command(cmd);
        assert!(
            app.action_flow.is_none(),
            ":{cmd} armed an action despite --deny-write"
        );
        assert!(
            app.error_message.is_some(),
            ":{cmd} refused silently — the operator needs to be told"
        );
    }
}

// --- the mutating commands the write tables never listed -------------
//
// From the 131-command dispatch sweep. `WRITE_COMMANDS` pins the
// option-setting commands — the ones with no `deny_write` of their own.
// Everything that gates *inside* its own handler was therefore in no
// list at all, so nothing pinned that it kept doing so. All of these
// were verified to refuse before being listed here; none of them was a
// hole, but none of them was pinned either.

#[tokio::test]
async fn every_gated_command_is_refused_in_read_only_mode() {
    for cmd in GATED_COMMANDS {
        let mut app = read_only_app_with_env();
        app.execute_command(cmd);
        let err = app.error_message.as_deref().unwrap_or_default();
        assert!(
            err.contains("read-only mode"),
            ":{cmd} was not refused by the safety gate — got {err:?}"
        );
    }
}

#[tokio::test]
async fn swap_is_refused_in_read_only_mode() {
    // Needs a second env in the same application, or it is turned away
    // on the argument before the gate is ever consulted — which is what
    // made it look ungated on first inspection.
    let mut app = read_only_app_with_env();
    app.environments
        .push(mk_env("api-staging", "uflexi", "Web", "Green"));
    app.view.invalidate();
    app.rebuild_view();
    app.table_state.select(Some(0));

    app.execute_command("swap api-staging");
    let err = app.error_message.as_deref().unwrap_or_default();
    assert!(err.contains("read-only mode"), ":swap got {err:?}");
}

#[tokio::test]
async fn ssm_run_is_refused_in_read_only_mode() {
    // Same shape: it needs cached instances from an open Detail pane
    // before it reaches the gate.
    let mut app = read_only_app_with_env();
    app.open_detail();
    if let Some(d) = app.detail.as_mut() {
        d.instances = vec![crate::aws::Instance {
            id: "i-0abc".into(),
            health: "Ok".into(),
            color: "Green".into(),
            causes: Vec::new(),
            instance_type: "t3.medium".into(),
            availability_zone: "eu-west-2a".into(),
            launched_at: None,
        }];
    }

    app.execute_command("ssm-run uptime");
    let err = app.error_message.as_deref().unwrap_or_default();
    assert!(err.contains("read-only mode"), ":ssm-run got {err:?}");
}

/// `safety.envs.NAME.read_only` must protect an env from being swapped
/// INTO, not just out of.
///
/// A CNAME swap rewrites BOTH environments' DNS, so it is a write to the
/// target as much as to the source. But the only `deny_write` on this
/// path was in `open_action_menu`, against the *selected* env — and the
/// target is chosen afterwards, from a picker. So a pin on `green` did
/// nothing if you selected `blue` first and swapped towards it.
///
/// This drives the real flow — open the menu on the unpinned env, pick
/// the pinned one — rather than calling `deny_write` directly, which
/// would only prove the gate function works and not that anything calls
/// it. The first version of this test made exactly that mistake and
/// passed against the unfixed code.
#[tokio::test]
async fn a_read_only_env_cannot_be_swapped_into() {
    let mut app = test_app();
    app.environments = vec![
        mk_env("blue", "shop", "WebServer", "Green"),
        mk_env("green", "shop", "WebServer", "Green"),
    ];
    app.rebuild_view();
    app.cfg.safety_envs.insert("green".into(), true);
    assert!(app.is_read_only_for("green"), "the pin must be in effect");
    assert!(!app.is_read_only_for("blue"), "the source is writable");

    // Select the UNPINNED env; the menu opens because only it is checked.
    app.table_state.select(Some(0));
    assert!(app.open_action_menu(), "`blue` is writable");
    app.advance_action_flow(crate::app::Action::SwapCnames);

    // The picker should be offering `green` as the swap target.
    let picking = matches!(
        app.action_flow,
        Some(crate::app::ActionFlow::SwapTarget { .. })
    );
    assert!(picking, "swap opens a target picker");

    // Choose it. This is the moment the target becomes known.
    press(&mut app, KeyCode::Enter, KeyModifiers::NONE);

    // It must NOT have reached a confirm modal.
    let confirmed = matches!(app.action_flow, Some(crate::app::ActionFlow::Confirm(_)));
    assert!(
        !confirmed,
        "a swap INTO a read-only env must be refused before the confirm \
         modal, not dispatched"
    );
    let msg = app
        .error_message
        .clone()
        .or_else(|| app.status_message.clone())
        .unwrap_or_default();
    assert!(
        msg.contains("green"),
        "the refusal must name the pinned env so the operator knows which \
         pin stopped it, got: {msg:?}"
    );
}

/// The command path has the same hole as the picker path, so it needs
/// the same gate. `:swap TARGET` routes through
/// `open_parameterised_action`, which checks the env it was handed —
/// the SOURCE — and never looked at the target.
///
/// Separate test from the picker one because they are separate entry
/// points into the same write, and fixing one is exactly how the other
/// gets left behind.
#[tokio::test]
async fn swap_cnames_command_also_gates_the_target() {
    let mut app = test_app();
    app.environments = vec![
        mk_env("blue", "shop", "WebServer", "Green"),
        mk_env("green", "shop", "WebServer", "Green"),
    ];
    app.rebuild_view();
    app.cfg.safety_envs.insert("green".into(), true);
    app.table_state.select(Some(0)); // `blue` — writable

    app.execute_command("swap green");

    let confirmed = matches!(app.action_flow, Some(crate::app::ActionFlow::Confirm(_)));
    assert!(
        !confirmed,
        "`:swap green` must be refused when `green` is pinned \
         read-only, even though the selected env `blue` is writable"
    );
    let msg = app
        .error_message
        .clone()
        .or_else(|| app.status_message.clone())
        .unwrap_or_default();
    assert!(
        msg.contains("green"),
        "the refusal must name the pinned env, got: {msg:?}"
    );
}

/// The success path of the swap picker, which the refusal tests above do
/// not cover.
///
/// Found by `cargo mutants --in-diff`: deleting `swap_with` from the
/// `ConfirmModal` the picker builds survived the whole suite. The modal
/// would then carry no target, and the dispatch would fall through to
/// "swap target missing" — after the operator had confirmed. Two tests
/// asserted the swap is REFUSED when the target is pinned; none asserted
/// the target actually arrives when it is not.
///
/// Exactly the "a change that adds a distinction must be chased to every
/// call site" rule, turned on the change that added the distinction.
#[tokio::test]
async fn the_swap_picker_carries_its_target_into_the_confirm_modal() {
    let mut app = test_app();
    app.environments = vec![
        mk_env("blue", "shop", "WebServer", "Green"),
        mk_env("green", "shop", "WebServer", "Green"),
    ];
    app.rebuild_view();
    app.table_state.select(Some(0)); // `blue`, neither env pinned

    assert!(app.open_action_menu());
    app.advance_action_flow(crate::app::Action::SwapCnames);
    assert!(
        matches!(
            app.action_flow,
            Some(crate::app::ActionFlow::SwapTarget { .. })
        ),
        "swap opens a target picker"
    );

    press(&mut app, KeyCode::Enter, KeyModifiers::NONE);

    let Some(crate::app::ActionFlow::Confirm(modal)) = &app.action_flow else {
        panic!("choosing a target must open the confirm modal");
    };
    assert_eq!(
        modal.action,
        crate::app::Action::SwapCnames,
        "and it must be the swap it was opened for"
    );
    assert_eq!(
        modal.params.swap_with.as_deref(),
        Some("green"),
        "the chosen target must ride on the modal — without it the dispatch \
         reaches `swap target missing` only after the operator confirms"
    );
    assert_eq!(
        modal.target_env, "blue",
        "and the source must be the selected env, not the picked one"
    );
}

/// `:rollback` must not roll back the env the cursor happens to be on
/// when the result lands.
///
/// `:rollback` fetches the target env's recent events, finds the
/// previously-deployed version, then opens the deploy-confirm modal —
/// and that modal targets the SELECTED env. So if the cursor moved
/// while the fetch was in flight, the modal would offer env A's previous
/// version for deployment to env B. `handle_rollback_target` guards
/// against it and says so in a comment.
///
/// `cargo mutants` found both directions of that guard surviving, so
/// nothing tested it. The generation guard does not help here: the
/// generation only advances on a context switch (profile/region), not on
/// moving the cursor between envs in the same account.
#[tokio::test]
async fn a_rollback_result_does_not_target_whatever_env_is_selected_now() {
    let mut app = test_app();
    app.environments = vec![
        mk_env("api-prod", "shop", "WebServer", "Green"),
        mk_env("worker-prod", "shop", "Worker", "Green"),
    ];
    app.rebuild_view();
    app.table_state.select(Some(0)); // `:rollback` issued for api-prod

    let ev = |vl: Option<&str>| crate::aws::Event {
        at: None,
        env: "api-prod".into(),
        application: "shop".into(),
        message: "Deploying new version".into(),
        severity: "INFO".into(),
        version_label: vl.map(String::from),
    };
    // Newest first: current is v2, so the prior version is v1.
    let events = vec![ev(Some("v2")), ev(Some("v1"))];

    // The operator moves the cursor while the fetch is in flight.
    app.table_state.select(Some(1)); // now on worker-prod

    let gen = app.generation;
    app.handle_msg(crate::app::AppMsg::RollbackTarget {
        gen,
        env_name: "api-prod".to_string(),
        current_version: "v2".to_string(),
        result: Ok(events),
    });

    assert!(
        app.action_flow.is_none(),
        "no confirm modal may open: the modal targets the SELECTED env, \
         which is now worker-prod, and this result is about api-prod"
    );
    let msg = app.error_message.clone().unwrap_or_default();
    assert!(
        msg.contains("selection moved"),
        "and the operator must be told why nothing happened, got: {msg:?}"
    );
}

/// The other half: with the cursor still on the target env, the rollback
/// must actually proceed — or the guard above could be "never roll back"
/// and still pass.
#[tokio::test]
async fn a_rollback_result_opens_the_modal_when_the_cursor_stayed_put() {
    let mut app = test_app();
    app.environments = vec![mk_env("api-prod", "shop", "WebServer", "Green")];
    app.rebuild_view();
    app.table_state.select(Some(0));

    let ev = |vl: Option<&str>| crate::aws::Event {
        at: None,
        env: "api-prod".into(),
        application: "shop".into(),
        message: "Deploying new version".into(),
        severity: "INFO".into(),
        version_label: vl.map(String::from),
    };
    let gen = app.generation;
    app.handle_msg(crate::app::AppMsg::RollbackTarget {
        gen,
        env_name: "api-prod".to_string(),
        current_version: "v2".to_string(),
        result: Ok(vec![ev(Some("v2")), ev(Some("v1"))]),
    });

    let Some(crate::app::ActionFlow::Confirm(modal)) = &app.action_flow else {
        panic!("the rollback should open a deploy-confirm modal");
    };
    assert_eq!(modal.target_env, "api-prod");
    assert_eq!(
        modal.params.deploy_version.as_deref(),
        Some("v1"),
        "and it must offer the PREVIOUS version, not the current one"
    );
}

/// The type-the-env-name confirmation must actually compare the text.
///
/// Terminate opens a `ConfirmKind::TypeName` modal: the operator has to
/// type the environment's name and press Enter. `cargo mutants` found
/// THREE survivors on that comparison — the guard replaced with `true`,
/// with `false`, and the `==` flipped to `!=` — so neither direction was
/// tested.
///
/// Replaced with `true` it is the worst outcome in this codebase:
/// pressing Enter with an empty field, or with any text at all,
/// dispatches a terminate. The comment beside it calls the typed-name
/// guard the thing that "already prevents accidental dispatch", with the
/// 5s cancel window as a last-ditch rescue — so this is the primary
/// protection, not the backup.
#[tokio::test]
async fn terminate_requires_the_env_name_typed_exactly() {
    async fn modal_for_terminate() -> App {
        let mut app = test_app();
        app.environments = vec![mk_env("api-prod", "shop", "WebServer", "Green")];
        app.rebuild_view();
        app.table_state.select(Some(0));
        // Via the menu, so `mode` becomes `Mode::Action` — without it the
        // typed characters route to the NORMAL keymap and never reach the
        // confirm field.
        assert!(app.open_action_menu(), "the action menu should open");
        app.advance_action_flow(crate::app::Action::Terminate);
        let Some(crate::app::ActionFlow::Confirm(m)) = &app.action_flow else {
            panic!("terminate should open a confirm modal");
        };
        assert_eq!(
            m.kind,
            crate::app::ConfirmKind::TypeName,
            "terminate must be type-to-confirm, not Y/N"
        );
        app
    }

    // Nothing typed: Enter must not dispatch.
    let mut app = modal_for_terminate().await;
    press(&mut app, KeyCode::Enter, KeyModifiers::NONE);
    assert!(
        app.pending_dispatch.is_none(),
        "Enter on an EMPTY type-to-confirm field must not queue a terminate"
    );
    assert!(app.action_flow.is_some(), "and the modal must stay open");

    // Wrong name: Enter must not dispatch.
    let mut app = modal_for_terminate().await;
    for c in "api-prd".chars() {
        press(&mut app, KeyCode::Char(c), KeyModifiers::NONE);
    }
    press(&mut app, KeyCode::Enter, KeyModifiers::NONE);
    assert!(
        app.pending_dispatch.is_none(),
        "a MISTYPED env name must not queue a terminate — this is the guard \
         the modal's own comment calls the thing that prevents accidental \
         dispatch"
    );

    // Exact name: Enter dispatches. Without this the guard could be
    // "never confirm" and the two assertions above would still pass.
    let mut app = modal_for_terminate().await;
    for c in "api-prod".chars() {
        press(&mut app, KeyCode::Char(c), KeyModifiers::NONE);
    }
    press(&mut app, KeyCode::Enter, KeyModifiers::NONE);
    assert!(
        app.pending_dispatch.is_some(),
        "the EXACT env name must confirm, or terminate is unreachable"
    );
    assert!(
        app.action_flow.is_none(),
        "and the modal closes into the cancel window"
    );
}

// ── type-to-confirm gates ─────────────────────────────────────────────
//
// The 2026-08-26 mutation sweep found the DLQ purge's type-the-env-name
// gate completely untested — all three of its mutants survived,
// including `==` flipped to `!=`, which purges when the typed name is
// WRONG. `p` on a DLQ is not recoverable.
//
// The audit that followed found only one other such gate (Terminate),
// and that one was properly covered. But the audit was a one-off, and a
// third gate added tomorrow would ship the same way. This turns it into
// a standing check: every place production compares typed input against
// an expected value is classified here, and a gate has to name the test
// that proves it.

/// What a typed-input comparison is for.
enum TypedUse {
    /// A confirmation gate on an irreversible operation. Names the test
    /// that proves it refuses a near-miss and accepts an exact match.
    Gate(&'static str),
    /// Not a gate — rendering, or a change check. Says why.
    NotAGate(&'static str),
}

/// Confirmation state: every `confirm_*` field DECLARED on a type.
///
/// Added after the guard below let a real one through. Its first version
/// covered only typed confirmations (`X.text() == Y`), which is narrower
/// than its name suggested — the saved-configs delete confirm is a y/n
/// gate, so it sat outside the guard entirely and had every arm
/// survivable, including one where Enter applied a config instead of
/// deleting it. Confirmation state turns out to be consistently named,
/// so it is enumerable after all.
///
/// Keyed `file::field`, because one file can hold several.
const CONFIRM_STATE: &[(&str, TypedUse)] = &[
    (
        "src/mode_dlq.rs::confirm_purge",
        TypedUse::Gate("a_purge_fires_only_when_the_typed_name_matches"),
    ),
    (
        "src/mode_dlq.rs::confirm_delete_id",
        TypedUse::Gate("a_delete_confirm_takes_yes_and_cancels_on_anything_else"),
    ),
    (
        "src/app/types.rs::confirm_delete",
        TypedUse::Gate("a_delete_confirm_can_be_declined_and_ignores_navigation"),
    ),
    (
        "src/mode_detail.rs::config_delete_confirm",
        TypedUse::Gate("x_arms_the_delete_belonging_to_the_focused_tab_and_no_other"),
    ),
    (
        "src/mode_detail.rs::instance_terminate_confirm",
        TypedUse::Gate("x_arms_the_delete_belonging_to_the_focused_tab_and_no_other"),
    ),
    (
        "src/ui/overlays.rs::confirm_delete",
        TypedUse::NotAGate(
            "a render function's parameter, not state — it draws the \
             prompt the gate in app/types.rs owns.",
        ),
    ),
];

/// Every `X.text() == Y` in production. See the note above.
const TYPED_COMPARISONS: &[(&str, TypedUse)] = &[
    (
        "src/app/mode_dlq_handlers.rs",
        TypedUse::Gate("a_purge_fires_only_when_the_typed_name_matches"),
    ),
    (
        "src/app/action_flow.rs",
        TypedUse::Gate("terminate_requires_the_env_name_typed_exactly"),
    ),
    (
        "src/ui/action.rs",
        TypedUse::NotAGate(
            "render only — colours the typed text by whether it matches. \
             The gate it mirrors is action_flow.rs's.",
        ),
    ),
    (
        "src/ui/dlq.rs",
        TypedUse::NotAGate("render only — same mirror for the purge prompt."),
    ),
    (
        "src/app/config_edit.rs",
        TypedUse::NotAGate(
            "change detection, not confirmation: an unedited value is \
             submitted as a no-op rather than refused.",
        ),
    ),
];

#[test]
fn every_confirmation_gate_names_its_test() {
    // 1. The list must cover every comparison in production, so a new
    //    gate cannot be added without being classified.
    let mut found: Vec<String> = Vec::new();
    for (path, text) in super::scan::source_files() {
        if super::scan::is_test_path(&path) {
            continue;
        }
        for line in text.lines() {
            if super::scan::strip_line_comment(line).contains(".text() == ") {
                found.push(path.clone());
            }
        }
    }
    found.sort();
    found.dedup();

    let listed: Vec<&str> = TYPED_COMPARISONS.iter().map(|(p, _)| *p).collect();
    for f in &found {
        assert!(
            listed.contains(&f.as_str()),
            "{f} compares typed input against an expected value and is not \
             classified in TYPED_COMPARISONS. If it gates an irreversible \
             operation it needs a test that refuses a near-miss; if it \
             doesn't, say so there."
        );
    }
    for l in &listed {
        assert!(
            found.contains(&l.to_string()),
            "TYPED_COMPARISONS names {l}, which no longer compares typed \
             input — drop the entry rather than leave it asserting nothing."
        );
    }

    // 2. Every gate's named test must actually exist. A renamed test
    //    would otherwise leave a gate claiming cover it doesn't have.
    let all_tests: String = super::scan::source_files()
        .into_iter()
        .filter(|(p, _)| super::scan::is_test_path(p))
        .map(|(_, t)| t)
        .collect();
    for (path, use_) in TYPED_COMPARISONS {
        if let TypedUse::Gate(test_name) = use_ {
            assert!(
                all_tests.contains(&format!("fn {test_name}(")),
                "{path} is a confirmation gate on an irreversible \
                 operation, and the test it names — {test_name} — does not \
                 exist. Either it was renamed, or the gate is uncovered."
            );
        }
    }

    // 3. A "not a gate" claim has to carry a reason. Without this the
    //    payload is decoration — clippy says so, and the cheapest way
    //    to silence this guard would be `NotAGate("")`.
    for (path, use_) in TYPED_COMPARISONS {
        if let TypedUse::NotAGate(why) = use_ {
            assert!(
                why.len() > 20,
                "{path} is classified as not a confirmation gate, which is \
                 the classification that exempts it from needing a test. \
                 Say why in more than a few words: {why:?}"
            );
        }
    }

    // 4. The same three checks for confirmation STATE, which is the
    //    half this guard originally missed.
    let mut found_state: Vec<String> = Vec::new();
    for (path, text) in super::scan::source_files() {
        if super::scan::is_test_path(&path) {
            continue;
        }
        for line in text.lines() {
            let t = super::scan::strip_line_comment(line).trim();
            let Some(rest) = t.strip_prefix("pub ").or(Some(t)) else {
                continue;
            };
            let rest = rest.strip_prefix("pub(crate) ").unwrap_or(rest);
            // BOTH orders. The first version of this scan matched only
            // `confirm_*`, which is how `config_delete_confirm` and
            // `instance_terminate_confirm` — two real gates on
            // irreversible operations — stayed outside a guard whose
            // stated job is "every confirmation field". That is the same
            // mistake this guard's docstring already records making
            // once: a check narrower than its own name.
            //
            // Matched on the field NAME rather than a prefix, so a third
            // convention (`pending_delete_confirmed`, say) would also be
            // caught.
            let name_part = rest.split(':').next().unwrap_or("").trim();
            if !(name_part.starts_with("confirm_") || name_part.ends_with("_confirm")) {
                continue;
            }
            let Some((field, ty)) = rest.split_once(':') else {
                continue;
            };
            // A DECLARATION has a type on the right (`bool`,
            // `Option<String>`); an initialiser has a value (`false`,
            // `None`). Only declarations are the surface.
            let ty = ty.trim().trim_end_matches(',').trim();
            if !(ty == "bool" || ty.starts_with("Option<") || ty.starts_with("String")) {
                continue;
            }
            found_state.push(format!("{path}::{}", field.trim()));
        }
    }
    found_state.sort();
    found_state.dedup();
    assert!(
        found_state.len() >= 5,
        "expected at least five confirmation declarations; found \
         {found_state:?} — the scan is broken"
    );

    let listed_state: Vec<&str> = CONFIRM_STATE.iter().map(|(p, _)| *p).collect();
    for f in &found_state {
        assert!(
            listed_state.contains(&f.as_str()),
            "{f} is confirmation state and is not classified in \
             CONFIRM_STATE. If it gates an irreversible operation it \
             needs a test that the DECLINE path works; if it doesn't, \
             say so there."
        );
    }
    for l in &listed_state {
        assert!(
            found_state.contains(&l.to_string()),
            "CONFIRM_STATE names {l}, which no longer exists — drop it \
             rather than leave it asserting nothing."
        );
    }
    for (path, use_) in CONFIRM_STATE {
        match use_ {
            TypedUse::Gate(test_name) => assert!(
                all_tests.contains(&format!("fn {test_name}(")),
                "{path} is a confirmation gate and the test it names — \
                 {test_name} — does not exist."
            ),
            TypedUse::NotAGate(why) => assert!(
                why.len() > 20,
                "{path} is exempted from needing a test; say why in more \
                 than a few words: {why:?}"
            ),
        }
    }

    // 5. Non-vacuity: at least the two known gates.
    let gates = TYPED_COMPARISONS
        .iter()
        .filter(|(_, u)| matches!(u, TypedUse::Gate(_)))
        .count();
    assert!(
        gates >= 2,
        "expected at least the Terminate and DLQ-purge gates; found {gates}"
    );
}

/// `Ctrl-J` / `Ctrl-K` must not move the swap-target picker.
///
/// `^K` is the command-palette chord, advertised in the footer on every
/// screen. Without the `!CONTROL` guards on these arms it also moves the
/// selection in this picker — so an operator reaching for the palette
/// silently changes which environment they are about to swap production
/// DNS onto, and the next `Enter` acts on it. Both guards were free in
/// the 2026-08-27 sweep.
///
/// Drives the real flow rather than poking `Picker` directly: the point
/// is that the KEY HANDLER honours the guard, not that a picker can move.
#[tokio::test]
async fn ctrl_chords_do_not_move_the_swap_target_picker() {
    let selected = |app: &App| -> Option<String> {
        match app.action_flow.as_ref() {
            Some(crate::app::ActionFlow::SwapTarget { picker, .. }) => picker.selected_value(),
            _ => panic!("not in the swap picker"),
        }
    };
    let open = || {
        let mut app = test_app();
        app.environments = vec![
            mk_env("blue", "shop", "WebServer", "Green"),
            mk_env("green", "shop", "WebServer", "Green"),
            mk_env("amber", "shop", "WebServer", "Green"),
        ];
        app.rebuild_view();
        app.table_state.select(Some(0));
        assert!(app.open_action_menu());
        app.advance_action_flow(crate::app::Action::SwapCnames);
        app
    };

    // Plain j / k / Down / Up move it — the guard must not block the
    // ordinary case, which is how "always refuse" would pass.
    for key in [KeyCode::Char('j'), KeyCode::Down] {
        let mut app = open();
        let before = selected(&app);
        press(&mut app, key, KeyModifiers::NONE);
        assert_ne!(selected(&app), before, "{key:?} should move the picker");
    }

    // The same keys with Ctrl held must not.
    for key in [KeyCode::Char('j'), KeyCode::Char('k')] {
        let mut app = open();
        let before = selected(&app);
        press(&mut app, key, KeyModifiers::CONTROL);
        assert_eq!(
            selected(&app),
            before,
            "Ctrl-{key:?} moved the swap target — reaching for the palette \
             must not re-aim a production DNS swap"
        );
    }
}

/// A refused write must leave a trace.
///
/// The gap this closes: a blocked write never dispatches, so no
/// `dispatched`/`completed` pair was ever written and repeated attempts
/// on a pinned env were indistinguishable from nobody trying at all.
///
/// Reads the log back rather than asserting on a formatter, so the
/// wiring is pinned and not a copy of it. Follows the append-only
/// delta convention from `tests/region.rs`: every test in this process
/// shares one audit file, so the env name is unique to this test and
/// the delta is taken with `strip_prefix`.
#[tokio::test]
async fn a_refused_write_is_recorded_with_its_rule_and_remedy() {
    let env_name = "refusal-audit-probe-env";
    let path = crate::util::cache_dir().join("audit.log");
    let before = std::fs::read_to_string(&path).unwrap_or_default();

    let mut app = test_app();
    app.cfg.safety_envs.insert(env_name.into(), true);
    assert!(app.deny_write(env_name, "Terminate"), "must refuse");

    let after = std::fs::read_to_string(&path).unwrap_or_default();
    let delta = after
        .strip_prefix(&before)
        .expect("the audit log is append-only");
    let lines: Vec<&str> = delta.lines().filter(|l| l.contains(env_name)).collect();
    assert_eq!(lines.len(), 1, "exactly one line for the refusal: {delta}");
    let line = lines[0];

    assert!(
        line.contains("stage=refused"),
        "a policy denial is not stage=skipped, which means a benign \
         non-dispatch: {line}"
    );
    assert!(line.contains("action=Terminate"), "{line}");
    assert!(
        line.contains("rule=env_pinned"),
        "the rule must be named by a stable token, not by prose that \
         moves when a toast is reworded: {line}"
    );
    assert!(
        line.contains(&format!("safety.envs.{env_name}.read_only")),
        "the remedy must name the control that would have to change: {line}"
    );
}

/// Demo mode refuses, and must STILL write no audit line.
///
/// `--demo` runs a synthetic fleet against a fake client; its whole
/// contract is that it touches nothing real. A refusal is the easiest
/// place to break that, because the refusal is genuine even though the
/// fleet is not.
#[tokio::test]
async fn demo_mode_refuses_without_writing_an_audit_line() {
    let env_name = "demo-refusal-probe-env";
    let path = crate::util::cache_dir().join("audit.log");
    let before = std::fs::read_to_string(&path).unwrap_or_default();

    let mut app = test_app();
    app.demo_mode = true;
    app.cfg.safety_envs.insert(env_name.into(), true);
    assert!(app.deny_write(env_name, "Terminate"), "demo must refuse");

    let after = std::fs::read_to_string(&path).unwrap_or_default();
    let delta = after.strip_prefix(&before).unwrap_or(&after);
    assert!(
        !delta.contains(env_name),
        "demo mode writes NO audit lines: {delta}"
    );
}

/// A write that is ALLOWED must not file a refusal.
///
/// Without this, an implementation that audits unconditionally passes
/// the refusal test above while filing a denial for every legal write.
#[tokio::test]
async fn an_allowed_write_files_no_refusal() {
    let env_name = "allowed-write-probe-env";
    let path = crate::util::cache_dir().join("audit.log");
    let before = std::fs::read_to_string(&path).unwrap_or_default();

    let mut app = test_app();
    assert!(!app.deny_write(env_name, "Restart"), "must allow");

    let after = std::fs::read_to_string(&path).unwrap_or_default();
    let delta = after.strip_prefix(&before).unwrap_or(&after);
    assert!(
        !delta.contains(env_name),
        "an allowed write is not a refusal: {delta}"
    );
}

/// A partially-readable safety policy must announce itself at startup,
/// not on the first blocked keystroke.
///
/// Driven through `for_tests`, which is the constructor `--demo` also
/// builds on. That matters: `deny_write` documents `--demo` as the way
/// to validate `safety.envs.*` before going live, so a demo session
/// that stayed quiet about an unparseable pin would be hiding the one
/// thing wrong with the config it was being used to check.
#[tokio::test]
async fn an_unreadable_safety_config_announces_itself_at_startup() {
    let cfg = crate::config::parse("safety.envs.uflexi-prod = true\n");
    assert_eq!(
        cfg.safety_parse_errors.len(),
        1,
        "fixture must actually be malformed, or this test proves nothing"
    );

    let app = App::for_tests(crate::aws::AwsClient::stub(), cfg);
    let msg = app
        .error_message
        .as_deref()
        .expect("a policy that refuses every write must say so up front");
    assert!(msg.contains("writes refused"), "{msg}");
    assert!(
        msg.contains("uflexi-prod"),
        "the banner must name the offending line, not just that one exists: {msg}"
    );

    // And a clean config stays quiet.
    let clean = crate::config::parse("safety.envs.uflexi-prod.read_only = true\n");
    let app = App::for_tests(crate::aws::AwsClient::stub(), clean);
    assert!(
        app.error_message.is_none(),
        "a healthy session must not open with a warning: {:?}",
        app.error_message
    );
}

/// A batch refusal must file one line per locked env, each matchable
/// and each in that env's own region.
///
/// The joined form (`target=env-a,env-b`) matched no env, so `ebman
/// audit --env env-a` found nothing — and the region lookup missed too
/// and fell back to home, which is the wrong-region bug `region_for_name`
/// carries a comment about.
#[tokio::test]
async fn a_batch_refusal_files_one_matchable_line_per_env() {
    let a = "batch-refusal-probe-a";
    let b = "batch-refusal-probe-b";
    let path = crate::util::cache_dir().join("audit.log");
    let before = std::fs::read_to_string(&path).unwrap_or_default();

    let mut app = test_app();
    for (n, region) in [(a, "us-east-1"), (b, "ap-south-1")] {
        let mut env = mk_env(n, "uflexi", "Web", "Green");
        env.region = Some(region.into());
        app.environments.push(env);
        app.cfg.safety_envs.insert(n.into(), true);
    }
    app.rebuild_view();

    assert!(
        app.deny_write_batch(&[a.to_string(), b.to_string()], "Terminate"),
        "both envs are pinned"
    );

    let after = std::fs::read_to_string(&path).unwrap_or_default();
    let delta = after
        .strip_prefix(&before)
        .expect("the audit log is append-only");

    for (n, region) in [(a, "us-east-1"), (b, "ap-south-1")] {
        let lines: Vec<&str> = delta
            .lines()
            .filter(|l| l.contains(&format!("target={n}")))
            .collect();
        assert_eq!(lines.len(), 1, "one matchable line for {n}: {delta}");
        assert!(
            lines[0].contains(&format!("region={region}")),
            "each refusal takes its own env's region, not home: {}",
            lines[0]
        );
    }
    assert!(
        !delta.contains(&format!("{a},{b}")),
        "no joined target — it matches no env: {delta}"
    );
}

/// The safety-config banner must survive a refresh.
///
/// It is not a transient notice: while the policy is only partially
/// readable, every write is refused for the whole session. The refresh
/// completion clears transient messages, which wiped it within one
/// cycle — so a live session showed it briefly and then let the
/// operator discover the refusal at a confirm modal instead. It
/// persisted only under `--demo`, which never refreshes, which is why
/// the demo-only test did not catch it.
#[tokio::test]
async fn the_safety_banner_survives_a_refresh() {
    let cfg = crate::config::parse("safety.envs.uflexi-prod = true\n");
    assert_eq!(
        cfg.safety_parse_errors.len(),
        1,
        "fixture must be malformed"
    );

    let mut app = App::for_tests(crate::aws::AwsClient::stub(), cfg);
    assert!(app.error_message.is_some(), "banner shows at startup");

    // Drive a refresh the way a live session does: snapshot, then apply.
    app.status_snapshot_at_refresh = Some((app.status_message.clone(), app.error_message.clone()));
    app.apply_refresh(app.fanout_epoch, Ok(vec![]), vec![]);

    let msg = app
        .error_message
        .as_deref()
        .expect("the banner must survive — the writes are still refused");
    assert!(msg.contains("writes refused"), "{msg}");

    // A healthy config still ends the refresh quiet.
    let clean = crate::config::parse("safety.envs.uflexi-prod.read_only = true\n");
    let mut app = App::for_tests(crate::aws::AwsClient::stub(), clean);
    app.status_snapshot_at_refresh = Some((app.status_message.clone(), app.error_message.clone()));
    app.apply_refresh(app.fanout_epoch, Ok(vec![]), vec![]);
    assert!(
        app.error_message.is_none(),
        "a healthy session must not gain a banner: {:?}",
        app.error_message
    );
}

/// A fleet-wide refusal must read as fleet-wide, not as a list of
/// individually-locked envs.
///
/// `deny_write_batch` used to carry its own hand-written list of which
/// rungs are env-independent, and the list drifted in the same release
/// that added `SafetyConfigUnreadable` — so one broken config line
/// produced "2 of 2 selected env(s) locked (a, b)", which describes
/// per-env pins the operator does not have. The knowledge now lives on
/// the `Refusal` enum, where a new variant cannot dodge the question.
#[tokio::test]
async fn a_fleet_wide_refusal_is_not_reported_as_per_env_pins() {
    let cfg = crate::config::parse("safety.envs.uflexi-prod = true\n");
    let mut app = App::for_tests(crate::aws::AwsClient::stub(), cfg);

    let envs = vec!["env-a".to_string(), "env-b".to_string()];
    assert!(app.deny_write_batch(&envs, "Terminate"), "must refuse");

    let msg = app.error_message.as_deref().expect("a refusal toast");
    assert!(
        msg.contains("safety config unreadable"),
        "the whole-fleet reason must lead: {msg}"
    );
    assert!(
        !msg.contains("selected env(s) locked"),
        "one broken config line is not a set of per-env pins: {msg}"
    );

    // The env-scoped rungs still produce the per-env list.
    let mut app = test_app();
    app.cfg.safety_envs.insert("env-a".into(), true);
    assert!(app.deny_write_batch(&envs, "Terminate"));
    let msg = app.error_message.as_deref().expect("a refusal toast");
    assert!(
        msg.contains("selected env(s) locked"),
        "a real per-env pin must still name what to deselect: {msg}"
    );
}

/// The safety banner must not starve the partial-failure notice.
///
/// "Some regions failed and their environments are NOT shown" is the
/// only channel telling an operator that data is missing. The banner
/// has a second channel — the refusal itself, in full, the moment a
/// write is attempted. Filling the slot first meant a broken safety
/// line plus one throttled region hid the missing-envs warning for the
/// whole session.
#[tokio::test]
async fn the_safety_banner_yields_to_the_partial_failure_notice() {
    let cfg = crate::config::parse("safety.envs.uflexi-prod = true\n");
    let mut app = App::for_tests(crate::aws::AwsClient::stub(), cfg);

    app.status_snapshot_at_refresh = Some((app.status_message.clone(), app.error_message.clone()));
    app.apply_refresh(
        app.fanout_epoch,
        Ok(vec![]),
        vec!["eu-west-2: throttled".to_string()],
    );

    let msg = app.error_message.as_deref().expect("a notice");
    assert!(
        msg.contains("NOT shown"),
        "missing data is the notice with no second channel: {msg}"
    );

    // With no partial failure, the banner takes the slot as before.
    app.status_snapshot_at_refresh = Some((app.status_message.clone(), app.error_message.clone()));
    app.apply_refresh(app.fanout_epoch, Ok(vec![]), vec![]);
    assert!(
        app.error_message
            .as_deref()
            .is_some_and(|m| m.contains("writes refused")),
        "the banner returns once the slot is free: {:?}",
        app.error_message
    );
}