ignition-core 1.1.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
//! The gateway HTTP seam: a coarse [`GatewayApi`] trait so actions never
//! touch reqwest types, plus the production [`ReqwestGatewayApi`].
//!
//! LOCKED: the trait uses `async_trait` (research Open Question 2,
//! resolved) — dyn-compatible today, ubiquitous. The trait stays COARSE —
//! one method per capability, not per endpoint — so Phase 2 grows it
//! without churn.
//!
//! Auth-header rule (verified against a live 8.3.6 gateway, 02-RESEARCH
//! §Auth Model): a token credential sends `X-Ignition-API-Token`; a basic
//! credential sends `Authorization: Basic <b64>`; NEVER both — enforced by
//! a match in [`ReqwestGatewayApi::apply_auth`], the ONE place
//! [`Secret::expose`] is called outside the secret module (the
//! grep-auditable redaction boundary; CORE-02).
//!
//! Basic is loudly demoted there: valid Basic credentials → 401 on every
//! 8.3 `/data` route (verified), so each use warns — never silently
//! retried. Note gateway-info itself DOES require auth under 8.3 default
//! security (header-less → 401, re-verified live 2026-08-21 — the 83-api
//! collection's `auth: none` tag does not hold); a `None` credential
//! proceeds header-less and classifies the answer.
//!
//! Redirects are never followed (`Policy::none()`): an uncommissioned
//! gateway 302s EVERYTHING to `/welcome` and the default follow would
//! render the wizard's HTML as a 200 (02-RESEARCH Pitfall 6). The 3xx is
//! classified by [`classify`] instead.
//!
//! Every request runs the pipeline: build URL → apply auth (opt-in) →
//! send (transport error → `Network`) → [`classify`] → parse the body.
//! Nothing ever calls `.json()` on a response that skipped `classify()`.

use std::path::Path;
use std::time::Duration;

pub mod apicall;
pub mod backup;
mod classify;
pub mod connections;
pub mod diagnostics;
pub mod eam;
pub mod gan;
pub mod idp;
pub mod license;
pub mod logs;
pub mod metrics;
pub mod projects;
pub mod query;
pub mod redundancy;
pub mod resources;
pub mod restart;
pub mod scripts_codec;
pub mod sessions;
pub mod status;
pub mod tags;
pub mod trial;
pub mod version;
pub mod webdev;
pub mod workspace;

use crate::client::connections::GatewayConnection;
use crate::client::diagnostics::BundleStatusWire;
use crate::client::eam::{
    DeleteOutcome, EamHistoryItem, EamScheduledTask, EamTaskRecord, ModifyOutcome,
};
use crate::client::gan::GanStatusWire;
use crate::client::license::LicenseStatusWire;
use crate::client::logs::{LogDownload, LogEntry, LogQuery, LoggerInfo};
use crate::client::metrics::{CurrentGauges, PerformanceCharts, ThreadCounts};
use crate::client::projects::{
    ExportMeta, ImportOutcome, ProjectCopy, ProjectCreate, ProjectModify, ProjectRecord,
    ProjectRenameBody,
};
use crate::client::query::ListEnvelope;
use crate::client::redundancy::RedundancyStatusWire;
use crate::client::restart::SecurityProperties;
use crate::client::sessions::{DesignerInfo, PerspectiveSession, VisionClient};
use crate::client::status::{ModuleInfo, Overview, StatusPing};
use crate::client::tags::{TagProviderCreate, TagProviderRecord};
use crate::client::trial::{BannerSet, TrialWire};
use crate::client::version::GatewayInfo;
use crate::client::webdev::{RouteBody, RouteProbe};
use crate::config::{Credential, Profile};
use crate::error::CoreError;

/// GET path of the gateway-info capability.
const GATEWAY_INFO_PATH: &str = "/data/api/v1/gateway-info";

/// One capability per method — coarse on purpose. Phase 2 adds status,
/// modules, metrics, … as methods here; actions never see reqwest types.
///
/// (All impl bodies live in the ONE `impl GatewayApi for
/// ReqwestGatewayApi` block below: Rust rejects a second impl block of
/// the same trait for the same type, so the per-capability files own the
/// models + verified path constants and this block owns the delegation.)
#[async_trait::async_trait]
pub trait GatewayApi: Send + Sync {
    /// Fetch `/data/api/v1/gateway-info`.
    async fn gateway_info(&self) -> Result<GatewayInfo, CoreError>;
    /// Fetch `/data/api/v1/overview` (authed) — platform + runtime.
    async fn overview(&self) -> Result<Overview, CoreError>;
    /// Fetch `/StatusPing` **header-less** (auth=false) — the
    /// unauthenticated readiness anchor: it must keep answering when
    /// credentials are broken or absent and mid-restart (02-02).
    async fn status_ping(&self) -> Result<StatusPing, CoreError>;
    /// Fetch `/data/api/v1/modules/healthy` (`quarantined = false`) or
    /// `/modules/quarantined` (`true`) with the standard list params.
    async fn modules(
        &self,
        quarantined: bool,
        query: &query::ListQuery,
    ) -> Result<ListEnvelope<ModuleInfo>, CoreError>;
    /// Fetch `/data/api/v1/systemPerformance/currentGauges` (authed) —
    /// cpu in PERCENT (contrast [`Overview::cpu`], a 0–1 fraction).
    async fn metrics_current(&self) -> Result<CurrentGauges, CoreError>;
    /// Fetch `/data/api/v1/systemPerformance/charts` (authed) — historic
    /// cpu/heap/non-heap datapoints (epoch-ms timestamps).
    async fn metrics_historic(&self) -> Result<PerformanceCharts, CoreError>;
    /// Fetch `/data/api/v1/systemPerformance/threads` (authed) — thread
    /// execution counts (running/waiting/timedWaiting/blocked).
    async fn metrics_threads(&self) -> Result<ThreadCounts, CoreError>;
    /// Fetch `/data/api/v1/designers` (authed) — active Designer
    /// sessions (02-03, HLTH-08).
    async fn designers(
        &self,
        query: &query::ListQuery,
    ) -> Result<ListEnvelope<DesignerInfo>, CoreError>;
    /// Fetch `/data/perspective/api/v1/sessions/` (authed) — the EXACT
    /// trailing slash is the contract (Pitfall 8; module-scoped prefix).
    async fn perspective_sessions(
        &self,
        query: &query::ListQuery,
    ) -> Result<ListEnvelope<PerspectiveSession>, CoreError>;
    /// Fetch `/data/vision/api/v1/clients` (authed) — active Vision
    /// clients (designer shape + `tagCount`).
    async fn vision_clients(
        &self,
        query: &query::ListQuery,
    ) -> Result<ListEnvelope<VisionClient>, CoreError>;
    /// DELETE `/data/perspective/api/v1/sessions?sessionId=<id>` (+ an
    /// optional `message` shown to the session's user) — NO trailing
    /// slash on the DELETE (spec). Audit-logged server-side.
    async fn terminate_perspective_session(
        &self,
        id: &str,
        message: Option<&str>,
    ) -> Result<(), CoreError>;
    /// DELETE `/data/vision/api/v1/client/{id}` — terminate a Vision
    /// client. Audit-logged server-side.
    async fn terminate_vision_client(&self, id: &str) -> Result<(), CoreError>;
    /// DELETE `/data/api/v1/designer/{id}` — prune a Designer session.
    /// Audit-logged server-side.
    async fn prune_designer(&self, id: &str) -> Result<(), CoreError>;
    /// Fetch `/data/api/v1/resources/list/ignition/database-connection`
    /// (authed) — the web UI's Connections→Databases poll (HLTH-05).
    /// `healthchecks` is raw passthrough (LOW-confidence populated
    /// shape, research Open Question 1).
    async fn database_connections(&self) -> Result<ListEnvelope<GatewayConnection>, CoreError>;
    /// Fetch `/data/api/v1/resources/list/ignition/opc-connection`
    /// (authed) — the Connections→OPC poll (HLTH-06), same family.
    async fn opc_connections(&self) -> Result<ListEnvelope<GatewayConnection>, CoreError>;
    /// Fetch `/data/api/v1/logs` (authed) with [`LogQuery`] — the tail
    /// primitive: `startTime` (epoch ms) is the cursor, no server push
    /// exists (02-04, HLTH-03). The query ALWAYS carries an explicit
    /// `limit` (Pitfall 9 — the server default is unlimited).
    async fn logs(&self, filter: &LogQuery) -> Result<ListEnvelope<LogEntry>, CoreError>;
    /// GET `/data/api/v1/logs/download` (authed, per-request 120 s
    /// timeout) — a SQLite `.idb` archive, returned byte-for-byte with
    /// the `Content-Disposition` filename and `Content-Type`. NEVER
    /// zipped/extracted (Pitfall 7; Don't-Hand-Roll table).
    async fn logs_download(&self) -> Result<LogDownload, CoreError>;
    /// Fetch `/data/api/v1/logs/loggers` (authed) — the logger registry
    /// (HLTH-04; ~1250 loggers on a fresh gateway).
    async fn loggers(
        &self,
        query: &query::ListQuery,
    ) -> Result<ListEnvelope<LoggerInfo>, CoreError>;
    /// POST `/data/api/v1/logs/loggers/{loggerName}?level=X` (authed,
    /// empty body, NO CSRF — verified: token mutations need none).
    /// Logger names are Java identifiers `[A-Za-z0-9._]` — URL-safe,
    /// embedded as-is. Audit-logged server-side.
    async fn set_logger_level(&self, logger: &str, level: &str) -> Result<(), CoreError>;
    /// POST `/data/api/v1/logs/levelreset` (authed, empty body) — reset
    /// all custom logger levels to defaults. Audit-logged server-side.
    async fn reset_logger_levels(&self) -> Result<(), CoreError>;
    /// POST `/data/api/v1/restart-tasks/restart?confirm=true` (authed,
    /// empty body, NO CSRF — token mutations need none) — the one big
    /// red button. The gateway answers 200 with the literal body `true`
    /// almost immediately; the ~40 s wait is poller-side (02-05's
    /// `restart --wait` owns it). Audit-logged server-side.
    async fn restart(&self) -> Result<(), CoreError>;
    /// POST `/data/api/v1/scan/projects` (authed) — the harmless
    /// project-rescan write probe (`ign doctor --check-write`; 2xx =
    /// write permission, 403 = read-only token).
    async fn scan_projects(&self) -> Result<(), CoreError>;
    /// GET `/data/api/v1/resources/ignition/security-properties`
    /// (authed) — the security config singleton; the doctor's
    /// permissions deep-dive surfaces `readPermissions`/
    /// `writePermissions` verbatim (passthrough shape).
    async fn security_properties(&self) -> Result<SecurityProperties, CoreError>;
    /// GET `/system/webdev/<route>` (authed) reporting the RAW HTTP
    /// status — the doctor's route-presence probe (404 = absent;
    /// 200/401/403 = exists). Deliberately NOT classified: presence
    /// IS the answer; only transport failures are errors.
    async fn webdev_route_status(&self, route: &str) -> Result<u16, CoreError>;
    /// POST `/system/webdev/{project}/cli/{route}` (authed + any
    /// caller headers — scriptExec's secret gate) with the action
    /// JSON. classify() runs for transport/status errors, BUT the
    /// 200 BODY is the route envelope `{ok, data|error}` — WebDev
    /// IGNORES `status`, so denials ride HTTP 200: `ok:false` maps
    /// `error.code` onto the taxonomy (05-03), `ok:true` returns
    /// `data`. HTTP 200 alone is NEVER a success verdict.
    async fn webdev_route_call(
        &self,
        project: &str,
        route: &str,
        body: &serde_json::Value,
        extra_headers: &[(&str, &str)],
    ) -> Result<serde_json::Value, CoreError>;
    /// POST the route action with a PER-REQUEST timeout override —
    /// the large-payload escape hatch (the `get_bytes`
    /// `RequestBuilder::timeout` pattern, 02-04/09-05): the 30 s
    /// client default would truncate the Phase-11 bulk exportTags
    /// transfer (research Pitfall 6), so the bulk arms override with
    /// [`crate::client::tags::TAGS_EXPORT_TIMEOUT`]. Default body =
    /// the plain call — test doubles and any impl without an
    /// override path ride the client default (the override only
    /// lengthens the ceiling; request/response semantics are the
    /// same classify + envelope parse).
    async fn webdev_route_call_with_timeout(
        &self,
        project: &str,
        route: &str,
        body: &serde_json::Value,
        extra_headers: &[(&str, &str)],
        _timeout: Duration,
    ) -> Result<serde_json::Value, CoreError> {
        self.webdev_route_call(project, route, body, extra_headers)
            .await
    }
    /// POST the route's `{"action":"version"}` handshake and
    /// discriminate ([`webdev::RouteProbe`]): 200-body-ok →
    /// `Present{route_version}`, 405 → `Absent` (the live-proven 8.3
    /// marker — NOT 404), 402 → `Unlicensed`, 401/403 → `AuthGated`,
    /// 200-body-denial → `Denied{code,message}`. Deliberately NOT
    /// classified — the status code IS the answer (the
    /// `webdev_route_status` precedent); only transport failures and
    /// shapes the enum has no variant for (wizard redirects, 503
    /// restarts, foreign 404s) are errors.
    async fn webdev_route_probe(
        &self,
        project: &str,
        route: &str,
        extra_headers: &[(&str, &str)],
    ) -> Result<RouteProbe, CoreError>;
    /// GET `/data/api/v1/projects/list` (authed) — every RUNNABLE
    /// project with inheritance info from the items themselves
    /// (PROJ-01; standard list params, `limit=-1` UI convention).
    async fn projects(
        &self,
        query: &query::ListQuery,
    ) -> Result<ListEnvelope<ProjectRecord>, CoreError>;
    /// GET `/data/api/v1/projects/find/{name}` (authed, name
    /// percent-encoded per segment) — one project's full record; 404 →
    /// `NotFound` via classify (this doubles as 03-02's collision
    /// pre-check).
    async fn project_find(&self, name: &str) -> Result<ProjectRecord, CoreError>;
    /// POST `/data/api/v1/projects` (authed, JSON body) — create. Ok
    /// classification IS the success contract (create's response body
    /// is unverified LOW — the restart `literal true` precedent;
    /// callers that want data re-`find`). Audit-logged server-side.
    async fn project_create(&self, body: &ProjectCreate) -> Result<(), CoreError>;
    /// POST `/data/api/v1/projects/copy` (authed, body exactly
    /// `{"fromName":…,"toName":…}`) — an exact copy of all resources.
    /// Audit-logged server-side.
    async fn project_copy(&self, from: &str, to: &str) -> Result<(), CoreError>;
    /// POST `/data/api/v1/projects/rename/{name}` (authed, body
    /// `{"name": "<new>"}`) — native rename, NOT copy+delete.
    /// Audit-logged server-side.
    async fn project_rename(&self, name: &str, new_name: &str) -> Result<(), CoreError>;
    /// PUT `/data/api/v1/projects/{name}` (authed, JSON body WITHOUT
    /// `name`) — modify/reparent (`set --parent` IS the inheritance
    /// move). Audit-logged server-side.
    async fn project_modify(&self, name: &str, body: &ProjectModify) -> Result<(), CoreError>;
    /// DELETE `/data/api/v1/projects/{name}?confirm=true` (authed,
    /// empty body) — the server's own confirmation guard rides the
    /// QUERY string (Pitfall 8: BOTH layers, always — the CLI's
    /// `--yes` and the wire's `confirm=true`). Audit-logged
    /// server-side.
    async fn project_delete(&self, name: &str) -> Result<(), CoreError>;
    /// GET `/data/api/v1/projects/export/{name}` (authed, per-request
    /// [`projects::PROJECT_EXPORT_TIMEOUT`] = 120 s) — the project ZIP
    /// STREAMED to `out` chunk-by-chunk via `bytes_stream` (Pitfall 2:
    /// NO `Vec<u8>` accumulation anywhere), with the disposition
    /// filename + byte count in the meta. Audit-relevant only as a
    /// read (exports never mutate).
    async fn project_export_to_file(&self, name: &str, out: &Path)
    -> Result<ExportMeta, CoreError>;
    /// POST `/data/api/v1/projects/import/{name}?overwrite=<bool>`
    /// (authed, per-request [`projects::PROJECT_IMPORT_TIMEOUT`] =
    /// 300 s) — the ZIP as the RAW body with `Content-Type:
    /// application/zip` and a known `Content-Length` (a `Vec<u8>`
    /// sidesteps the chunked-encoding question entirely — Pitfall 3's
    /// timeout is handled by the override). Synchronous, no job IDs
    /// (verified). Audit-logged server-side.
    async fn project_import(
        &self,
        name: &str,
        zip: Vec<u8>,
        overwrite: bool,
    ) -> Result<ImportOutcome, CoreError>;
    /// GET `/data/api/v1/resources/list/ignition/tag-provider`
    /// (authed) — the tag-provider resource list: full records
    /// incl. `config`, `metrics.tagCount`, `healthchecks.status`
    /// (05-04, TAGS-01 — the NATIVE provider seam; no deployed
    /// route involved). Standard list params (limit=-1, the UI
    /// convention).
    async fn tag_provider_list(
        &self,
        query: &query::ListQuery,
    ) -> Result<ListEnvelope<TagProviderRecord>, CoreError>;
    /// GET `/data/api/v1/resources/find/ignition/tag-provider/{name}`
    /// (authed, name percent-encoded per segment) — one provider's
    /// full record incl. the `signature` the chained delete needs.
    /// 404 → `NotFound` via classify.
    async fn tag_provider_find(&self, name: &str) -> Result<TagProviderRecord, CoreError>;
    /// POST `/data/api/v1/resources/ignition/tag-provider` (authed)
    /// with a JSON **ARRAY** body of create records — the
    /// live-proven create shape (05-RESEARCH provider table).
    /// Audit-logged server-side.
    async fn tag_provider_create(&self, body: &[TagProviderCreate]) -> Result<(), CoreError>;
    /// DELETE `/data/api/v1/resources/ignition/tag-provider/{name}/{signature}`
    /// (authed, both segments percent-encoded) — delete-by-signature;
    /// the signature comes from find. Audit-logged server-side.
    async fn tag_provider_delete(&self, name: &str, signature: &str) -> Result<(), CoreError>;
    /// GET `/data/api/v1/trial` — the trial state, live-verified
    /// UNAUTHENTICATED on 8.3.3 + 8.3.6 (both trial states): auth
    /// headers ride ONLY when the client carries a credential (fresh
    /// rigs have none — the version-command degradation precedent,
    /// rig-family edition).
    async fn trial_status_wire(&self) -> Result<TrialWire, CoreError>;
    /// GET `/data/api/v1/overview/banners` — the trial cross-check
    /// (severity/expireTime semantics, Pitfall 7). Same conditional
    /// auth as [`Self::trial_status_wire`].
    async fn banners(&self) -> Result<BannerSet, CoreError>;
    /// POST `/data/api/v1/trial` (authed, empty body) — the trial
    /// RESET, tier 0 of the ladder: a token credential plausibly
    /// satisfies it without CSRF (token mutations need none — the
    /// restart/set-logger precedent). The 2xx body IS the fresh
    /// [`TrialWire`] (live-observed). NOTE (live-discovered state
    /// gate): the gateway 403s resets on a NON-expired trial — the
    /// action layer pre-checks expiry.
    async fn trial_reset_wire(&self) -> Result<TrialWire, CoreError>;
    /// GET `/data/api/v1/backup?type={roaming|all}` (authed,
    /// [`backup::BACKUP_TIMEOUT`] = 300 s, `Accept:
    /// application/octet-stream`) — the portable gwbk STREAMED to
    /// `out` chunk-by-chunk through the 03-02 `download_to_file`
    /// pipeline (the ONE streaming body-consumption site — never a
    /// `Vec<u8>`, Pitfall 2). Byte count + metadata ride out in
    /// [`ExportMeta`] (04-04, RIG-04; 07-02 param-ized the type —
    /// `Roaming` stays the caller default).
    async fn backup_download(
        &self,
        out: &Path,
        backup_type: backup::BackupType,
    ) -> Result<ExportMeta, CoreError>;
    /// POST `/data/api/v1/backup` (authed, [`backup::BACKUP_TIMEOUT`]
    /// = 300 s) — the RESTORE: the gwbk bytes as a RAW
    /// `application/octet-stream` body (NOT multipart — the postman
    /// collection's exact shape) with the four scope params EXPLICIT
    /// on the query string. Synchronous AND followed by a gateway
    /// restart (Pitfall 6): the 2xx means the restore was ACCEPTED —
    /// the actions layer owns the post-restore RUNNING wait. The
    /// upload direction buffers by design (the import precedent).
    async fn backup_restore(&self, gwbk: &Path) -> Result<(), CoreError>;
    /// GET `/data/eam/api/v1/eam-tasks/history` (authed) — task run
    /// history, the standard `{items, metadata}` envelope. `limit`
    /// defaults to [`eam::EAM_HISTORY_DEFAULT_LIMIT`] (200 — EAM
    /// history grows unboundedly; an explicit limit ALWAYS rides the
    /// wire, the logs discipline). A stock (non-controller) gateway
    /// 403s → [`CoreError::EamNotController`] via classify
    /// (path-scoped message classification — never a misleading
    /// `auth_rejected`).
    async fn eam_task_history(
        &self,
        limit: Option<u32>,
        search: Option<&str>,
    ) -> Result<ListEnvelope<EamHistoryItem>, CoreError>;
    /// GET `/data/api/v1/resources/list/com.inductiveautomation.eam/
    /// eam-tasks` (authed) — task DEFINITIONS through the standard
    /// config-resource family (the tag-provider pattern; available
    /// on stock gateways — no controller needed for definitions).
    async fn eam_task_definitions(&self) -> Result<ListEnvelope<EamTaskRecord>, CoreError>;
    /// GET `/data/api/v1/resources/find/com.inductiveautomation.eam/
    /// eam-tasks/{name}` (authed) — one definition's full record
    /// incl. the `scheduledTaskState` healthcheck
    /// (`currentState`/`nextScheduled`/`owner` under `details`) and
    /// the mutation `signature`. 404 → `NotFound` via classify.
    async fn eam_task_find(&self, name: &str) -> Result<EamTaskRecord, CoreError>;
    /// POST `/data/api/v1/resources/com.inductiveautomation.eam/
    /// eam-tasks` (authed) with a JSON **ARRAY** body of one
    /// definition record — the config-resource create shape (the
    /// tag-provider precedent). Ok classification IS the success
    /// contract (create's response body is unverified — the
    /// project-create precedent; callers that want data re-find).
    /// Audit-logged server-side.
    async fn eam_task_create(&self, definition: &serde_json::Value) -> Result<(), CoreError>;
    /// POST `/data/eam/api/v1/eam-tasks/force/{owner}/{name}` (authed,
    /// empty body) — dispatch a task NOW. Live-proven success shape:
    /// **204** (any 2xx is done — the route-status style; execution
    /// OUTCOMES surface later in history as data, never on this
    /// response). Runtime seam: the controller gate classifies.
    async fn eam_task_force(&self, owner: &str, name: &str) -> Result<(), CoreError>;
    /// POST `/data/eam/api/v1/eam-tasks/suspend/{name}` (authed,
    /// empty body) — suspend the task's scheduler trigger.
    /// Live-proven success shape: **204**; the flag PERSISTS into
    /// `config.profile.isSuspended` (10-LIVE-CAPTURES §1c/Decision 1).
    /// Requires a live scheduler trigger — an OnDemand/untriggered
    /// (or unknown-named, §7) task answers 500 Jetty HTML, which
    /// classifies as `Internal` with the page's own message (no
    /// honest 404 exists on this seam).
    async fn eam_task_suspend(&self, name: &str) -> Result<(), CoreError>;
    /// POST `/data/eam/api/v1/eam-tasks/resume/{name}` (authed,
    /// empty body) — the inverse of [`Self::eam_task_suspend`]:
    /// **204** success, `isSuspended` back to `false` (§1d). Unknown
    /// names answer 500 HTML naming the task (§7).
    async fn eam_task_resume(&self, name: &str) -> Result<(), CoreError>;
    /// POST `/data/eam/api/v1/eam-tasks/cancel/{name}` (authed,
    /// empty body) — cancel a PENDING execution. Always **204** on
    /// the captured shapes: nothing-pending AND unknown-name are
    /// silent successes (§7) — cancel is never a name-validation
    /// tool (the actions layer owns find-before-write).
    async fn eam_task_cancel(&self, name: &str) -> Result<(), CoreError>;
    /// GET `/data/eam/api/v1/eam-tasks/scheduled/{running}` (authed)
    /// — the pending-execution read; `{running}` is the LITERAL word
    /// `true`/`false` (§2). Answers the standard
    /// `{items, metadata}` envelope; this method unwraps it to the
    /// items ([`EamScheduledTask`] — 13 capture-locked keys,
    /// `taskState` String vocabulary). A stock gateway 403s →
    /// [`CoreError::EamNotController`] via the same path-scoped arm
    /// as every runtime seam call.
    async fn eam_tasks_scheduled(&self, running: bool) -> Result<Vec<EamScheduledTask>, CoreError>;
    /// PUT `/data/api/v1/resources/com.inductiveautomation.eam/
    /// eam-tasks` (authed) with a single-element JSON **ARRAY**
    /// carrying the FULL find record (settings included — omitting
    /// `config.settings` ⇒ 422, the create trap) and the ORIGINAL
    /// `signature`. The 200 body is the captured
    /// [`ModifyOutcome`] `{success, changes[], problem}`
    /// (§6a); `None` = a 2xx with an empty body (lenient). Rename via
    /// PUT is NOT supported (§5: changed name + original signature ⇒
    /// 404 — the actions layer must compose create-new + delete-old).
    async fn eam_task_modify(
        &self,
        definition: &serde_json::Value,
    ) -> Result<Option<ModifyOutcome>, CoreError>;
    /// DELETE `/data/api/v1/resources/com.inductiveautomation.eam/
    /// eam-tasks/{name}/{signature}` (authed, both segments
    /// percent-encoded) with `?collection=core` ALWAYS (the
    /// collection VALUE — `collection=eam-tasks` 404s, §3c) and
    /// `confirm=true` only when the caller opts in: a lone-resource
    /// delete SUCCEEDS without it (§3b) and the confirm-demand shape
    /// is UNOBSERVED (§3d) — never hard-coded. The 200 body is the
    /// captured [`DeleteOutcome`] (adds `references`). A signature
    /// mismatch answers HTTP 500 + `problem` — see the
    /// [`eam`] module docs for the recorded FINDING (not classified
    /// here; slug decision belongs to 10-03/10-04).
    async fn eam_task_delete(
        &self,
        name: &str,
        signature: &str,
        confirm: bool,
    ) -> Result<DeleteOutcome, CoreError>;
    /// The raw passthrough (09-03, EXT-01): send `call` with its
    /// arbitrary method, caller headers, query pairs, and optional raw
    /// body (ANY method — GET/DELETE bodies allowed, curl parity).
    /// Auth rides [`ReqwestGatewayApi::apply_auth`] (the ONE
    /// `Secret::expose` site — user auth-pattern headers are refused
    /// by [`apicall::refuse_auth_headers`] at the CLI/action layer,
    /// never stripped); classification rides the api-call pipeline
    /// ([`ReqwestGatewayApi::send_and_classify_for_api`]), so an
    /// unclassified gateway 4xx is `GatewayClientError` (exit 2,
    /// verbatim capped body). The 2xx body returns VERBATIM
    /// ([`apicall::ApiCallData`] — `RawValue` passthrough: no field
    /// dropped, no value coerced, key order preserved); a non-JSON
    /// 2xx body is the honest internal-class refusal. The usage
    /// guards live in [`apicall`] and the action layer — BOTH run
    /// them, so in-process callers cannot skip the checks.
    async fn api_call(
        &self,
        call: &apicall::ApiCallRequest,
    ) -> Result<apicall::ApiCallData, CoreError>;
    /// GET `/data/api/v1/licenses` (authed) — the license inventory
    /// (09-04). The wire model is PARTIAL-CURATED: the morning-check
    /// skeleton typed, array elements + `details` passthrough (the
    /// fresh-rig captures answered empty arrays — element shapes are
    /// not capture-proven).
    async fn license_status(&self) -> Result<LicenseStatusWire, CoreError>;
    /// GET `/data/api/v1/redundancy` (authed) — the flat 11-field
    /// redundancy status (09-04). Units are capture-locked at the
    /// model (`uptime` ms-since-start wall-clock-proven; the
    /// `lastSyncTimestamp` `-1` sentinel normalized via
    /// [`redundancy::RedundancyStatusWire::last_sync_epoch_ms`]).
    async fn redundancy_status(&self) -> Result<RedundancyStatusWire, CoreError>;
    /// GET `/data/api/v1/overview/gan` (authed) — the 5-field GAN
    /// summary (09-04); a non-GAN gateway's zero-connection body IS
    /// the canonical capture.
    async fn gan_status(&self) -> Result<GanStatusWire, CoreError>;
    /// POST `/data/api/v1/diagnostics/bundle/generate` (authed, no
    /// body) — start bundle generation (09-05). The 200 body IS the
    /// fresh [`BundleStatusWire`] (live capture:
    /// `{"state":"Generating"}`). Audit-logged server-side.
    async fn bundle_generate(&self) -> Result<BundleStatusWire, CoreError>;
    /// GET `/data/api/v1/diagnostics/bundle/status` (authed) — the
    /// status poll: captured state vocabulary + `fileSize` (bytes,
    /// absent while generating — 09-LIVE-CAPTURES §5).
    async fn bundle_status(&self) -> Result<BundleStatusWire, CoreError>;
    /// GET `/data/api/v1/diagnostics/bundle/download` (authed,
    /// per-request [`diagnostics::BUNDLE_DOWNLOAD_TIMEOUT`] = 300 s —
    /// Pitfall 8: the 30 s client default would truncate MB-sized
    /// bundles) — the ZIP STREAMED to `out` chunk-by-chunk through the
    /// `download_to_file` pipeline (classify-first; NO `Vec<u8>`
    /// anywhere). The `Content-Disposition` filename + `Content-Type`
    /// ride the pipeline's [`ExportMeta`].
    async fn bundle_download(&self, out: &Path) -> Result<ExportMeta, CoreError>;
}

/// Production [`GatewayApi`] over reqwest.
pub struct ReqwestGatewayApi {
    base: url::Url,
    credential: Option<Credential>,
    client: reqwest::Client,
}

impl ReqwestGatewayApi {
    /// Build from a resolved profile (post env-overlay — the dispatch site
    /// owns that precedence) and an optional credential (`None` = proceed
    /// header-less; the gateway's answer is then classified — 401 under
    /// 8.3 default security).
    ///
    /// Timeouts: 10s connect / 30s overall (per-class refinements land in
    /// Phase 2). `ssl_verify = false` accepts invalid certs — dev-rig
    /// only, per-profile, never global.
    pub fn new(profile: &Profile, credential: Option<Credential>) -> Result<Self, CoreError> {
        let client = build_client(profile.ssl_verify)?;
        Ok(Self {
            base: profile.url.clone(),
            credential,
            client,
        })
    }

    /// Test constructor: base URL + credential, no profile needed.
    pub fn for_tests(base_url: &str, credential: Option<Credential>) -> Self {
        Self {
            base: url::Url::parse(base_url).expect("test base URL parses"),
            credential,
            client: build_client(true).expect("test client builds"),
        }
    }

    /// The full request URL for `path` (bases are normalized to a trailing
    /// slash; an absolute path replaces from root).
    fn url_for(&self, path: &str) -> url::Url {
        self.base.join(path).expect("base joins an absolute path")
    }

    /// The auth-header rule in ONE place: token XOR basic XOR neither — a
    /// match, not if/if-else chains. [`Secret::expose`] is called at
    /// exactly this site (the redaction boundary MOVED here in 02-01, not
    /// duplicated).
    ///
    /// Basic carries a loud demotion warning: it cannot authenticate 8.3
    /// `/data` routes (verified: valid commissioned credentials → 401) —
    /// warn once per call, never silently retry (02-RESEARCH Auth §2).
    fn apply_auth(&self, request: reqwest::RequestBuilder) -> reqwest::RequestBuilder {
        let mut request = request;
        match &self.credential {
            Some(Credential::Token(token)) => {
                request = request.header("X-Ignition-API-Token", token.expose());
            }
            Some(Credential::Basic(user, password)) => {
                tracing::warn!(
                    "Basic auth does not authenticate Ignition 8.3 /data routes \
                     (verified: valid credentials → 401); use an API token"
                );
                request = request.basic_auth(user.expose(), Some(password.expose()));
            }
            None => {}
        }
        request
    }

    /// GET `path` (with pre-built query `pairs` when given) → classify →
    /// deserialize into `T`. `auth = false` fetches header-less (the
    /// `/StatusPing` readiness probe, 02-02 — it must work with broken
    /// credentials). Callers build pairs via `to_query_pairs()` so the
    /// param-name mapping stays in the capability files.
    async fn get_json<T: serde::de::DeserializeOwned>(
        &self,
        path: &str,
        pairs: Option<&[(String, String)]>,
        auth: bool,
    ) -> Result<T, CoreError> {
        let url = self.url_for(path);
        let mut request = self.client.get(url.clone());
        if let Some(pairs) = pairs {
            request = request.query(&pairs);
        }
        if auth {
            request = self.apply_auth(request);
        }
        let response = self.send_and_classify(request, &url).await?;
        response.json::<T>().await.map_err(|err| {
            CoreError::Internal(format!(
                "response from {url} did not match the expected shape: {err}"
            ))
        })
    }

    /// GET `path` → classify → read the response as BYTES plus the
    /// `Content-Disposition` filename and `Content-Type` — the
    /// archive-download pipeline (02-04). `timeout` overrides the 30 s
    /// client default PER REQUEST (a large `.idb` archive must not be
    /// truncated) — `RequestBuilder::timeout`, not a second client.
    async fn get_bytes(&self, path: &str, timeout: Duration) -> Result<LogDownload, CoreError> {
        let url = self.url_for(path);
        let request = self.client.get(url.clone()).timeout(timeout);
        let request = self.apply_auth(request);
        let response = self.send_and_classify(request, &url).await?;
        let filename = response
            .headers()
            .get(reqwest::header::CONTENT_DISPOSITION)
            .and_then(|value| value.to_str().ok())
            .and_then(logs::filename_from_content_disposition);
        let content_type = response
            .headers()
            .get(reqwest::header::CONTENT_TYPE)
            .and_then(|value| value.to_str().ok())
            .map(str::to_string);
        let bytes = response.bytes().await.map_err(|err| CoreError::Network {
            url: url.to_string(),
            source: Some(err),
            observation: None,
        })?;
        Ok(LogDownload {
            bytes: bytes.to_vec(),
            filename,
            content_type,
        })
    }

    /// GET `path` → classify → STREAM the body to `out` chunk-by-chunk
    /// — the file-download pipeline (03-02). The response body is
    /// consumed HERE, at a pipeline site, classify-first like every
    /// other: an error answer must classify (never stream), and on
    /// success each `bytes_stream()` chunk goes straight through
    /// `AsyncWriteExt::write_all` into a `tokio::fs::File` — NO
    /// `Vec<u8>` accumulation anywhere (Pitfall 2: a multi-hundred-MB
    /// export ZIP must not buffer in memory). The response metadata
    /// (`Content-Disposition` filename, `Content-Type`) and the
    /// chunk-counted byte total ride out in [`ExportMeta`]. Requires
    /// the workspace `reqwest` `stream` + `tokio` `fs` features (the
    /// research-flagged dep gap this plan closed).
    ///
    /// `accept` adds an OPTIONAL `Accept` header for the callers whose
    /// server contract names one (04-04's gwbk download sends
    /// `application/octet-stream`; the 03-02 export sends none) — a
    /// minimal parameterization that keeps THIS the one streaming
    /// site instead of forking a second copy of the chunk loop.
    async fn download_to_file(
        &self,
        path: &str,
        out: &Path,
        timeout: Duration,
        accept: Option<&str>,
    ) -> Result<ExportMeta, CoreError> {
        use futures_util::StreamExt;
        use tokio::io::AsyncWriteExt;

        let url = self.url_for(path);
        let mut request = self.client.get(url.clone()).timeout(timeout);
        if let Some(accept) = accept {
            request = request.header(reqwest::header::ACCEPT, accept);
        }
        let request = self.apply_auth(request);
        let response = self.send_and_classify(request, &url).await?;
        let filename = response
            .headers()
            .get(reqwest::header::CONTENT_DISPOSITION)
            .and_then(|value| value.to_str().ok())
            .and_then(logs::filename_from_content_disposition);
        let content_type = response
            .headers()
            .get(reqwest::header::CONTENT_TYPE)
            .and_then(|value| value.to_str().ok())
            .map(str::to_string);

        let mut file = tokio::fs::File::create(out).await.map_err(|err| {
            CoreError::Internal(format!("cannot create {}: {err}", out.display()))
        })?;
        let mut stream = response.bytes_stream();
        let mut bytes: u64 = 0;
        while let Some(chunk) = stream.next().await {
            let chunk = chunk.map_err(|err| CoreError::Network {
                url: url.to_string(),
                source: Some(err),
                observation: None,
            })?;
            file.write_all(&chunk).await.map_err(|err| {
                CoreError::Internal(format!("cannot write {}: {err}", out.display()))
            })?;
            bytes += chunk.len() as u64;
        }
        file.flush()
            .await
            .map_err(|err| CoreError::Internal(format!("cannot flush {}: {err}", out.display())))?;
        Ok(ExportMeta {
            filename,
            bytes,
            content_type,
        })
    }

    /// POST `path` with `pairs` as QUERY params and an empty body →
    /// classify → hand back the response (callers read `true`/JSON as
    /// their capability needs). Production callers since 02-04:
    /// `set_logger_level`, `reset_logger_levels` (and 02-05's restart
    /// with `confirm=true`). Token-auth POSTs need NO CSRF (verified
    /// 02-RESEARCH §Auth Model).
    async fn post_empty(
        &self,
        path: &str,
        pairs: &[(&str, String)],
        auth: bool,
    ) -> Result<reqwest::Response, CoreError> {
        let url = self.url_for(path);
        let mut request = self.client.post(url.clone()).query(pairs);
        if auth {
            request = self.apply_auth(request);
        }
        self.send_and_classify(request, &url).await
    }

    /// DELETE `path` with `pairs` as QUERY params (empty body) →
    /// classify → `Ok(())` on any classified success. Token-auth DELETEs
    /// need NO CSRF (verified 02-RESEARCH §Auth Model: CSRF is only for
    /// cookie/session auth); the classified bodies (`{terminated: N}`,
    /// `{message: …}`) are advisory — Ok classification IS the success
    /// contract.
    async fn delete_with_query(
        &self,
        path: &str,
        pairs: &[(&str, String)],
    ) -> Result<(), CoreError> {
        let url = self.url_for(path);
        let mut request = self.client.delete(url.clone()).query(pairs);
        request = self.apply_auth(request);
        self.send_and_classify(request, &url).await.map(|_| ())
    }

    /// POST `path` with a JSON body → classify → hand back the response
    /// (callers read the body as their capability needs; the project
    /// mutations treat Ok classification AS the success contract —
    /// those bodies are unverified LOW, the restart `literal true`
    /// precedent). Token-auth POSTs need NO CSRF (verified
    /// 02-RESEARCH §Auth Model). One of the two body-carrying pipeline
    /// helpers (03-01); serde serializes struct fields in declaration order, so
    /// recorded bodies are deterministic for the wiremock pins.
    async fn post_json<T: serde::Serialize + ?Sized>(
        &self,
        path: &str,
        body: &T,
    ) -> Result<reqwest::Response, CoreError> {
        let url = self.url_for(path);
        let request = self.apply_auth(self.client.post(url.clone()).json(body));
        self.send_and_classify(request, &url).await
    }

    /// POST the action JSON to a webdev route with caller headers +
    /// auth applied, returning `(full URL, response)` — the shared
    /// head of the two webdev seam methods (05-03). NO classify here:
    /// `webdev_route_probe` reads the raw status (the code IS the
    /// answer); `webdev_route_call` classifies downstream. Transport
    /// failures map to `Network` like every pipeline.
    async fn webdev_post_raw(
        &self,
        project: &str,
        route: &str,
        body: &serde_json::Value,
        extra_headers: &[(&str, &str)],
        timeout: Option<Duration>,
    ) -> Result<(String, reqwest::Response), CoreError> {
        let path = webdev::route_url(project, route);
        let url = self.url_for(&path);
        let mut request = self.client.post(url.clone()).json(body);
        if let Some(t) = timeout {
            // Per-request override WITHOUT a second client — the
            // RequestBuilder::timeout pattern (02-04/09-05).
            request = request.timeout(t);
        }
        for (name, value) in extra_headers {
            request = request.header(*name, *value);
        }
        let request = self.apply_auth(request);
        let response = request.send().await.map_err(|err| CoreError::Network {
            url: url.to_string(),
            source: Some(err),
            observation: None,
        })?;
        Ok((url.to_string(), response))
    }

    /// PUT `path` with a JSON body → classify → `Ok(())` (modify/
    /// reparent; resource puts in 03-03). Token-auth PUTs need NO
    /// CSRF. The classify-first rule holds: nothing consumes a body
    /// that skipped classify.
    async fn put_json<T: serde::Serialize + ?Sized>(
        &self,
        path: &str,
        body: &T,
    ) -> Result<(), CoreError> {
        let url = self.url_for(path);
        let request = self.apply_auth(self.client.put(url.clone()).json(body));
        self.send_and_classify(request, &url).await.map(|_| ())
    }

    /// Send + transport-error mapping + [`classify`] — the shared tail of
    /// every pipeline helper. Transport failures (connect/timeout/TLS) →
    /// `Network` (exit 4); everything the gateway ANSWERED goes through
    /// the classifier. Curated traffic: `api_call = false` — the
    /// catch-all cannot fire without the parameter (09-01 Pitfall 1).
    async fn send_and_classify(
        &self,
        request: reqwest::RequestBuilder,
        url: &url::Url,
    ) -> Result<reqwest::Response, CoreError> {
        let response = request.send().await.map_err(|err| CoreError::Network {
            url: url.to_string(),
            source: Some(err),
            observation: None,
        })?;
        classify::classify(response, url.as_ref(), false).await
    }

    /// The api-call-scoped pipeline entry (09-01): identical
    /// transport-error → `Network` mapping, then [`classify`] with
    /// `api_call = true` so an unclassified gateway 4xx maps to
    /// `GatewayClientError` (exit 2, verbatim capped body) instead of
    /// `Internal`. Public because `ign api call`'s action layer (09-03)
    /// is the production consumer and the contract tests
    /// (tests/api_classify_contract.rs) pin the full exit partition
    /// through it — nothing in the curated pipeline switches to it.
    pub async fn send_and_classify_for_api(
        &self,
        request: reqwest::RequestBuilder,
        url: &url::Url,
    ) -> Result<reqwest::Response, CoreError> {
        let response = request.send().await.map_err(|err| CoreError::Network {
            url: url.to_string(),
            source: Some(err),
            observation: None,
        })?;
        classify::classify(response, url.as_ref(), true).await
    }
}

fn build_client(ssl_verify: bool) -> Result<reqwest::Client, CoreError> {
    let mut builder = reqwest::Client::builder()
        // Never follow redirects: an uncommissioned gateway 302s everything
        // to /welcome and the follow would render the wizard HTML as a 200
        // (02-RESEARCH Pitfall 6). classify() maps the 3xx instead.
        .redirect(reqwest::redirect::Policy::none())
        .connect_timeout(Duration::from_secs(10))
        .timeout(Duration::from_secs(30));
    if !ssl_verify {
        builder = builder.danger_accept_invalid_certs(true);
    }
    builder
        .build()
        .map_err(|err| CoreError::Internal(format!("cannot build HTTP client: {err}")))
}

#[async_trait::async_trait]
impl GatewayApi for ReqwestGatewayApi {
    async fn gateway_info(&self) -> Result<GatewayInfo, CoreError> {
        let mut info: GatewayInfo = self.get_json(GATEWAY_INFO_PATH, None, true).await?;
        info.endpoint = Some(self.url_for(GATEWAY_INFO_PATH).to_string());
        Ok(info)
    }

    async fn overview(&self) -> Result<Overview, CoreError> {
        self.get_json(status::OVERVIEW_PATH, None, true).await
    }

    async fn status_ping(&self) -> Result<StatusPing, CoreError> {
        // auth = false — the whole point: the readiness anchor must not
        // depend on credentials (pinned by the wiremock header-absence
        // proof in tests/status_contract.rs).
        self.get_json(status::STATUS_PING_PATH, None, false).await
    }

    async fn modules(
        &self,
        quarantined: bool,
        query: &query::ListQuery,
    ) -> Result<ListEnvelope<ModuleInfo>, CoreError> {
        let path = if quarantined {
            status::MODULES_QUARANTINED_PATH
        } else {
            status::MODULES_HEALTHY_PATH
        };
        self.get_json(path, Some(&query.to_query_pairs()), true)
            .await
    }

    async fn metrics_current(&self) -> Result<CurrentGauges, CoreError> {
        self.get_json(metrics::CURRENT_GAUGES_PATH, None, true)
            .await
    }

    async fn metrics_historic(&self) -> Result<PerformanceCharts, CoreError> {
        self.get_json(metrics::CHARTS_PATH, None, true).await
    }

    async fn metrics_threads(&self) -> Result<ThreadCounts, CoreError> {
        self.get_json(metrics::THREADS_PATH, None, true).await
    }

    async fn designers(
        &self,
        query: &query::ListQuery,
    ) -> Result<ListEnvelope<DesignerInfo>, CoreError> {
        self.get_json(
            sessions::DESIGNERS_PATH,
            Some(&query.to_query_pairs()),
            true,
        )
        .await
    }

    async fn perspective_sessions(
        &self,
        query: &query::ListQuery,
    ) -> Result<ListEnvelope<PerspectiveSession>, CoreError> {
        // The trailing slash is PART OF THE PATH (Pitfall 8) — url_for's
        // join preserves it; the exact-path wiremock matcher in
        // tests/sessions_contract.rs pins it.
        self.get_json(
            sessions::PERSPECTIVE_SESSIONS_LIST_PATH,
            Some(&query.to_query_pairs()),
            true,
        )
        .await
    }

    async fn vision_clients(
        &self,
        query: &query::ListQuery,
    ) -> Result<ListEnvelope<VisionClient>, CoreError> {
        self.get_json(
            sessions::VISION_CLIENTS_PATH,
            Some(&query.to_query_pairs()),
            true,
        )
        .await
    }

    async fn terminate_perspective_session(
        &self,
        id: &str,
        message: Option<&str>,
    ) -> Result<(), CoreError> {
        // sessionId is a QUERY param on the spec's DELETE route — never
        // a body (recorded-request proof in tests/sessions_contract.rs).
        let mut pairs = vec![("sessionId", id.to_string())];
        if let Some(message) = message {
            pairs.push(("message", message.to_string()));
        }
        self.delete_with_query(sessions::PERSPECTIVE_SESSIONS_TERMINATE_PATH, &pairs)
            .await
    }

    async fn terminate_vision_client(&self, id: &str) -> Result<(), CoreError> {
        self.delete_with_query(&sessions::vision_client_terminate_path(id), &[])
            .await
    }

    async fn prune_designer(&self, id: &str) -> Result<(), CoreError> {
        self.delete_with_query(&sessions::designer_prune_path(id), &[])
            .await
    }

    async fn database_connections(&self) -> Result<ListEnvelope<GatewayConnection>, CoreError> {
        // The UI polls the resource list with limit=-1 — same convention
        // as every other list capability.
        self.get_json(
            connections::DATABASE_CONNECTIONS_PATH,
            Some(&query::ListQuery::default().to_query_pairs()),
            true,
        )
        .await
    }

    async fn opc_connections(&self) -> Result<ListEnvelope<GatewayConnection>, CoreError> {
        self.get_json(
            connections::OPC_CONNECTIONS_PATH,
            Some(&query::ListQuery::default().to_query_pairs()),
            true,
        )
        .await
    }

    async fn logs(&self, filter: &LogQuery) -> Result<ListEnvelope<LogEntry>, CoreError> {
        // Explicit limit ALWAYS rides the wire (Pitfall 9) — enforced by
        // LogQuery::to_query_pairs, pinned by the contract test.
        self.get_json(logs::LOGS_PATH, Some(&filter.to_query_pairs()), true)
            .await
    }

    async fn logs_download(&self) -> Result<LogDownload, CoreError> {
        // Per-request timeout override: the 30 s client default would
        // truncate large archives (per-class timeout WITHOUT a second
        // client — RequestBuilder::timeout, 02-RESEARCH §Architecture).
        self.get_bytes(logs::LOGS_DOWNLOAD_PATH, Duration::from_secs(120))
            .await
    }

    async fn loggers(
        &self,
        query: &query::ListQuery,
    ) -> Result<ListEnvelope<LoggerInfo>, CoreError> {
        self.get_json(logs::LOGGERS_PATH, Some(&query.to_query_pairs()), true)
            .await
    }

    async fn set_logger_level(&self, logger: &str, level: &str) -> Result<(), CoreError> {
        // `level` rides the QUERY string against an EMPTY body (verified
        // live: 200 + the level flips; recorded-request proof in
        // tests/logs_contract.rs).
        self.post_empty(
            &logs::logger_set_path(logger),
            &[("level", level.to_string())],
            true,
        )
        .await
        .map(|_| ())
    }

    async fn reset_logger_levels(&self) -> Result<(), CoreError> {
        self.post_empty(logs::LEVEL_RESET_PATH, &[], true)
            .await
            .map(|_| ())
    }

    async fn restart(&self) -> Result<(), CoreError> {
        // `confirm=true` rides the QUERY string against an empty body
        // (the verified shape; recorded-request proof in
        // tests/restart_wait_contract.rs). Token-auth POSTs need no
        // CSRF (02-RESEARCH §Auth Model).
        let response = self
            .post_empty(
                restart::RESTART_PATH,
                &[("confirm", "true".to_string())],
                true,
            )
            .await?;
        // Success-shape drift guard: the verified body is the literal
        // `true`. Any other 2xx body still means the POST was accepted
        // — warn, don't fail (the wait half reports what happens next).
        let body = response.text().await.unwrap_or_default();
        if body.trim() != "true" {
            tracing::warn!(
                body = %body,
                "restart POST answered an unexpected 2xx body (expected the literal `true`)"
            );
        }
        Ok(())
    }

    async fn scan_projects(&self) -> Result<(), CoreError> {
        self.post_empty(restart::SCAN_PROJECTS_PATH, &[], true)
            .await
            .map(|_| ())
    }

    async fn security_properties(&self) -> Result<SecurityProperties, CoreError> {
        self.get_json(restart::SECURITY_PROPERTIES_PATH, None, true)
            .await
    }

    async fn webdev_route_status(&self, route: &str) -> Result<u16, CoreError> {
        // The raw-status probe: send, surface the status code, never
        // classify (404 vs 200/401/403 is the ANSWER, not an error).
        // Only transport failures (DNS/refused/timeout) error out.
        let path = restart::webdev_route_path(route);
        let url = self.url_for(&path);
        let request = self.apply_auth(self.client.get(url.clone()));
        let response = request.send().await.map_err(|err| CoreError::Network {
            url: url.to_string(),
            source: Some(err),
            observation: None,
        })?;
        Ok(response.status().as_u16())
    }

    async fn webdev_route_call(
        &self,
        project: &str,
        route: &str,
        body: &serde_json::Value,
        extra_headers: &[(&str, &str)],
    ) -> Result<serde_json::Value, CoreError> {
        // classify() runs normally for transport/status errors; the
        // 200 BODY is then the route envelope — WebDev ignores
        // `status`, so denials ride HTTP 200 and the body verdict is
        // the ONLY success oracle (never the status line alone).
        let (url, response) = self
            .webdev_post_raw(project, route, body, extra_headers, None)
            .await?;
        let response = classify::classify(response, &url, false).await?;
        let text = response.text().await.unwrap_or_default();
        match webdev::parse_route_body(&text)? {
            RouteBody::Ok(data) => Ok(data),
            RouteBody::Denied {
                code,
                message,
                traceback,
            } => Err(webdev::denial_to_error(
                &code,
                &message,
                traceback.as_deref(),
                url,
            )),
        }
    }

    async fn webdev_route_call_with_timeout(
        &self,
        project: &str,
        route: &str,
        body: &serde_json::Value,
        extra_headers: &[(&str, &str)],
        timeout: Duration,
    ) -> Result<serde_json::Value, CoreError> {
        // The SAME classify + envelope-parse tail as
        // `webdev_route_call` — the ONLY delta is the per-request
        // ceiling (behavior-identical request semantics).
        let (url, response) = self
            .webdev_post_raw(project, route, body, extra_headers, Some(timeout))
            .await?;
        let response = classify::classify(response, &url, false).await?;
        let text = response.text().await.unwrap_or_default();
        match webdev::parse_route_body(&text)? {
            RouteBody::Ok(data) => Ok(data),
            RouteBody::Denied {
                code,
                message,
                traceback,
            } => Err(webdev::denial_to_error(
                &code,
                &message,
                traceback.as_deref(),
                url,
            )),
        }
    }

    async fn webdev_route_probe(
        &self,
        project: &str,
        route: &str,
        extra_headers: &[(&str, &str)],
    ) -> Result<RouteProbe, CoreError> {
        // NOT classified — the status code IS the answer (the
        // webdev_route_status precedent): 405/402/401 discriminate
        // presence/licensing/gating, and a 200 body carries the
        // version handshake or the structured denial.
        let (url, response) = self
            .webdev_post_raw(
                project,
                route,
                &serde_json::json!({"action": "version"}),
                extra_headers,
                None,
            )
            .await?;
        let status = response.status();
        if status.is_success() {
            let text = response.text().await.unwrap_or_default();
            return match webdev::parse_route_body(&text)? {
                RouteBody::Ok(data) => {
                    let route_version = data
                        .get("routeVersion")
                        .and_then(serde_json::Value::as_str)
                        .map(str::to_string)
                        .ok_or_else(|| {
                            CoreError::Internal(format!(
                                "webdev route version action from {url} answered no routeVersion"
                            ))
                        })?;
                    Ok(RouteProbe::Present { route_version })
                }
                RouteBody::Denied {
                    code,
                    message,
                    traceback,
                } => Ok(RouteProbe::Denied {
                    code,
                    message,
                    traceback,
                }),
            };
        }
        match status.as_u16() {
            401 | 403 => Ok(RouteProbe::AuthGated),
            402 => Ok(RouteProbe::Unlicensed),
            405 => Ok(RouteProbe::Absent),
            // Shapes the enum has no variant for (wizard redirects,
            // mid-restart 503s, foreign 404s) — reuse classify's
            // status mappings verbatim; every non-success response
            // classifies to Err, and the Ok arm is unreachable by
            // construction (all 2xx took the body branch above).
            _ => match classify::classify(response, &url, false).await {
                Err(err) => Err(err),
                Ok(_) => Err(CoreError::Internal(format!(
                    "unexpected HTTP {status} from webdev route probe at {url}"
                ))),
            },
        }
    }

    async fn projects(
        &self,
        query: &query::ListQuery,
    ) -> Result<ListEnvelope<ProjectRecord>, CoreError> {
        // Standard list params (limit=-1 = the UI's "everything").
        self.get_json(
            projects::PROJECTS_LIST_PATH,
            Some(&query.to_query_pairs()),
            true,
        )
        .await
    }

    async fn project_find(&self, name: &str) -> Result<ProjectRecord, CoreError> {
        // The {name} segment is percent-encoded (Pitfall 6) — the
        // spaced-name recorded-request proof in tests/projects_contract.rs.
        self.get_json(&projects::project_find_path(name), None, true)
            .await
    }

    async fn project_create(&self, body: &ProjectCreate) -> Result<(), CoreError> {
        // Ok classification IS the success contract; callers that want
        // data re-`find` (the actions layer's read-back).
        self.post_json(projects::PROJECTS_CREATE_PATH, body)
            .await
            .map(|_| ())
    }

    async fn project_copy(&self, from: &str, to: &str) -> Result<(), CoreError> {
        let body = ProjectCopy {
            from_name: from.to_string(),
            to_name: to.to_string(),
        };
        self.post_json(projects::PROJECTS_COPY_PATH, &body)
            .await
            .map(|_| ())
    }

    async fn project_rename(&self, name: &str, new_name: &str) -> Result<(), CoreError> {
        let body = ProjectRenameBody {
            name: new_name.to_string(),
        };
        self.post_json(&projects::project_rename_path(name), &body)
            .await
            .map(|_| ())
    }

    async fn project_modify(&self, name: &str, body: &ProjectModify) -> Result<(), CoreError> {
        self.put_json(&projects::project_modify_path(name), body)
            .await
    }

    async fn project_delete(&self, name: &str) -> Result<(), CoreError> {
        // BOTH guard layers (Pitfall 8): the CLI already refused
        // without --yes (exit 2, pre-resolution) AND the wire request
        // always carries the server's own `confirm=true` query param
        // (wiremock recorded-request proof).
        self.delete_with_query(
            &projects::project_delete_path(name),
            &[("confirm", "true".to_string())],
        )
        .await
    }

    async fn project_export_to_file(
        &self,
        name: &str,
        out: &Path,
    ) -> Result<ExportMeta, CoreError> {
        // The 120 s per-request override rides the RequestBuilder (the
        // logs-download precedent); the streaming itself lives in
        // download_to_file (classify FIRST, then chunk loop). No
        // `Accept` header — the export contract never named one.
        self.download_to_file(
            &projects::project_export_path(name),
            out,
            projects::PROJECT_EXPORT_TIMEOUT,
            None,
        )
        .await
    }

    async fn project_import(
        &self,
        name: &str,
        zip: Vec<u8>,
        overwrite: bool,
    ) -> Result<ImportOutcome, CoreError> {
        // `overwrite` rides the QUERY string; the ZIP is the RAW body
        // with Content-Type application/zip and a known Content-Length
        // (Vec<u8> — chunked encoding never enters the picture). The
        // 300 s per-request override owns Pitfall 3. Token-auth POSTs
        // need no CSRF (02-RESEARCH §Auth Model).
        let url = self.url_for(&projects::project_import_path(name));
        let request = self
            .client
            .post(url.clone())
            .timeout(projects::PROJECT_IMPORT_TIMEOUT)
            .query(&[("overwrite", if overwrite { "true" } else { "false" })])
            .header(reqwest::header::CONTENT_TYPE, "application/zip")
            .body(zip);
        let request = self.apply_auth(request);
        let response = self.send_and_classify(request, &url).await?;
        // Opaque-success: parse the body when it is a JSON OBJECT,
        // else the fallback object (the body is unverified MEDIUM —
        // restart's `literal true` is the same family and normalizes
        // the same way, so agents always see a stable object shape).
        let body = response.text().await.unwrap_or_default();
        let parsed = serde_json::from_str::<serde_json::Value>(body.trim())
            .ok()
            .filter(|value| value.is_object())
            .unwrap_or_else(|| serde_json::json!({"status": "success"}));
        // Denial honesty (05-07, UAT Gap 1): the gateway refuses
        // imports over HTTP 200 with {success:false, problem} —
        // live-witnessed while NOTHING landed. ONE seam here fixes
        // every import caller at once (resource put/delete, project
        // import, webdev deploy) — per-caller checks are forbidden;
        // this IS the contract (the WebDev 200-denial precedent
        // applied to the import family).
        if let Some(problem) = projects::import_denied(&parsed) {
            return Err(CoreError::ImportDenied {
                project: name.to_string(),
                problem,
                endpoint: Some(url.to_string()),
            });
        }
        Ok(ImportOutcome { response: parsed })
    }

    async fn tag_provider_list(
        &self,
        query: &query::ListQuery,
    ) -> Result<ListEnvelope<TagProviderRecord>, CoreError> {
        // Standard list params (limit=-1 = the UI's "everything") —
        // the connections-family resource lists' exact shape.
        self.get_json(
            tags::TAG_PROVIDERS_LIST_PATH,
            Some(&query.to_query_pairs()),
            true,
        )
        .await
    }

    async fn tag_provider_find(&self, name: &str) -> Result<TagProviderRecord, CoreError> {
        self.get_json(&tags::tag_provider_find_path(name), None, true)
            .await
    }

    async fn tag_provider_create(&self, body: &[TagProviderCreate]) -> Result<(), CoreError> {
        // The ARRAY body is the wire contract (a bare object 400s);
        // serde serializes elements in declaration order so the
        // recorded body is deterministic. Ok classification IS the
        // success contract (the project-create precedent).
        self.post_json(tags::TAG_PROVIDERS_CREATE_PATH, body)
            .await
            .map(|_| ())
    }

    async fn tag_provider_delete(&self, name: &str, signature: &str) -> Result<(), CoreError> {
        // The signature rides the PATH (from find) — the
        // live-proven delete-by-signature chain; both segments
        // percent-encoded through the ONE locked encoder.
        self.delete_with_query(&tags::tag_provider_delete_path(name, signature), &[])
            .await
    }

    async fn trial_status_wire(&self) -> Result<TrialWire, CoreError> {
        // Conditional auth: the endpoints answer unauthenticated
        // (live-verified both rigs), so a header-less client degrades
        // cleanly — but a carried credential rides along harmlessly
        // (future-proofing if a gateway version starts gating them).
        let auth = self.credential.is_some();
        self.get_json(trial::TRIAL_PATH, None, auth).await
    }

    async fn banners(&self) -> Result<BannerSet, CoreError> {
        let auth = self.credential.is_some();
        self.get_json(trial::BANNERS_PATH, None, auth).await
    }

    async fn trial_reset_wire(&self) -> Result<TrialWire, CoreError> {
        // Empty body, authed POST (the UI mutation's exact shape —
        // decompiled ia-gateway.js: {method:"POST",
        // url:"/data/api/v1/trial"}). Token-auth POSTs need no CSRF
        // (02-RESEARCH §Auth Model); on 403 the tier-1 session+CSRF
        // flow takes over (actions layer owns the ladder).
        let response = self.post_empty(trial::TRIAL_PATH, &[], true).await?;
        let body = response.text().await.unwrap_or_default();
        serde_json::from_str(&body).map_err(|err| {
            CoreError::Internal(format!(
                "trial reset response did not match the trial shape: {err}"
            ))
        })
    }

    async fn backup_download(
        &self,
        out: &Path,
        backup_type: backup::BackupType,
    ) -> Result<ExportMeta, CoreError> {
        // Pure reuse: the type query rides the path builder, the
        // Accept header rides the helper's optional param, and the
        // 300 s class rides the RequestBuilder — the 03-02 chunk loop
        // stays THE one streaming body-consumption site (04-04).
        self.download_to_file(
            &backup::backup_download_path(backup_type),
            out,
            backup::BACKUP_TIMEOUT,
            Some(backup::BACKUP_ACCEPT),
        )
        .await
    }

    async fn backup_restore(&self, gwbk: &Path) -> Result<(), CoreError> {
        // The upload direction buffers BY DESIGN (the import
        // precedent: a known Content-Length raw body sidesteps the
        // chunked-encoding question entirely). Token-auth POSTs need
        // no CSRF (02-RESEARCH §Auth Model). Ok classification IS the
        // acceptance contract — the actions layer owns the
        // post-restore RUNNING wait (Pitfall 6: the gateway restarts
        // after answering).
        let body = tokio::fs::read(gwbk)
            .await
            .map_err(|err| CoreError::InvalidInput {
                reason: format!("cannot read {}: {err}", gwbk.display()),
            })?;
        let url = self.url_for(backup::BACKUP_PATH);
        let request = self
            .client
            .post(url.clone())
            .timeout(backup::BACKUP_TIMEOUT)
            .query(&backup::restore_query())
            .header(reqwest::header::CONTENT_TYPE, "application/octet-stream")
            .body(body);
        let request = self.apply_auth(request);
        self.send_and_classify(request, &url).await.map(|_| ())
    }

    async fn eam_task_history(
        &self,
        limit: Option<u32>,
        search: Option<&str>,
    ) -> Result<ListEnvelope<EamHistoryItem>, CoreError> {
        let query = query::ListQuery {
            limit: limit
                .map(i64::from)
                .unwrap_or(eam::EAM_HISTORY_DEFAULT_LIMIT),
            search: search.map(str::to_string),
            ..query::ListQuery::default()
        };
        self.get_json(eam::EAM_HISTORY_PATH, Some(&query.to_query_pairs()), true)
            .await
    }

    async fn eam_task_definitions(&self) -> Result<ListEnvelope<EamTaskRecord>, CoreError> {
        // Standard list params (limit=-1 = the UI's "everything") —
        // definition counts are small; the connections-family
        // resource lists' exact shape.
        self.get_json(
            &eam::eam_tasks_list_path(),
            Some(&query::ListQuery::default().to_query_pairs()),
            true,
        )
        .await
    }

    async fn eam_task_find(&self, name: &str) -> Result<EamTaskRecord, CoreError> {
        self.get_json(&eam::eam_task_find_path(name), None, true)
            .await
    }

    async fn eam_task_create(&self, definition: &serde_json::Value) -> Result<(), CoreError> {
        // The ARRAY body is the wire contract (a bare object 400s —
        // the tag-provider create precedent); the caller's composed
        // definition rides as the single element. Ok classification
        // IS the success contract.
        self.post_json(&eam::eam_tasks_create_path(), &[definition])
            .await
            .map(|_| ())
    }

    async fn eam_task_force(&self, owner: &str, name: &str) -> Result<(), CoreError> {
        // Empty body, authed POST — 204 is the live-proven success
        // shape; classify()'s 2xx pass-through IS the oracle (any
        // 2xx = dispatched; outcomes land in history as data).
        self.post_empty(&eam::eam_force_path(owner, name), &[], true)
            .await
            .map(|_| ())
    }

    async fn eam_task_suspend(&self, name: &str) -> Result<(), CoreError> {
        // Empty body, authed POST — 204 is the captured success shape
        // (10-LIVE-CAPTURES §1b/§1c); the suspend/resume failure
        // modes are 500 HTML (classify → Internal with the page's
        // message — the module-doc finding; no 404 exists here).
        self.post_empty(&eam::eam_task_suspend_path(name), &[], true)
            .await
            .map(|_| ())
    }

    async fn eam_task_resume(&self, name: &str) -> Result<(), CoreError> {
        // Same shape as suspend: 204 success (§1b/§1d — resume of a
        // never-suspended task is ALSO a 204; idempotent wire).
        self.post_empty(&eam::eam_task_resume_path(name), &[], true)
            .await
            .map(|_| ())
    }

    async fn eam_task_cancel(&self, name: &str) -> Result<(), CoreError> {
        // 204 whether a pending execution existed, the task has
        // nothing pending, or the name is unknown (§7) — cancel is
        // wire-idempotent; name validation is the actions layer's
        // find-before-write job.
        self.post_empty(&eam::eam_task_cancel_path(name), &[], true)
            .await
            .map(|_| ())
    }

    async fn eam_tasks_scheduled(&self, running: bool) -> Result<Vec<EamScheduledTask>, CoreError> {
        // The standard {items, metadata} envelope (§2 — byte-identical
        // shape across both rigs, incl. the empty-list quiet body);
        // this method unwraps the envelope to the items.
        let envelope: query::ListEnvelope<EamScheduledTask> = self
            .get_json(&eam::eam_tasks_scheduled_path(running), None, true)
            .await?;
        Ok(envelope.items)
    }

    async fn eam_task_modify(
        &self,
        definition: &serde_json::Value,
    ) -> Result<Option<ModifyOutcome>, CoreError> {
        // The ARRAY body is the wire contract (single element — the
        // §6a capture; a bare object is not the shape the resource
        // PUT family speaks). The classify-first rule holds, then the
        // captured 200 body parses into ModifyOutcome (None = a 2xx
        // that carried no body — the lenient `Option` per the plan).
        let url = self.url_for(&eam::eam_tasks_modify_path());
        let request = self.apply_auth(self.client.put(url.clone()).json(&[definition]));
        let response = self.send_and_classify(request, &url).await?;
        let text = response.text().await.unwrap_or_default();
        if text.trim().is_empty() {
            return Ok(None);
        }
        serde_json::from_str(&text).map(Some).map_err(|err| {
            CoreError::Internal(format!(
                "response from {url} did not match the expected shape: {err}"
            ))
        })
    }

    async fn eam_task_delete(
        &self,
        name: &str,
        signature: &str,
        confirm: bool,
    ) -> Result<DeleteOutcome, CoreError> {
        // `collection=core` ALWAYS (the captured success value — the
        // type token 404s, §3c); `confirm=true` rides ONLY on
        // explicit opt-in (a lone-resource delete succeeds without
        // it, §3b; the confirm-demand shape is unobserved, §3d —
        // never hard-coded). The 200 body is the captured
        // DeleteOutcome; classify-first as everywhere.
        let url = self.url_for(&eam::eam_task_delete_path(name, signature));
        let mut pairs: Vec<(&str, String)> = vec![("collection", "core".to_string())];
        if confirm {
            pairs.push(("confirm", "true".to_string()));
        }
        let request = self.apply_auth(self.client.delete(url.clone()).query(&pairs));
        let response = self.send_and_classify(request, &url).await?;
        let text = response.text().await.unwrap_or_default();
        serde_json::from_str(&text).map_err(|err| {
            CoreError::Internal(format!(
                "response from {url} did not match the expected shape: {err}"
            ))
        })
    }

    async fn api_call(
        &self,
        call: &apicall::ApiCallRequest,
    ) -> Result<apicall::ApiCallData, CoreError> {
        let url = self.url_for(&call.path);
        // Any RFC verb (lowercase input normalized); an unparseable
        // method is a usage-class refusal BEFORE the wire — reqwest's
        // own `Method` parse is the validator (no hand-rolled list).
        let method =
            reqwest::Method::from_bytes(call.method.to_uppercase().as_bytes()).map_err(|_| {
                CoreError::InvalidInput {
                    reason: format!(
                        "{:?} is not a valid HTTP method — use an RFC verb \
                     (GET/POST/PUT/DELETE/PATCH/HEAD, …)",
                        call.method
                    ),
                }
            })?;
        let mut request = self.client.request(method, url.clone());
        for (name, value) in &call.headers {
            // reqwest's `.header()` PANICS on an invalid name/value —
            // these strings are user-supplied, so they are validated
            // HERE: a bad header is an exit-2 refusal, never a crash
            // (the webdev extra_headers loop never carried raw user
            // input; this one does).
            let name =
                reqwest::header::HeaderName::from_bytes(name.trim().as_bytes()).map_err(|_| {
                    CoreError::InvalidInput {
                        reason: format!("{name:?} is not a valid HTTP header name"),
                    }
                })?;
            let value = reqwest::header::HeaderValue::from_str(value).map_err(|_| {
                CoreError::InvalidInput {
                    reason: format!("{value:?} is not a valid HTTP header value"),
                }
            })?;
            request = request.header(name, value);
        }
        // The ONE query mechanism: reqwest's own serializer (the same
        // `.query(&pairs)` shape every other capability uses) — never
        // a `?` smuggled through the path (validate_path refuses it).
        if !call.query.is_empty() {
            request = request.query(&call.query);
        }
        if let Some(body) = &call.body {
            // Raw TEXT on ANY method — GET/DELETE body passthrough is
            // allowed (curl parity; the gateway's answer classifies).
            request = request.body(body.clone());
        }
        // THE auth site: profile credentials only (the redaction
        // boundary); the pipeline tail is the api-call-scoped
        // classifier so unclassified gateway 4xx ride
        // GatewayClientError instead of Internal.
        let request = self.apply_auth(request);
        let response = self.send_and_classify_for_api(request, &url).await?;
        let status = response.status().as_u16();
        let text = response.text().await.map_err(|err| CoreError::Network {
            url: url.to_string(),
            source: Some(err),
            observation: None,
        })?;
        // THE verbatim decision (research OQ1): `from_string` both
        // preserves the gateway's bytes (key order, unknown fields)
        // AND validates JSON in one call — no parse-re-serialize. A
        // non-JSON 2xx body is the documented internal-class honesty
        // refusal (binary endpoints ride the download pipelines).
        let data = serde_json::value::RawValue::from_string(text).map_err(|err| {
            CoreError::Internal(format!(
                "the gateway answered 2xx with a non-JSON body — api call returns \
                 JSON; use logs/backup downloads for binary endpoints ({err})"
            ))
        })?;
        Ok(apicall::ApiCallData { status, data })
    }

    async fn license_status(&self) -> Result<LicenseStatusWire, CoreError> {
        // auth = true — a /data route under 8.3 default security (the
        // gateway-info rule); the capture session rode a token header.
        self.get_json(license::LICENSES_PATH, None, true).await
    }

    async fn redundancy_status(&self) -> Result<RedundancyStatusWire, CoreError> {
        self.get_json(redundancy::REDUNDANCY_PATH, None, true).await
    }

    async fn gan_status(&self) -> Result<GanStatusWire, CoreError> {
        self.get_json(gan::GAN_OVERVIEW_PATH, None, true).await
    }

    async fn bundle_generate(&self) -> Result<BundleStatusWire, CoreError> {
        // Empty body, authed POST (the restart/set-logger precedent;
        // token mutations need no CSRF). The 200 body IS the status
        // wire per capture ({"state":"Generating"}) — classify-first
        // through the shared pipeline, then parse.
        let url = self.url_for(diagnostics::DIAGNOSTICS_GENERATE_PATH);
        let response = self
            .send_and_classify(self.apply_auth(self.client.post(url.clone())), &url)
            .await?;
        response.json::<BundleStatusWire>().await.map_err(|err| {
            CoreError::Internal(format!(
                "response from {url} did not match the expected shape: {err}"
            ))
        })
    }

    async fn bundle_status(&self) -> Result<BundleStatusWire, CoreError> {
        // auth = true — a /data route under 8.3 default security; the
        // capture session rode a token header.
        self.get_json(diagnostics::DIAGNOSTICS_STATUS_PATH, None, true)
            .await
    }

    async fn bundle_download(&self, out: &Path) -> Result<ExportMeta, CoreError> {
        // The 300 s per-request override rides the RequestBuilder
        // inside download_to_file (Pitfall 8: the 30 s client default
        // would truncate MB-sized bundles); the chunk loop stays THE
        // one streaming body-consumption site. No Accept header — the
        // capture named none (Content-Type: application/zip is the
        // answer). Disposition filename + content type ride ExportMeta.
        self.download_to_file(
            diagnostics::DIAGNOSTICS_DOWNLOAD_PATH,
            out,
            diagnostics::BUNDLE_DOWNLOAD_TIMEOUT,
            None,
        )
        .await
    }
}

#[cfg(test)]
mod tests {
    use super::ReqwestGatewayApi;

    /// Exercises `post_empty` end-to-end with the shape 02-04's
    /// set-logger-level route uses (query param + empty body): the
    /// verified restart shape is a 200 with literal body `true`,
    /// classified Ok — and the query param rides the request.
    #[tokio::test]
    async fn post_empty_sends_query_param_and_empty_body() {
        let server = wiremock::MockServer::start().await;
        let guard = wiremock::Mock::given(wiremock::matchers::method("POST"))
            .and(wiremock::matchers::path(
                "/data/api/v1/restart-tasks/restart",
            ))
            .and(wiremock::matchers::query_param("confirm", "true"))
            .respond_with(wiremock::ResponseTemplate::new(200).set_body_string("true"))
            .expect(1)
            .mount_as_scoped(&server)
            .await;

        let api = ReqwestGatewayApi::for_tests(&server.uri(), None);
        let response = api
            .post_empty(
                "/data/api/v1/restart-tasks/restart",
                &[("confirm", "true".to_string())],
                true,
            )
            .await
            .expect("200 classifies Ok");
        assert_eq!(response.status(), reqwest::StatusCode::OK);

        let requests = guard.received_requests().await;
        assert_eq!(requests.len(), 1);
        assert!(
            requests[0].body.is_empty(),
            "the POST carries NO body — params ride the query string"
        );
    }
}