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
//! Typed error taxonomy — THE exit-code contract for `ign`.
//!
//! The mapping error-class → exit code is LOCKED (Phase-1 API freeze). The
//! table exists in exactly two places: [`CoreError::exit_code`] here and the
//! README — kept in sync by the `exit_code_mapping_enumerated` unit test and
//! the golden-file tests in `crates/ignition-cli/tests/`.
//!
//! | exit | class          | slugs
//! |------|----------------|-----------------------------------------------
//! | 1    | internal       | `internal`
//! | 2    | usage          | `confirmation_required`, `invalid_import_file`, `invalid_input`, `gateway_client_error` (09-01) (clap renders its own usage errors — never hook clap)
//! | 3    | config         | `profile_not_found`, `no_active_profile`, `secret_unavailable`, `config_invalid`, `poll_interval_too_small` (08-01)
//! | 4    | network        | `network_error`
//! | 5    | auth           | `auth_rejected`
//! | 6    | target_state   | `gateway_too_old`, `gateway_not_commissioned`, `gateway_restarting`, `not_found`, `project_exists`, `resource_binary`, `trial_not_expired` (04-03), `provider_not_found` (05-04), `routes_not_deployed`, `webdev_unlicensed`, `route_version_mismatch`, `webdev_route_error` (05-03), `tag_collision` (05-05), `alarm_journal_missing` (05-06), `import_denied` (05-07), `session_not_prunable` (06-07), `eam_not_controller` (07-02), `eam_task_type_refused` (07-02), `eam_task_in_flight` (07-06), `script_exec_not_configured` (07-03), `lint_tool_absent` (07-04), `provider_root_unsupported` (07-06), `bundle_not_available` (09-07)
//! | 7    | rig            | `rig_error` (reserved — first used in Phase 4)
//!
//! Slugs are public contract: never respell them. Exit codes are public
//! contract: never renumber them (the enumerated test guards both).

use serde::Serialize;

/// The `ign tui` TTY-refusal reason (06-07). The InvalidInput hint is
/// content-addressed off this exact string: the frozen taxonomy keeps
/// ONE usage-input variant (no hint field, no new variant), but the
/// TTY refusal's fix is terminal-related, not `--file`/stdin —
/// [`CoreError::hint`] special-cases this one reason while every other
/// raise site keeps the resource-put default. Construct via
/// [`CoreError::tui_tty_refusal`] so the reason/hint pair cannot drift.
pub const TUI_TTY_REFUSAL_REASON: &str = "ign tui requires a terminal (stdout is not a TTY)";

/// The TAGS-12 loss-gate refusal reason prefix (11-07 gap closure). The
/// InvalidInput hint is content-addressed off this literal: the loss
/// gate's reason is DYNAMIC prose (the CLI's `render_loss_prose` header
/// `loss report ({label}): …` plus per-fact lines), so unlike
/// [`TUI_TTY_REFUSAL_REASON`] the sentinel cannot be the whole reason —
/// it is the stable header prefix instead. Same slug (`invalid_input`),
/// same exit 2 (frozen taxonomy; only the hint differs) — the 06-07
/// TTY-refusal pattern at one removal. The contract_tags loss-gate
/// pins are the drift guard: if the prose header ever changes, the
/// hint silently regresses to the generic default and those pins fail.
pub const LOSS_GATE_REFUSAL_REASON_PREFIX: &str = "loss report (";

/// The api-call catch-all's body cap (09-01): a gateway 4xx body rides
/// [`CoreError::GatewayClientError`] VERBATIM up to this many bytes; a
/// larger body is truncated at [`truncate_api_body`] with the explicit
/// [`GATEWAY_CLIENT_BODY_TRUNCATION_MARKER`]. 4 KiB is the plan-locked
/// cap — an unbounded passthrough would let a pathological gateway
/// page flood the agent's envelope.
pub const GATEWAY_CLIENT_BODY_CAP_BYTES: usize = 4096;

/// The truncation marker [`truncate_api_body`] appends when the api-call
/// body exceeds [`GATEWAY_CLIENT_BODY_CAP_BYTES`]. ASCII-pinned (no
/// multi-byte characters) so golden-file consumers never see an encoding
/// surprise at the cut.
pub const GATEWAY_CLIENT_BODY_TRUNCATION_MARKER: &str = "... [truncated]";

/// The ONE construction site for a capped api-call body: returns `body`
/// verbatim when it fits [`GATEWAY_CLIENT_BODY_CAP_BYTES`], otherwise its
/// first cap bytes (on a UTF-8 char boundary) plus
/// [`GATEWAY_CLIENT_BODY_TRUNCATION_MARKER`]. The variant always carries
/// its final form — construction cannot forget the cap.
pub fn truncate_api_body(body: &str) -> String {
    if body.len() <= GATEWAY_CLIENT_BODY_CAP_BYTES {
        return body.to_string();
    }
    let mut end = GATEWAY_CLIENT_BODY_CAP_BYTES;
    while !body.is_char_boundary(end) {
        end -= 1;
    }
    let mut truncated = body[..end].to_string();
    truncated.push_str(GATEWAY_CLIENT_BODY_TRUNCATION_MARKER);
    truncated
}

/// Every failure `ign` can report. One variant per contract class; `code()`,
/// `exit_code()`, `hint()` are total functions over it.
#[derive(Debug, thiserror::Error)]
pub enum CoreError {
    /// Unexpected runtime failure — the catch-all; report as a bug. Exit 1.
    #[error("internal error: {0}")]
    Internal(String),

    /// Destructive operation invoked without `--yes`. Exit 2 (same class as
    /// usage: it names a flag the caller must add; clap renders its own
    /// usage errors with its exit 2 — never hook clap).
    #[error("{operation} is destructive; rerun with --yes to confirm")]
    ConfirmationRequired { operation: String },

    /// An import byte source the caller must fix (wrong file, too big,
    /// unreadable). Exit 2 — usage class: it names what the CALLER must
    /// change, like [`Self::ConfirmationRequired`] (03-02).
    #[error("invalid import file: {reason}")]
    InvalidImportFile { reason: String },

    /// The gateway ANSWERED the import POST with HTTP 200 but the
    /// body says `{"success": false, "problem": "…"}` — the
    /// denial-rides-200 class the WebDev family handles (05-01)
    /// applied to the project-import family (05-07, UAT Gap 1):
    /// without this check the import caller reports ok while nothing
    /// landed. Exit 6 — target state: the gateway refused the
    /// import (the problem text names why, verbatim).
    #[error("gateway rejected the project import for {project:?}: {problem}")]
    ImportDenied {
        /// The project the import was headed for.
        project: String,
        /// The gateway's own `problem` text (verbatim when present).
        problem: String,
        /// URL of the import request, when known.
        endpoint: Option<String>,
    },

    /// A command input the caller must fix (unreadable `--file`, failed
    /// stdin read). Exit 2 — usage class, the generic sibling of
    /// [`Self::InvalidImportFile`] (03-03: `resource put`'s byte
    /// source).
    #[error("invalid input: {reason}")]
    InvalidInput { reason: String },

    /// Named profile absent from config. Exit 3.
    #[error("profile {name:?} not found (known profiles: {known:?})")]
    ProfileNotFound { name: String, known: Vec<String> },

    /// No `--profile`, no `IGNITION_PROFILE`, no active profile in config.
    /// Exit 3. Constructible from the CLI once config resolution lands
    /// (01-03); the taxonomy is complete on day one.
    #[error("no active profile configured")]
    NoActiveProfile,

    /// No credential resolvable for the profile (env, token_env, keyring all
    /// missed or failed). Exit 3.
    #[error("secret unavailable for profile {profile:?}")]
    SecretUnavailable { profile: String },

    /// Config file unreadable or wrong shape. Exit 3.
    #[error("invalid configuration: {reason}")]
    ConfigInvalid { reason: String },

    /// A profile's `poll_interval_secs` is below the 1-second floor
    /// (08-01, TUIX-05 clamp): sub-second gateway polling is refused at
    /// load time — the TUI's background refresh cadence may not hammer
    /// the gateway. Exit 3 — the CONFIG class (the Phase-7 additive-slug
    /// precedent, e.g. `eam_not_controller`: same exit class, own slug,
    /// never a new exit code — the 1–7 taxonomy is frozen).
    #[error("profile {profile:?}: poll_interval_secs must be >= 1 (sub-second polling refused)")]
    PollIntervalTooSmall {
        /// The profile carrying the refused value.
        profile: String,
    },

    /// Gateway unreachable / timeout / TLS failure. Exit 4.
    ///
    /// `source: None` marks a POLL deadline expiry (02-04 `poll.rs`):
    /// same class, same slug (`network_error`), no new variant — the
    /// transport-error `source` a real failure carries is simply
    /// absent, and `url` describes what was being waited on instead
    /// (the poll's subject). The deadline's last observation rides
    /// `observation` (09-07): when it is `Some` the gateway ANSWERED
    /// with a concrete state, and the message leads with "no terminal
    /// state" — it NEVER claims unreachability for an observed
    /// answer; `None` keeps the plain unreachability wording.
    #[error(
        "{lead} at {url}{source_note}{observation_note}",
        lead = if observation.is_some() {
            "no terminal state"
        } else {
            "gateway unreachable"
        },
        source_note = source.as_ref().map(|source| format!(": {source}")).unwrap_or_default(),
        observation_note = observation
            .as_deref()
            .map(|obs| format!("; last observation: {obs}"))
            .unwrap_or_default()
    )]
    Network {
        url: String,
        #[source]
        source: Option<reqwest::Error>,
        /// The poll deadline's last concrete observation (e.g. the
        /// gateway's reported state) — `None` for transport failures
        /// and observation-less deadlines. `Some` ⇒ the gateway
        /// answered; the Display never says "unreachable" then.
        observation: Option<String>,
    },

    /// Gateway reachable but rejected credentials (401/403). Exit 5.
    #[error("gateway rejected credentials (HTTP {status})")]
    Auth {
        status: u16,
        /// URL/path of the request that was rejected, when known.
        endpoint: Option<String>,
    },

    /// Gateway reachable but the command is invalid for its current state —
    /// version below minimum, uncommissioned, mid-restart, or a missing
    /// resource. Exit 6.
    #[error("gateway version {found} is below minimum {minimum}")]
    GatewayTooOld {
        found: String,
        minimum: String,
        /// URL/path of the request that answered, when known.
        endpoint: Option<String>,
    },

    /// Gateway reachable but uncommissioned — every `/data` route 302s to
    /// `/welcome` (verified on a fresh 8.3.6 container; 02-RESEARCH
    /// §Error-Body Sniffing). Exit 6.
    #[error("gateway at {} is not commissioned", endpoint.as_deref().unwrap_or("unknown address"))]
    GatewayNotCommissioned {
        /// URL that was redirected to the commissioning wizard.
        endpoint: Option<String>,
    },

    /// Gateway restarting — webserver answers (503) but services are down
    /// (verified restart lifecycle: webserver never drops the connection).
    /// Exit 6.
    #[error("gateway is restarting (webserver up, services down)")]
    GatewayRestarting {
        /// URL that answered 503.
        endpoint: Option<String>,
    },

    /// Named resource absent (404) — terminating a nonexistent session id,
    /// an unknown path, or a pre-8.3 gateway's JSON
    /// `{"message": "No route match for path: …"}`. Exit 6.
    #[error("resource not found on the gateway")]
    NotFound {
        /// URL that answered 404.
        endpoint: Option<String>,
    },

    /// A project of this name already exists and the import's collision
    /// policy is abort — the CLI-side pre-check refused BEFORE any
    /// upload (the server's own answer remains the backstop). Exit 6 —
    /// target state: the command is invalid for the gateway's current
    /// state (03-02, the GatewayTooOld action-built-variant precedent:
    /// constructed by the actions layer, not classify).
    #[error("project {name} already exists on the gateway")]
    ProjectExists {
        /// The colliding project name.
        name: String,
        /// URL of the pre-check request, when known.
        endpoint: Option<String>,
    },

    /// A binary (data.bin-class) resource met the surgical JSON/text
    /// loop — REFUSED rather than corrupted through it. Exit 6 —
    /// target state: the command is invalid for that resource's
    /// nature; the export/import family owns binary resources
    /// (Pitfall 7).
    #[error("resource {path:?} has binary content — not editable via the resource loop")]
    ResourceBinary {
        /// The resource path that was refused.
        path: String,
        /// URL of the request involved, when known.
        endpoint: Option<String>,
    },

    /// The gateway refuses trial resets while the trial is still
    /// active — live-discovered on 8.3.3 during 04-03's spike: the
    /// reset POST answers 403 on a NON-expired trial (verified from
    /// the browser page itself with the exact UI headers), and 200 +
    /// the flip on an expired one. The action layer's expiry pre-check
    /// turns that misleading auth-shaped 403 into the honest
    /// target-state refusal. Exit 6 (the ProjectExists precedent:
    /// action-constructed, not classify).
    #[error(
        "trial is not expired ({remaining_s}s left) — the gateway only honors resets once the trial expires"
    )]
    TrialNotExpired {
        /// Seconds left on the active trial.
        remaining_s: i64,
        /// URL of the rig's trial endpoint, when known.
        endpoint: Option<String>,
    },

    /// The WebDev route family a command depends on is not deployed —
    /// the presence probe answered 405, the live-proven 8.3 absent
    /// marker (missing routes AND missing projects both answer 405,
    /// NOT 404; 05-RESEARCH Pitfall 1). Exit 6 — target state: the
    /// command is invalid until `ign webdev deploy` installs the
    /// routes (the TrialNotExpired precedent: action-constructed, not
    /// classify).
    #[error(
        "webdev routes are not deployed (probe of {route:?} in project {project:?} answered 405)"
    )]
    RoutesNotDeployed {
        /// The deploy project the probe targeted.
        project: String,
        /// The route folder the probe named.
        route: String,
        /// Path of the probe request, when known.
        endpoint: Option<String>,
    },

    /// The WebDev module answered 402 — installed but unlicensed (a
    /// trial-expired gateway; live-verified cross-version on 8.3.6,
    /// 05-RESEARCH §Servlet). Exit 6 — no `/system/webdev` route can
    /// answer until the gateway is licensed.
    #[error(
        "the WebDev module is unlicensed on this gateway (HTTP 402 — trial-expired rigs cannot serve /system/webdev routes)"
    )]
    WebdevUnlicensed {
        /// Path of the probe request, when known.
        endpoint: Option<String>,
    },

    /// A deployed route's handshake version differs from the embedded
    /// bundle's — the CLI refuses rather than auto-upgrading either
    /// side (roadmap-locked: actionable error, no auto-upgrade
    /// magic). Exit 6.
    #[error("route {route:?} version mismatch: deployed {deployed}, this CLI expects {expected}")]
    RouteVersionMismatch {
        /// The route folder that answered.
        route: String,
        /// The route's deployed `routeVersion`.
        deployed: String,
        /// The embedded bundle's version
        /// ([`crate::webdev::ROUTE_BUNDLE_VERSION`]).
        expected: String,
        /// Path of the probe request, when known.
        endpoint: Option<String>,
    },

    /// A tag provider of this name does not exist — the
    /// find→signature→delete chain's find half missed (05-04,
    /// TAGS-01). Exit 6 — target state: the named thing is absent
    /// (the ProjectExists precedent family: action-constructed, not
    /// classify — the honest, family-specific refusal over a bare
    /// 404).
    #[error("tag provider {name:?} not found on the gateway")]
    ProviderNotFound {
        /// The provider name that missed.
        name: String,
        /// URL of the find request, when known.
        endpoint: Option<String>,
    },

    /// A WebDev route answered HTTP 200 with a body denial
    /// (`{ok:false, error{code,message}}`) whose machine code this CLI
    /// does not specifically map — code + message ride verbatim so
    /// agents can branch on the stable route contract (05-01). Exit 6
    /// — target state: the deployed route refused the action.
    #[error("webdev route denied the call ({code}): {message}")]
    WebdevRouteError {
        /// The route's machine error code (stable contract).
        code: String,
        /// The route's human message.
        message: String,
        /// Path of the request, when known.
        endpoint: Option<String>,
    },

    /// A tag import under abort policy found EXISTING tags at the
    /// target provider (05-05, TAGS-09) — the browse pre-check
    /// refuses BEFORE any route write (the LOCKED Phase-3 collision
    /// matrix mapped onto configure's 'a'/'o'). Exit 6 — target
    /// state: the named tags exist; overwrite is the explicit,
    /// guarded opt-in.
    #[error(
        "tag collision importing into provider {provider:?}: {} already exist(s)",
        names.join(", ")
    )]
    TagCollision {
        /// The target provider the import was headed for.
        provider: String,
        /// The colliding top-level tag names the pre-check found.
        names: Vec<String>,
        /// URL of the pre-check browse request, when known.
        endpoint: Option<String>,
    },

    /// The gateway has no alarm-journal profile configured — alarm
    /// history has nowhere to read from. The alarms route's
    /// structured `no_alarm_journal` denial maps here (the
    /// denial_to_error seam, 05-06 TAGS-07): DEFAULT rigs hit this
    /// ALWAYS, because the journal is a config-resource chain —
    /// database connection + `ignition/alarm-journal` profile + the
    /// `general-alarm-settings` singleton pointing at it. Exit 6 —
    /// target state: the command is invalid for the gateway's
    /// current state until that chain is provisioned (the honest,
    /// actionable refusal over a bare route error).
    #[error(
        "no alarm journal profile is configured on this gateway — alarm history has nothing to read"
    )]
    AlarmJournalMissing {
        /// URL of the alarms route request, when known.
        endpoint: Option<String>,
    },

    /// Pruning a LIVE Designer session entry — the gateway's prune
    /// route answers 409 (empty body, wire-verified on 8.3.3,
    /// 06-UAT test 6): prune removes STALE entries only, so the
    /// command is invalid while the Designer is still open. Exit 6 —
    /// target state (additive slug in the frozen taxonomy's
    /// established growth pattern; classify()'s ROUTE-SCOPED 409 arm
    /// constructs this — the first classify-constructed refusal added
    /// since the 02-01 set).
    #[error("designer session {id} is live — the gateway refused the prune")]
    SessionNotPrunable {
        /// The Designer session id that was refused.
        id: String,
        /// URL of the refused DELETE, when known.
        endpoint: Option<String>,
    },

    /// Docker/compose rig failure. Exit 7. Reserved — first used in Phase 4;
    /// trivially constructible so the taxonomy enumerates completely today.
    #[error("rig error: {0}")]
    Rig(String),

    /// The gateway's EAM module is not configured as a controller —
    /// every `/data/eam/api/v1/*` runtime endpoint answers 403 with
    /// "This operation can only be performed when EAM is configured
    /// as a controller" on a stock gateway (live-proven 8.3.3,
    /// 07-RESEARCH): a STATE refusal, not auth — the token is fine,
    /// the module's role is not. Message-classified at the classify
    /// seam, path-scoped to `/data/eam/` so generic 403s elsewhere
    /// cannot shift (the trial_not_expired pattern, classify
    /// edition). Exit 6 — target state.
    #[error(
        "EAM is not configured as a controller on this gateway — every EAM runtime \
         operation refuses until the module's installMode is flipped"
    )]
    EamNotController {
        /// URL of the refused request, when known.
        endpoint: Option<String>,
    },

    /// A provider-ROOT tag path (`[default]` alone, or a bare first
    /// segment that resolves to a provider) met the tagConfig route
    /// — `system.tag.getConfiguration`/`exportTags` need an RPC
    /// context WebDev threads don't carry (live-proven 8.3.3
    /// b2026012009, both gateways; 07-UAT test 12). The route
    /// refuses honestly (pre-call bracket detection + RpcContext
    /// translation for the bare form) instead of surfacing the
    /// IllegalStateException as a generic route error; subtree
    /// paths (`[default]folder`) are the supported form. Exit 6 —
    /// target state: a platform limitation, not a bug.
    #[error(
        "provider-root tag paths are not supported by the deployed route (the gateway needs an \
         RPC context WebDev threads don't carry) — target a subtree like [provider]folder"
    )]
    ProviderRootUnsupported {
        /// URL of the tagConfig route request, when known.
        endpoint: Option<String>,
    },

    /// An `eam task new` whose type is in the REFUSED set —
    /// `eam_restoreBackup`, `eam_installModules`, `eam_remoteUpgrade`
    /// are fleet-destructive (they push backups/modules/upgrades to
    /// every AGENT target), and the CLI refuses them outright over
    /// guard-everything: honest refusal with the v2 scope pointer
    /// (the planner-locked create ladder's top rung). Exit 6 —
    /// target state (additive slug alongside Task 2's).
    #[error(
        "EAM task type {task_type} is fleet-destructive — refused (restore/install/upgrade \
         are EXT-03 (v2) scope; run them from the EAM console)"
    )]
    EamTaskTypeRefused {
        /// The refused `profile.type` token.
        task_type: String,
    },

    /// An `eam task force` whose slot a leftover run occupies — the
    /// force route answers 409 with the gateway's own Jetty page
    /// ("Task 'X (forced)' already exists! It must be completed or
    /// deleted before another task of this type can be force
    /// executed."; live-captured 8.3.3, 07-UAT test 7). Exit 6 —
    /// target state (the `session_not_prunable` precedent,
    /// force-route edition): the gateway's state refused the command,
    /// not a bug; classify()'s path-scoped 409 arm constructs this.
    #[error("EAM task {task} has a run in flight — the gateway refused the force: {detail}")]
    EamTaskInFlight {
        /// The forced task's name (the force URL's last segment).
        task: String,
        /// The gateway's Jetty page message verbatim when sniffed;
        /// the '(forced)' fallback text otherwise.
        detail: String,
        /// URL of the refused force POST, when known.
        endpoint: Option<String>,
    },

    /// The scriptExec route is not configured for this profile — no
    /// webdev secret is persisted, which can only mean `ign webdev
    /// deploy --with-script-exec` has never run (deploy persists the
    /// secret 0600 BEFORE upload, so a deployed route without a
    /// stored secret is not a reachable state). `ign script run`'s
    /// opt-in is STRUCTURAL — the deploy flag — so the verb carries
    /// no `--yes` guard and refuses here instead (07-03, SCRPT-01:
    /// the TrialNotExpired precedent — action-constructed, not
    /// classify). Exit 6 — target state.
    #[error(
        "scriptExec is not configured for profile {profile:?} — the secret-gated route deploys \
         only via the explicit opt-in"
    )]
    ScriptExecNotConfigured {
        /// The profile whose secret store is empty.
        profile: String,
    },

    /// `ign lint` found no `ignition-lint` executable on PATH — the
    /// delegation has nothing to delegate to (07-04, INTR-02). The
    /// hint carries the install command + repo. Exit 6 — target
    /// state (additive slug; the environment lacks the tool, the
    /// command is fine).
    #[error("ignition-lint is not installed (no executable found on PATH)")]
    LintToolAbsent,

    /// The gateway answered the api call with a 4xx this CLI does not
    /// curate — the caller's request is the problem, and the body is
    /// theirs to read. Exit 2 (usage class; additive slug — the
    /// poll_interval_too_small precedent: same class, own slug, no new
    /// exit code). Constructed ONLY by the api-call-scoped classify arm
    /// (09-01: the `api_call` parameter) — a curated command's 4xx keeps
    /// its existing classification (the catch-all cannot fire without
    /// the parameter). The body is the gateway's answer VERBATIM,
    /// truncated at [`GATEWAY_CLIENT_BODY_CAP_BYTES`] with the explicit
    /// [`GATEWAY_CLIENT_BODY_TRUNCATION_MARKER`] via [`truncate_api_body`]
    /// at construction.
    #[error("gateway rejected the api call (HTTP {status} from {endpoint}): {body}")]
    GatewayClientError {
        /// HTTP status the gateway answered with.
        status: u16,
        /// Full URL of the rejected request.
        endpoint: String,
        /// The response body VERBATIM, truncated at
        /// [`GATEWAY_CLIENT_BODY_CAP_BYTES`] with an explicit marker.
        body: String,
    },

    /// No diagnostics bundle is available — the status poll ANSWERED
    /// with a captured TERMINAL steady state meaning "no current
    /// bundle" (`Invalid`: live-proven on 8.3.6 rig ign-p9-836,
    /// 2026-09-07 UAT / 09-UAT.md Gap 3 — a `Valid` bundle decays to
    /// `Invalid` within ~2 minutes UNPROMPTED and stays `Invalid`;
    /// only a fresh generate changes it, polling cannot). Exit 6 —
    /// target state (the `ImportDenied` precedent: a gateway-answered
    /// refusal riding its own class, action-constructed by `bundle
    /// wait`'s probe, not classify).
    #[error(
        "no diagnostics bundle available (gateway reports state {state:?}) — run \
         `ign diagnostics bundle generate` first; polling cannot change this state"
    )]
    BundleNotAvailable {
        /// The observed steady state (the captured unavailable
        /// vocabulary, e.g. `Invalid`).
        state: String,
    },
}

impl CoreError {
    /// Stable machine slug — public contract, never respell.
    pub fn code(&self) -> &'static str {
        match self {
            Self::Internal(_) => "internal",
            Self::ConfirmationRequired { .. } => "confirmation_required",
            Self::InvalidImportFile { .. } => "invalid_import_file",
            Self::ImportDenied { .. } => "import_denied",
            Self::InvalidInput { .. } => "invalid_input",
            Self::ProfileNotFound { .. } => "profile_not_found",
            Self::NoActiveProfile => "no_active_profile",
            Self::SecretUnavailable { .. } => "secret_unavailable",
            Self::ConfigInvalid { .. } => "config_invalid",
            Self::PollIntervalTooSmall { .. } => "poll_interval_too_small",
            Self::Network { .. } => "network_error",
            Self::Auth { .. } => "auth_rejected",
            Self::GatewayTooOld { .. } => "gateway_too_old",
            Self::GatewayNotCommissioned { .. } => "gateway_not_commissioned",
            Self::GatewayRestarting { .. } => "gateway_restarting",
            Self::NotFound { .. } => "not_found",
            Self::ProjectExists { .. } => "project_exists",
            Self::ResourceBinary { .. } => "resource_binary",
            Self::TrialNotExpired { .. } => "trial_not_expired",
            Self::ProviderNotFound { .. } => "provider_not_found",
            Self::RoutesNotDeployed { .. } => "routes_not_deployed",
            Self::WebdevUnlicensed { .. } => "webdev_unlicensed",
            Self::RouteVersionMismatch { .. } => "route_version_mismatch",
            Self::WebdevRouteError { .. } => "webdev_route_error",
            Self::TagCollision { .. } => "tag_collision",
            Self::AlarmJournalMissing { .. } => "alarm_journal_missing",
            Self::SessionNotPrunable { .. } => "session_not_prunable",
            Self::Rig(_) => "rig_error",
            Self::EamNotController { .. } => "eam_not_controller",
            Self::ProviderRootUnsupported { .. } => "provider_root_unsupported",
            Self::EamTaskTypeRefused { .. } => "eam_task_type_refused",
            Self::EamTaskInFlight { .. } => "eam_task_in_flight",
            Self::ScriptExecNotConfigured { .. } => "script_exec_not_configured",
            Self::LintToolAbsent => "lint_tool_absent",
            Self::GatewayClientError { .. } => "gateway_client_error",
            Self::BundleNotAvailable { .. } => "bundle_not_available",
        }
    }

    /// The LOCKED exit-code mapping — the only place exit codes are decided.
    pub fn exit_code(&self) -> u8 {
        match self {
            Self::Internal(_) => 1,
            Self::ConfirmationRequired { .. }
            | Self::InvalidImportFile { .. }
            | Self::InvalidInput { .. }
            | Self::GatewayClientError { .. } => 2,
            Self::ProfileNotFound { .. }
            | Self::NoActiveProfile
            | Self::SecretUnavailable { .. }
            | Self::ConfigInvalid { .. }
            | Self::PollIntervalTooSmall { .. } => 3,
            Self::Network { .. } => 4,
            Self::Auth { .. } => 5,
            Self::GatewayTooOld { .. }
            | Self::GatewayNotCommissioned { .. }
            | Self::GatewayRestarting { .. }
            | Self::NotFound { .. }
            | Self::ProjectExists { .. }
            | Self::ResourceBinary { .. }
            | Self::TrialNotExpired { .. }
            | Self::ProviderNotFound { .. }
            | Self::RoutesNotDeployed { .. }
            | Self::WebdevUnlicensed { .. }
            | Self::RouteVersionMismatch { .. }
            | Self::WebdevRouteError { .. }
            | Self::TagCollision { .. }
            | Self::AlarmJournalMissing { .. }
            | Self::SessionNotPrunable { .. }
            | Self::ImportDenied { .. }
            | Self::EamNotController { .. }
            | Self::ProviderRootUnsupported { .. }
            | Self::EamTaskTypeRefused { .. }
            | Self::EamTaskInFlight { .. }
            | Self::ScriptExecNotConfigured { .. }
            | Self::LintToolAbsent
            | Self::BundleNotAvailable { .. } => 6,
            Self::Rig(_) => 7,
        }
    }

    /// Actionable next step (CORE-05). Every class carries one.
    pub fn hint(&self) -> Option<String> {
        match self {
            Self::Internal(_) => Some(
                "internal errors are bugs; re-run with -vv and report the \
                 diagnostics output"
                    .to_string(),
            ),
            Self::ConfirmationRequired { .. } => Some(
                "this operation is destructive; re-run with --yes or set \
                   IGNITION_YES=1"
                    .to_string(),
            ),
            Self::InvalidImportFile { .. } => Some(
                "import expects a project-export ZIP (PK\\x03\\x04 magic) of at \
                   most 512 MB — pass a file produced by `ign project export` \
                   via --file (or `-` to pipe one on stdin)"
                    .to_string(),
            ),
            Self::ImportDenied { problem, .. } => Some(format!(
                "the gateway refused the import over a 200 answer — the problem \
                   text above is the gateway's own; `ign project export` of the \
                   current state is the honest baseline for hand-editing ({problem})"
            )),
            Self::InvalidInput { reason } => Some(
                if reason == TUI_TTY_REFUSAL_REASON {
                    // The ONE contextual InvalidInput hint (06-07): the
                    // TTY refusal's fix is terminal-related — the
                    // --file/stdin default is meaningless for a pipe.
                    "run `ign tui` in an interactive terminal (the cockpit \
                     needs a TTY on stdout — not a pipe or redirect)"
                } else if reason.starts_with(LOSS_GATE_REFUSAL_REASON_PREFIX) {
                    // The loss-gate refusal (11-07): the message above already names
                    // every finding and ends with the actionable guidance — the hint
                    // restates it for envelope readers instead of the file-read
                    // default, which is meaningless here (the file WAS readable).
                    "the loss report above names what this import would drop or \
                     coerce — re-run with --yes to import anyway"
                } else {
                    "fix the input source — a readable file path via --file, or `-` \
                     to pipe the content on stdin"
                }
                .to_string(),
            ),
            Self::ProfileNotFound { known, .. } => Some(if known.is_empty() {
                "no profiles configured yet; run `ign profile add` to create \
                     one"
                .to_string()
            } else {
                format!(
                    "known profiles: {}; run `ign profile add` to add another",
                    known.join(", ")
                )
            }),
            Self::NoActiveProfile => Some(
                "pass --profile NAME, set IGNITION_PROFILE, or mark a profile \
                 active with `ign profile use`"
                    .to_string(),
            ),
            Self::SecretUnavailable { profile } => Some(format!(
                "set IGNITION_TOKEN (or token_env in the profile), or store a \
                 keyring entry: service 'ignition-cli', user 'profile:{profile}'"
            )),
            Self::ConfigInvalid { .. } => Some(
                "verify the config file is valid TOML with [profiles.NAME] \
                 tables; `ign profile add` writes a known-good one"
                    .to_string(),
            ),
            Self::PollIntervalTooSmall { profile } => Some(format!(
                "set poll_interval_secs to 1 or higher in [profiles.{profile}], \
                 or remove the key to use the default cadence"
            )),
            Self::Network {
                url,
                observation,
                ..
            } => Some(match observation {
                Some(observation) => format!(
                    "the gateway answered but no terminal state arrived before the deadline — \
                     the last observation was: {observation}; address that state, not the \
                     connection ({url})"
                ),
                None => format!("check the gateway is reachable at {url} (host, port, VPN, TLS)"),
            }),
            Self::Auth { status, .. } => Some(match status {
                401 => {
                    // 401 = token not recognized — the #1 setup failure is
                    // a key-only header (verified: key-only → 401, full
                    // `name:key` → 200; Basic is dead on 8.3 /data).
                    "token not recognized — the X-Ignition-API-Token header must be the FULL `name:key` string from the gateway UI (Platform→Security→API Keys); Basic auth does not work on 8.3 /data routes — create an API token"
                }
                403 => {
                    // 403 = recognized but under-permitted (verified
                    // semantics; see 02-RESEARCH Auth §4/§5).
                    "token recognized but under-permitted — Ignition token setup is three parts: (1) token holds an adequate security level, (2) gateway read/write permissions include that level, (3) 'Require secure connections' is unchecked for http gateways; run `ign doctor` for a diagnosis"
                }
                _ => "check the credential; Ignition token setup is three parts: security level, write permissions, token assignment",
            }
            .to_string()),
            Self::GatewayTooOld { minimum, .. } => {
                Some(format!("upgrade the gateway to at least {minimum}"))
            }
            Self::GatewayNotCommissioned { .. } => Some(
                "open http://<host>:<port>/welcome in a browser and complete the \
                 commissioning wizard"
                    .to_string(),
            ),
            Self::GatewayRestarting { .. } => Some(
                "wait for readiness with `ign wait restart` or retry in ~1 minute".to_string(),
            ),
            Self::NotFound { .. } => Some(
                "check the id/path; a 404 JSON 'No route match' body can also mean \
                  a pre-8.3 gateway"
                    .to_string(),
            ),
            Self::ProjectExists { .. } => Some(
                "the default collision policy refuses to overwrite; re-run with \
                  --collision-policy overwrite to replace it — overwrite \
                  REPLACES the ENTIRE project (resources absent from the ZIP \
                  are deleted; merge is Designer-only)"
                    .to_string(),
            ),
            Self::ResourceBinary { .. } => Some(
                "resource content is binary — use `ign project export`/`import` \
                  for data.bin-class resources"
                    .to_string(),
            ),
            Self::TrialNotExpired { .. } => Some(
                "wait for the trial to expire (watch `ign rig trial status`), or \
                  run `ign rig reset --yes` for a completely fresh trial volume"
                    .to_string(),
            ),
            Self::RoutesNotDeployed { .. } => Some(
                "run `ign webdev deploy` to install the CLI's WebDev routes into \
                  the gateway, then retry"
                    .to_string(),
            ),
            Self::WebdevUnlicensed { .. } => Some(
                "license the gateway — the WebDev module answers 402 while \
                  unlicensed (on a rig, `ign rig trial reset --yes` restarts an \
                  expired trial)"
                    .to_string(),
            ),
            Self::RouteVersionMismatch { deployed, expected, .. } => {
                // Direction decides the fix (roadmap criterion): an older
                // deployed route → redeploy from THIS binary; a NEWER
                // deployed route → this CLI is behind (the route bundle
                // travels with the binary). Same slug either way.
                let newer = semver::Version::parse(deployed)
                    .ok()
                    .zip(semver::Version::parse(expected).ok())
                    .is_some_and(|(deployed, expected)| deployed > expected);
                Some(if newer {
                    "the deployed routes are NEWER than this CLI — update ign \
                      (the route bundle travels with the binary)"
                        .to_string()
                } else {
                    "run `ign webdev deploy` to redeploy the route version \
                      this CLI expects"
                        .to_string()
                })
            }
            Self::ProviderNotFound { .. } => Some(
                "check the provider name; `ign tags provider list` shows the \
                  gateway's tag providers"
                    .to_string(),
            ),
            Self::TagCollision { .. } => Some(
                "re-run with --collision-policy overwrite to replace the \
                  existing tags (destructive: requires --yes)"
                    .to_string(),
            ),
            Self::AlarmJournalMissing { .. } => Some(
                "alarm history needs a journal profile — provision a database \
                  connection + alarm-journal profile on the gateway (and point \
                  the general-alarm-settings singleton at it), then retry; see \
                  the README 'Alarm history' section"
                    .to_string(),
            ),
            Self::SessionNotPrunable { .. } => Some(
                "close the Designer first — prune removes stale entries only".to_string(),
            ),
            Self::WebdevRouteError { code, .. } => Some(if code == "secret_required" || code == "secret_mismatch" {
                "the scriptExec route is secret-gated — deploy it with `ign \
                  webdev deploy --with-script-exec` (the secret is generated \
                  and stored in the profile config at 0600); a mismatch means \
                  the route was deployed with a different secret: redeploy or \
                  pass --rotate-secret"
                    .to_string()
            } else {
                "the deployed route refused the action — the code and message \
                  are the route's stable contract; `ign webdev status` \
                  diagnoses the deployment"
                    .to_string()
            }),
            Self::EamNotController { .. } => Some(
                "flip the gateway's EAM role: config-resource PUT on \
                   com.inductiveautomation.eam/module-settings with \
                   installMode \"Controller\" (array body carrying the current \
                   signature) — a manual gateway-role decision this CLI \
                   deliberately does not automate; see the README 'EAM tasks' \
                   section"
                    .to_string(),
            ),
            Self::ProviderRootUnsupported { .. } => Some(
                "target a subtree path like [provider]folder — provider-ROOT \
                   forms ([default] alone, or a bare provider name) need an \
                   RPC context WebDev threads don't carry (8.3.3); subtree \
                   paths are the supported form"
                    .to_string(),
            ),
            Self::EamTaskTypeRefused { .. } => Some(
                "restore/install/upgrade tasks dispatch fleet-wide (every \
                   agent target); run them from the Ignition EAM console — \
                   EXT-03 (v2) will scope them into the CLI"
                    .to_string(),
            ),
            Self::EamTaskInFlight { .. } => Some(
                "complete or delete the leftover '(forced)' run from the EAM \
                   console — no ign verb deletes runs; the slot frees once the \
                   run is resolved"
                    .to_string(),
            ),
            Self::ScriptExecNotConfigured { .. } => Some(
                "run `ign webdev deploy --with-script-exec` to deploy the route and \
                  generate + persist its secret (the deploy flag IS the opt-in — \
                  `ign script run` has no --yes by design)"
                    .to_string(),
            ),
            Self::LintToolAbsent => Some(
                "install the linter: `uv tool install ignition-lint-toolkit` \
                 (or `pip install ignition-lint-toolkit`) — \
                 github.com/TheThoughtagen/ignition-lint; then re-run with \
                 ignition-lint on PATH"
                    .to_string(),
            ),
            Self::GatewayClientError { .. } => Some(
                "the gateway rejected this request — the body above is the \
                 gateway's own answer; fix the path/method/body, or use a \
                 curated `ign` command when one exists"
                    .to_string(),
            ),
            Self::BundleNotAvailable { .. } => Some(
                "generate a fresh bundle with `ign diagnostics bundle generate`, \
                 then wait again — the gateway reports no current bundle and \
                 polling cannot produce one"
                    .to_string(),
            ),
            Self::Rig(_) => Some(
                "check Docker is running and inspect the rig containers \
                 (docker ps)"
                    .to_string(),
            ),
        }
    }

    /// URL/path of the request involved, when one was — populated for the
    /// network, auth, and target-state classes (CORE-05).
    pub fn endpoint(&self) -> Option<String> {
        match self {
            Self::Network { url, .. } => Some(url.clone()),
            Self::Auth { endpoint, .. } => endpoint.clone(),
            Self::GatewayTooOld { endpoint, .. }
            | Self::GatewayNotCommissioned { endpoint }
            | Self::GatewayRestarting { endpoint }
            | Self::NotFound { endpoint }
            | Self::ProjectExists { endpoint, .. }
            | Self::ResourceBinary { endpoint, .. }
            | Self::TrialNotExpired { endpoint, .. }
            | Self::ProviderNotFound { endpoint, .. }
            | Self::RoutesNotDeployed { endpoint, .. }
            | Self::WebdevUnlicensed { endpoint }
            | Self::RouteVersionMismatch { endpoint, .. }
            | Self::WebdevRouteError { endpoint, .. }
            | Self::TagCollision { endpoint, .. }
            | Self::AlarmJournalMissing { endpoint }
            | Self::SessionNotPrunable { endpoint, .. }
            | Self::ImportDenied { endpoint, .. }
            | Self::EamNotController { endpoint }
            | Self::ProviderRootUnsupported { endpoint }
            | Self::EamTaskInFlight { endpoint, .. } => endpoint.clone(),
            _ => None,
        }
    }

    /// The `ign tui` TTY refusal (06-07): InvalidInput carrying the
    /// ONE reason whose hint is terminal-contextual — see
    /// [`TUI_TTY_REFUSAL_REASON`]. Same slug, same exit 2 (frozen
    /// taxonomy; only the hint differs).
    pub fn tui_tty_refusal() -> Self {
        Self::InvalidInput {
            reason: TUI_TTY_REFUSAL_REASON.to_string(),
        }
    }

    /// Build the LOCKED failure envelope for this error (field order is part
    /// of the golden contract: `ok`, `profile`, `error` then `code`,
    /// `message`, `endpoint`, `hint`).
    pub fn envelope<'a>(&self, profile: Option<&'a str>) -> ErrorEnvelope<'a> {
        ErrorEnvelope {
            ok: false,
            profile,
            error: ErrorBody {
                code: self.code(),
                message: self.to_string(),
                endpoint: self.endpoint(),
                hint: self.hint(),
            },
        }
    }
}

/// LOCKED failure envelope shape: exactly the top-level fields `ok`,
/// `profile`, `error` — changing the set is a breaking change for agents.
#[derive(Debug, Serialize)]
pub struct ErrorEnvelope<'a> {
    /// Always `false` in this envelope.
    pub ok: bool,
    /// Active profile echoed in every output (CORE-01); `None` until config
    /// resolution lands.
    pub profile: Option<&'a str>,
    /// The typed error body.
    pub error: ErrorBody,
}

/// LOCKED error body: `code` (stable slug), `message` (human-readable),
/// `endpoint` (when a request was involved), `hint` (actionable next step).
#[derive(Debug, Serialize)]
pub struct ErrorBody {
    /// Stable slug from [`CoreError::code`] — never respelled.
    pub code: &'static str,
    /// Human-readable description.
    pub message: String,
    /// URL/path when a request was involved.
    pub endpoint: Option<String>,
    /// Actionable next step.
    pub hint: Option<String>,
}

#[cfg(test)]
mod tests {
    use super::{
        CoreError, ErrorBody, ErrorEnvelope, GATEWAY_CLIENT_BODY_CAP_BYTES,
        GATEWAY_CLIENT_BODY_TRUNCATION_MARKER, LOSS_GATE_REFUSAL_REASON_PREFIX, truncate_api_body,
    };

    /// Build a real `reqwest::Error` for the Network variant: a request to
    /// an unroutable loopback port fails at connect time (instant refusal —
    /// `reqwest::Error` has no public constructor).
    fn network_error() -> CoreError {
        let rt = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .expect("test runtime");
        let url = "http://127.0.0.1:1";
        let source = rt
            .block_on(reqwest::get(url))
            .expect_err("request to an unroutable port must fail");
        CoreError::Network {
            url: url.to_string(),
            source: Some(source),
            observation: None,
        }
    }

    /// Pitfall-5 guard: the FULL 1–7 taxonomy enumerated on day one so no
    /// later phase can silently renumber it or respell a slug. The slugs are
    /// asserted against literals — that IS the stability contract.
    #[test]
    fn exit_code_mapping_enumerated() {
        let cases: Vec<(CoreError, u8, &'static str)> = vec![
            (CoreError::Internal("boom".into()), 1, "internal"),
            (
                CoreError::ConfirmationRequired {
                    operation: "project download".into(),
                },
                2,
                "confirmation_required",
            ),
            (
                CoreError::InvalidImportFile {
                    reason: "missing ZIP magic".into(),
                },
                2,
                "invalid_import_file",
            ),
            (
                CoreError::InvalidInput {
                    reason: "cannot read put.json".into(),
                },
                2,
                "invalid_input",
            ),
            (
                CoreError::ProfileNotFound {
                    name: "nope".into(),
                    known: vec!["dev".into()],
                },
                3,
                "profile_not_found",
            ),
            (CoreError::NoActiveProfile, 3, "no_active_profile"),
            (
                CoreError::SecretUnavailable {
                    profile: "dev".into(),
                },
                3,
                "secret_unavailable",
            ),
            (
                CoreError::ConfigInvalid {
                    reason: "bad toml".into(),
                },
                3,
                "config_invalid",
            ),
            (
                CoreError::PollIntervalTooSmall {
                    profile: "dev".into(),
                },
                3,
                "poll_interval_too_small",
            ),
            (network_error(), 4, "network_error"),
            (
                CoreError::Auth {
                    status: 401,
                    endpoint: None,
                },
                5,
                "auth_rejected",
            ),
            (
                CoreError::GatewayTooOld {
                    found: "8.1.0".into(),
                    minimum: "8.3.1".into(),
                    endpoint: None,
                },
                6,
                "gateway_too_old",
            ),
            (
                CoreError::GatewayNotCommissioned {
                    endpoint: Some("http://gw:8088/data/api/v1/gateway-info".into()),
                },
                6,
                "gateway_not_commissioned",
            ),
            (
                CoreError::GatewayRestarting {
                    endpoint: Some("http://gw:8088/data/api/v1/gateway-info".into()),
                },
                6,
                "gateway_restarting",
            ),
            (
                CoreError::NotFound {
                    endpoint: Some("http://gw:8088/data/api/v1/designer/42".into()),
                },
                6,
                "not_found",
            ),
            (
                CoreError::ProjectExists {
                    name: "PlantFloor".into(),
                    endpoint: None,
                },
                6,
                "project_exists",
            ),
            (
                CoreError::ResourceBinary {
                    path: "com.x/perspective/session-permissions".into(),
                    endpoint: None,
                },
                6,
                "resource_binary",
            ),
            (
                CoreError::TrialNotExpired {
                    remaining_s: 6590,
                    endpoint: Some("http://localhost:9088/data/api/v1/trial".into()),
                },
                6,
                "trial_not_expired",
            ),
            (
                CoreError::ProviderNotFound {
                    name: "nope".into(),
                    endpoint: Some("/data/api/v1/resources/find/ignition/tag-provider/nope".into()),
                },
                6,
                "provider_not_found",
            ),
            (
                CoreError::RoutesNotDeployed {
                    project: "ign-cli".into(),
                    route: "tags".into(),
                    endpoint: Some("/system/webdev/ign-cli/cli/tags".into()),
                },
                6,
                "routes_not_deployed",
            ),
            (
                CoreError::WebdevUnlicensed {
                    endpoint: Some("/system/webdev/ign-cli/cli/tags".into()),
                },
                6,
                "webdev_unlicensed",
            ),
            (
                CoreError::RouteVersionMismatch {
                    route: "tags".into(),
                    deployed: "0.9.0".into(),
                    expected: "1.0.0".into(),
                    endpoint: Some("/system/webdev/ign-cli/cli/tags".into()),
                },
                6,
                "route_version_mismatch",
            ),
            (
                CoreError::WebdevRouteError {
                    code: "route_error".into(),
                    message: "boom".into(),
                    endpoint: Some("/system/webdev/ign-cli/cli/tags".into()),
                },
                6,
                "webdev_route_error",
            ),
            (
                CoreError::TagCollision {
                    provider: "p5import".into(),
                    names: vec!["T1".into(), "P5".into()],
                    endpoint: Some("/system/webdev/ign-cli/cli/tags".into()),
                },
                6,
                "tag_collision",
            ),
            (
                CoreError::AlarmJournalMissing {
                    endpoint: Some("/system/webdev/ign-cli/cli/alarms".into()),
                },
                6,
                "alarm_journal_missing",
            ),
            (
                CoreError::ImportDenied {
                    project: "PlantFloor".into(),
                    problem: "resource already exists: ResourceId{resourcePath=com.example, collectionName=views}".into(),
                    endpoint: Some("http://gw:8088/data/api/v1/projects/import/PlantFloor?overwrite=true".into()),
                },
                6,
                "import_denied",
            ),
            (
                CoreError::SessionNotPrunable {
                    id: "d-live-1".into(),
                    endpoint: Some("http://gw:8088/data/api/v1/designer/d-live-1".into()),
                },
                6,
                "session_not_prunable",
            ),
            (
                CoreError::EamNotController {
                    endpoint: Some("http://gw:8088/data/eam/api/v1/eam-tasks/history".into()),
                },
                6,
                "eam_not_controller",
            ),
            (
                CoreError::ProviderRootUnsupported {
                    endpoint: Some("/system/webdev/ign-cli/cli/tagConfig".into()),
                },
                6,
                "provider_root_unsupported",
            ),
            (
                CoreError::EamTaskTypeRefused {
                    task_type: "eam_remoteUpgrade".into(),
                },
                6,
                "eam_task_type_refused",
            ),
            (
                CoreError::EamTaskInFlight {
                    task: "cli-research-backup".into(),
                    detail: "Task 'cli-research-backup (forced)' already exists! It must be completed or deleted before another task of this type can be force executed.".into(),
                    endpoint: Some(
                        "http://gw:8088/data/eam/api/v1/eam-tasks/force/eam/cli-research-backup"
                            .into(),
                    ),
                },
                6,
                "eam_task_in_flight",
            ),
            (
                CoreError::ScriptExecNotConfigured {
                    profile: "dev".into(),
                },
                6,
                "script_exec_not_configured",
            ),
            (CoreError::LintToolAbsent, 6, "lint_tool_absent"),
            (
                CoreError::BundleNotAvailable {
                    state: "Invalid".into(),
                },
                6,
                "bundle_not_available",
            ),
            (
                CoreError::GatewayClientError {
                    status: 400,
                    endpoint: "http://gw:8088/data/api/v1/nonexistent".into(),
                    body: r#"{"error":{"code":"NOT_FOUND"}}"#.into(),
                },
                2,
                "gateway_client_error",
            ),
            (CoreError::Rig("compose up failed".into()), 7, "rig_error"),
        ];
        for (err, code, slug) in cases {
            assert_eq!(err.exit_code(), code, "wrong exit code for: {err}");
            assert_eq!(err.code(), slug, "unstable slug for: {err}");
        }
    }

    /// The (exit_code, slug) literal table the Three-Place rule syncs.
    /// DUPLICATED from [`exit_code_mapping_enumerated`]'s triple list by
    /// design: that test is the literal source of truth (enum ↔ literals);
    /// this flat table is what the README cross-check runs against, so a
    /// drift inside error.rs surfaces as a disagreement instead of silently
    /// re-shuffling both sides. Keep the two lists in lockstep — the
    /// enumerated test fails if the enum respells/renumbers, and a stale
    /// copy here fails the README check below until updated.
    const EXIT_SLUG_LITERALS: &[(u8, &str)] = &[
        (1, "internal"),
        (2, "confirmation_required"),
        (2, "invalid_import_file"),
        (2, "invalid_input"),
        (2, "gateway_client_error"),
        (3, "profile_not_found"),
        (3, "no_active_profile"),
        (3, "secret_unavailable"),
        (3, "config_invalid"),
        (3, "poll_interval_too_small"),
        (4, "network_error"),
        (5, "auth_rejected"),
        (6, "gateway_too_old"),
        (6, "gateway_not_commissioned"),
        (6, "gateway_restarting"),
        (6, "not_found"),
        (6, "project_exists"),
        (6, "resource_binary"),
        (6, "trial_not_expired"),
        (6, "provider_not_found"),
        (6, "routes_not_deployed"),
        (6, "webdev_unlicensed"),
        (6, "route_version_mismatch"),
        (6, "webdev_route_error"),
        (6, "tag_collision"),
        (6, "alarm_journal_missing"),
        (6, "import_denied"),
        (6, "session_not_prunable"),
        (6, "eam_not_controller"),
        (6, "eam_task_type_refused"),
        (6, "eam_task_in_flight"),
        (6, "script_exec_not_configured"),
        (6, "lint_tool_absent"),
        (6, "provider_root_unsupported"),
        (6, "bundle_not_available"),
        (7, "rig_error"),
    ];

    /// Parse the README's exit-code table: rows `| <exit> | class | meaning |
    /// \`slug\`, ... |` where `<exit>` is 1–7 (row 0 is the success row, no
    /// slugs). Parsing is SCOPED to the `## Exit codes` section — the README
    /// contains unrelated tables whose rows coincidentally begin `| 5 |`,
    /// `| 3 |`, etc. Std-only string ops: split on `|`, trim, take the LAST
    /// non-empty cell as the slug column (the meaning column can carry
    /// backticked non-slugs like `--yes`), and keep the backtick-delimited
    /// tokens that start with an ASCII letter and contain no spaces.
    fn parse_readme_exit_table(readme: &str) -> Vec<(u8, Vec<String>)> {
        let section = readme.split("## Exit codes").nth(1).unwrap_or_default();
        let mut rows = Vec::new();
        let table_lines = section
            .lines()
            .skip_while(|line| !line.trim_start().starts_with('|'));
        for line in table_lines {
            if !line.trim_start().starts_with('|') {
                break; // table ended
            }
            let cells: Vec<&str> = line.split('|').map(str::trim).collect();
            let Some(exit) = cells.get(1).and_then(|cell| cell.parse::<u8>().ok()) else {
                continue;
            };
            if !(1..=7).contains(&exit) {
                continue;
            }
            let slug_cell = cells
                .iter()
                .rev()
                .find(|cell| !cell.is_empty())
                .copied()
                .unwrap_or_default();
            let slugs: Vec<String> = slug_cell
                .split('`')
                .enumerate()
                .filter(|(idx, _)| idx % 2 == 1)
                .map(|(_, token)| token.trim().to_string())
                .filter(|token| {
                    token.starts_with(|c: char| c.is_ascii_alphabetic()) && !token.contains(' ')
                })
                .collect();
            rows.push((exit, slugs));
        }
        rows
    }

    /// CORE-11, the Three-Place slug rule made executable: the exit-code
    /// table exists in the enum ([`CoreError::exit_code`]), this file's
    /// literal triples, and the README — and the README side is now
    /// machine-checked. The README is parsed verbatim via `include_str!`
    /// and cross-checked against the literal table in BOTH directions:
    /// (a) every literal slug appears under its exit code (a README row
    /// that lost or misspelled a slug fails), (b) every README slug token
    /// exists in the literal table (a stale/deleted row fails). Exit 6
    /// carries 23 slugs, so the full cross-check is the value — not the
    /// happy-path smoke.
    #[test]
    fn readme_exit_table_agreement() {
        let readme = include_str!("../../../README.md");
        let rows = parse_readme_exit_table(readme);
        assert!(
            rows.len() >= 7,
            "README exit-code table not found — the parser must see all 7 \
             failure-class rows (found {})",
            rows.len()
        );

        // Direction (a): every literal (exit, slug) is present in the
        // README row matching its exit code.
        for (exit, slug) in EXIT_SLUG_LITERALS {
            let row = rows
                .iter()
                .find(|(readme_exit, _)| readme_exit == exit)
                .unwrap_or_else(|| panic!("README table has no row for exit {exit}"));
            assert!(
                row.1.iter().any(|s| s == slug),
                "README exit-{exit} row is missing slug {slug:?} (row: {:?})",
                row.1
            );
        }

        // Direction (b): every README slug token exists in the literal
        // table under the same exit code — catches stale/deleted rows.
        for (exit, slugs) in &rows {
            for slug in slugs {
                assert!(
                    EXIT_SLUG_LITERALS
                        .iter()
                        .any(|(lit_exit, lit_slug)| lit_exit == exit && lit_slug == slug),
                    "README exit-{exit} row carries slug {slug:?} that no \
                     CoreError variant emits — stale table row or slug/exit \
                     drift between README and error.rs"
                );
            }
        }
    }

    /// CORE-05: config, auth, and target-state classes carry actionable
    /// hints (and every other class does too).
    #[test]
    fn hints_are_actionable_for_config_auth_target_state() {
        let profile_not_found = CoreError::ProfileNotFound {
            name: "x".into(),
            known: vec!["dev".into(), "prod".into()],
        };
        let hint = profile_not_found.hint().expect("hint required");
        assert!(
            hint.contains("dev"),
            "hint must list known profiles: {hint}"
        );
        assert!(
            hint.contains("ign profile add"),
            "hint must name the fix: {hint}"
        );

        let auth = CoreError::Auth {
            status: 403,
            endpoint: None,
        };
        let hint = auth.hint().expect("hint required");
        assert!(
            hint.contains("three parts"),
            "auth hint must name the three-part token setup: {hint}"
        );

        // Status-aware auth hints (02-RESEARCH Auth §4): 401 = not
        // recognized (name:key format), 403 = under-permitted.
        let unauthorized = CoreError::Auth {
            status: 401,
            endpoint: None,
        };
        let hint = unauthorized.hint().expect("hint required");
        assert!(
            hint.contains("name:key"),
            "401 hint must name the full name:key token format: {hint}"
        );
        assert!(
            hint.contains("API token"),
            "401 hint must say Basic cannot work: {hint}"
        );
        let hint403 = auth.hint().expect("hint required");
        assert!(
            hint403.contains("secure connections"),
            "403 hint must name the secure-channel part: {hint403}"
        );

        let too_old = CoreError::GatewayTooOld {
            found: "8.1.0".into(),
            minimum: "8.3.1".into(),
            endpoint: None,
        };
        let hint = too_old.hint().expect("hint required");
        assert!(
            hint.contains("8.3.1"),
            "target-state hint must name the minimum: {hint}"
        );

        // The WebDev refusal matrix (05-03): every hint names the fix
        // — `ign webdev deploy` for absent/older routes, `update ign`
        // for newer ones (the roadmap's actionable-error criterion).
        let undeployed = CoreError::RoutesNotDeployed {
            project: "ign-cli".into(),
            route: "tags".into(),
            endpoint: None,
        };
        let hint = undeployed.hint().expect("hint required");
        assert!(
            hint.contains("ign webdev deploy"),
            "absent-routes hint must name the fix: {hint}"
        );

        let older = CoreError::RouteVersionMismatch {
            route: "tags".into(),
            deployed: "0.9.0".into(),
            expected: "1.0.0".into(),
            endpoint: None,
        };
        let hint = older.hint().expect("hint required");
        assert!(
            hint.contains("ign webdev deploy") && !hint.contains("update ign"),
            "older-route hint says redeploy: {hint}"
        );

        let newer = CoreError::RouteVersionMismatch {
            route: "tags".into(),
            deployed: "1.1.0".into(),
            expected: "1.0.0".into(),
            endpoint: None,
        };
        let hint = newer.hint().expect("hint required");
        assert!(
            hint.contains("update ign") && !hint.contains("ign webdev deploy"),
            "newer-route hint says update ign: {hint}"
        );

        let secret_gate = CoreError::WebdevRouteError {
            code: "secret_required".into(),
            message: "missing x-ignition-cli-secret header".into(),
            endpoint: None,
        };
        let hint = secret_gate.hint().expect("hint required");
        assert!(
            hint.contains("--with-script-exec"),
            "secret-gate hint names the deploy flag: {hint}"
        );

        // The alarm-journal refusal (05-06): the hint names the missing
        // provisioning chain AND the README section.
        let journal = CoreError::AlarmJournalMissing { endpoint: None };
        let hint = journal.hint().expect("hint required");
        assert!(
            hint.contains("journal profile") && hint.contains("database connection"),
            "journal hint names the chain: {hint}"
        );
        assert!(
            hint.contains("README"),
            "journal hint points at the README section: {hint}"
        );

        // The live-designer prune refusal (06-07): the hint names the
        // action — close the Designer — and the stale-only semantics.
        let prunable = CoreError::SessionNotPrunable {
            id: "d-live-1".into(),
            endpoint: None,
        };
        let hint = prunable.hint().expect("hint required");
        assert!(
            hint.contains("close the Designer"),
            "prune hint must name the action: {hint}"
        );
        assert!(
            hint.contains("stale entries"),
            "prune hint must name stale-only semantics: {hint}"
        );

        // The TTY refusal's hint is contextual (06-07): the ONE
        // InvalidInput reason whose fix is terminal-related. Every
        // other reason keeps the --file/stdin resource-put hint (pinned
        // here so the special case can never leak or regress).
        let tty = CoreError::tui_tty_refusal();
        assert_eq!(tty.code(), "invalid_input", "slug unchanged");
        assert_eq!(tty.exit_code(), 2, "usage class unchanged");
        let hint = tty.hint().expect("hint required");
        assert!(
            hint.contains("interactive terminal"),
            "TTY hint must name the fix: {hint}"
        );
        assert!(
            !hint.contains("--file"),
            "TTY hint must not carry the resource-put hint: {hint}"
        );
        let put = CoreError::InvalidInput {
            reason: "cannot read put.json".into(),
        };
        let hint = put.hint().expect("hint required");
        assert!(
            hint.contains("--file") && hint.contains("stdin"),
            "resource-put hint unchanged: {hint}"
        );

        // The EAM controller state gate (07-02): the hint names the
        // manual flip recipe + the README section (role decisions
        // stay one config-PUT away from the CLI, never one flag).
        let controller = CoreError::EamNotController { endpoint: None };
        let hint = controller.hint().expect("hint required");
        assert!(
            hint.contains("installMode"),
            "controller hint names the flip: {hint}"
        );
        assert!(
            hint.contains("Controller"),
            "controller hint names the target role: {hint}"
        );
        assert!(
            hint.contains("README"),
            "controller hint points at the README section: {hint}"
        );

        // The refused task-type ladder top (07-02 Task 3): the hint
        // names the EAM console + the v2 scope pointer.
        let refused = CoreError::EamTaskTypeRefused {
            task_type: "eam_restoreBackup".into(),
        };
        assert_eq!(refused.exit_code(), 6, "target state");
        let hint = refused.hint().expect("hint required");
        assert!(
            hint.contains("EAM console"),
            "refused hint names where to run it: {hint}"
        );
        assert!(
            hint.contains("fleet-wide") || hint.contains("EXT-03"),
            "refused hint names the fleet consequence / scope: {hint}"
        );

        // The force-route 409 (07-06 gap 4): the hint names the
        // resolution — complete or delete the leftover '(forced)'
        // run via the EAM console (no ign verb deletes runs).
        let in_flight = CoreError::EamTaskInFlight {
            task: "cli-research-backup".into(),
            detail: "the previous '(forced)' run must be completed or deleted first".into(),
            endpoint: None,
        };
        assert_eq!(in_flight.exit_code(), 6, "target state");
        let hint = in_flight.hint().expect("hint required");
        assert!(
            hint.contains("EAM console"),
            "in-flight hint names where to resolve it: {hint}"
        );
        assert!(
            hint.contains("complete or delete"),
            "in-flight hint names the resolution: {hint}"
        );

        // The scriptExec structural gate (07-03): the hint names the
        // deploy flag VERBATIM — the flag IS the opt-in (no --yes
        // exists on script run).
        let unconfigured = CoreError::ScriptExecNotConfigured {
            profile: "dev".into(),
        };
        assert_eq!(unconfigured.exit_code(), 6, "target state");
        let hint = unconfigured.hint().expect("hint required");
        assert!(
            hint.contains("ign webdev deploy --with-script-exec"),
            "the hint names the deploy flag verbatim: {hint}"
        );

        // Totality: no class silently loses its hint later.
        let no_active = CoreError::NoActiveProfile;
        assert!(no_active.hint().is_some());
    }

    /// The failure envelope's serialized field order and endpoint population
    /// are contract: `ok`, `profile`, `error` / `code`, `message`,
    /// `endpoint`, `hint` (string-level comparison because `serde_json::Value`
    /// maps are key-sorted and would hide ordering).
    #[test]
    fn error_envelope_locked_shape_and_endpoint() {
        let auth = CoreError::Auth {
            status: 401,
            endpoint: Some("https://gw.example.com/data/api/v1/gateway-info".into()),
        };
        let envelope: ErrorEnvelope<'_> = auth.envelope(Some("dev"));
        let json = serde_json::to_string(&envelope).expect("serialize envelope");

        assert_eq!(
            json,
            concat!(
                r#"{"ok":false,"profile":"dev","error":{"code":"auth_rejected","#,
                r#""message":"gateway rejected credentials (HTTP 401)","#,
                r#""endpoint":"https://gw.example.com/data/api/v1/gateway-info","#,
                r#""hint":"token not recognized — the X-Ignition-API-Token header must be the FULL `name:key` string from the gateway UI (Platform→Security→API Keys); Basic auth does not work on 8.3 /data routes — create an API token"}}"#
            )
        );

        // Classes without a request involved carry no endpoint.
        let no_request = CoreError::NoActiveProfile;
        let body: &ErrorBody = &no_request.envelope(None).error;
        assert_eq!(body.endpoint, None);
    }

    /// The api-call body cap (09-01): a body at or under
    /// [`GATEWAY_CLIENT_BODY_CAP_BYTES`] rides verbatim (no marker); a
    /// larger body is truncated to the cap on a UTF-8 char boundary with
    /// the exact ASCII marker appended — and the cap is enforced at
    /// CONSTRUCTION, so the variant always carries its final form.
    #[test]
    fn truncates_at_cap_with_marker() {
        // Under the cap: byte-identical passthrough.
        let short = r#"{"error":{"code":"NOT_FOUND"}}"#;
        assert_eq!(truncate_api_body(short), short);
        assert!(!short.contains(GATEWAY_CLIENT_BODY_TRUNCATION_MARKER));

        // Exactly at the cap: still verbatim (the marker only joins an
        // OVER-cap body — the boundary is <=, not <).
        let exact = "x".repeat(GATEWAY_CLIENT_BODY_CAP_BYTES);
        assert_eq!(truncate_api_body(&exact), exact);

        // One byte over: truncated, marker appended, total size bounded.
        let over = "x".repeat(GATEWAY_CLIENT_BODY_CAP_BYTES + 1);
        let truncated = truncate_api_body(&over);
        assert!(
            truncated.ends_with(GATEWAY_CLIENT_BODY_TRUNCATION_MARKER),
            "truncated body must end with the explicit marker"
        );
        assert!(
            truncated.len()
                <= GATEWAY_CLIENT_BODY_CAP_BYTES + GATEWAY_CLIENT_BODY_TRUNCATION_MARKER.len(),
            "truncated body must stay within cap + marker: {}",
            truncated.len()
        );

        // A multi-byte character straddling the cap boundary does not
        // panic (the cut backs up to a char boundary) and still carries
        // the marker.
        let multibyte = "é".repeat(GATEWAY_CLIENT_BODY_CAP_BYTES); // 2 bytes each
        let truncated = truncate_api_body(&multibyte);
        assert!(truncated.ends_with(GATEWAY_CLIENT_BODY_TRUNCATION_MARKER));
        assert!(
            truncated
                .is_char_boundary(truncated.len() - GATEWAY_CLIENT_BODY_TRUNCATION_MARKER.len())
        );
    }

    /// The loss-gate hint override (11-07 gap closure): a reason with the
    /// [`LOSS_GATE_REFUSAL_REASON_PREFIX`] sentinel carries the --yes
    /// hint, while every OTHER InvalidInput reason (generic file-read)
    /// and the TTY-refusal precedent keep their hints byte-identically.
    /// The loss-gate reason is built from the CONST via format! — a
    /// string literal of the sentinel text here would be a third
    /// production-literal hit and break the prefix-uniqueness gate the
    /// plan's verify pins.
    #[test]
    fn loss_gate_hint_override_and_neighbors_unchanged() {
        // Sentinel-prefixed reason (dynamic prose after the header):
        // the --yes hint, never the file-read default.
        let loss_gate = CoreError::InvalidInput {
            reason: format!(
                "{}xml): the scan reports 2 finding(s) before the import:\nre-run \
                 with --yes to import anyway",
                LOSS_GATE_REFUSAL_REASON_PREFIX
            ),
        };
        assert_eq!(loss_gate.code(), "invalid_input", "slug unchanged");
        assert_eq!(loss_gate.exit_code(), 2, "usage class unchanged");
        let hint = loss_gate.hint().expect("hint required");
        assert!(
            hint.contains("--yes"),
            "loss-gate hint must name the --yes re-run: {hint}"
        );
        assert!(
            hint.contains("loss report above"),
            "loss-gate hint must point back at the report: {hint}"
        );
        assert!(
            !hint.contains("fix the input source"),
            "the file-read default must never leak onto the loss-gate path: {hint}"
        );

        // Generic InvalidInput: the file-read default UNCHANGED (the
        // regression pin for every other raise site).
        let generic = CoreError::InvalidInput {
            reason: "x is not valid JSON: expected value at line 1".into(),
        };
        let hint = generic.hint().expect("hint required");
        assert!(
            hint.contains("--file") && hint.contains("stdin"),
            "resource-put hint unchanged: {hint}"
        );
        assert!(
            !hint.contains("--yes"),
            "the --yes hint must not leak onto generic reasons: {hint}"
        );

        // The TTY-refusal precedent intact (06-07).
        let tty = CoreError::tui_tty_refusal();
        let hint = tty.hint().expect("hint required");
        assert!(
            hint.contains("interactive terminal"),
            "TTY hint unchanged: {hint}"
        );
        assert!(
            !hint.contains("--yes"),
            "the --yes hint must not leak onto the TTY path: {hint}"
        );
    }
}