ignition-core 1.2.0

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

mod common;

use common::IgnitionMock;
use ignition_core::client::{GatewayApi, ReqwestGatewayApi};
use ignition_core::config::{Credential, Secret};

fn token_credential() -> Credential {
    Credential::Token(Secret::new("eam:tokengeneratedlive"))
}

/// The live-captured history page shape (trimmed to two items): the
/// UUID-string taskIds (8.3.3 wire-faithful — 07-05 gap 1), the
/// forced-run taskName suffix, the Failed level with GNET detail,
/// epoch-ms numbers.
fn history_page() -> serde_json::Value {
    serde_json::json!({
        "items": [
            {
                "taskId": "c3d5ebc2-0b91-40fc-8417-3af372071547",
                "taskName": "nightly-backup (forced)",
                "taskStart": 1787930000000_i64,
                "taskEnd": 1787930009000_i64,
                "target": "_controller",
                "level": "Failed",
                "detail": "Gateway network for agent '_controller' is currently not connected, the connection status is 'NotDefined'",
                "taskType": "eam_backup"
            },
            {
                "taskId": "d4e6fcd3-1c92-410d-8528-4ba483082658",
                "taskName": "nightly-backup",
                "taskStart": 1787920000000_i64,
                "taskEnd": 1787920005000_i64,
                "target": "_controller",
                "level": "Success",
                "detail": null,
                "taskType": "eam_backup"
            }
        ],
        "metadata": {"total": 2, "matching": 2, "limit": 200, "offset": 0}
    })
}

/// The task-definition LIST page (config-resource shape; no state on
/// list records) + the FIND answer (definition + scheduledTaskState
/// + signature).
fn definition_list_page() -> serde_json::Value {
    serde_json::json!({
        "items": [
            {
                "name": "nightly-backup",
                "collection": "eam-tasks",
                "type": "com.inductiveautomation.eam",
                "config": {
                    "profile": {
                        "type": "eam_backup",
                        "scheduleMode": "OnDemand"
                    },
                    "settings": {
                        "targetGateways": ["gw-a"],
                        "targetGroups": [],
                        "concurrentBackups": 2,
                        "forceBackups": true
                    }
                }
            }
        ],
        "metadata": {"total": 1, "matching": 1, "limit": -1, "offset": 0}
    })
}

fn definition_find_body() -> serde_json::Value {
    serde_json::json!({
        "name": "nightly-backup",
        "collection": "eam-tasks",
        "type": "com.inductiveautomation.eam",
        "config": {"profile": {"type": "eam_backup", "scheduleMode": "OnDemand"}},
        "signature": "sig-abc123",
        "scheduledTaskState": {
            "currentState": "IDLE",
            "details": {"owner": "eam", "nextScheduled": null}
        }
    })
}

const HISTORY_PATH: &str = "/data/eam/api/v1/eam-tasks/history";
const TASKS_LIST_PATH: &str = "/data/api/v1/resources/list/com.inductiveautomation.eam/eam-tasks";
// The find path rides the ONE locked per-segment encoder — hyphens
// over-encode to %2D (over-encoding is safe; the server decodes
// before matching). Pinning the ENCODED path IS the discipline pin.
const TASKS_FIND_PATH: &str =
    "/data/api/v1/resources/find/com.inductiveautomation.eam/eam-tasks/nightly%2Dbackup";

/// THE history pin: the runtime GET rides with an EXPLICIT limit
/// (default 200 — never the server's unlimited default) and the
/// search passthrough; items round-trip wire-faithful.
#[tokio::test]
async fn eam_history_sends_explicit_limit_and_search() {
    let mock = IgnitionMock::start().await;
    let guard = wiremock::Mock::given(wiremock::matchers::method("GET"))
        .and(wiremock::matchers::path(HISTORY_PATH))
        .and(wiremock::matchers::query_param("limit", "50"))
        .and(wiremock::matchers::query_param("offset", "0"))
        .and(wiremock::matchers::query_param("search", "backup"))
        .respond_with(wiremock::ResponseTemplate::new(200).set_body_json(history_page()))
        .expect(1)
        .mount_as_scoped(&mock.server)
        .await;

    let api = ReqwestGatewayApi::for_tests(&mock.uri(), Some(token_credential()));
    let result = ignition_core::actions::eam::eam_history(&api, Some(50), Some("backup"))
        .await
        .expect("history reads");
    assert_eq!(result.count, 2);
    assert_eq!(result.items[0].task_name, "nightly-backup (forced)");
    assert_eq!(result.items[0].level.as_deref(), Some("Failed"));
    assert!(
        result.items[0]
            .detail
            .as_deref()
            .is_some_and(|d| d.contains("not connected"))
    );
    assert_eq!(guard.received_requests().await.len(), 1);
}

/// The default limit pin: no --limit → limit=200 rides the wire
/// (Pitfall 9's discipline, EAM edition).
#[tokio::test]
async fn eam_history_defaults_to_the_explicit_200_limit() {
    let mock = IgnitionMock::start().await;
    let guard = wiremock::Mock::given(wiremock::matchers::method("GET"))
        .and(wiremock::matchers::path(HISTORY_PATH))
        .and(wiremock::matchers::query_param("limit", "200"))
        .respond_with(wiremock::ResponseTemplate::new(200).set_body_json(history_page()))
        .expect(1)
        .mount_as_scoped(&mock.server)
        .await;

    let api = ReqwestGatewayApi::for_tests(&mock.uri(), Some(token_credential()));
    ignition_core::actions::eam::eam_history(&api, None, None)
        .await
        .expect("history reads");
    assert_eq!(guard.received_requests().await.len(), 1);
}

/// The definitions LIST pin: the config-resource seam with the
/// standard list params (limit=-1, the UI everything convention) —
/// available on STOCK gateways (no controller needed).
#[tokio::test]
async fn eam_tasks_list_rides_the_config_resource_seam() {
    let mock = IgnitionMock::start().await;
    let guard = wiremock::Mock::given(wiremock::matchers::method("GET"))
        .and(wiremock::matchers::path(TASKS_LIST_PATH))
        .and(wiremock::matchers::query_param("limit", "-1"))
        .respond_with(wiremock::ResponseTemplate::new(200).set_body_json(definition_list_page()))
        .expect(1)
        .mount_as_scoped(&mock.server)
        .await;

    let api = ReqwestGatewayApi::for_tests(&mock.uri(), Some(token_credential()));
    let result = ignition_core::actions::eam::eam_tasks(&api)
        .await
        .expect("definitions list");
    assert_eq!(result.tasks.len(), 1);
    assert_eq!(result.tasks[0].name, "nightly-backup");
    assert_eq!(result.tasks[0].task_type.as_deref(), Some("eam_backup"));
    assert_eq!(result.tasks[0].schedule_mode.as_deref(), Some("OnDemand"));
    assert_eq!(
        result.tasks[0].current_state, None,
        "list records carry no state — null, honestly"
    );
    assert_eq!(guard.received_requests().await.len(), 1);
}

/// The FIND pin: the definition + its scheduledTaskState (the
/// summary's current_state source) + the signature.
#[tokio::test]
async fn eam_task_detail_carries_definition_and_state() {
    let mock = IgnitionMock::start().await;
    mock.list_json("GET", TASKS_FIND_PATH, definition_find_body())
        .await;

    let api = ReqwestGatewayApi::for_tests(&mock.uri(), Some(token_credential()));
    let result = ignition_core::actions::eam::eam_task_detail(&api, "nightly-backup")
        .await
        .expect("find reads");
    assert_eq!(result.name, "nightly-backup");
    assert_eq!(
        result.state["currentState"],
        serde_json::json!("IDLE"),
        "the healthcheck rides as data"
    );
    assert_eq!(
        result.definition["scheduledTaskState"]["details"]["owner"],
        serde_json::json!("eam"),
        "the owner (force's target) round-trips"
    );
}

/// An unknown definition name rides the config-resource not_found
/// path (404 → classify).
#[tokio::test]
async fn eam_task_detail_unknown_name_is_not_found() {
    let mock = IgnitionMock::start().await;
    mock.html_error(
        "GET",
        "/data/api/v1/resources/find/com.inductiveautomation.eam/eam-tasks/nope",
        404,
    )
    .await;
    let api = ReqwestGatewayApi::for_tests(&mock.uri(), Some(token_credential()));
    let err = ignition_core::actions::eam::eam_task_detail(&api, "nope")
        .await
        .expect_err("404 classifies NotFound");
    assert_eq!(err.exit_code(), 6);
    assert_eq!(err.code(), "not_found");
}

/// THE STATE GATE: the controller 403 on the RUNTIME seam (Jetty
/// HTML body carrying the live-captured message) classifies to the
/// additive `eam_not_controller` slug — exit 6, never auth_rejected —
/// pinned at the ACTION layer (through the whole client pipeline).
#[tokio::test]
async fn controller_403_classifies_eam_not_controller() {
    let mock = IgnitionMock::start().await;
    wiremock::Mock::given(wiremock::matchers::method("GET"))
        .and(wiremock::matchers::path(HISTORY_PATH))
        .respond_with(wiremock::ResponseTemplate::new(403).set_body_raw(
            "<html><head><title>Error 403</title></head><body><h2>HTTP ERROR 403 Forbidden</h2><table><tr><th>MESSAGE:</th><td>This operation can only be performed when EAM is configured as a controller.</td></tr></table></body></html>".as_bytes().to_vec(),
            "text/html;charset=iso-8859-1",
        ))
        .expect(1)
        .mount(&mock.server)
        .await;

    let api = ReqwestGatewayApi::for_tests(&mock.uri(), Some(token_credential()));
    let err = ignition_core::actions::eam::eam_history(&api, None, None)
        .await
        .expect_err("the controller 403 refuses");
    assert_eq!(err.exit_code(), 6, "target state, not auth");
    assert_eq!(err.code(), "eam_not_controller");
    let hint = err.hint().expect("hint required");
    assert!(
        hint.contains("installMode") && hint.contains("Controller"),
        "the hint names the manual flip: {hint}"
    );
}

/// The state gate is CONTENT-scoped: an EAM-path 403 WITHOUT the
/// controller message keeps the honest under-permitted Auth mapping.
#[tokio::test]
async fn eam_403_without_the_message_stays_auth() {
    let mock = IgnitionMock::start().await;
    wiremock::Mock::given(wiremock::matchers::method("GET"))
        .and(wiremock::matchers::path(HISTORY_PATH))
        .respond_with(wiremock::ResponseTemplate::new(403).set_body_raw(
            "<html><head><title>Error 403</title></head><body><h2>HTTP ERROR 403 Forbidden</h2><table><tr><th>MESSAGE:</th><td>Forbidden</td></tr></table></body></html>".as_bytes().to_vec(),
            "text/html;charset=iso-8859-1",
        ))
        .expect(1)
        .mount(&mock.server)
        .await;

    let api = ReqwestGatewayApi::for_tests(&mock.uri(), Some(token_credential()));
    let err = ignition_core::actions::eam::eam_history(&api, None, None)
        .await
        .expect_err("a plain 403 stays auth");
    assert_eq!(err.exit_code(), 5);
    assert_eq!(err.code(), "auth_rejected");
}

/// The state gate is PATH-scoped: a NON-EAM path answering the same
/// message cannot shift the classification (generic 403 → Auth).
#[tokio::test]
async fn non_eam_403_with_the_message_stays_auth() {
    let mock = IgnitionMock::start().await;
    wiremock::Mock::given(wiremock::matchers::method("GET"))
        .and(wiremock::matchers::path("/data/api/v1/gateway-info"))
        .respond_with(
            wiremock::ResponseTemplate::new(403).set_body_raw(
                "This operation can only be performed when EAM is configured as a controller."
                    .as_bytes()
                    .to_vec(),
                "text/plain",
            ),
        )
        .expect(1)
        .mount(&mock.server)
        .await;

    let api = ReqwestGatewayApi::for_tests(&mock.uri(), Some(token_credential()));
    let err = api
        .gateway_info()
        .await
        .expect_err("off-path 403 stays auth");
    assert_eq!(err.exit_code(), 5);
    assert_eq!(err.code(), "auth_rejected");
}

// ---- Task 3: the guarded writes ----

const TASKS_CREATE_PATH: &str = "/data/api/v1/resources/com.inductiveautomation.eam/eam-tasks";

/// THE create body pin (a) — K=V auto-typing: `--target gw-a
/// --setting concurrentBackups=2 --setting forceBackups=true`
/// composes the ARRAY body with `targetGateways: ["gw-a"]`,
/// `concurrentBackups: 2` (JSON number), `forceBackups: true` (JSON
/// bool) — NO stringly-typed leaks. The body is pinned VERBATIM
/// (serde_json maps are key-sorted — the deterministic order the
/// recorded-request discipline pins).
#[tokio::test]
async fn task_create_posts_array_body_with_typed_settings() {
    let mock = IgnitionMock::start().await;
    let guard = wiremock::Mock::given(wiremock::matchers::method("POST"))
        .and(wiremock::matchers::path(TASKS_CREATE_PATH))
        .respond_with(wiremock::ResponseTemplate::new(200))
        .expect(1)
        .mount_as_scoped(&mock.server)
        .await;

    let api = ReqwestGatewayApi::for_tests(&mock.uri(), Some(token_credential()));
    let result = ignition_core::actions::eam::eam_task_create(
        &api,
        "nightly-backup",
        "eam_backup",
        &["gw-a".to_string()],
        &[
            "concurrentBackups=2".to_string(),
            "forceBackups=true".to_string(),
        ],
        None,
        "OnDemand",
    )
    .await
    .expect("create posts");
    assert_eq!(result.task_type, "eam_backup");

    let requests = guard.received_requests().await;
    assert_eq!(requests.len(), 1);
    let body: serde_json::Value = serde_json::from_slice(&requests[0].body).expect("body parses");
    assert_eq!(
        body,
        serde_json::json!([{
            "config": {
                "profile": {"scheduleMode": "OnDemand", "type": "eam_backup"},
                "settings": {
                    "concurrentBackups": 2,
                    "forceBackups": true,
                    "targetGateways": ["gw-a"],
                    "targetGroups": []
                }
            },
            "name": "nightly-backup"
        }]),
        "the ARRAY body, composed definition verbatim — the live 8.3.3 \
         profile/settings split with settings TYPED"
    );
}

/// THE create body pin (b) — the `--definition` file path: a
/// full-JSON overlay carrying the live-captured eam_backup settings
/// shape (`targetGateways`/`targetGroups` arrays, `concurrentBackups`
/// int, `forceBackups` bool) deep-merged over the composed
/// `config.settings` (zero `--target` defaults to
/// `["_controller"]`; the overlay's arrays REPLACE it).
#[tokio::test]
async fn task_create_deep_merges_the_definition_file() {
    let mock = IgnitionMock::start().await;
    let guard = wiremock::Mock::given(wiremock::matchers::method("POST"))
        .and(wiremock::matchers::path(TASKS_CREATE_PATH))
        .respond_with(wiremock::ResponseTemplate::new(200))
        .expect(1)
        .mount_as_scoped(&mock.server)
        .await;

    let overlay = serde_json::json!({
        "targetGateways": ["gw-a", "gw-b"],
        "targetGroups": [],
        "concurrentBackups": 3,
        "forceBackups": false
    });
    let api = ReqwestGatewayApi::for_tests(&mock.uri(), Some(token_credential()));
    ignition_core::actions::eam::eam_task_create(
        &api,
        "fleet-backup",
        "eam_backup",
        &[],
        &[],
        Some(&overlay),
        "OnDemand",
    )
    .await
    .expect("create posts");

    let requests = guard.received_requests().await;
    let body: serde_json::Value = serde_json::from_slice(&requests[0].body).expect("body parses");
    assert_eq!(
        body,
        serde_json::json!([{
            "config": {
                "profile": {"scheduleMode": "OnDemand", "type": "eam_backup"},
                "settings": {
                    "concurrentBackups": 3,
                    "forceBackups": false,
                    "targetGateways": ["gw-a", "gw-b"],
                    "targetGroups": []
                }
            },
            "name": "fleet-backup"
        }]),
        "the overlay's typed/array settings deep-merged over the composed config.settings"
    );
}

/// The refused ladder rung at the ACTION layer: a fleet-destructive
/// type NEVER reaches a client (zero requests) — exit 6,
/// `eam_task_type_refused`, the message names the EXT-03 scope.
#[tokio::test]
async fn task_create_refused_type_never_reaches_the_wire() {
    let mock = IgnitionMock::start().await;
    let api = ReqwestGatewayApi::for_tests(&mock.uri(), Some(token_credential()));
    for refused in [
        "eam_restoreBackup",
        "eam_installModules",
        "eam_remoteUpgrade",
    ] {
        let err = ignition_core::actions::eam::eam_task_create(
            &api,
            "danger",
            refused,
            &["gw-a".to_string()],
            &[],
            None,
            "OnDemand",
        )
        .await
        .expect_err("fleet-destructive types refuse");
        assert_eq!(err.exit_code(), 6);
        assert_eq!(err.code(), "eam_task_type_refused");
        let message = err.to_string();
        assert!(
            message.contains(refused) && message.contains("fleet-destructive"),
            "the message names the type + consequence: {message}"
        );
        assert!(
            message.contains("EXT-03"),
            "the message points at the v2 scope: {message}"
        );
    }
    assert!(
        mock.server
            .received_requests()
            .await
            .unwrap_or_default()
            .is_empty(),
        "refusals do no network work"
    );
}

/// A malformed `--setting` refuses `invalid_input` (exit 2) before
/// any network work.
#[tokio::test]
async fn task_create_malformed_setting_refuses_pre_network() {
    let mock = IgnitionMock::start().await;
    let api = ReqwestGatewayApi::for_tests(&mock.uri(), Some(token_credential()));
    let err = ignition_core::actions::eam::eam_task_create(
        &api,
        "t",
        "eam_backup",
        &[],
        &["noequalsign".to_string()],
        None,
        "OnDemand",
    )
    .await
    .expect_err("malformed K=V refuses");
    assert_eq!(err.exit_code(), 2);
    assert_eq!(err.code(), "invalid_input");
    assert!(
        mock.server
            .received_requests()
            .await
            .unwrap_or_default()
            .is_empty()
    );
}

/// THE force sequence pin (10-03: the preview IS the pre-flight —
/// EAMW-04): find GET → BOTH scheduled segments (the preview's
/// pending read, quiet here) → force POST (owner from the
/// healthcheck's `scheduledTaskState.details.owner`) → history GET —
/// exactly 5 requests, the 204 accepted, and the honest history
/// read-back surfaces the Forced/Failed outcome as data.
#[tokio::test]
async fn task_force_is_the_five_request_sequence() {
    let mock = IgnitionMock::start().await;
    // 1. find — carries the owner under the healthcheck details.
    mock.list_json(
        "GET",
        "/data/api/v1/resources/find/com.inductiveautomation.eam/eam-tasks/nightly%2Dbackup",
        serde_json::json!({
            "name": "nightly-backup",
            "config": {"profile": {"type": "eam_backup", "scheduleMode": "OnDemand"}},
            "scheduledTaskState": {
                "currentState": "IDLE",
                "details": {"owner": "eam"}
            }
        }),
    )
    .await;
    // 2+3. the preview's pending read — both literal segments.
    mock.list_json("GET", SCHEDULED_FALSE_PATH, scheduled_true_page())
        .await;
    mock.list_json("GET", SCHEDULED_TRUE_PATH, scheduled_true_page())
        .await;
    // 4. force — the live-proven 204.
    wiremock::Mock::given(wiremock::matchers::method("POST"))
        .and(wiremock::matchers::path(
            "/data/eam/api/v1/eam-tasks/force/eam/nightly-backup",
        ))
        .respond_with(wiremock::ResponseTemplate::new(204))
        .expect(1)
        .mount(&mock.server)
        .await;
    // 5. history re-read — the forced run's entry.
    wiremock::Mock::given(wiremock::matchers::method("GET"))
        .and(wiremock::matchers::path(HISTORY_PATH))
        .respond_with(
            wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "items": [
                    {
                        "taskId": "e5f7ade4-2da3-421e-9639-5cb594193769",
                        "taskName": "nightly-backup (forced)",
                        "taskStart": 1787930000000_i64,
                        "taskEnd": 1787930009000_i64,
                        "target": "_controller",
                        "level": "Failed",
                        "detail": "Gateway network for agent '_controller' is currently not connected",
                        "taskType": "eam_backup"
                    }
                ],
                "metadata": {"total": 1, "matching": 1, "limit": 20, "offset": 0}
            })),
        )
        .expect(1)
        .mount(&mock.server)
        .await;

    let api = ReqwestGatewayApi::for_tests(&mock.uri(), Some(token_credential()));
    let result = ignition_core::actions::eam::eam_task_force(&api, "nightly-backup")
        .await
        .expect("the sequence completes");
    assert_eq!(result.owner, "eam", "owner resolved from the healthcheck");
    assert!(result.dispatched);
    let entry = result.history.expect("the forced entry is visible");
    assert_eq!(entry.task_name, "nightly-backup (forced)");
    assert_eq!(
        entry.level.as_deref(),
        Some("Failed"),
        "the outcome is data"
    );

    let requests = mock.server.received_requests().await.unwrap_or_default();
    assert_eq!(
        requests.len(),
        5,
        "find → scheduled/false → scheduled/true → force → history, exactly"
    );
    let sequence: Vec<(&str, String)> = requests
        .iter()
        .map(|request| (request.method.as_str(), request.url.path().to_string()))
        .collect();
    assert_eq!(
        sequence,
        vec![
            (
                "GET",
                "/data/api/v1/resources/find/com.inductiveautomation.eam/eam-tasks/nightly%2Dbackup"
                    .to_string()
            ),
            ("GET", SCHEDULED_FALSE_PATH.to_string()),
            ("GET", SCHEDULED_TRUE_PATH.to_string()),
            (
                "POST",
                "/data/eam/api/v1/eam-tasks/force/eam/nightly-backup".to_string()
            ),
            ("GET", "/data/eam/api/v1/eam-tasks/history".to_string()),
        ],
        "the request SEQUENCE is the contract"
    );
}

/// Owner fallback: a find answer WITHOUT the healthcheck owner
/// forces against the live-captured default `"eam"`.
#[tokio::test]
async fn task_force_owner_falls_back_to_eam() {
    let mock = IgnitionMock::start().await;
    mock.list_json(
        "GET",
        "/data/api/v1/resources/find/com.inductiveautomation.eam/eam-tasks/bare",
        serde_json::json!({"name": "bare", "config": {}}),
    )
    .await;
    // The preview's pending read tolerates the quiet bodies (§8).
    mock.list_json("GET", SCHEDULED_FALSE_PATH, scheduled_true_page())
        .await;
    mock.list_json("GET", SCHEDULED_TRUE_PATH, scheduled_true_page())
        .await;
    wiremock::Mock::given(wiremock::matchers::method("POST"))
        .and(wiremock::matchers::path(
            "/data/eam/api/v1/eam-tasks/force/eam/bare",
        ))
        .respond_with(wiremock::ResponseTemplate::new(204))
        .expect(1)
        .mount(&mock.server)
        .await;
    wiremock::Mock::given(wiremock::matchers::method("GET"))
        .and(wiremock::matchers::path(HISTORY_PATH))
        .respond_with(
            wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "items": [],
                "metadata": {"total": 0, "matching": 0, "limit": 20, "offset": 0}
            })),
        )
        .expect(1)
        .mount(&mock.server)
        .await;

    let api = ReqwestGatewayApi::for_tests(&mock.uri(), Some(token_credential()));
    let result = ignition_core::actions::eam::eam_task_force(&api, "bare")
        .await
        .expect("fallback owner forces");
    assert_eq!(result.owner, "eam");
    assert!(result.history.is_none(), "no entry yet — null, honestly");
}

// ---- 10-02: the write surface (capture-locked per 10-LIVE-CAPTURES.md) ----

/// The captured lifecycle-path segments (raw names, §1/§7).
const SUSPEND_PATH: &str = "/data/eam/api/v1/eam-tasks/suspend/nightly-backup";
const RESUME_PATH: &str = "/data/eam/api/v1/eam-tasks/resume/nightly-backup";
const CANCEL_PATH: &str = "/data/eam/api/v1/eam-tasks/cancel/nightly-backup";
const SCHEDULED_FALSE_PATH: &str = "/data/eam/api/v1/eam-tasks/scheduled/false";
const SCHEDULED_TRUE_PATH: &str = "/data/eam/api/v1/eam-tasks/scheduled/true";
// The delete path rides the ONE locked per-segment encoder (the
// find-path discipline pin above: hyphens over-encode to %2D).
const TASKS_DELETE_PATH: &str =
    "/data/api/v1/resources/com.inductiveautomation.eam/eam-tasks/nightly%2Dbackup/sig%2Dabc123";

/// The captured controller-state 403 HTML (the state-gate message;
/// identical body rides every /data/eam/api/v1/* route).
fn controller_403_body() -> Vec<u8> {
    "<html><head><title>Error 403</title></head><body><h2>HTTP ERROR 403 Forbidden</h2><table><tr><th>MESSAGE:</th><td>This operation can only be performed when EAM is configured as a controller.</td></tr></table></body></html>".as_bytes().to_vec()
}

/// The captured scheduled row, VERBATIM (8.3.6 09:59:39Z +
/// byte-identical 8.3.3 09:59:40Z — 10-LIVE-CAPTURES §2): all 13
/// keys, the human-label type, the Scheduled can* truth cell.
fn scheduled_false_page() -> serde_json::Value {
    serde_json::json!({
        "items": [
            {
                "name": "ign-p10-scratch-sched",
                "owner": "eam",
                "type": "Collect Backup",
                "execStart": null,
                "message": "",
                "repeats": true,
                "canPause": true,
                "canResume": false,
                "canCancel": true,
                "taskState": "Scheduled",
                "isForced": false,
                "isRunning": false,
                "progress": 0.0
            }
        ],
        "metadata": {"total": 1, "matching": 1, "limit": -1, "offset": 0}
    })
}

/// The captured quiet-controller body (10-LIVE-CAPTURES §8 — the
/// canonical scheduled/true answer).
fn scheduled_true_page() -> serde_json::Value {
    serde_json::json!({
        "items": [],
        "metadata": {"total": 0, "matching": 0, "limit": -1, "offset": 0}
    })
}

/// THE suspend pin (capture: 10-LIVE-CAPTURES §1c/§1d — 204 success
/// on both rigs): POST to the exact raw-name path, 204 consumed,
/// ZERO request body (the post_empty shape).
#[tokio::test]
async fn suspend_204_pins_post_path_and_empty_body() {
    let mock = IgnitionMock::start().await;
    let guard = wiremock::Mock::given(wiremock::matchers::method("POST"))
        .and(wiremock::matchers::path(SUSPEND_PATH))
        .respond_with(wiremock::ResponseTemplate::new(204))
        .expect(1)
        .mount_as_scoped(&mock.server)
        .await;

    let api = ReqwestGatewayApi::for_tests(&mock.uri(), Some(token_credential()));
    api.eam_task_suspend("nightly-backup")
        .await
        .expect("the 204 is the success shape");

    let requests = guard.received_requests().await;
    assert_eq!(requests.len(), 1);
    assert_eq!(requests[0].url.path(), SUSPEND_PATH);
    assert!(
        requests[0].body.is_empty(),
        "lifecycle POSTs carry NO body — params ride nothing"
    );
}

/// THE resume pin (capture: §1b/§1d — 204 on both rigs, incl. a
/// never-suspended task).
#[tokio::test]
async fn resume_204_pins_post_path_and_empty_body() {
    let mock = IgnitionMock::start().await;
    let guard = wiremock::Mock::given(wiremock::matchers::method("POST"))
        .and(wiremock::matchers::path(RESUME_PATH))
        .respond_with(wiremock::ResponseTemplate::new(204))
        .expect(1)
        .mount_as_scoped(&mock.server)
        .await;

    let api = ReqwestGatewayApi::for_tests(&mock.uri(), Some(token_credential()));
    api.eam_task_resume("nightly-backup")
        .await
        .expect("the 204 is the success shape");

    let requests = guard.received_requests().await;
    assert_eq!(requests.len(), 1);
    assert_eq!(requests[0].url.path(), RESUME_PATH);
    assert!(requests[0].body.is_empty());
}

/// THE cancel pin (capture: §7 — 204 always, nothing-pending AND
/// unknown-name alike; wire-idempotent).
#[tokio::test]
async fn cancel_204_pins_post_path_and_empty_body() {
    let mock = IgnitionMock::start().await;
    let guard = wiremock::Mock::given(wiremock::matchers::method("POST"))
        .and(wiremock::matchers::path(CANCEL_PATH))
        .respond_with(wiremock::ResponseTemplate::new(204))
        .expect(1)
        .mount_as_scoped(&mock.server)
        .await;

    let api = ReqwestGatewayApi::for_tests(&mock.uri(), Some(token_credential()));
    api.eam_task_cancel("nightly-backup")
        .await
        .expect("the 204 is the success shape");

    let requests = guard.received_requests().await;
    assert_eq!(requests.len(), 1);
    assert_eq!(requests[0].url.path(), CANCEL_PATH);
    assert!(requests[0].body.is_empty());
}

/// The controller-403 gate on SUSPEND (10-02 pitfall-6 discipline,
/// one test per verb): the path-scoped arm catches the new runtime
/// URL — the captured controller message classifies
/// `eam_not_controller`, never auth_rejected.
#[tokio::test]
async fn suspend_controller_403_classifies_eam_not_controller() {
    let mock = IgnitionMock::start().await;
    wiremock::Mock::given(wiremock::matchers::method("POST"))
        .and(wiremock::matchers::path(SUSPEND_PATH))
        .respond_with(
            wiremock::ResponseTemplate::new(403)
                .set_body_raw(controller_403_body(), "text/html;charset=iso-8859-1"),
        )
        .expect(1)
        .mount(&mock.server)
        .await;

    let api = ReqwestGatewayApi::for_tests(&mock.uri(), Some(token_credential()));
    let err = api
        .eam_task_suspend("nightly-backup")
        .await
        .expect_err("the controller 403 refuses");
    assert_eq!(err.exit_code(), 6, "target state, not auth");
    assert_eq!(err.code(), "eam_not_controller");
}

/// The controller-403 gate on RESUME (same proof, second verb).
#[tokio::test]
async fn resume_controller_403_classifies_eam_not_controller() {
    let mock = IgnitionMock::start().await;
    wiremock::Mock::given(wiremock::matchers::method("POST"))
        .and(wiremock::matchers::path(RESUME_PATH))
        .respond_with(
            wiremock::ResponseTemplate::new(403)
                .set_body_raw(controller_403_body(), "text/html;charset=iso-8859-1"),
        )
        .expect(1)
        .mount(&mock.server)
        .await;

    let api = ReqwestGatewayApi::for_tests(&mock.uri(), Some(token_credential()));
    let err = api
        .eam_task_resume("nightly-backup")
        .await
        .expect_err("the controller 403 refuses");
    assert_eq!(err.exit_code(), 6);
    assert_eq!(err.code(), "eam_not_controller");
}

/// The controller-403 gate on CANCEL (same proof, third verb).
#[tokio::test]
async fn cancel_controller_403_classifies_eam_not_controller() {
    let mock = IgnitionMock::start().await;
    wiremock::Mock::given(wiremock::matchers::method("POST"))
        .and(wiremock::matchers::path(CANCEL_PATH))
        .respond_with(
            wiremock::ResponseTemplate::new(403)
                .set_body_raw(controller_403_body(), "text/html;charset=iso-8859-1"),
        )
        .expect(1)
        .mount(&mock.server)
        .await;

    let api = ReqwestGatewayApi::for_tests(&mock.uri(), Some(token_credential()));
    let err = api
        .eam_task_cancel("nightly-backup")
        .await
        .expect_err("the controller 403 refuses");
    assert_eq!(err.exit_code(), 6);
    assert_eq!(err.code(), "eam_not_controller");
}

/// Message-scoping still holds on the NEW paths (the existing
/// non-message test extended to one new verb): an EAM-path 403
/// WITHOUT the controller message keeps the honest Auth mapping.
#[tokio::test]
async fn new_runtime_verb_403_without_the_message_stays_auth() {
    let mock = IgnitionMock::start().await;
    wiremock::Mock::given(wiremock::matchers::method("POST"))
        .and(wiremock::matchers::path(SUSPEND_PATH))
        .respond_with(
            wiremock::ResponseTemplate::new(403).set_body_raw(
                "<html><head><title>Error 403</title></head><body><h2>HTTP ERROR 403 Forbidden</h2><table><tr><th>MESSAGE:</th><td>Forbidden</td></tr></table></body></html>".as_bytes().to_vec(),
                "text/html;charset=iso-8859-1",
            ),
        )
        .expect(1)
        .mount(&mock.server)
        .await;

    let api = ReqwestGatewayApi::for_tests(&mock.uri(), Some(token_credential()));
    let err = api
        .eam_task_suspend("nightly-backup")
        .await
        .expect_err("a plain 403 stays auth");
    assert_eq!(err.exit_code(), 5);
    assert_eq!(err.code(), "auth_rejected");
}

/// THE scheduled read pin, `scheduled/false` (capture VERBATIM:
/// 10-LIVE-CAPTURES §2): the row parses wire-faithful — the captured
/// taskState string rides verbatim, the can* truth cell holds, the
/// human-label type never conflates with profile.type.
#[tokio::test]
async fn scheduled_false_read_parses_the_captured_row() {
    let mock = IgnitionMock::start().await;
    let guard = wiremock::Mock::given(wiremock::matchers::method("GET"))
        .and(wiremock::matchers::path(SCHEDULED_FALSE_PATH))
        .respond_with(wiremock::ResponseTemplate::new(200).set_body_json(scheduled_false_page()))
        .expect(1)
        .mount_as_scoped(&mock.server)
        .await;

    let api = ReqwestGatewayApi::for_tests(&mock.uri(), Some(token_credential()));
    let tasks = api
        .eam_tasks_scheduled(false)
        .await
        .expect("the read parses");
    assert_eq!(tasks.len(), 1);
    let row = &tasks[0];
    assert_eq!(row.name, "ign-p10-scratch-sched");
    assert_eq!(row.owner, "eam");
    assert_eq!(
        row.task_type.as_deref(),
        Some("Collect Backup"),
        "the human label rides verbatim"
    );
    assert_eq!(row.exec_start, None, "execStart null while scheduled");
    assert!(row.can_pause && !row.can_resume && row.can_cancel);
    assert_eq!(
        row.task_state, "Scheduled",
        "the captured taskState string, verbatim"
    );
    assert!(!row.is_forced && !row.is_running);
    assert_eq!(row.progress, 0.0);
    assert_eq!(guard.received_requests().await.len(), 1);
}

/// THE scheduled read pin, `scheduled/true` (capture VERBATIM:
/// §8's empty-list quiet-controller body) — empty Vec, honestly.
#[tokio::test]
async fn scheduled_true_read_parses_the_empty_body() {
    let mock = IgnitionMock::start().await;
    wiremock::Mock::given(wiremock::matchers::method("GET"))
        .and(wiremock::matchers::path(SCHEDULED_TRUE_PATH))
        .respond_with(wiremock::ResponseTemplate::new(200).set_body_json(scheduled_true_page()))
        .expect(1)
        .mount(&mock.server)
        .await;

    let api = ReqwestGatewayApi::for_tests(&mock.uri(), Some(token_credential()));
    let tasks = api.eam_tasks_scheduled(true).await.expect("empty parses");
    assert!(tasks.is_empty(), "the quiet body is an honest empty list");
}

/// THE modify pin (capture: §6a full-record echo-modify): the
/// REQUEST BODY is the FULL single-element array INCLUDING
/// `config.settings` (the 422 trap — §6b) and the ORIGINAL
/// `signature` key; the 200 body parses into ModifyOutcome with the
/// post-write newSignature (§6a verbatim response).
#[tokio::test]
async fn task_modify_puts_full_array_body_and_parses_the_outcome() {
    let mock = IgnitionMock::start().await;
    let guard = wiremock::Mock::given(wiremock::matchers::method("PUT"))
        .and(wiremock::matchers::path(TASKS_CREATE_PATH))
        .respond_with(wiremock::ResponseTemplate::new(200).set_body_json(
            serde_json::json!({
                "success": true,
                "changes": [
                    {
                        "name": "ign-p10-scratch-sched",
                        "type": "com.inductiveautomation.eam/eam-tasks",
                        "collection": "core",
                        "newSignature": "0d0dfea2919abb1f02fc86baea73d99696626524169a9ac36526044f89ac16e0"
                    }
                ],
                "problem": null
            }),
        ))
        .expect(1)
        .mount_as_scoped(&mock.server)
        .await;

    // The FULL find record (the §6a baseline shape): settings ride,
    // the ORIGINAL signature rides, only the mutated key differs.
    let full_record = serde_json::json!({
        "name": "ign-p10-scratch-sched",
        "type": "com.inductiveautomation.eam",
        "collection": "core",
        "enabled": true,
        "version": 1,
        "signature": "e5ac8bee3a6ba85e40923c0e02d29507600c57519eb8e4d78bd8c258197fe9c6",
        "config": {
            "profile": {
                "type": "eam_backup",
                "isSuspended": false,
                "scheduleMode": "Scheduled",
                "scheduleDetails": "0/30 * * * * ?"
            },
            "settings": {
                "targetGateways": ["_controller"],
                "targetGroups": [],
                "concurrentBackups": 0,
                "forceBackups": false
            }
        },
        "data": ["config.json"]
    });

    let api = ReqwestGatewayApi::for_tests(&mock.uri(), Some(token_credential()));
    let outcome = api
        .eam_task_modify(&full_record)
        .await
        .expect("the 200 body parses")
        .expect("the body is present (not the lenient None)");
    assert!(outcome.success);
    assert_eq!(outcome.changes.len(), 1);
    assert_eq!(
        outcome.changes[0].new_signature.as_deref(),
        Some("0d0dfea2919abb1f02fc86baea73d99696626524169a9ac36526044f89ac16e0"),
        "newSignature is authoritative for the NEXT mutation"
    );
    assert_eq!(outcome.problem, None, "problem null on every success");

    let requests = guard.received_requests().await;
    assert_eq!(requests.len(), 1);
    let body: serde_json::Value = serde_json::from_slice(&requests[0].body).expect("body parses");
    let array = body.as_array().expect("the body is a JSON ARRAY");
    assert_eq!(array.len(), 1, "single-element array — the §6a shape");
    let sent = &array[0];
    assert!(
        sent["config"]["settings"].is_object()
            && !sent["config"]["settings"].as_object().unwrap().is_empty(),
        "config.settings RIDES — omitting it is the 422 trap (§6b)"
    );
    assert!(
        sent["signature"].is_string(),
        "the ORIGINAL signature key is present — the modify contract"
    );
    assert_eq!(
        sent, &full_record,
        "echo-modify: the full record lands verbatim"
    );
}

/// THE delete pin (capture: §3b — correct signature, no confirm, 200
/// success; §3c — `collection=core` is the proven-correct value, the
/// type token 404s): the RECORDED request carries `collection=core`
/// and NO confirm param; the captured success body parses into
/// DeleteOutcome (references []).
#[tokio::test]
async fn task_delete_pins_query_params_and_parses_the_success_body() {
    let mock = IgnitionMock::start().await;
    let guard = wiremock::Mock::given(wiremock::matchers::method("DELETE"))
        .and(wiremock::matchers::path(TASKS_DELETE_PATH))
        .and(wiremock::matchers::query_param("collection", "core"))
        .and(wiremock::matchers::query_param_is_missing("confirm"))
        .respond_with(wiremock::ResponseTemplate::new(200).set_body_json(
            serde_json::json!({
                "success": true,
                "changes": [
                    {
                        "name": "ign-p10-scratch-sched",
                        "type": "com.inductiveautomation.eam/eam-tasks",
                        "collection": "core",
                        "newSignature": "ec961ee921c63b18013094870ed2664331e965c4770fdf84bfe136e0b4164244"
                    }
                ],
                "problem": null,
                "references": []
            }),
        ))
        .expect(1)
        .mount_as_scoped(&mock.server)
        .await;

    let api = ReqwestGatewayApi::for_tests(&mock.uri(), Some(token_credential()));
    let outcome = api
        .eam_task_delete("nightly-backup", "sig-abc123", false)
        .await
        .expect("the captured success body parses");
    assert!(outcome.success);
    assert_eq!(outcome.changes[0].name, "ign-p10-scratch-sched");
    assert_eq!(
        outcome.changes[0].new_signature.as_deref(),
        Some("ec961ee921c63b18013094870ed2664331e965c4770fdf84bfe136e0b4164244"),
        "the DELETED resource's final signature rides changes[].newSignature"
    );
    assert_eq!(
        outcome.references,
        Some(Vec::new()),
        "references [] on success, honestly empty"
    );

    let requests = guard.received_requests().await;
    assert_eq!(requests.len(), 1);
    assert_eq!(
        requests[0].url.query(),
        Some("collection=core"),
        "the exact captured query — confirm absent on the default delete"
    );
}

/// The confirm OPT-IN rides the wire (capture: §3c's successful
/// `?confirm=true&collection=core` request): both params together,
/// exact order pinned on the recorded query string.
#[tokio::test]
async fn task_delete_confirm_opt_in_rides_the_query() {
    let mock = IgnitionMock::start().await;
    let guard = wiremock::Mock::given(wiremock::matchers::method("DELETE"))
        .and(wiremock::matchers::path(TASKS_DELETE_PATH))
        .and(wiremock::matchers::query_param("collection", "core"))
        .and(wiremock::matchers::query_param("confirm", "true"))
        .respond_with(wiremock::ResponseTemplate::new(200).set_body_json(
            serde_json::json!({
                "success": true,
                "changes": [
                    {
                        "name": "ign-p10-scratch-sched",
                        "type": "com.inductiveautomation.eam/eam-tasks",
                        "collection": "core",
                        "newSignature": "e3610cfe01c7df086da6596ccfbb7735abd5b8f2ceafd5916944919975902acf"
                    }
                ],
                "problem": null,
                "references": []
            }),
        ))
        .expect(1)
        .mount_as_scoped(&mock.server)
        .await;

    let api = ReqwestGatewayApi::for_tests(&mock.uri(), Some(token_credential()));
    api.eam_task_delete("nightly-backup", "sig-abc123", true)
        .await
        .expect("the confirmed delete parses");

    let requests = guard.received_requests().await;
    assert_eq!(
        requests[0].url.query(),
        Some("collection=core&confirm=true"),
        "the §3c captured request shape"
    );
}

/// THE FINDING PIN (10-LIVE-CAPTURES §3a/§4 + Decision 4, verbatim
/// 8.3.6 body): a signature mismatch answers HTTP **500** with a JSON
/// `{success:false, changes:[], problem{message, stacktrace}}` — the
/// current taxonomy has no honest slug (Three-Place rule: the
/// client layer does NOT classify unilaterally), so it lands as
/// `internal` (exit 1) with the problem body DISCARDED by the
/// classifier. Recorded here as the visible reference for the
/// 10-03/10-04 slug decision — the `signature mismatch` substring is
/// the stable discriminator across 8.3.3/8.3.6.
#[tokio::test]
async fn task_delete_signature_mismatch_500_is_the_recorded_finding() {
    let mock = IgnitionMock::start().await;
    wiremock::Mock::given(wiremock::matchers::method("DELETE"))
        .and(wiremock::matchers::path(TASKS_DELETE_PATH))
        .and(wiremock::matchers::query_param("collection", "core"))
        .respond_with(wiremock::ResponseTemplate::new(500).set_body_json(
            serde_json::json!({
                "success": false,
                "changes": [],
                "problem": {
                    "message": "DELETE illegal: signature mismatch for 'ResourceId{resourcePath=com.inductiveautomation.eam/eam-tasks/ign-p10-scratch-sched, collectionName=core}'",
                    "stacktrace": [
                        "com.inductiveautomation.ignition.common.resourcecollection.PushException: DELETE illegal: signature mismatch for …",
                        "\tat com.inductiveautomation.ignition.gateway.resourcecollection.ChangeOperationValidationHandler$AtomicPushValidationHandler.throwIfInvalid(ChangeOperationValidationHandler.java:61)"
                    ]
                },
                "references": null
            }),
        ))
        .expect(1)
        .mount(&mock.server)
        .await;

    let api = ReqwestGatewayApi::for_tests(&mock.uri(), Some(token_credential()));
    let err = api
        .eam_task_delete("nightly-backup", "sig-abc123", false)
        .await
        .expect_err("the 500 refusal is not a success");
    assert_eq!(
        err.exit_code(),
        1,
        "the FINDING: exit-1 for a client-fixable mismatch"
    );
    assert_eq!(
        err.code(),
        "internal",
        "no honest slug yet — 10-03/10-04 decides"
    );
}

/// The captured lifecycle FAILURE shape (§1a verbatim): suspend of
/// an OnDemand/untriggered task answers 500 Jetty HTML — classified
/// `internal` with the page's own message surfaced (the
/// html_error_parts enrichment). Honest reference for 10-03's
/// find-before-write: suspend cannot distinguish unknown-task from
/// untriggered-task by status alone (§7).
#[tokio::test]
async fn suspend_500_html_failure_surfaces_the_page_message() {
    let mock = IgnitionMock::start().await;
    wiremock::Mock::given(wiremock::matchers::method("POST"))
        .and(wiremock::matchers::path(SUSPEND_PATH))
        .respond_with(
            wiremock::ResponseTemplate::new(500).set_body_raw(
                "<html>\n<head>\n<meta http-equiv=\"Content-Type\" content=\"text/html;charset=ISO-8859-1\"/>\n<title>Error 500</title>\n</head>\n<body><h2>HTTP ERROR 500 Task could not be suspended</h2>\n<table>\n<tr><th>URI:</th><td>/data/eam/api/v1/eam-tasks/suspend/ign-p10-scratch</td></tr>\n<tr><th>STATUS:</th><td>500</td></tr>\n<tr><th>MESSAGE:</th><td>Task could not be suspended</td></tr>\n</table>\n\n</body>\n</html>\n".as_bytes().to_vec(),
                "text/html;charset=iso-8859-1",
            ),
        )
        .expect(1)
        .mount(&mock.server)
        .await;

    let api = ReqwestGatewayApi::for_tests(&mock.uri(), Some(token_credential()));
    let err = api
        .eam_task_suspend("nightly-backup")
        .await
        .expect_err("the captured 500 refusal");
    assert_eq!(err.exit_code(), 1);
    assert_eq!(err.code(), "internal");
    assert!(
        err.to_string().contains("Task could not be suspended"),
        "the Jetty page's message rides the error detail: {err}"
    );
}

/// The 404 classification catches the new runtime URLs —
/// **spec-shaped, NOT capture-proven (10-01 limitation: 10-LIVE-CAPTURES
/// §7 records that lifecycle verbs answer 500/204 for unknown names;
/// NO 404 was ever captured on the /data/eam seam)**. This pins the
/// defensive classification only: if a curated-path 404 ever answers
/// here (route absence after a version change), it stays `not_found`
/// via the existing arm — zero new classify sites for 10-02.
#[tokio::test]
async fn runtime_verb_404_is_the_defensive_not_found_classification() {
    let mock = IgnitionMock::start().await;
    wiremock::Mock::given(wiremock::matchers::method("POST"))
        .and(wiremock::matchers::path(SUSPEND_PATH))
        .respond_with(wiremock::ResponseTemplate::new(404))
        .expect(1)
        .mount(&mock.server)
        .await;

    let api = ReqwestGatewayApi::for_tests(&mock.uri(), Some(token_credential()));
    let err = api
        .eam_task_suspend("nightly-backup")
        .await
        .expect_err("404 classifies NotFound");
    assert_eq!(err.exit_code(), 6);
    assert_eq!(err.code(), "not_found");
}

// ---- 10-03: the ACTION layer (find-first lifecycle with
// authoritative re-checks — the composition the pure fns + the
// client pins above only PARTIALLY prove) ----

/// A find responder answering the FIRST call with `first` and every
/// later call with `then` — the find→write→read-back flows need the
/// two answers to differ (e.g. `isSuspended` false → true). A
/// stateful responder (not two same-matcher mocks) so the answer
/// order can NEVER depend on wiremock's multi-mock match ordering.
fn find_responder(
    first: serde_json::Value,
    then: serde_json::Value,
) -> impl Fn(&wiremock::Request) -> wiremock::ResponseTemplate {
    use std::sync::Mutex;
    let calls = Mutex::new(0usize);
    move |_request| {
        let mut calls = calls.lock().expect("counter locks");
        *calls += 1;
        let body = if *calls == 1 {
            first.clone()
        } else {
            then.clone()
        };
        wiremock::ResponseTemplate::new(200).set_body_json(body)
    }
}

/// THE suspend action sequence: find (isSuspended false) → suspend
/// POST (204) → find read-back (isSuspended true — Decision 1's
/// persistence proof). The result reports the pre-write state, the
/// persisted flag, and `fired: true` — exactly 2 finds + 1 POST.
#[tokio::test]
async fn suspend_action_finds_then_posts_then_readbacks_the_flag() {
    let mock = IgnitionMock::start().await;
    let find = |suspended: bool| {
        serde_json::json!({
            "name": "nightly-backup",
            "config": {"profile": {"type": "eam_backup", "isSuspended": suspended, "scheduleMode": "Scheduled"}},
            "signature": "sig-abc123",
            "scheduledTaskState": {"currentState": "Scheduled", "details": {"owner": "eam"}}
        })
    };
    wiremock::Mock::given(wiremock::matchers::method("GET"))
        .and(wiremock::matchers::path(TASKS_FIND_PATH))
        .respond_with(find_responder(find(false), find(true)))
        .expect(2)
        .mount(&mock.server)
        .await;
    let post = wiremock::Mock::given(wiremock::matchers::method("POST"))
        .and(wiremock::matchers::path(SUSPEND_PATH))
        .respond_with(wiremock::ResponseTemplate::new(204))
        .expect(1)
        .mount_as_scoped(&mock.server)
        .await;

    let api = ReqwestGatewayApi::for_tests(&mock.uri(), Some(token_credential()));
    let result = ignition_core::actions::eam::eam_task_suspend(&api, "nightly-backup")
        .await
        .expect("the lifecycle sequence completes");
    assert_eq!(result.task, "nightly-backup");
    assert_eq!(result.action, "suspended");
    assert_eq!(
        result.previous_state.as_deref(),
        Some("Scheduled"),
        "the find healthcheck's currentState, pre-write"
    );
    assert_eq!(
        result.config_suspended,
        Some(true),
        "the read-back proves the flag PERSISTED (capture Decision 1)"
    );
    assert_eq!(result.pending, None);
    assert!(result.fired);
    assert_eq!(result.reason, None);
    assert_eq!(post.received_requests().await.len(), 1, "one POST rode");
}

/// The suspend re-check at the ACTION layer: an already-suspended
/// task (find proves isSuspended true) refuses exit 2 naming the
/// task BEFORE the wire — the gateway's own answer would be the
/// indistinguishable 500 "Task could not be suspended" (§1a/§7).
#[tokio::test]
async fn suspend_action_refuses_already_suspended_pre_write() {
    let mock = IgnitionMock::start().await;
    wiremock::Mock::given(wiremock::matchers::method("GET"))
        .and(wiremock::matchers::path(TASKS_FIND_PATH))
        .respond_with(wiremock::ResponseTemplate::new(200).set_body_json(
            serde_json::json!({
                "name": "nightly-backup",
                "config": {"profile": {"type": "eam_backup", "isSuspended": true, "scheduleMode": "Scheduled"}},
                "scheduledTaskState": {"currentState": "Suspended", "details": {"owner": "eam"}}
            }),
        ))
        .expect(1)
        .mount(&mock.server)
        .await;
    // expect(0): if the action wrongly fires, the server-drop
    // verification fails the test.
    wiremock::Mock::given(wiremock::matchers::method("POST"))
        .and(wiremock::matchers::path(SUSPEND_PATH))
        .respond_with(wiremock::ResponseTemplate::new(204))
        .expect(0)
        .mount(&mock.server)
        .await;

    let api = ReqwestGatewayApi::for_tests(&mock.uri(), Some(token_credential()));
    let err = ignition_core::actions::eam::eam_task_suspend(&api, "nightly-backup")
        .await
        .expect_err("already-suspended refuses pre-write");
    assert_eq!(err.exit_code(), 2);
    assert_eq!(err.code(), "invalid_input");
    let message = err.to_string();
    assert!(
        message.contains("nightly-backup") && message.contains("already suspended"),
        "the refusal names the task + state: {message}"
    );
}

/// The cancel no-op: nothing pending (both scheduled reads quiet)
/// returns the honest no-op result (`fired: false`, the reason
/// names it) WITHOUT firing the POST — mirroring the gateway's own
/// silent-204 semantics for cancel-with-nothing-pending (§7) minus
/// the pointless round trip.
#[tokio::test]
async fn cancel_action_without_pending_is_an_honest_noop() {
    let mock = IgnitionMock::start().await;
    wiremock::Mock::given(wiremock::matchers::method("GET"))
        .and(wiremock::matchers::path(TASKS_FIND_PATH))
        .respond_with(wiremock::ResponseTemplate::new(200).set_body_json(
            serde_json::json!({
                "name": "nightly-backup",
                "config": {"profile": {"type": "eam_backup", "isSuspended": false, "scheduleMode": "OnDemand"}},
                "scheduledTaskState": {"currentState": "Stopped", "details": {"owner": "eam"}}
            }),
        ))
        .expect(1)
        .mount(&mock.server)
        .await;
    for running in ["false", "true"] {
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path(format!(
                "/data/eam/api/v1/eam-tasks/scheduled/{running}"
            )))
            .respond_with(wiremock::ResponseTemplate::new(200).set_body_json(scheduled_true_page()))
            .expect(1)
            .mount(&mock.server)
            .await;
    }
    wiremock::Mock::given(wiremock::matchers::method("POST"))
        .and(wiremock::matchers::path(CANCEL_PATH))
        .respond_with(wiremock::ResponseTemplate::new(204))
        .expect(0)
        .mount(&mock.server)
        .await;

    let api = ReqwestGatewayApi::for_tests(&mock.uri(), Some(token_credential()));
    let result = ignition_core::actions::eam::eam_task_cancel(&api, "nightly-backup")
        .await
        .expect("the no-op is a success-shaped result");
    assert_eq!(result.action, "cancelled");
    assert!(!result.fired, "nothing pending — the POST did not ride");
    assert_eq!(
        result.reason.as_deref(),
        Some("no pending execution"),
        "the honest reason rides the always-keys model"
    );
    assert_eq!(result.previous_state.as_deref(), Some("Stopped"));
}

/// The cancel fire path: a pending row with the captured can* truth
/// cell (canCancel true) → POST → the post-write scheduled read
/// shows the row GONE — `fired: true`, `pending: null`.
#[tokio::test]
async fn cancel_action_fires_against_a_cancellable_row() {
    let mock = IgnitionMock::start().await;
    wiremock::Mock::given(wiremock::matchers::method("GET"))
        .and(wiremock::matchers::path(TASKS_FIND_PATH))
        .respond_with(wiremock::ResponseTemplate::new(200).set_body_json(
            serde_json::json!({
                "name": "nightly-backup",
                "config": {"profile": {"type": "eam_backup", "isSuspended": false, "scheduleMode": "Scheduled"}},
                "scheduledTaskState": {"currentState": "Scheduled", "details": {"owner": "eam"}}
            }),
        ))
        .expect(1)
        .mount(&mock.server)
        .await;
    // scheduled/false is read pre-write (the captured row present —
    // name adjusted to the test task) and post-write (row gone).
    let row_page = |name: &str| {
        let mut page = scheduled_false_page();
        page["items"][0]["name"] = serde_json::json!(name);
        page
    };
    wiremock::Mock::given(wiremock::matchers::method("GET"))
        .and(wiremock::matchers::path(SCHEDULED_FALSE_PATH))
        .respond_with(find_responder(
            row_page("nightly-backup"),
            scheduled_true_page(),
        ))
        .expect(2)
        .mount(&mock.server)
        .await;
    // BOTH segments read pre- AND post-write (10-03: a Running row
    // lives only in the true segment — never short-circuited).
    wiremock::Mock::given(wiremock::matchers::method("GET"))
        .and(wiremock::matchers::path(SCHEDULED_TRUE_PATH))
        .respond_with(wiremock::ResponseTemplate::new(200).set_body_json(scheduled_true_page()))
        .expect(2)
        .mount(&mock.server)
        .await;
    wiremock::Mock::given(wiremock::matchers::method("POST"))
        .and(wiremock::matchers::path(CANCEL_PATH))
        .respond_with(wiremock::ResponseTemplate::new(204))
        .expect(1)
        .mount(&mock.server)
        .await;

    let api = ReqwestGatewayApi::for_tests(&mock.uri(), Some(token_credential()));
    let result = ignition_core::actions::eam::eam_task_cancel(&api, "nightly-backup")
        .await
        .expect("the cancel sequence completes");
    assert!(result.fired);
    assert_eq!(result.reason, None);
    assert_eq!(
        result.pending, None,
        "the post-write read proves the execution is gone"
    );
    assert_eq!(result.previous_state.as_deref(), Some("Scheduled"));
}

// ---- 10-03 Task 2: the modify/delete ACTION layer ----

/// The full find fixture for the modify action (the §6a baseline +
/// the §0 key inventory — everything find answers rides the clone).
fn modify_find_fixture() -> serde_json::Value {
    serde_json::json!({
        "type": "com.inductiveautomation.eam/eam-tasks",
        "name": "ign-p10-scratch-sched",
        "description": "scratch",
        "enabled": true,
        "version": 1,
        "collection": "core",
        "collections": ["core"],
        "signature": "e5ac8bee3a6ba85e40923c0e02d29507600c57519eb8e4d78bd8c258197fe9c6",
        "config": {
            "profile": {
                "type": "eam_backup",
                "isSuspended": false,
                "scheduleMode": "Scheduled",
                "scheduleDetails": "0/30 * * * * ?"
            },
            "settings": {
                "targetGateways": ["_controller"],
                "targetGroups": [],
                "concurrentBackups": 0,
                "forceBackups": false
            }
        },
        "data": ["config.json"],
        "attributes": {"uuid": "c1aa2b52-46ad-46ea-962b-9d2498f35db1", "enabled": true},
        "metrics": {},
        "healthchecks": {
            "scheduledTaskState": {
                "currentState": "Scheduled",
                "details": {"owner": "eam", "nextScheduled": "1788947835694"}
            }
        }
    })
}

const MODIFY_FIND_PATH: &str =
    "/data/api/v1/resources/find/com.inductiveautomation.eam/eam-tasks/ign%2Dp10%2Dscratch%2Dsched";

/// THE modify action pin: find → clone EVERY key → enabled-only
/// mutation → the PUT body is the FULL single record (settings,
/// signature, collection, unknown round-trip keys ALL present —
/// the never-compose-from-scratch invariant ON THE WIRE) → the
/// post-PUT find read-back rides the result.
#[tokio::test]
async fn modify_action_preserves_the_full_record_on_the_wire() {
    let mock = IgnitionMock::start().await;
    let fixture = modify_find_fixture();
    let mut post_write = fixture.clone();
    post_write["enabled"] = serde_json::json!(false);
    post_write["signature"] =
        serde_json::json!("0d0dfea2919abb1f02fc86baea73d99696626524169a9ac36526044f89ac16e0");
    wiremock::Mock::given(wiremock::matchers::method("GET"))
        .and(wiremock::matchers::path(MODIFY_FIND_PATH))
        .respond_with(find_responder(fixture.clone(), post_write.clone()))
        .expect(2)
        .mount(&mock.server)
        .await;

    let mut expected_body = fixture.clone();
    expected_body["enabled"] = serde_json::json!(false);
    let put = wiremock::Mock::given(wiremock::matchers::method("PUT"))
        .and(wiremock::matchers::path(TASKS_CREATE_PATH))
        .respond_with(wiremock::ResponseTemplate::new(200).set_body_json(
            serde_json::json!({
                "success": true,
                "changes": [
                    {
                        "name": "ign-p10-scratch-sched",
                        "type": "com.inductiveautomation.eam/eam-tasks",
                        "collection": "core",
                        "newSignature": "0d0dfea2919abb1f02fc86baea73d99696626524169a9ac36526044f89ac16e0"
                    }
                ],
                "problem": null
            }),
        ))
        .expect(1)
        .mount_as_scoped(&mock.server)
        .await;

    let api = ReqwestGatewayApi::for_tests(&mock.uri(), Some(token_credential()));
    let result = ignition_core::actions::eam::eam_task_modify(
        &api,
        "ign-p10-scratch-sched",
        ignition_core::actions::eam::TaskChange {
            enabled: Some(false),
            ..Default::default()
        },
    )
    .await
    .expect("the full-record RMW completes");
    assert_eq!(result.task, "ign-p10-scratch-sched");
    assert_eq!(result.changed, vec!["enabled".to_string()]);
    assert!(
        result
            .put_outcome
            .as_ref()
            .expect("the 200 body rode")
            .success
    );
    assert_eq!(
        result.put_outcome.as_ref().unwrap().changes[0]
            .new_signature
            .as_deref(),
        Some("0d0dfea2919abb1f02fc86baea73d99696626524169a9ac36526044f89ac16e0"),
        "newSignature is authoritative for the NEXT mutation (§6a)"
    );
    assert_eq!(
        result.readback["signature"], post_write["signature"],
        "the read-back proves the landing"
    );
    assert_eq!(
        result.definition["config"]["settings"], fixture["config"]["settings"],
        "the verbatim PUT body preserved config.settings"
    );

    // THE wire pin: the PUT body is the FULL single-element array —
    // the expected body is the fixture with ONLY `enabled` moved.
    let requests = put.received_requests().await;
    assert_eq!(requests.len(), 1);
    let body: serde_json::Value = serde_json::from_slice(&requests[0].body).expect("body parses");
    assert_eq!(
        body,
        serde_json::json!([expected_body]),
        "never-compose-from-scratch ON THE WIRE: every find key rides, only the targeted key moved"
    );
}

/// The delete action derives the signature FROM find (no signature
/// parameter on the public fn) and the default delete carries NO
/// confirm param (Decision 3 — never hard-coded): the captured §3b
/// success body lands `deleted: true` + the affected names.
#[tokio::test]
async fn delete_action_derives_the_signature_and_sends_no_confirm() {
    let mock = IgnitionMock::start().await;
    wiremock::Mock::given(wiremock::matchers::method("GET"))
        .and(wiremock::matchers::path(TASKS_FIND_PATH))
        .respond_with(
            wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "name": "nightly-backup",
                "collection": "core",
                "signature": "sig-abc123",
                "config": {"profile": {"type": "eam_backup", "scheduleMode": "OnDemand"}},
                "scheduledTaskState": {"currentState": "Stopped", "details": {"owner": "eam"}}
            })),
        )
        .expect(1)
        .mount(&mock.server)
        .await;
    let guard = wiremock::Mock::given(wiremock::matchers::method("DELETE"))
        .and(wiremock::matchers::path(TASKS_DELETE_PATH))
        .and(wiremock::matchers::query_param("collection", "core"))
        .and(wiremock::matchers::query_param_is_missing("confirm"))
        .respond_with(wiremock::ResponseTemplate::new(200).set_body_json(
            serde_json::json!({
                "success": true,
                "changes": [
                    {
                        "name": "nightly-backup",
                        "type": "com.inductiveautomation.eam/eam-tasks",
                        "collection": "core",
                        "newSignature": "ec961ee921c63b18013094870ed2664331e965c4770fdf84bfe136e0b4164244"
                    }
                ],
                "problem": null,
                "references": []
            }),
        ))
        .expect(1)
        .mount_as_scoped(&mock.server)
        .await;

    let api = ReqwestGatewayApi::for_tests(&mock.uri(), Some(token_credential()));
    let result = ignition_core::actions::eam::eam_task_delete(&api, "nightly-backup")
        .await
        .expect("the delete completes");
    assert_eq!(result.task, "nightly-backup");
    assert!(result.deleted);
    assert_eq!(
        result.changes[0].new_signature.as_deref(),
        Some("ec961ee921c63b18013094870ed2664331e965c4770fdf84bfe136e0b4164244"),
        "the DELETED resource's final signature rides changes[] (§9)"
    );
    assert_eq!(
        result.affected,
        vec!["nightly-backup".to_string()],
        "a lone-resource delete touches exactly the deleted resource"
    );
    let requests = guard.received_requests().await;
    assert_eq!(
        requests[0].url.query(),
        Some("collection=core"),
        "NO confirm on the default delete (Decision 3)"
    );
}

/// The confirm-demand retry (Decision 3 as written): a body-level
/// `success: false` (the UNOBSERVED §3d shape — spec-shaped fixture)
/// re-runs ONCE with confirm=true; the confirmed answer is the
/// result. Hard-coding confirm on the FIRST attempt is forbidden —
/// it would bypass a genuine multi-resource warning.
#[tokio::test]
async fn delete_action_retries_with_confirm_on_the_demand_shape() {
    let mock = IgnitionMock::start().await;
    wiremock::Mock::given(wiremock::matchers::method("GET"))
        .and(wiremock::matchers::path(TASKS_FIND_PATH))
        .respond_with(
            wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "name": "nightly-backup",
                "collection": "core",
                "signature": "sig-abc123",
                "config": {"profile": {"type": "eam_backup", "scheduleMode": "Scheduled"}}
            })),
        )
        .expect(1)
        .mount(&mock.server)
        .await;
    // First attempt (no confirm): the confirm-demand answer.
    wiremock::Mock::given(wiremock::matchers::method("DELETE"))
        .and(wiremock::matchers::path(TASKS_DELETE_PATH))
        .and(wiremock::matchers::query_param("collection", "core"))
        .and(wiremock::matchers::query_param_is_missing("confirm"))
        .respond_with(
            wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "success": false,
                "changes": [],
                "problem": null,
                "references": [
                    {"name": "dependent-thing", "type": "some/dependent-type"}
                ]
            })),
        )
        .expect(1)
        .mount(&mock.server)
        .await;
    // The one sanctioned retry: confirm=true + collection=core.
    wiremock::Mock::given(wiremock::matchers::method("DELETE"))
        .and(wiremock::matchers::path(TASKS_DELETE_PATH))
        .and(wiremock::matchers::query_param("collection", "core"))
        .and(wiremock::matchers::query_param("confirm", "true"))
        .respond_with(wiremock::ResponseTemplate::new(200).set_body_json(
            serde_json::json!({
                "success": true,
                "changes": [
                    {
                        "name": "nightly-backup",
                        "type": "com.inductiveautomation.eam/eam-tasks",
                        "collection": "core",
                        "newSignature": "e3610cfe01c7df086da6596ccfbb7735abd5b8f2ceafd5916944919975902acf"
                    }
                ],
                "problem": null,
                "references": []
            }),
        ))
        .expect(1)
        .mount(&mock.server)
        .await;

    let api = ReqwestGatewayApi::for_tests(&mock.uri(), Some(token_credential()));
    let result = ignition_core::actions::eam::eam_task_delete(&api, "nightly-backup")
        .await
        .expect("the confirm retry lands the delete");
    assert!(result.deleted);
    assert_eq!(
        result.affected,
        vec!["nightly-backup".to_string()],
        "the confirmed delete's references are honestly empty"
    );
}

/// The stale-signature diagnostic at the ACTION layer (the
/// client/eam.rs FINDING, classified on EVIDENCE — the `signature
/// mismatch` substring never reaches this layer): the 500 mismatch
/// + a post-failure find showing a DIFFERENT signature (a concurrent
/// write — captures prove mismatches leave the resource untouched)
/// maps to exit 2 invalid_input with re-run guidance. No new slugs.
#[tokio::test]
async fn delete_action_maps_a_proven_stale_signature_to_exit_2() {
    let mock = IgnitionMock::start().await;
    let fresh = |sig: &str| {
        serde_json::json!({
            "name": "nightly-backup",
            "collection": "core",
            "signature": sig,
            "config": {"profile": {"type": "eam_backup", "scheduleMode": "OnDemand"}}
        })
    };
    wiremock::Mock::given(wiremock::matchers::method("GET"))
        .and(wiremock::matchers::path(TASKS_FIND_PATH))
        .respond_with(find_responder(fresh("sig-abc123"), fresh("sig-concurrent")))
        .expect(2)
        .mount(&mock.server)
        .await;
    // The captured §3a mismatch body (8.3.6 verbatim message).
    wiremock::Mock::given(wiremock::matchers::method("DELETE"))
        .and(wiremock::matchers::path(TASKS_DELETE_PATH))
        .and(wiremock::matchers::query_param("collection", "core"))
        .respond_with(wiremock::ResponseTemplate::new(500).set_body_json(
            serde_json::json!({
                "success": false,
                "changes": [],
                "problem": {
                    "message": "DELETE illegal: signature mismatch for 'ResourceId{resourcePath=com.inductiveautomation.eam/eam-tasks/nightly-backup, collectionName=core}'",
                    "stacktrace": ["com.inductiveautomation.ignition.common.resourcecollection.PushException: DELETE illegal: signature mismatch for …"]
                },
                "references": null
            }),
        ))
        .expect(1)
        .mount(&mock.server)
        .await;

    let api = ReqwestGatewayApi::for_tests(&mock.uri(), Some(token_credential()));
    let err = ignition_core::actions::eam::eam_task_delete(&api, "nightly-backup")
        .await
        .expect_err("the stale-signature write refuses");
    assert_eq!(err.exit_code(), 2, "client-fixable — the usage class");
    assert_eq!(err.code(), "invalid_input");
    let message = err.to_string();
    assert!(
        message.contains("changed concurrently") && message.contains("signature mismatch"),
        "the diagnostic names the conflict + the re-run path: {message}"
    );
}

/// THE force preview pin (EAMW-04): the force result carries the
/// composed blast-radius preview — targets from the find's
/// `config.settings.targetGateways`, the pending row from the
/// scheduled read, and the factual impact naming task + agents.
#[tokio::test]
async fn force_action_composes_the_blast_radius_preview() {
    let mock = IgnitionMock::start().await;
    mock.list_json(
        "GET",
        "/data/api/v1/resources/find/com.inductiveautomation.eam/eam-tasks/nightly%2Dbackup",
        serde_json::json!({
            "name": "nightly-backup",
            "config": {
                "profile": {"type": "eam_backup", "scheduleMode": "Scheduled"},
                "settings": {"targetGateways": ["gw-a", "gw-b"], "targetGroups": []}
            },
            "scheduledTaskState": {
                "currentState": "Scheduled",
                "details": {"owner": "eam"}
            }
        }),
    )
    .await;
    // The captured scheduled row (§2), adjusted to the task name.
    let row_page = {
        let mut page = scheduled_false_page();
        page["items"][0]["name"] = serde_json::json!("nightly-backup");
        page
    };
    mock.list_json("GET", SCHEDULED_FALSE_PATH, row_page).await;
    mock.list_json("GET", SCHEDULED_TRUE_PATH, scheduled_true_page())
        .await;
    wiremock::Mock::given(wiremock::matchers::method("POST"))
        .and(wiremock::matchers::path(
            "/data/eam/api/v1/eam-tasks/force/eam/nightly-backup",
        ))
        .respond_with(wiremock::ResponseTemplate::new(204))
        .expect(1)
        .mount(&mock.server)
        .await;
    mock.list_json(
        "GET",
        HISTORY_PATH,
        serde_json::json!({
            "items": [],
            "metadata": {"total": 0, "matching": 0, "limit": 20, "offset": 0}
        }),
    )
    .await;

    let api = ReqwestGatewayApi::for_tests(&mock.uri(), Some(token_credential()));
    let result = ignition_core::actions::eam::eam_task_force(&api, "nightly-backup")
        .await
        .expect("the force sequence completes");
    let preview = &result.preview;
    assert_eq!(preview.verb, "force");
    assert_eq!(preview.task, "nightly-backup");
    assert_eq!(
        preview.target_gateways,
        vec!["gw-a".to_string(), "gw-b".to_string()],
        "the AGENTS the force touches"
    );
    assert_eq!(preview.pending_executions.len(), 1);
    assert!(preview.pending_executions[0].can_cancel);
    assert_eq!(preview.owner.as_deref(), Some("eam"));
    let impact = &preview.controller_impact;
    assert!(
        impact.contains("dispatches task nightly-backup") && impact.contains("2 agents"),
        "the force impact names task + agents: {impact}"
    );
    // The single-line render embeds the composed facts.
    let line = ignition_core::actions::eam::render_preview_line(preview);
    assert!(
        line.starts_with("force nightly-backup:")
            && line.contains("targets: [gw-a, gw-b] pending: 1"),
        "the confirmation-line format: {line}"
    );
}