marque-ism 0.2.1

ISM vocabulary types, generated CVE enums, and Span for marque
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
// SPDX-FileCopyrightText: 2026 Knitli Inc.
//
// SPDX-License-Identifier: LicenseRef-MarqueLicense-1.0

//! `IsmAttributes` — the canonical in-memory representation of a classification marking.
//!
//! Mirrors the IC ISM XML attribute model. Every source format (free text, XML, web forms)
//! normalizes into this struct before rule validation.
//!
//! # Type design
//! Multi-value fields use `Box<[T]>` rather than `Vec<T>` to avoid over-allocation
//! after parsing. Most markings have 0–4 values per field.
//!
//! # Classification systems
//!
//! A marking carries exactly one classification system: US, FGI (non-US),
//! NATO, or JOINT. This is represented by [`MarkingClassification`]. Non-US
//! classifications start with `//` (the US classification slot is empty).
//!
//! When the parser encounters two classification systems in one marking
//! (e.g., `SECRET//NATO SECRET//NOFORN`), it resolves to
//! [`MarkingClassification::Conflict`] — US wins at the greater of the two
//! levels, and the foreign part is preserved for rule-generated fixes.
//!
//! # Code generation
//! CVE enum variants (`SciControl`, `DissemControl`, `DeclassExemption`) are
//! generated by `build.rs` from ODNI CVE XML files and re-exported from
//! `crate::generated::values`.
//!
//! SAR is NOT code-generated — SAR program identifiers are agency-assigned
//! codewords, not a closed vocabulary. SAR is modeled structurally via
//! [`SarMarking`] / [`SarProgram`] / [`SarCompartment`].

use crate::date::IsmDate;
use crate::generated::values;
use crate::span::Span;

// Re-export generated enum types for convenience.
pub use values::{DeclassExemption, DissemControl, SciControl, SciControlBare};

/// Canonical in-memory representation of a classification marking.
///
/// Produced by `marque-core::parser` from scanner candidates.
/// Consumed by `marque-rules::Rule` implementations for validation.
///
/// # Block ordering (CAPCO)
///
/// Fields are ordered per CAPCO block sequence:
/// Classification → SCI → SAR → FGI marker → Dissem (incl. REL TO)
#[non_exhaustive]
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct IsmAttributes {
    /// The marking's classification system and level.
    /// `None` means parsing failed to identify a classification.
    pub classification: Option<MarkingClassification>,

    /// SCI controls (e.g., SI, TK, HCS-P). Ordered per CAPCO block ordering.
    ///
    /// This is the *enum projection* populated by the parser's CVE exact-match
    /// path. Retained for back-compat with existing rules (E010, E011). New
    /// rules that need compartment / sub-compartment structure should read
    /// [`IsmAttributes::sci_markings`] instead.
    pub sci_controls: Box<[SciControl]>,

    /// Structural view of SCI category-block entries.
    ///
    /// Each entry corresponds to one `/`-separated marking within an SCI
    /// category block (e.g., `//SI-G/TK-BLFH//` yields two `SciMarking`
    /// entries). Populated alongside `sci_controls`; `sci_markings` is the
    /// authoritative source for rules that inspect compartments or
    /// sub-compartments. See spec 003-sci-compartments.
    pub sci_markings: Box<[SciMarking]>,

    /// Special Access Required block, if present. Only one SAR block is
    /// permitted per marking per §A.6; cardinality is `Option`, not `Vec`.
    /// See [`SarMarking`] for the structural representation.
    pub sar_markings: Option<SarMarking>,

    /// Atomic Energy Act markings (CAPCO Register §6).
    ///
    /// Includes RD, FRD, CNWDI, TFNI, SIGMA, and UCNI variants.
    /// Positioned between SAR and FGI in CAPCO block ordering.
    pub aea_markings: Box<[AeaMarking]>,

    /// FGI block in US-classified markings: `FGI` or `FGI [LIST]`.
    ///
    /// Present when a US-classified document references foreign government
    /// information. This is the *marker* in the banner/portion — distinct
    /// from [`MarkingClassification::Fgi`], which means the marking IS
    /// foreign-classified.
    ///
    /// `None` when no FGI marker is present.
    pub fgi_marker: Option<FgiMarker>,

    /// Dissemination controls (e.g., NOFORN, RELIDO, ORCON, FISA).
    pub dissem_controls: Box<[DissemControl]>,

    /// Non-IC dissemination controls (e.g., LIMDIS, SBU, LES, SSI).
    ///
    /// Separate authority framework (CAPCO Register §9), distinct from IC
    /// dissem controls. In classified documents these are generally portion-
    /// only and stripped from banners, but some values propagate to the
    /// classified banner; see [`NonIcDissem::propagates_to_classified_banner`]
    /// for the authoritative rule. On unclassified pages they propagate to
    /// the banner. LES-NF and SBU-NF carry NOFORN treatment even when
    /// stripped.
    pub non_ic_dissem: Box<[NonIcDissem]>,

    /// REL TO country / country-group codes. USA must be present and
    /// first when the marking targets a US release.
    ///
    /// Holds the full CAPCO country-code surface — trigraphs (`USA`,
    /// `GBR`), tetragraphs / country-group codes (`FVEY`, `ACGU`,
    /// `NATO`, `RSMA`, …), and the longer registered codes (`EU`,
    /// `AUSTRALIA_GROUP`). Tetragraph membership expansion (FVEY →
    /// {AUS, CAN, GBR, NZL, USA}) happens at banner-roll-up time in
    /// [`PageContext::expected_rel_to`], not at parse time, so this
    /// list preserves the source vocabulary as written.
    ///
    /// Structurally part of the dissem block (comma-delimited), but
    /// kept as a typed field for E002 and REL TO validation rules.
    pub rel_to: Box<[CountryCode]>,

    /// Declassification date from CAB (ISM precision-tier union).
    ///
    /// Typed as [`IsmDate`] to preserve the precision tier from the original
    /// source. In CAPCO text markings the parser accepts:
    /// - `YYYY` (4-digit year → [`IsmDate::Year`])
    /// - `YYYYMMDD` (8-digit no-hyphen → [`IsmDate::Date`])
    /// - ISO 8601 with hyphens (`YYYY-MM-DD`, etc.) for XML-sourced markings.
    ///
    /// `Year(y)` represents the entire calendar year — its end-of-span is
    /// December 31 of year `y`, which is later than any date in that year.
    /// Use [`IsmDate::end_cmp`] when determining the most-conservative
    /// (furthest-out) date across portions.
    pub declassify_on: Option<IsmDate>,

    /// Free-text "Classified By" identifier from CAB.
    pub classified_by: Option<Box<str>>,

    /// Free-text "Derived From" source from CAB.
    pub derived_from: Option<Box<str>>,

    /// Declassification exemption code from CAB (e.g., 25X1, 50X1-HUM).
    pub declass_exemption: Option<DeclassExemption>,

    /// Per-token byte spans into the *original source buffer*, recorded by
    /// the parser as it walks the marking string. Phase 3 added this so
    /// rules can point at the exact offending byte range instead of the
    /// whole marking. Empty for CAB markings (CAB parsing is line-structured
    /// and doesn't go through the token-walking path).
    ///
    /// Indexing convention: `token_spans` is in document order. To find the
    /// span for the Nth `DissemControl`, walk the slice and pick the Nth
    /// entry whose `kind == TokenKind::DissemControl`.
    pub token_spans: Box<[TokenSpan]>,
}

impl IsmAttributes {
    /// Convenience accessor: returns the US classification level if this
    /// marking uses the US or Conflict classification system.
    ///
    /// Returns `None` for pure FGI, NATO, or JOINT markings (use
    /// `self.classification` directly for those).
    pub fn us_classification(&self) -> Option<Classification> {
        match self.classification {
            Some(MarkingClassification::Us(c)) => Some(c),
            Some(MarkingClassification::Conflict { us, .. }) => Some(us),
            _ => None,
        }
    }
}

/// One parser-recognized token plus its byte span in the original source.
///
/// Used by Phase 3 rules to surface byte-precise diagnostic spans without
/// re-parsing the source. The `text` field carries the literal token bytes
/// so rules that need the source content (E006, E007, E008 against migration
/// keys) can look up entries without threading `&[u8] source` through every
/// `Rule::check` signature.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TokenSpan {
    pub kind: TokenKind,
    pub span: Span,
    pub text: Box<str>,
}

/// Discriminant for `TokenSpan`. Phase 3 rules read these to filter
/// token-span lookups by category.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum TokenKind {
    /// Classification level token (S, SECRET, TS, TOP SECRET, ...).
    Classification,
    /// SCI control token (SI, TK, HCS, ...).
    ///
    /// Emitted by the existing CVE exact-match path. For new structural
    /// parsing (spec 003-sci-compartments) see [`TokenKind::SciSystem`],
    /// [`TokenKind::SciCompartment`], and [`TokenKind::SciSubCompartment`].
    SciControl,
    /// Structural SCI control-system anchor (e.g., `SI`, `TK`, `123`).
    ///
    /// Emitted by the structural SCI parser introduced in spec
    /// 003-sci-compartments alongside the existing [`TokenKind::SciControl`]
    /// token for exact-CVE matches.
    SciSystem,
    /// Structural SCI compartment identifier (e.g., `G` in `SI-G`).
    SciCompartment,
    /// Structural SCI sub-compartment identifier (e.g., `ABCD` in `SI-G ABCD`).
    SciSubCompartment,
    /// Legacy SAR identifier token. Superseded by `SarIndicator` +
    /// `SarProgram` + `SarCompartment` + `SarSubCompartment` after the
    /// structural SAR model landed. No longer emitted by the parser.
    #[deprecated(note = "use SarIndicator/SarProgram/SarCompartment/SarSubCompartment")]
    SarIdentifier,
    /// SAR category indicator — `SAR-` or `SPECIAL ACCESS REQUIRED-`.
    /// One per SAR block; serves as the anchor for block-ordering rules.
    SarIndicator,
    /// SAR program identifier (e.g., `BP`, `BUTTER POPCORN`).
    SarProgram,
    /// SAR compartment identifier (e.g., `J12`).
    SarCompartment,
    /// SAR sub-compartment identifier (e.g., `J54`).
    SarSubCompartment,
    /// Atomic Energy Act marking token (RD, FRD, CNWDI, TFNI, SIGMA ##, etc.).
    AeaMarking,
    /// FGI marker token (`FGI`, `FGI DEU`, `FGI DEU GBR`).
    FgiMarker,
    /// Dissemination control token (NOFORN, NF, ORCON, OC, RELIDO, ...).
    DissemControl,
    /// Non-IC dissemination control token (LIMDIS, DS, SBU, LES, SSI, ...).
    NonIcDissem,
    /// REL TO country trigraph (USA, GBR, AUS, ...). One per token, not the
    /// whole REL TO list.
    RelToTrigraph,
    /// The full `REL TO ...` block text. Recorded so E013 can inspect the
    /// raw source for delimiter errors (spaces instead of commas).
    RelToBlock,
    /// Declassification exemption code in CAB or banner (25X1, 50X1-HUM).
    DeclassExemption,
    /// Declassification date in CAB or banner (YYYYMMDD or YYYY).
    DeclassDate,
    /// `//` separator between blocks. Recorded so E004 can detect extra/
    /// missing separator runs.
    Separator,
    /// A non-empty block that did not match any known token kind. E008 fires
    /// one diagnostic per `Unknown` entry.
    Unknown,
}

// ===========================================================================
// SAR (Special Access Required) structural types
// ===========================================================================
//
// See CAPCO Register §H.5 (pp 99–102) and §A.6 (pp 15–17) for the source
// grammar. SAR identifiers are agency-assigned codewords and cannot be
// enumerated — this type hierarchy validates shape and roll-up rather than
// membership.

/// Complete SAR category block parsed from a marking.
///
/// Produced by `marque-core::parser::parse_sar_category` (P2) and stored on
/// [`IsmAttributes::sar_markings`]. Only one SAR block is permitted per
/// marking per §A.6; multiple `//SAR-…//` blocks in the same marking yield
/// an `E030 sar-indicator-repeat` diagnostic.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SarMarking {
    /// The form of SAR indicator used in the source marking.
    pub indicator: SarIndicator,
    /// Programs in the order they appeared. Sort-order validation is
    /// performed by rule E028, not at parse time.
    pub programs: Box<[SarProgram]>,
}

/// Which SAR indicator form a marking uses. Banner lines may use either;
/// portion marks may only use `Abbrev` (rule E026 enforces this).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SarIndicator {
    /// `SAR-` (portion and banner).
    Abbrev,
    /// `SPECIAL ACCESS REQUIRED-` (banner only).
    Full,
}

/// A single Special Access Program with optional compartments.
///
/// Identifier forms (§A.6 grammar):
/// - Abbreviated: 2–3 alphanumeric characters (`BP`, `CD`, `XR`).
/// - Full (nickname): uppercase letters with optional spaces
///   (`BUTTER POPCORN`).
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SarProgram {
    /// Program identifier as it appeared in the source.
    pub identifier: Box<str>,
    /// Compartments in source order. May be empty.
    pub compartments: Box<[SarCompartment]>,
}

/// A compartment within a SAR program, optionally carrying sub-compartments.
///
/// §H.5 p100 explicitly forbids depicting hierarchy below the sub-compartment
/// level.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SarCompartment {
    /// Compartment identifier (alphanumeric).
    pub identifier: Box<str>,
    /// Sub-compartments in source order. May be empty.
    pub sub_compartments: Box<[Box<str>]>,
}

impl SarMarking {
    /// Construct a [`SarMarking`] from an indicator form and a list of
    /// programs. `programs` SHOULD be in source order — sort validation is
    /// performed by rule E028, not here.
    pub fn new(indicator: SarIndicator, programs: Box<[SarProgram]>) -> Self {
        Self {
            indicator,
            programs,
        }
    }
}

impl SarProgram {
    /// Construct a [`SarProgram`] with an optional compartment list.
    pub fn new(identifier: Box<str>, compartments: Box<[SarCompartment]>) -> Self {
        Self {
            identifier,
            compartments,
        }
    }
}

impl SarCompartment {
    /// Construct a [`SarCompartment`] with an optional sub-compartment list.
    pub fn new(identifier: Box<str>, sub_compartments: Box<[Box<str>]>) -> Self {
        Self {
            identifier,
            sub_compartments,
        }
    }
}

// ===========================================================================
// Classification types
// ===========================================================================

/// The classification system and level for a marking.
///
/// A marking has exactly one classification system. When the parser finds
/// two (e.g., `SECRET//NATO SECRET//...`), it resolves to [`Conflict`](Self::Conflict).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MarkingClassification {
    /// US IC classification.
    Us(Classification),
    /// Non-US (FGI) classification: `//GBR S//...`
    Fgi(FgiClassification),
    /// NATO classification: `//NS//...`
    Nato(NatoClassification),
    /// JOINT classification (US co-owned): `//JOINT S USA GBR//...`
    Joint(JointClassification),
    /// Parser found two classification systems in one marking.
    ///
    /// US wins, upgraded to the greater of the two levels.
    /// The foreign part is preserved so rules can suggest the FGI fix.
    ///
    /// Example: `SECRET//COSMIC TOP SECRET//REL TO USA, NATO`
    /// → `us: TopSecret`, `foreign: Nato(CosmicTopSecret)`
    /// → fix: `TOP SECRET//FGI NATO//REL TO USA, NATO`
    Conflict {
        /// Resolved US classification (max of both levels).
        us: Classification,
        /// The foreign classification that should become an FGI marker.
        foreign: Box<ForeignClassification>,
    },
}

impl MarkingClassification {
    /// The effective classification level for ordering purposes, regardless of
    /// classification system.
    ///
    /// NATO levels are mapped to their US equivalents via
    /// [`NatoClassification::us_equivalent`]. All systems use the
    /// [`Classification`] ladder for comparison so that `Iterator::max()` on
    /// a mixed set of portions returns the most restrictive level overall.
    pub fn effective_level(&self) -> Classification {
        match self {
            Self::Us(c) => *c,
            Self::Fgi(f) => f.level,
            Self::Nato(n) => n.us_equivalent(),
            Self::Joint(j) => j.level,
            Self::Conflict { us, .. } => *us,
        }
    }
}

impl Default for MarkingClassification {
    fn default() -> Self {
        Self::Us(Classification::Unclassified)
    }
}

/// The non-US classification in a [`MarkingClassification::Conflict`].
///
/// Preserves enough information for rules to generate the FGI fix:
/// the foreign system, its level, and any associated countries.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ForeignClassification {
    Fgi(FgiClassification),
    Nato(NatoClassification),
    Joint(JointClassification),
}

// ---------------------------------------------------------------------------
// Classification level (US ladder + RESTRICTED for foreign interop)
// ---------------------------------------------------------------------------

/// Classification level. Ordered by restrictiveness: U < R < C < S < TS.
///
/// Includes `Restricted` for foreign-origin markings — many non-US
/// classification systems (and NATO) have a RESTRICTED level between
/// UNCLASSIFIED and CONFIDENTIAL.
///
/// The derived `Ord` reflects restrictiveness ordering so that
/// `Iterator::max()` returns the most restrictive level.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Classification {
    Unclassified,
    Restricted,
    Confidential,
    Secret,
    TopSecret,
}

impl Classification {
    /// Banner form (full words, no abbreviations).
    pub fn banner_str(self) -> &'static str {
        match self {
            Self::Unclassified => "UNCLASSIFIED",
            Self::Restricted => "RESTRICTED",
            Self::Confidential => "CONFIDENTIAL",
            Self::Secret => "SECRET",
            Self::TopSecret => "TOP SECRET",
        }
    }

    /// Portion form (abbreviation used in portion markings).
    pub fn portion_str(self) -> &'static str {
        match self {
            Self::Unclassified => "U",
            Self::Restricted => "R",
            Self::Confidential => "C",
            Self::Secret => "S",
            Self::TopSecret => "TS",
        }
    }
}

// ---------------------------------------------------------------------------
// FGI classification (non-US, country-prefixed)
// ---------------------------------------------------------------------------

/// Non-US (FGI) classification.
///
/// Two forms exist:
///
/// - **Source-acknowledged**: country trigraph(s) identify the originator.
///   `//GBR S//REL TO USA, GBR`
/// - **Source-concealed**: `FGI` replaces the country trigraph(s) when
///   the originating country is sensitive. `//FGI S//REL TO USA, GBR`
///   An empty `countries` list indicates source-concealed FGI.
///
/// Countries are space-delimited in the source marking.
///
/// # Banner aggregation
///
/// If a document contains **any** source-concealed FGI portions alongside
/// source-acknowledged FGI portions, the banner must use `FGI` without
/// country codes — revealing the country list would compromise the
/// concealed source. This rule is enforced at the `PageContext` level
/// during banner validation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FgiClassification {
    /// Originating countries (space-delimited in source).
    /// Empty for source-concealed FGI (`//FGI S//...`).
    pub countries: Box<[CountryCode]>,
    /// Classification level (includes RESTRICTED).
    pub level: Classification,
}

// ---------------------------------------------------------------------------
// NATO classification
// ---------------------------------------------------------------------------

/// NATO classification ladder with optional SAP designation.
///
/// NATO uses a separate classification system governed by treaty.
/// Not everyone with a US clearance is cleared for NATO; many US systems
/// are not approved for NATO information.
///
/// # NATO SAP markings
///
/// Three NATO SAP programs exist, each with specific constraints:
///
/// - **ATOMAL**: Applies to CTS, NS, and NC levels. Space-separated in
///   banner (`COSMIC TOP SECRET ATOMAL`). Portion marks: CTSA, NSAT, NCA.
///   Alternative portion forms CTS-A, NS-A, NC-A also appear in practice.
/// - **BOHEMIA**: CTS-only. Hyphenated (`COSMIC TOP SECRET-BOHEMIA` → `CTS-B`).
/// - **BALK**: CTS-only, exercise replacement for BOHEMIA.
///   Hyphenated (`COSMIC TOP SECRET-BALK` → `CTS-BALK`).
///
/// Per the CAPCO Register, bare `COSMIC TOP SECRET` requires either
/// BOHEMIA or BALK — standalone CTS without a SAP suffix is an error.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum NatoClassification {
    NatoUnclassified,       // NU
    NatoRestricted,         // NR
    NatoConfidential,       // NC
    NatoConfidentialAtomal, // NCA (alt: NC-A)
    NatoSecret,             // NS
    NatoSecretAtomal,       // NSAT (alt: NS-A)
    CosmicTopSecret,        // CTS (requires BOHEMIA or BALK)
    CosmicTopSecretAtomal,  // CTSA (alt: CTS-A)
    CosmicTopSecretBohemia, // CTS-B
    CosmicTopSecretBalk,    // CTS-BALK
}

impl NatoClassification {
    /// Banner form (full words, as used in banner marking lines).
    pub fn banner_str(self) -> &'static str {
        match self {
            Self::NatoUnclassified => "NATO UNCLASSIFIED",
            Self::NatoRestricted => "NATO RESTRICTED",
            Self::NatoConfidential => "NATO CONFIDENTIAL",
            Self::NatoConfidentialAtomal => "NATO CONFIDENTIAL ATOMAL",
            Self::NatoSecret => "NATO SECRET",
            Self::NatoSecretAtomal => "NATO SECRET ATOMAL",
            Self::CosmicTopSecret => "COSMIC TOP SECRET",
            Self::CosmicTopSecretAtomal => "COSMIC TOP SECRET ATOMAL",
            Self::CosmicTopSecretBohemia => "COSMIC TOP SECRET-BOHEMIA",
            Self::CosmicTopSecretBalk => "COSMIC TOP SECRET-BALK",
        }
    }

    /// Portion form (primary abbreviation from the CAPCO Register).
    pub fn portion_str(self) -> &'static str {
        match self {
            Self::NatoUnclassified => "NU",
            Self::NatoRestricted => "NR",
            Self::NatoConfidential => "NC",
            Self::NatoConfidentialAtomal => "NCA",
            Self::NatoSecret => "NS",
            Self::NatoSecretAtomal => "NSAT",
            Self::CosmicTopSecret => "CTS",
            Self::CosmicTopSecretAtomal => "CTSA",
            Self::CosmicTopSecretBohemia => "CTS-B",
            Self::CosmicTopSecretBalk => "CTS-BALK",
        }
    }

    /// The base classification level (without SAP), for ordering comparisons.
    pub fn base_level(self) -> NatoLevel {
        match self {
            Self::NatoUnclassified => NatoLevel::NatoUnclassified,
            Self::NatoRestricted => NatoLevel::NatoRestricted,
            Self::NatoConfidential | Self::NatoConfidentialAtomal => NatoLevel::NatoConfidential,
            Self::NatoSecret | Self::NatoSecretAtomal => NatoLevel::NatoSecret,
            Self::CosmicTopSecret
            | Self::CosmicTopSecretAtomal
            | Self::CosmicTopSecretBohemia
            | Self::CosmicTopSecretBalk => NatoLevel::CosmicTopSecret,
        }
    }

    /// Map the NATO level to the equivalent US classification for conflict
    /// resolution (US wins at the greater of the two).
    pub fn us_equivalent(self) -> Classification {
        match self.base_level() {
            NatoLevel::NatoUnclassified => Classification::Unclassified,
            NatoLevel::NatoRestricted => Classification::Restricted,
            NatoLevel::NatoConfidential => Classification::Confidential,
            NatoLevel::NatoSecret => Classification::Secret,
            NatoLevel::CosmicTopSecret => Classification::TopSecret,
        }
    }
}

/// NATO classification level without SAP, for ordering comparisons.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum NatoLevel {
    NatoUnclassified,
    NatoRestricted,
    NatoConfidential,
    NatoSecret,
    CosmicTopSecret,
}

// ---------------------------------------------------------------------------
// JOINT classification
// ---------------------------------------------------------------------------

/// JOINT classification: US is co-owner with other nations.
///
/// `//JOINT S USA GBR//REL TO USA, GBR`
///
/// Country list is space-delimited (NOT comma-delimited like REL TO).
/// Must include USA. All JOINT participants must also appear in REL TO.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct JointClassification {
    /// Classification level (US ladder, includes RESTRICTED).
    pub level: Classification,
    /// Co-owning countries (space-delimited in source). Must include USA.
    pub countries: Box<[CountryCode]>,
}

// ---------------------------------------------------------------------------
// Atomic Energy Act markings
// ---------------------------------------------------------------------------

/// Atomic Energy Act information markings (CAPCO Register §6).
///
/// AEA markings appear as a single `//`-delimited block in the marking string,
/// using hyphen separators for compound forms:
/// - `SECRET//RD//NOFORN` — RD alone
/// - `SECRET//RD-CNWDI//NOFORN` — RD with CNWDI modifier
/// - `SECRET//RD-SIGMA 20//NOFORN` — RD with SIGMA compartment
/// - `SECRET//RD-SIGMA 18 20//NOFORN` — RD with multiple SIGMAs
/// - `SECRET//FRD//NOFORN` — FRD alone
/// - `SECRET//FRD-SIGMA 14//NOFORN` — FRD with SIGMA
///
/// Standalone (non-compound) markings:
/// - `UNCLASSIFIED//DOD UCNI` / `(U//DCNI)`
/// - `UNCLASSIFIED//DOE UCNI` / `(U//UCNI)`
/// - `SECRET//TFNI//NOFORN` / `(S//TFNI//NF)`
///
/// # Key rules (CAPCO-2016)
///
/// - RD and FRD always require NOFORN unless a sharing agreement exists
///   (default severity: Error, configurable to Warn via `.marque.toml`)
/// - CNWDI may only be used with TS or S RD (not standalone, not with FRD)
/// - SIGMA 14, 15, 18, 20 may only be used with TS or S RD or FRD
/// - RD takes precedence over FRD and TFNI in both banners and portions
/// - SIGMA numbers must be in numerical order, space-separated
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum AeaMarking {
    /// Compound RD block: `RD`, `RD-CNWDI`, `RD-SIGMA 20`, `RD-CNWDI-SIGMA 18 20`
    Rd(RdBlock),
    /// Compound FRD block: `FRD`, `FRD-SIGMA 14`
    Frd(FrdBlock),
    /// DOD UCNI / DCNI — standalone, unclassified only
    DodUcni,
    /// DOE UCNI / UCNI — standalone, unclassified only
    DoeUcni,
    /// TFNI — standalone
    Tfni,
}

/// Restricted Data block with optional modifiers.
///
/// Rendered as `RD`, `RD-CNWDI`, `RD-SIGMA 20`, or `RD-CNWDI-SIGMA 18 20`.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct RdBlock {
    /// Whether CNWDI is present. Only valid with TS or S classification.
    pub cnwdi: bool,
    /// SIGMA compartment numbers (14, 15, 18, 20). Must be in numerical order.
    /// Empty if no SIGMA designation.
    pub sigma: Box<[u8]>,
}

impl Default for RdBlock {
    fn default() -> Self {
        Self {
            cnwdi: false,
            sigma: Box::new([]),
        }
    }
}

/// Formerly Restricted Data block with optional SIGMA modifier.
///
/// Rendered as `FRD` or `FRD-SIGMA 14`.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct FrdBlock {
    /// SIGMA compartment numbers. Must be in numerical order.
    /// Empty if no SIGMA designation.
    pub sigma: Box<[u8]>,
}

impl Default for FrdBlock {
    fn default() -> Self {
        Self {
            sigma: Box::new([]),
        }
    }
}

impl AeaMarking {
    /// Banner-line form.
    pub fn banner_str(&self) -> String {
        match self {
            Self::Rd(rd) => {
                let mut s = "RD".to_owned();
                if rd.cnwdi {
                    s.push_str("-CNWDI");
                }
                if !rd.sigma.is_empty() {
                    s.push_str("-SIGMA ");
                    let nums: Vec<String> = rd.sigma.iter().map(|n| n.to_string()).collect();
                    s.push_str(&nums.join(" "));
                }
                s
            }
            Self::Frd(frd) => {
                let mut s = "FRD".to_owned();
                if !frd.sigma.is_empty() {
                    s.push_str("-SIGMA ");
                    let nums: Vec<String> = frd.sigma.iter().map(|n| n.to_string()).collect();
                    s.push_str(&nums.join(" "));
                }
                s
            }
            Self::DodUcni => "DOD UCNI".to_owned(),
            Self::DoeUcni => "DOE UCNI".to_owned(),
            Self::Tfni => "TFNI".to_owned(),
        }
    }

    /// Portion mark form.
    pub fn portion_str(&self) -> String {
        match self {
            Self::Rd(rd) => {
                let mut s = "RD".to_owned();
                if rd.cnwdi {
                    s.push_str("-CNWDI");
                }
                if !rd.sigma.is_empty() {
                    s.push_str("-SG ");
                    let nums: Vec<String> = rd.sigma.iter().map(|n| n.to_string()).collect();
                    s.push_str(&nums.join(" "));
                }
                s
            }
            Self::Frd(frd) => {
                let mut s = "FRD".to_owned();
                if !frd.sigma.is_empty() {
                    s.push_str("-SG ");
                    let nums: Vec<String> = frd.sigma.iter().map(|n| n.to_string()).collect();
                    s.push_str(&nums.join(" "));
                }
                s
            }
            Self::DodUcni => "DCNI".to_owned(),
            Self::DoeUcni => "UCNI".to_owned(),
            Self::Tfni => "TFNI".to_owned(),
        }
    }

    /// Parse a `//`-delimited AEA block from either banner or portion form.
    ///
    /// Handles compound tokens: `RD`, `RD-CNWDI`, `RD-SIGMA 20`,
    /// `RD-CNWDI-SIGMA 18 20`, `FRD`, `FRD-SIGMA 14`, etc.
    pub fn parse(s: &str) -> Option<Self> {
        // Standalone non-compound markings.
        match s {
            "DOD UCNI" | "DCNI" => return Some(Self::DodUcni),
            "DOE UCNI" | "UCNI" => return Some(Self::DoeUcni),
            "TFNI" | "TRANSCLASSIFIED FOREIGN NUCLEAR INFORMATION" => return Some(Self::Tfni),
            _ => {}
        }

        // RD compound block: RD, RD-CNWDI, RD-SIGMA ##, RD-CNWDI-SIGMA ##,
        // RESTRICTED DATA, RESTRICTED DATA-CNWDI, etc.
        if s == "RD" || s == "RESTRICTED DATA" {
            return Some(Self::Rd(RdBlock::default()));
        }
        if let Some(rest) = s
            .strip_prefix("RD-")
            .or_else(|| s.strip_prefix("RESTRICTED DATA-"))
        {
            return Self::parse_rd_modifiers(rest);
        }

        // FRD compound block: FRD, FRD-SIGMA ##,
        // FORMERLY RESTRICTED DATA, etc.
        if s == "FRD" || s == "FORMERLY RESTRICTED DATA" {
            return Some(Self::Frd(FrdBlock::default()));
        }
        if let Some(rest) = s
            .strip_prefix("FRD-")
            .or_else(|| s.strip_prefix("FORMERLY RESTRICTED DATA-"))
        {
            return Self::parse_frd_modifiers(rest);
        }

        None
    }

    /// Parse RD modifiers after the `RD-` prefix.
    /// Handles: `CNWDI`, `SIGMA ##`, `CNWDI-SIGMA ##`, `SG ##`, `CNWDI-SG ##`.
    fn parse_rd_modifiers(s: &str) -> Option<Self> {
        let mut cnwdi = false;
        let mut rest = s;

        // Check for CNWDI prefix.
        if let Some(after) = rest.strip_prefix("CNWDI") {
            cnwdi = true;
            rest = after.strip_prefix('-').unwrap_or(after);
        } else if rest == "N" {
            // DoD shorthand: RD-N means RD-CNWDI (per CAPCO-2016 §6)
            return Some(Self::Rd(RdBlock {
                cnwdi: true,
                sigma: Box::new([]),
            }));
        }

        // Check for SIGMA/SG.
        let sigma = parse_sigma_numbers(rest);

        if rest.is_empty() || !sigma.is_empty() {
            Some(Self::Rd(RdBlock {
                cnwdi,
                sigma: sigma.into(),
            }))
        } else {
            None
        }
    }

    /// Parse FRD modifiers after the `FRD-` prefix.
    /// Handles: `SIGMA ##`, `SG ##`.
    fn parse_frd_modifiers(s: &str) -> Option<Self> {
        let sigma = parse_sigma_numbers(s);
        if !sigma.is_empty() {
            Some(Self::Frd(FrdBlock {
                sigma: sigma.into(),
            }))
        } else {
            None
        }
    }
}

/// Parse SIGMA/SG numbers from a string like `SIGMA 18 20` or `SG 14`.
fn parse_sigma_numbers(s: &str) -> Vec<u8> {
    let rest = s
        .strip_prefix("SIGMA ")
        .or_else(|| s.strip_prefix("SG "))
        .unwrap_or("");
    if rest.is_empty() {
        return vec![];
    }
    rest.split_whitespace()
        .filter_map(|n| n.parse::<u8>().ok())
        .collect()
}

impl std::fmt::Display for AeaMarking {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.portion_str())
    }
}

// ---------------------------------------------------------------------------
// FGI marker (in US-classified markings)
// ---------------------------------------------------------------------------

/// FGI marker in a US-classified marking: `FGI` or `FGI [LIST]`.
///
/// Appears in the FGI block (after SAR, before dissem controls) when a
/// US-classified document references foreign government information.
///
/// This is NOT the same as [`FgiClassification`] — that represents a
/// marking where the classification itself IS foreign. This marker says
/// "this US-classified marking contains foreign government information."
///
/// An empty `countries` list represents source-concealed FGI (no country
/// attribution). If a document mixes source-concealed and source-acknowledged
/// FGI portions, the banner must use the bare `FGI` form without countries
/// to avoid compromising the concealed source.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FgiMarker {
    /// Countries (space-delimited in source).
    /// Empty for source-concealed FGI.
    pub countries: Box<[CountryCode]>,
}

// ===========================================================================
// Non-IC dissemination controls
// ===========================================================================

/// Non-Intelligence Community dissemination control markings (CAPCO Register §9).
///
/// These operate under a separate authority framework from IC dissem controls.
/// In classified documents, most non-IC dissem controls appear **only in portion
/// markings** — they are stripped from banners. However, some controls propagate
/// to classified banners: LIMDIS (NGA Title 10), LES, LES-NF, and SSI. See
/// [`NonIcDissem::propagates_to_classified_banner`] for the authoritative list.
/// When the page is **unclassified**, all non-IC dissem controls propagate to
/// the banner.
///
/// LES-NF and SBU-NF carry NOFORN treatment even when stripped from the banner.
///
/// # CUI note
///
/// CUI (Controlled Unclassified Information) is recognized but not validated.
/// Full CUI rule support is planned for a dedicated crate. The IC equivalent
/// (FOUO) remains in active use in the `DissemControl` enum.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
pub enum NonIcDissem {
    /// LIMITED DISTRIBUTION / LIMDIS / DS
    Limdis,
    /// EXCLUSIVE DISTRIBUTION / EXDIS / XD
    Exdis,
    /// NO DISTRIBUTION / NODIS / ND
    Nodis,
    /// SENSITIVE BUT UNCLASSIFIED / SBU / SBU
    Sbu,
    /// SENSITIVE BUT UNCLASSIFIED NOFORN / SBU NOFORN / SBU-NF
    /// Carries NOFORN treatment even when stripped from banner.
    SbuNf,
    /// LAW ENFORCEMENT SENSITIVE / LES / LES
    Les,
    /// LAW ENFORCEMENT SENSITIVE NOFORN / LES NOFORN / LES-NF
    /// Carries NOFORN treatment even when stripped from banner.
    LesNf,
    /// SENSITIVE SECURITY INFORMATION / SSI / SSI
    Ssi,
}

impl NonIcDissem {
    /// Banner-line abbreviation form.
    pub fn banner_str(self) -> &'static str {
        match self {
            Self::Limdis => "LIMDIS",
            Self::Exdis => "EXDIS",
            Self::Nodis => "NODIS",
            Self::Sbu => "SBU",
            Self::SbuNf => "SBU NOFORN",
            Self::Les => "LES",
            Self::LesNf => "LES NOFORN",
            Self::Ssi => "SSI",
        }
    }

    /// Portion mark abbreviation.
    pub fn portion_str(self) -> &'static str {
        match self {
            Self::Limdis => "DS",
            Self::Exdis => "XD",
            Self::Nodis => "ND",
            Self::Sbu => "SBU",
            Self::SbuNf => "SBU-NF",
            Self::Les => "LES",
            Self::LesNf => "LES-NF",
            Self::Ssi => "SSI",
        }
    }

    /// Parse from either banner or portion form.
    pub fn parse(s: &str) -> Option<Self> {
        match s {
            "LIMDIS" | "DS" => Some(Self::Limdis),
            "EXDIS" | "XD" => Some(Self::Exdis),
            "NODIS" | "ND" => Some(Self::Nodis),
            "SBU" => Some(Self::Sbu),
            "SBU NOFORN" | "SBU-NF" => Some(Self::SbuNf),
            "LES" => Some(Self::Les),
            "LES NOFORN" | "LES-NF" => Some(Self::LesNf),
            "SSI" => Some(Self::Ssi),
            _ => None,
        }
    }

    /// Returns true if this control carries NOFORN treatment.
    pub fn carries_noforn(self) -> bool {
        matches!(self, Self::SbuNf | Self::LesNf)
    }

    /// Returns true if this control propagates to classified banners.
    ///
    /// Authoritative source: `crates/capco/docs/CAPCO-2016.md` §H.9
    /// "Precedence Rules for Banner Line Guidance" for each marking.
    /// The per-marking rows below cite the specific line of the vendored
    /// manual.
    ///
    /// | Marking  | Propagates | Source (CAPCO-2016 §H.9)                                                                                            |
    /// |----------|------------|----------------------------------------------------------------------------------------------------------------------|
    /// | LIMDIS   | no         | line 4180: "When a document contains LIMDIS and classified portions, LIMDIS is not used in the banner line."         |
    /// | EXDIS    | yes        | line 4240: "If EXDIS is contained in any portion … EXDIS must appear in the banner line." Example banner: `SECRET//NOFORN//EXDIS` |
    /// | NODIS    | yes        | line 4300: "If NODIS is contained in any portion of a document, it must appear in the banner line." Example banner: `SECRET//NOFORN//NODIS` |
    /// | SBU      | no         | line 4358: "When a document contains SBU and classified portions, SBU is not used in the banner line."               |
    /// | SBU-NF   | no (†)     | line 4408: SBU NOFORN "Applicable only to unclassified information." (The §H.9 notional example on p179 shows a `SECRET//NOFORN` banner with a `(U//SBU-NF)` portion — SBU-NF absent from banner.) |
    /// | LES      | yes        | line 4479: "The LES marking always appears in the banner line if contained in any portion, regardless of classification level." |
    /// | LES-NF   | yes (*)    | line 4557: "The LES marking always appears in the banner line if LES information (either LES or LES NOFORN) is contained in the document, regardless of the document's classification level." |
    /// | SSI      | yes        | line 4651: "If the SSI marking is contained in any portion of a document it must appear in the banner line, regardless of the document's overall classification level." |
    ///
    /// (*) LES-NF carries a §H.9 canonicalization that is **not modeled
    ///     here**: in classified docs, `LES NOFORN` → `LES` at the banner
    ///     with NOFORN split into the dissem block (line 4558: "the 'LES'
    ///     marking is used in the banner line and the NOFORN marking is
    ///     applied as a Dissemination Control Marking. For example:
    ///     `SECRET//NOFORN//LES`."). The split itself is handled by
    ///     [`crate::PageContext::expected_non_ic_dissem`]; this predicate
    ///     only answers the binary "does the marking appear in the
    ///     banner at all?" question, which is what W003 consumes.
    ///     Treating `SECRET//LES NOFORN` as non-canonical (so that the
    ///     canonicalization becomes fixable) is a separate page-rewrite
    ///     concern, not a W003 concern.
    ///
    /// (†) "Does not propagate" for SBU-NF refers to the **SBU** half of
    ///     the marking — the literal `SBU NOFORN` banner form is
    ///     non-canonical in a classified document per §H.9 line 4408
    ///     ("applicable only to unclassified information"). The **NOFORN
    ///     half does propagate** via
    ///     [`crate::PageContext::expected_non_ic_dissem`], which splits a
    ///     portion-level `SBU-NF` into `SBU + NF-flag` and emits the
    ///     resulting NOFORN into the classified banner's dissem block.
    ///     So a document with a `(U//SBU-NF)` portion rolls up to a
    ///     `SECRET//NOFORN` banner (NOFORN present, SBU dropped), not
    ///     `SECRET//SBU NOFORN`. W003 therefore fires on the literal
    ///     `SECRET//SBU NOFORN` banner input because that surface form
    ///     is the non-canonical one, not because NOFORN is disallowed.
    pub fn propagates_to_classified_banner(self) -> bool {
        match self {
            // Do NOT propagate — banner-absent in classified documents.
            Self::Limdis | Self::Sbu | Self::SbuNf => false,
            // DO propagate — "must appear in the banner line" per §H.9.
            Self::Exdis | Self::Nodis | Self::Les | Self::LesNf | Self::Ssi => true,
        }
    }

    /// All valid values.
    pub const ALL: &[NonIcDissem] = &[
        Self::Limdis,
        Self::Exdis,
        Self::Nodis,
        Self::Sbu,
        Self::SbuNf,
        Self::Les,
        Self::LesNf,
        Self::Ssi,
    ];
}

impl std::fmt::Display for NonIcDissem {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.portion_str())
    }
}

// ===========================================================================
// CountryCode
// ===========================================================================

/// Maximum byte length of a CAPCO country code.
///
/// The longest entry in `CVEnumISMCATRelTo.xsd` is `AUSTRALIA_GROUP`
/// (15 bytes); 16 leaves one byte of headroom for any future
/// addition without forcing a struct-layout change.
const COUNTRY_CODE_CAPACITY: usize = 16;

/// A CAPCO country / country-group code, 2–16 ASCII bytes.
///
/// Covers every entry in the CVE country code list:
/// - 1× 2-char (`EU`)
/// - 280× 3-char trigraphs (`USA`, `GBR`, `AUS`, …)
/// - 58× 4-char tetragraphs / country-group codes (`FVEY`, `ACGU`,
///   `NATO`, `RSMA`, …)
/// - 1× 15-char (`AUSTRALIA_GROUP`)
///
/// The inner bytes are private; construction goes through
/// [`CountryCode::try_new`] which enforces the CAPCO byte-set invariant
/// (ASCII uppercase letters, ASCII digits, underscore — covers `AX2`,
/// `AX3`, `AUSTRALIA_GROUP`, and the standard alpha trigraphs/
/// tetragraphs) so that [`CountryCode::as_str`] can return a `&str`
/// infallibly without panicking at runtime.
///
/// `Copy` is preserved so the type composes in iterator chains and
/// `BTreeSet`-based intersection without manual `.clone()` calls.
/// The fixed-array form keeps each `CountryCode` entry inline in
/// `IsmAttributes::rel_to` (`Box<[CountryCode]>`) on the parsing
/// hot path — no per-code heap allocation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct CountryCode {
    /// Code bytes, zero-padded after `len`. Derived `Ord` compares
    /// lexicographically on the padded bytes; zero-padding makes
    /// shorter codes with a shared prefix sort first, matching `&str`
    /// ordering on ASCII.
    bytes: [u8; COUNTRY_CODE_CAPACITY],
    /// Active byte count, `2..=COUNTRY_CODE_CAPACITY`.
    len: u8,
}

impl CountryCode {
    /// The always-valid `USA` country code constant.
    ///
    /// Constructed via [`CountryCode::try_new`] in `const` context;
    /// the `expect` is statically unreachable for `b"USA"` (3 bytes,
    /// all ASCII uppercase) and exists only to satisfy `const`
    /// unwrap.
    pub const USA: Self = match Self::try_new(b"USA") {
        Some(c) => c,
        None => panic!("CountryCode::USA literal must satisfy try_new invariants"),
    };

    /// Returns `true` if `b` is in the CAPCO country-code byte set:
    /// ASCII uppercase letter, ASCII digit, or underscore. Digits cover
    /// `AX2`/`AX3`; underscore covers `AUSTRALIA_GROUP`.
    #[inline]
    const fn is_valid_byte(b: u8) -> bool {
        b.is_ascii_uppercase() || b.is_ascii_digit() || b == b'_'
    }

    /// Attempt to construct a country code from a byte slice.
    ///
    /// Returns `None` if `bytes`:
    /// - is shorter than 2 bytes (`EU` is the shortest CVE entry) or
    ///   longer than [`COUNTRY_CODE_CAPACITY`] bytes
    /// - contains any byte outside the CAPCO country-code byte set
    ///   (ASCII uppercase letter, ASCII digit, underscore)
    ///
    /// Membership in the CVE recognition set is a separate check —
    /// see [`crate::CapcoTokenSet::is_trigraph`] (the trait method
    /// covers any known country code, not only 3-char trigraphs).
    #[inline]
    pub const fn try_new(bytes: &[u8]) -> Option<Self> {
        let len = bytes.len();
        if len < 2 || len > COUNTRY_CODE_CAPACITY {
            return None;
        }
        let mut padded = [0u8; COUNTRY_CODE_CAPACITY];
        let mut i = 0;
        while i < len {
            if !Self::is_valid_byte(bytes[i]) {
                return None;
            }
            padded[i] = bytes[i];
            i += 1;
        }
        Some(Self {
            bytes: padded,
            len: len as u8,
        })
    }

    /// Return the country code as a string slice.
    ///
    /// Infallible because construction via [`CountryCode::try_new`]
    /// (or [`CountryCode::USA`]) guarantees every active byte is in the
    /// CAPCO byte set, which is a subset of ASCII / valid UTF-8.
    #[inline]
    pub fn as_str(&self) -> &str {
        // SAFETY: `CountryCode` can only be constructed via
        // `try_new` or constants (e.g. `CountryCode::USA`) that
        // route through `try_new` in const context. Both paths
        // require every active byte to be ASCII uppercase, ASCII
        // digit, or underscore. ASCII is a subset of valid UTF-8.
        #[allow(unsafe_code)]
        unsafe {
            std::str::from_utf8_unchecked(self.as_bytes())
        }
    }

    /// Active byte slice (excludes the zero padding).
    #[inline]
    pub fn as_bytes(&self) -> &[u8] {
        &self.bytes[..self.len as usize]
    }

    /// Number of active bytes, `2..=COUNTRY_CODE_CAPACITY`.
    #[inline]
    pub const fn len(&self) -> usize {
        self.len as usize
    }

    /// Always `false` — `CountryCode` invariants forbid empty codes.
    /// Provided for clippy-`len_without_is_empty` compliance.
    #[inline]
    pub const fn is_empty(&self) -> bool {
        false
    }
}

impl std::fmt::Display for CountryCode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

#[cfg(test)]
#[cfg_attr(coverage_nightly, coverage(off))]
mod country_code_tests {
    use super::CountryCode;

    #[test]
    fn try_new_accepts_two_byte_eu() {
        let eu = CountryCode::try_new(b"EU").unwrap();
        assert_eq!(eu.as_str(), "EU");
        assert_eq!(eu.len(), 2);
    }

    #[test]
    fn try_new_accepts_three_byte_trigraph() {
        let usa = CountryCode::try_new(b"USA").unwrap();
        assert_eq!(usa, CountryCode::USA);
        assert_eq!(usa.as_str(), "USA");
    }

    #[test]
    fn try_new_accepts_four_byte_tetragraph() {
        let fvey = CountryCode::try_new(b"FVEY").unwrap();
        assert_eq!(fvey.as_str(), "FVEY");
        assert_eq!(fvey.len(), 4);
    }

    #[test]
    fn try_new_accepts_australia_group_with_underscore() {
        let ag = CountryCode::try_new(b"AUSTRALIA_GROUP").unwrap();
        assert_eq!(ag.as_str(), "AUSTRALIA_GROUP");
        assert_eq!(ag.len(), 15);
    }

    #[test]
    fn try_new_accepts_digits_in_ax2_ax3() {
        assert_eq!(CountryCode::try_new(b"AX2").unwrap().as_str(), "AX2");
        assert_eq!(CountryCode::try_new(b"AX3").unwrap().as_str(), "AX3");
    }

    #[test]
    fn try_new_rejects_too_short() {
        assert!(CountryCode::try_new(b"").is_none());
        assert!(CountryCode::try_new(b"X").is_none());
    }

    #[test]
    fn try_new_rejects_too_long() {
        // 17 bytes — one over capacity.
        assert!(CountryCode::try_new(b"ABCDEFGHIJKLMNOPQ").is_none());
    }

    #[test]
    fn try_new_rejects_lowercase() {
        assert!(CountryCode::try_new(b"usa").is_none());
        assert!(CountryCode::try_new(b"Fvey").is_none());
    }

    #[test]
    fn try_new_rejects_non_ascii() {
        // 'É' is two UTF-8 bytes (0xC3 0x89); first byte fails the
        // is_valid_byte check.
        let bytes = "ÉU".as_bytes();
        assert!(CountryCode::try_new(bytes).is_none());
    }

    #[test]
    fn ord_matches_str_lex_for_mixed_lengths() {
        let eu = CountryCode::try_new(b"EU").unwrap();
        let aus = CountryCode::try_new(b"AUS").unwrap();
        let usa = CountryCode::USA;
        let usab = CountryCode::try_new(b"USAB").unwrap();
        let mut all = [eu, aus, usa, usab];
        all.sort();
        assert_eq!(all[0].as_str(), "AUS");
        assert_eq!(all[1].as_str(), "EU");
        assert_eq!(all[2].as_str(), "USA");
        assert_eq!(all[3].as_str(), "USAB");
    }

    #[test]
    fn copy_semantics_preserved() {
        let original = CountryCode::USA;
        let copy = original;
        // Both still usable — `Copy` not `Move`.
        assert_eq!(original, copy);
        assert_eq!(original.as_str(), copy.as_str());
    }

    #[test]
    fn display_renders_active_bytes_only() {
        // Display impl writes the active byte slice; the zero
        // padding past `len` must never reach the formatter.
        let usa = CountryCode::USA;
        let fvey = CountryCode::try_new(b"FVEY").unwrap();
        let ag = CountryCode::try_new(b"AUSTRALIA_GROUP").unwrap();
        assert_eq!(format!("{usa}"), "USA");
        assert_eq!(format!("{fvey}"), "FVEY");
        assert_eq!(format!("{ag}"), "AUSTRALIA_GROUP");
    }

    #[test]
    fn as_bytes_excludes_zero_padding() {
        let usa = CountryCode::USA;
        assert_eq!(usa.as_bytes(), b"USA");
        let fvey = CountryCode::try_new(b"FVEY").unwrap();
        assert_eq!(fvey.as_bytes(), b"FVEY");
    }

    #[test]
    fn is_empty_invariant_always_false() {
        // `try_new` rejects `len < 2`, so a constructed `CountryCode`
        // is never empty. `is_empty` exists only to satisfy clippy's
        // `len_without_is_empty`; pin the invariant so a future
        // refactor that loosens `try_new` is forced to revisit it.
        assert!(!CountryCode::USA.is_empty());
        assert!(!CountryCode::try_new(b"EU").unwrap().is_empty());
        assert!(!CountryCode::try_new(b"AUSTRALIA_GROUP").unwrap().is_empty());
    }

    #[test]
    fn usa_constant_matches_try_new() {
        // `pub const USA` constructs via `try_new` in const context.
        // Pin the equivalence so a future change to either path
        // (e.g., adding a normalization step to `try_new` but not
        // the const constructor) breaks loudly.
        let runtime = CountryCode::try_new(b"USA").unwrap();
        assert_eq!(CountryCode::USA, runtime);
        assert_eq!(CountryCode::USA.as_bytes(), runtime.as_bytes());
        assert_eq!(CountryCode::USA.len(), runtime.len());
    }
}

// ===========================================================================
// SCI structural types (spec 003-sci-compartments)
// ===========================================================================

/// A fully-parsed SCI category-block entry.
///
/// A banner or portion may carry multiple `SciMarking` entries separated by
/// `/` within one SCI category block (e.g., `//SI-G/TK-BLFH//`).
///
/// Construction is restricted to [`SciMarking::new`] (the struct is
/// `#[non_exhaustive]`) so new fields can be added without breaking the
/// parser.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SciMarking {
    /// The control-system anchor. One of the published bare control
    /// systems (see [`SciControlBare`]) or a structurally-parsed custom
    /// value.
    pub system: SciControlSystem,

    /// Compartments in source order. Sort-order validation is the concern
    /// of CAPCO rule E033 (not the parser).
    pub compartments: Box<[SciCompartment]>,

    /// If the `{system}-{first_compartment}` composite exactly matches an
    /// ODNI CVE value (e.g., `SI-G`, `HCS-P`, `TK-BLFH`), this records the
    /// matching [`SciControl`] variant. Only populated when the matching
    /// compartment has NO sub-compartments — sub-compartments imply the
    /// compound is a structural anchor rather than a CVE atom. `None`
    /// otherwise.
    pub canonical_enum: Option<SciControl>,
}

impl SciMarking {
    /// Construct a new `SciMarking`. Used by the parser (`marque-core`) to
    /// populate [`IsmAttributes::sci_markings`].
    pub fn new(
        system: SciControlSystem,
        compartments: Box<[SciCompartment]>,
        canonical_enum: Option<SciControl>,
    ) -> Self {
        Self {
            system,
            compartments,
            canonical_enum,
        }
    }
}

/// Which kind of SCI control system a [`SciMarking`] anchors on.
///
/// This is a closed set of two variants: either a published bare system
/// drawn from the live ODNI CVE, or an agency-allocated custom identifier
/// (per CAPCO-2016 §A.6 p15).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SciControlSystem {
    /// One of the published bare control systems.
    Published(SciControlBare),
    /// An agency-allocated system matching `[A-Z0-9]{2,5}` (per CAPCO-2016
    /// §A.6 p15 `123` example). Stores the raw text exactly as it appeared
    /// in the source.
    Custom(Box<str>),
}

/// A single compartment under an SCI control system.
///
/// Compartments carry an identifier plus zero or more sub-compartments in
/// source order. Construction is restricted to [`SciCompartment::new`]
/// (the struct is `#[non_exhaustive]`).
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SciCompartment {
    /// Compartment identifier (alphanumeric). Example: `G` in `SI-G`.
    pub identifier: Box<str>,
    /// Sub-compartments in source order. Example: `ABCD`, `DEFG` in
    /// `SI-G ABCD DEFG`.
    pub sub_compartments: Box<[Box<str>]>,
}

impl SciCompartment {
    /// Construct a new `SciCompartment`. Used by the parser to populate
    /// [`SciMarking::compartments`].
    pub fn new(identifier: Box<str>, sub_compartments: Box<[Box<str>]>) -> Self {
        Self {
            identifier,
            sub_compartments,
        }
    }
}

#[cfg(test)]
#[cfg_attr(coverage_nightly, coverage(off))]
mod tests {
    use super::*;

    #[test]
    fn classification_ord_is_restrictiveness() {
        assert!(Classification::Unclassified < Classification::Restricted);
        assert!(Classification::Restricted < Classification::Confidential);
        assert!(Classification::Confidential < Classification::Secret);
        assert!(Classification::Secret < Classification::TopSecret);
    }

    #[test]
    fn classification_banner_portion_round_trip() {
        for c in [
            Classification::Unclassified,
            Classification::Restricted,
            Classification::Confidential,
            Classification::Secret,
            Classification::TopSecret,
        ] {
            assert!(!c.banner_str().is_empty());
            assert!(!c.portion_str().is_empty());
        }
    }

    #[test]
    fn nato_us_equivalent_mapping() {
        assert_eq!(
            NatoClassification::CosmicTopSecret.us_equivalent(),
            Classification::TopSecret,
        );
        assert_eq!(
            NatoClassification::NatoSecret.us_equivalent(),
            Classification::Secret,
        );
        assert_eq!(
            NatoClassification::NatoRestricted.us_equivalent(),
            Classification::Restricted,
        );
    }

    #[test]
    fn nato_banner_portion_round_trip() {
        for n in [
            NatoClassification::NatoUnclassified,
            NatoClassification::NatoRestricted,
            NatoClassification::NatoConfidential,
            NatoClassification::NatoConfidentialAtomal,
            NatoClassification::NatoSecret,
            NatoClassification::NatoSecretAtomal,
            NatoClassification::CosmicTopSecret,
            NatoClassification::CosmicTopSecretAtomal,
            NatoClassification::CosmicTopSecretBohemia,
            NatoClassification::CosmicTopSecretBalk,
        ] {
            assert!(!n.banner_str().is_empty());
            assert!(!n.portion_str().is_empty());
        }
    }

    #[test]
    fn us_classification_convenience_returns_us() {
        let attrs = IsmAttributes {
            classification: Some(MarkingClassification::Us(Classification::Secret)),
            ..Default::default()
        };
        assert_eq!(attrs.us_classification(), Some(Classification::Secret));
    }

    #[test]
    fn us_classification_convenience_returns_none_for_nato() {
        let attrs = IsmAttributes {
            classification: Some(MarkingClassification::Nato(NatoClassification::NatoSecret)),
            ..Default::default()
        };
        assert_eq!(attrs.us_classification(), None);
    }

    #[test]
    fn us_classification_convenience_returns_resolved_for_conflict() {
        let attrs = IsmAttributes {
            classification: Some(MarkingClassification::Conflict {
                us: Classification::TopSecret,
                foreign: Box::new(ForeignClassification::Nato(
                    NatoClassification::CosmicTopSecret,
                )),
            }),
            ..Default::default()
        };
        assert_eq!(attrs.us_classification(), Some(Classification::TopSecret));
    }
}