lean-ctx-protocol 0.4.0

Open wire contracts for lean-ctx: events, observations, assignments, evidence gaps.
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
// SPDX-License-Identifier: Apache-2.0
//! Context Gateway v1 — the canonical, public decision contract.
//!
//! Every governed piece of context carries a [`ContextObjectPassportV1`]; the
//! gateway records one [`ContextDecisionV1`] per object and summarises a
//! delivery in one [`ContextDecisionReceiptV1`], which is the single source for
//! audit, HUD and SDK surfaces. The contract never carries content, secret
//! values or detector matches — only digests, counts and reason codes.
//!
//! Field-level invariants (principal, coverage, reason codes) are enforced at
//! construction *and* deserialization; cross-field invariants by `validate()`,
//! which `derive` and `canonical_digest` call. All of them fail closed:
//! - an unknown principal is explicit and never carries an identity;
//! - classification only ever rises through derivation ([`ClassificationV1::join`]);
//! - destination constraints only accumulate;
//! - a detector may not report more coverage than it inspected;
//! - a receipt's security counts must equal its per-object decisions.

use std::collections::BTreeSet;
use std::fmt::Write as _;

use serde::{Deserialize, Deserializer, Serialize, de::Error as DeError};
use sha2::{Digest, Sha256};

use crate::common::{
    TaskId, V1_SCHEMA_VERSION, ValidationError, deserialize_schema_version, validate_schema_version,
};
use crate::identity::{PolicyId, ProtocolReference, SemanticVersion, Sha256Digest, SourceId};

/// Bounds keep untrusted receipts from growing without limit.
pub const MAX_REASON_CODES: usize = 32;
pub const MAX_SIGNALS: usize = 256;
pub const MAX_DECISIONS: usize = 4_096;
pub const MAX_LINEAGE: usize = 256;
pub const MAX_POLICY_REFS: usize = 32;
const MAX_REASON_CODE_LEN: usize = 64;

// ─── Classification ─────────────────────────────────────────────────────────

/// The one classification lattice: `Public < Internal < Confidential < Restricted`.
///
/// Secrets and credentials are `Restricted`. There is deliberately no
/// `Default`: an unclassified object must be classified by the mode's rule
/// ([`GatewayModeV1::unclassified`]), never by an implicit fallback.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ClassificationV1 {
    Public,
    Internal,
    Confidential,
    Restricted,
}

impl ClassificationV1 {
    /// Information-flow join: a derived object is at least as sensitive as the
    /// most sensitive input.
    #[must_use]
    pub fn join(self, other: Self) -> Self {
        self.max(other)
    }
}

impl From<crate::team_context::TeamClassification> for ClassificationV1 {
    fn from(value: crate::team_context::TeamClassification) -> Self {
        use crate::team_context::TeamClassification as T;
        match value {
            T::Public => Self::Public,
            T::Internal => Self::Internal,
            T::Confidential => Self::Confidential,
            T::Restricted => Self::Restricted,
        }
    }
}

impl From<crate::knowledge::ClassificationLevel> for ClassificationV1 {
    fn from(value: crate::knowledge::ClassificationLevel) -> Self {
        use crate::knowledge::ClassificationLevel as K;
        match value {
            K::Public => Self::Public,
            K::Internal => Self::Internal,
            K::Confidential => Self::Confidential,
            K::Restricted => Self::Restricted,
        }
    }
}

impl From<crate::experiment::DataClassification> for ClassificationV1 {
    fn from(value: crate::experiment::DataClassification) -> Self {
        use crate::experiment::DataClassification as D;
        match value {
            D::Public => Self::Public,
            D::Internal => Self::Internal,
            D::Confidential => Self::Confidential,
            D::Restricted => Self::Restricted,
        }
    }
}

/// Projection of the VIA classification onto the two gateway axes. VIA mixes
/// sensitivity with placement (`LocalOnly`, `EnterprisePrivate`); the gateway
/// keeps placement as a [`DestinationConstraintV1`] so locality never depends
/// on a sensitivity estimate.
#[must_use]
pub fn project_via_classification(
    value: crate::edge_via::ViaClassificationV1,
) -> (ClassificationV1, Option<DestinationConstraintV1>) {
    use crate::edge_via::ViaClassificationV1 as V;
    match value {
        V::Public => (ClassificationV1::Public, None),
        V::Normal => (ClassificationV1::Internal, None),
        V::Sensitive => (ClassificationV1::Confidential, None),
        V::Secret => (ClassificationV1::Restricted, None),
        V::LocalOnly => (
            ClassificationV1::Confidential,
            Some(DestinationConstraintV1::LocalOnly),
        ),
        V::EnterprisePrivate => (
            ClassificationV1::Confidential,
            Some(DestinationConstraintV1::OrganizationPrivate),
        ),
    }
}

/// Operating posture of the gateway.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum GatewayModeV1 {
    /// Local-first, strong defaults, visible warnings.
    Developer,
    /// Organisation-controlled: identity and mandatory checks fail closed.
    Governed,
    /// Nothing leaves the trust boundary except to approved destinations.
    Sovereign,
}

impl GatewayModeV1 {
    /// Classification for an object no detector or label classified.
    #[must_use]
    pub fn unclassified(self) -> ClassificationV1 {
        match self {
            Self::Developer => ClassificationV1::Public,
            Self::Governed | Self::Sovereign => ClassificationV1::Internal,
        }
    }
}

// ─── Principal and destination ──────────────────────────────────────────────

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PrincipalKindV1 {
    Person,
    Team,
    Organization,
    Project,
    Agent,
    Session,
    Workload,
    /// No authenticated identity. Explicit, and never an authorization.
    Unknown,
}

/// Who requested the context. `Unknown` never carries an id; every other
/// kind must.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
pub struct PrincipalV1 {
    pub kind: PrincipalKindV1,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub id: Option<ProtocolReference>,
}

impl PrincipalV1 {
    pub fn new(kind: PrincipalKindV1, id: ProtocolReference) -> Result<Self, ValidationError> {
        if kind == PrincipalKindV1::Unknown {
            return Err(ValidationError::new(
                "an unknown principal must not carry an identity",
            ));
        }
        Ok(Self { kind, id: Some(id) })
    }

    #[must_use]
    pub fn unknown() -> Self {
        Self {
            kind: PrincipalKindV1::Unknown,
            id: None,
        }
    }

    #[must_use]
    pub fn is_known(&self) -> bool {
        self.kind != PrincipalKindV1::Unknown
    }
}

impl<'de> Deserialize<'de> for PrincipalV1 {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        #[derive(Deserialize)]
        #[serde(deny_unknown_fields)]
        struct Wire {
            kind: PrincipalKindV1,
            #[serde(default)]
            id: Option<ProtocolReference>,
        }
        let wire = Wire::deserialize(deserializer)?;
        match (wire.kind, wire.id) {
            (PrincipalKindV1::Unknown, None) => Ok(Self::unknown()),
            (PrincipalKindV1::Unknown, Some(_)) => Err(DeError::custom(
                "an unknown principal must not carry an identity",
            )),
            (_, None) => Err(DeError::custom("a known principal requires an id")),
            (kind, Some(id)) => Ok(Self { kind, id: Some(id) }),
        }
    }
}

/// Placement constraints that only ever accumulate through derivation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum DestinationConstraintV1 {
    /// Must never leave the local machine.
    LocalOnly,
    /// Only organisation-managed destinations (or local ones).
    OrganizationPrivate,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum DestinationLocalityV1 {
    Local,
    Remote,
    /// Not established. Never satisfies a locality constraint.
    Unknown,
}

/// Where the compiled context is delivered. Models LeanCTX itself uses
/// (detectors, summarisers) are destinations too.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct DestinationV1 {
    pub provider: ProtocolReference,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub model: Option<ProtocolReference>,
    pub locality: DestinationLocalityV1,
    /// True only when the destination is attested as organisation-managed.
    #[serde(default)]
    pub organization_managed: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub account_ref: Option<ProtocolReference>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub region: Option<ProtocolReference>,
}

impl DestinationV1 {
    /// Whether this destination may receive an object with `constraint`.
    #[must_use]
    pub fn satisfies(&self, constraint: DestinationConstraintV1) -> bool {
        match constraint {
            DestinationConstraintV1::LocalOnly => self.locality == DestinationLocalityV1::Local,
            DestinationConstraintV1::OrganizationPrivate => {
                self.locality == DestinationLocalityV1::Local
                    || (self.organization_managed && self.locality == DestinationLocalityV1::Remote)
            }
        }
    }

    /// Whether this destination satisfies every constraint in `constraints`.
    #[must_use]
    pub fn satisfies_all<'a>(
        &self,
        constraints: impl IntoIterator<Item = &'a DestinationConstraintV1>,
    ) -> bool {
        constraints
            .into_iter()
            .all(|constraint| self.satisfies(*constraint))
    }
}

// ─── Reason codes and policy references ─────────────────────────────────────

/// Stable, machine-readable reason: `[a-z][a-z0-9_.]{2,63}`.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
#[serde(transparent)]
pub struct ReasonCodeV1(String);

impl ReasonCodeV1 {
    pub fn new(value: impl Into<String>) -> Result<Self, ValidationError> {
        let value = value.into();
        let bytes = value.as_bytes();
        let valid = (3..=MAX_REASON_CODE_LEN).contains(&bytes.len())
            && bytes[0].is_ascii_lowercase()
            && bytes
                .iter()
                .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || *b == b'_' || *b == b'.');
        if !valid {
            return Err(ValidationError::new(format!(
                "reason code {value:?} must match [a-z][a-z0-9_.]{{2,63}}"
            )));
        }
        Ok(Self(value))
    }

    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl<'de> Deserialize<'de> for ReasonCodeV1 {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        Self::new(String::deserialize(deserializer)?).map_err(|e| DeError::custom(e.0))
    }
}

/// The exact policy that decided: identity, optional version, content digest.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PolicyRefV1 {
    pub id: PolicyId,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub version: Option<SemanticVersion>,
    pub digest: Sha256Digest,
}

// ─── Detector signals ───────────────────────────────────────────────────────

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum DetectorCategoryV1 {
    Secret,
    Pii,
    PromptInjection,
    Classification,
    Policy,
    Custom,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SeverityV1 {
    Info,
    Low,
    Medium,
    High,
    Critical,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CoverageKindV1 {
    /// Every byte of the object was inspected.
    Complete,
    /// Only part of the object was inspected (prefix, chunk budget, …).
    Partial,
    /// The detector cannot inspect this media type.
    Unsupported,
    /// The detector failed; nothing it reported can be relied on.
    Failed,
    /// Policy did not require this detector for this object.
    NotRequired,
}

/// What a detector actually looked at. A result never implies more coverage
/// than recorded here.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct DetectorCoverageV1 {
    pub kind: CoverageKindV1,
    pub bytes_total: u64,
    pub bytes_inspected: u64,
    pub chunks_total: u32,
    pub chunks_inspected: u32,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reason: Option<ReasonCodeV1>,
}

impl DetectorCoverageV1 {
    pub fn validate(&self) -> Result<(), ValidationError> {
        if self.bytes_inspected > self.bytes_total || self.chunks_inspected > self.chunks_total {
            return Err(ValidationError::new(
                "coverage must not inspect more than the object holds",
            ));
        }
        let all_bytes = self.bytes_inspected == self.bytes_total;
        match self.kind {
            CoverageKindV1::Complete if !all_bytes => Err(ValidationError::new(
                "complete coverage must inspect every byte",
            )),
            CoverageKindV1::Partial if all_bytes => Err(ValidationError::new(
                "partial coverage must leave bytes uninspected",
            )),
            _ => Ok(()),
        }
    }

    /// True only when the detector inspected the whole object.
    #[must_use]
    pub fn is_complete(&self) -> bool {
        self.kind == CoverageKindV1::Complete
    }
}

impl<'de> Deserialize<'de> for DetectorCoverageV1 {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        #[derive(Deserialize)]
        #[serde(deny_unknown_fields)]
        struct Wire {
            kind: CoverageKindV1,
            bytes_total: u64,
            bytes_inspected: u64,
            chunks_total: u32,
            chunks_inspected: u32,
            #[serde(default)]
            reason: Option<ReasonCodeV1>,
        }
        let w = Wire::deserialize(deserializer)?;
        let coverage = Self {
            kind: w.kind,
            bytes_total: w.bytes_total,
            bytes_inspected: w.bytes_inspected,
            chunks_total: w.chunks_total,
            chunks_inspected: w.chunks_inspected,
            reason: w.reason,
        };
        coverage.validate().map_err(|e| DeError::custom(e.0))?;
        Ok(coverage)
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum DetectorStatusV1 {
    Completed,
    Failed,
    TimedOut,
    Skipped,
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct DetectorRefV1 {
    pub id: ProtocolReference,
    pub version: SemanticVersion,
}

/// One detector's normalised result. Carries counts only — never the matched
/// value — so telemetry and receipts cannot leak what was detected.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct DetectorSignalV1 {
    pub detector: DetectorRefV1,
    pub category: DetectorCategoryV1,
    pub severity: SeverityV1,
    /// Confidence in thousandths. Not a probability unless `calibrated`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub confidence_milli: Option<u16>,
    #[serde(default)]
    pub calibrated: bool,
    pub evidence_count: u32,
    pub coverage: DetectorCoverageV1,
    pub status: DetectorStatusV1,
    pub latency_us: u64,
}

impl DetectorSignalV1 {
    pub fn validate(&self) -> Result<(), ValidationError> {
        self.coverage.validate()?;
        if self.confidence_milli.is_some_and(|c| c > 1_000) {
            return Err(ValidationError::new(
                "confidence_milli must be at most 1000",
            ));
        }
        let failed = matches!(
            self.status,
            DetectorStatusV1::Failed | DetectorStatusV1::TimedOut
        );
        if failed && self.coverage.is_complete() {
            return Err(ValidationError::new(
                "a failed or timed-out detector cannot claim complete coverage",
            ));
        }
        Ok(())
    }

    /// Whether this signal may satisfy a *required* detector: it ran to
    /// completion over the whole object.
    #[must_use]
    pub fn satisfies_requirement(&self) -> bool {
        self.status == DetectorStatusV1::Completed && self.coverage.is_complete()
    }
}

// ─── Decisions and transformations ──────────────────────────────────────────

/// Per-object outcome, ordered from least to most restrictive.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ContextDispositionV1 {
    Allow,
    AllowMinimized,
    AllowRedacted,
    AllowSummaryOnly,
    AllowLocalModelOnly,
    /// Held until an approver releases it; not delivered meanwhile.
    AllowWithApproval,
    Quarantine,
    Deny,
}

impl ContextDispositionV1 {
    /// Whether content (possibly transformed) reaches the destination now.
    #[must_use]
    pub fn delivers_content(self) -> bool {
        self <= Self::AllowLocalModelOnly
    }

    /// Combining two rules keeps the stricter outcome.
    #[must_use]
    pub fn most_restrictive(self, other: Self) -> Self {
        self.max(other)
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TransformationKindV1 {
    Redaction,
    Classification,
    Selection,
    Deduplication,
    StructuralExtraction,
    Compression,
    Summarization,
    Recovery,
    Reranking,
}

/// One step in an object's lineage: which transformation turned which input
/// digest into which output digest, and what it cost or saved.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct TransformationRecordV1 {
    pub kind: TransformationKindV1,
    pub input: Sha256Digest,
    pub output: Sha256Digest,
    pub tokens_before: u64,
    pub tokens_after: u64,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub reason_codes: Vec<ReasonCodeV1>,
}

/// The gateway's decision about one object. Anything but a plain `Allow`
/// must say why.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ContextDecisionV1 {
    pub object: Sha256Digest,
    pub disposition: ContextDispositionV1,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub reason_codes: Vec<ReasonCodeV1>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub signals: Vec<DetectorSignalV1>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub required_transformations: Vec<TransformationKindV1>,
}

impl ContextDecisionV1 {
    pub fn validate(&self) -> Result<(), ValidationError> {
        if self.disposition != ContextDispositionV1::Allow && self.reason_codes.is_empty() {
            return Err(ValidationError::new(
                "every non-allow decision requires at least one reason code",
            ));
        }
        if self.reason_codes.len() > MAX_REASON_CODES || self.signals.len() > MAX_SIGNALS {
            return Err(ValidationError::new("decision exceeds its bounds"));
        }
        for signal in &self.signals {
            signal.validate()?;
        }
        Ok(())
    }
}

// ─── Passport ───────────────────────────────────────────────────────────────

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SourceKindV1 {
    File,
    Shell,
    Search,
    Provider,
    Memory,
    Knowledge,
    Agent,
    Web,
    Other,
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SourceRefV1 {
    pub kind: SourceKindV1,
    pub id: SourceId,
}

/// How far the source is trusted, least trusted first.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TrustLevelV1 {
    Untrusted,
    Unknown,
    Internal,
    Trusted,
}

/// Security and optimisation metadata that travels with one object. Content
/// is referenced by digest, never embedded.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ContextObjectPassportV1 {
    #[serde(deserialize_with = "deserialize_schema_version")]
    pub schema_version: u32,
    pub object: Sha256Digest,
    pub source: SourceRefV1,
    pub principal: PrincipalV1,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub task: Option<TaskId>,
    pub classification: ClassificationV1,
    pub trust: TrustLevelV1,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub policy_refs: Vec<PolicyRefV1>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub risk_signals: Vec<DetectorSignalV1>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub destination_constraints: Vec<DestinationConstraintV1>,
    pub tokens: u64,
    pub bytes: u64,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub lineage: Vec<TransformationRecordV1>,
}

impl ContextObjectPassportV1 {
    pub fn validate(&self) -> Result<(), ValidationError> {
        validate_schema_version(self.schema_version)?;
        if self.policy_refs.len() > MAX_POLICY_REFS
            || self.risk_signals.len() > MAX_SIGNALS
            || self.lineage.len() > MAX_LINEAGE
        {
            return Err(ValidationError::new("passport exceeds its bounds"));
        }
        if !is_strictly_sorted(&self.destination_constraints)
            || !is_strictly_sorted(&self.policy_refs)
        {
            return Err(ValidationError::new(
                "destination constraints and policy refs must be sorted and unique",
            ));
        }
        for signal in &self.risk_signals {
            signal.validate()?;
        }
        Ok(())
    }

    /// Passport of an object derived from `inputs` by `step` (selection,
    /// summary, dedup, …). Information-flow rule: the result is at least as
    /// restricted as every input — classification is the join, constraints,
    /// policies and risk signals accumulate, trust drops to the least trusted
    /// input. Inputs must share one principal: context never silently crosses
    /// principals.
    pub fn derive(
        inputs: &[&Self],
        step: TransformationRecordV1,
        source: SourceRefV1,
        tokens: u64,
        bytes: u64,
    ) -> Result<Self, ValidationError> {
        let Some(first) = inputs.first() else {
            return Err(ValidationError::new(
                "derivation requires at least one input",
            ));
        };
        if inputs.iter().any(|p| p.principal != first.principal) {
            return Err(ValidationError::new(
                "derivation must not combine context of different principals",
            ));
        }
        let task = first.task.clone();
        let mut classification = first.classification;
        let mut trust = first.trust;
        let mut constraints = BTreeSet::new();
        let mut policies = BTreeSet::new();
        let mut signals = Vec::new();
        let mut lineage = Vec::new();
        for input in inputs {
            classification = classification.join(input.classification);
            trust = trust.min(input.trust);
            constraints.extend(input.destination_constraints.iter().copied());
            policies.extend(input.policy_refs.iter().cloned());
            for signal in &input.risk_signals {
                if !signals.contains(signal) {
                    signals.push(signal.clone());
                }
            }
            lineage.extend(input.lineage.iter().cloned());
        }
        let object = step.output.clone();
        lineage.push(step);
        let derived = Self {
            schema_version: V1_SCHEMA_VERSION,
            object,
            source,
            principal: first.principal.clone(),
            task,
            classification,
            trust,
            policy_refs: policies.into_iter().collect(),
            risk_signals: signals,
            destination_constraints: constraints.into_iter().collect(),
            tokens,
            bytes,
            lineage,
        };
        derived.validate()?;
        Ok(derived)
    }
}

fn is_strictly_sorted<T: Ord>(values: &[T]) -> bool {
    values.windows(2).all(|pair| pair[0] < pair[1])
}

// ─── Context quality section ────────────────────────────────────────────────

/// How strong the quality evidence is, weakest first.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum QualityEvidenceTierV1 {
    Mechanism,
    DeterministicQuality,
    RecordedRegression,
    LiveTaskEvaluation,
    ProductionOutcome,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum QualityStateV1 {
    Pass,
    Fail,
    Unmeasured,
}

/// Kinds of critical facts a retention probe checks — kinds only, never values.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum QualityProbeKindV1 {
    ErrorCode,
    TestResult,
    Status,
    Location,
    Path,
    Hash,
    Url,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct RetentionCountsV1 {
    pub retained: u64,
    pub recoverable: u64,
    pub lost: u64,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct QualityRetentionV1 {
    pub critical: RetentionCountsV1,
    pub important: RetentionCountsV1,
    /// Sorted and unique.
    pub lost_critical_kinds: Vec<QualityProbeKindV1>,
    /// Critical facts could not all be checked; the round can never pass.
    pub critical_unchecked: bool,
    pub truncated: bool,
    /// Secret lines are withheld and never count as recoverable.
    pub secret_lines_withheld: u64,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct QualityRecoveryV1 {
    pub handles_emitted: u64,
    pub handles_verified: u64,
    pub failures: u64,
    pub critical_failures: u64,
}

/// Deterministic context-quality evidence for one round.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ContextQualitySectionV1 {
    pub evidence_tier: QualityEvidenceTierV1,
    pub retention: QualityRetentionV1,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub recovery: Option<QualityRecoveryV1>,
    /// Task quality is never measured per round.
    pub task_quality: QualityStateV1,
    pub overall: QualityStateV1,
}

impl ContextQualitySectionV1 {
    /// The overall state the measured dimensions imply.
    #[must_use]
    pub fn derived_overall(&self) -> QualityStateV1 {
        let retention = &self.retention;
        let retention_failed = retention.critical_unchecked
            || retention.critical.lost > 0
            || !retention.lost_critical_kinds.is_empty();
        let recovery_failed = self
            .recovery
            .is_some_and(|recovery| recovery.critical_failures > 0 || recovery.failures > 0);
        let measured = retention.critical.retained
            + retention.critical.recoverable
            + retention.critical.lost
            + retention.important.retained
            + retention.important.recoverable
            + retention.important.lost
            > 0
            || retention.critical_unchecked
            || self.recovery.is_some();
        if retention_failed || recovery_failed {
            QualityStateV1::Fail
        } else if measured {
            QualityStateV1::Pass
        } else {
            QualityStateV1::Unmeasured
        }
    }

    pub fn validate(&self) -> Result<(), ValidationError> {
        if self.task_quality != QualityStateV1::Unmeasured {
            return Err(ValidationError::new(
                "task quality is never measured per round",
            ));
        }
        if !is_strictly_sorted(&self.retention.lost_critical_kinds) {
            return Err(ValidationError::new(
                "lost critical kinds must be sorted and unique",
            ));
        }
        if let Some(recovery) = self.recovery
            && (recovery.handles_verified.saturating_add(recovery.failures)
                > recovery.handles_emitted
                || recovery.critical_failures > recovery.failures)
        {
            return Err(ValidationError::new(
                "recovery counts must satisfy verified + failures <= emitted and critical <= failures",
            ));
        }
        if self.overall != self.derived_overall() {
            return Err(ValidationError::new(
                "overall quality must follow from the measured dimensions",
            ));
        }
        Ok(())
    }
}

// ─── Receipt ────────────────────────────────────────────────────────────────

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum DeliveryOutcomeV1 {
    Delivered,
    Withheld,
    Failed,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SourceCountsV1 {
    pub inspected: u32,
    pub permitted: u32,
    pub selected: u32,
    pub blocked: u32,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SecurityCountsV1 {
    pub redactions: u32,
    pub blocked_objects: u32,
    pub quarantined_objects: u32,
    pub injection_signals: u32,
    pub incomplete_coverage: u32,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct TokenAccountV1 {
    pub original: u64,
    pub delivered: u64,
}

/// Receipt schema version 2 (AP10-C4, `context-gateway-v2.md`): every
/// `decisions[].object` is keyed under the installation's receipt key and the
/// receipt names that key in [`ContextDecisionReceiptV1::object_digest`].
/// Version 1 receipts (plain SHA-256 objects) stay readable and valid.
pub const RECEIPT_V2_SCHEMA_VERSION: u32 = 2;

/// How the decision objects of a version 2 receipt are digested.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum ObjectDigestAlgorithmV2 {
    /// `HMAC-SHA256(key, "leanctx.receipt.object.v2" || 0x00 || v1_object)`,
    /// where `v1_object` is the `sha256:<hex>` a version 1 receipt would name.
    #[serde(rename = "hmac-sha256")]
    HmacSha256,
}

/// The key a version 2 receipt's decision objects are digested under: its
/// algorithm and a public identifier, never the key.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ReceiptObjectDigestV2 {
    pub algorithm: ObjectDigestAlgorithmV2,
    /// `rk-` and the first 32 hex digits of
    /// `HMAC-SHA256(key, "leanctx.receipt.key-id.v2")`: tells keys apart,
    /// reveals nothing of the key.
    pub key_id: String,
}

impl ReceiptObjectDigestV2 {
    pub fn validate(&self) -> Result<(), ValidationError> {
        let valid = self.key_id.strip_prefix("rk-").is_some_and(|hex| {
            hex.len() == 32 && hex.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
        });
        if valid {
            Ok(())
        } else {
            Err(ValidationError::new(
                "receipt key id must be rk- and 32 lowercase hex digits",
            ))
        }
    }
}

fn deserialize_receipt_schema_version<'de, D>(deserializer: D) -> Result<u32, D::Error>
where
    D: Deserializer<'de>,
{
    let version = u32::deserialize(deserializer)?;
    if version == V1_SCHEMA_VERSION || version == RECEIPT_V2_SCHEMA_VERSION {
        Ok(version)
    } else {
        Err(DeError::custom(format!(
            "unsupported receipt schema_version {version}; expected 1 or 2"
        )))
    }
}

/// One governed delivery: who asked, for what, what was considered, what was
/// withheld and why, what reached which destination under which policy.
///
/// The type keeps its V1 name; it carries both receipt schema versions. In
/// version 2 `decisions[].object` keeps its `sha256:<hex>` form but is keyed
/// ([`ObjectDigestAlgorithmV2`]) under the key `object_digest` names.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ContextDecisionReceiptV1 {
    #[serde(deserialize_with = "deserialize_receipt_schema_version")]
    pub schema_version: u32,
    /// Present exactly on a version 2 receipt.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub object_digest: Option<ReceiptObjectDigestV2>,
    pub receipt_id: ProtocolReference,
    pub mode: GatewayModeV1,
    pub principal: PrincipalV1,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub task: Option<TaskId>,
    pub destination: DestinationV1,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub policy: Option<PolicyRefV1>,
    pub sources: SourceCountsV1,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub decisions: Vec<ContextDecisionV1>,
    pub security: SecurityCountsV1,
    pub tokens: TokenAccountV1,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub final_context: Option<Sha256Digest>,
    pub outcome: DeliveryOutcomeV1,
    pub duration_us: u64,
    /// Context-quality evidence for this round (retention, recovery). Absent
    /// when nothing was measured; absent fields keep the receipt's digest.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub quality: Option<ContextQualitySectionV1>,
}

impl ContextDecisionReceiptV1 {
    /// Receipt consistency: counts must describe the recorded decisions, and
    /// only a delivered receipt names the delivered context.
    pub fn validate(&self) -> Result<(), ValidationError> {
        match (self.schema_version, &self.object_digest) {
            (V1_SCHEMA_VERSION, None) => {}
            (RECEIPT_V2_SCHEMA_VERSION, Some(object_digest)) => object_digest.validate()?,
            (V1_SCHEMA_VERSION | RECEIPT_V2_SCHEMA_VERSION, _) => {
                return Err(ValidationError::new(
                    "exactly a version 2 receipt names its object digest key",
                ));
            }
            (version, _) => {
                return Err(ValidationError::new(format!(
                    "unsupported receipt schema_version {version}; expected 1 or 2"
                )));
            }
        }
        if let Some(quality) = &self.quality {
            quality.validate()?;
        }
        if self.decisions.len() > MAX_DECISIONS {
            return Err(ValidationError::new("receipt exceeds its decision bound"));
        }
        for decision in &self.decisions {
            decision.validate()?;
        }
        let s = self.sources;
        if s.selected > s.permitted
            || u64::from(s.permitted) + u64::from(s.blocked) > u64::from(s.inspected)
        {
            return Err(ValidationError::new(
                "source counts must satisfy selected <= permitted and permitted + blocked <= inspected",
            ));
        }
        let count = |d: ContextDispositionV1| {
            self.decisions
                .iter()
                .filter(|decision| decision.disposition == d)
                .count()
        };
        if count(ContextDispositionV1::Deny) != self.security.blocked_objects as usize
            || count(ContextDispositionV1::Quarantine) != self.security.quarantined_objects as usize
        {
            return Err(ValidationError::new(
                "security counts must equal the recorded deny/quarantine decisions",
            ));
        }
        match (self.outcome, &self.final_context) {
            (DeliveryOutcomeV1::Delivered, None) => Err(ValidationError::new(
                "a delivered receipt must name the delivered context digest",
            )),
            (DeliveryOutcomeV1::Withheld | DeliveryOutcomeV1::Failed, Some(_)) => Err(
                ValidationError::new("only a delivered receipt may name a context digest"),
            ),
            _ => Ok(()),
        }
    }

    /// Deterministic content identity of the receipt (#498): SHA-256 over the
    /// canonical JSON (sorted keys, no whitespace).
    pub fn canonical_digest(&self) -> Result<Sha256Digest, ValidationError> {
        self.validate()?;
        let value = serde_json::to_value(self)
            .map_err(|e| ValidationError::new(format!("receipt serialization: {e}")))?;
        let bytes = serde_json::to_vec(&value)
            .map_err(|e| ValidationError::new(format!("receipt serialization: {e}")))?;
        sha256_digest(&bytes)
    }
}

/// The admission lifecycle for one exact request body. This does not change the
/// legacy ContextDecisionReceiptV1 wire format or its outcome semantics.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum EgressAdmissionOutcomeV1 {
    /// The policy admitted these bytes and their digest is bound; no send is implied.
    Prepared,
    /// Policy withheld the request before dispatch.
    Withheld,
    /// Admission could not produce a dispatchable request.
    Failed,
}

/// A versioned, content-addressable admission record for outbound request bytes.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct EgressAdmissionReceiptV1 {
    #[serde(deserialize_with = "deserialize_schema_version")]
    pub schema_version: u32,
    pub receipt_id: ProtocolReference,
    /// Digest of the associated ContextDecisionReceiptV1 when one was recorded.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub decision_receipt_digest: Option<Sha256Digest>,
    pub outcome: EgressAdmissionOutcomeV1,
    /// SHA-256 of the exact prepared wire bytes; present only for Prepared.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub prepared_bytes_digest: Option<Sha256Digest>,
}

impl EgressAdmissionReceiptV1 {
    pub fn validate(&self) -> Result<(), ValidationError> {
        validate_schema_version(self.schema_version)?;
        match self.outcome {
            EgressAdmissionOutcomeV1::Prepared => {
                if self.prepared_bytes_digest.is_none() {
                    return Err(ValidationError::new(
                        "a prepared egress receipt must bind the prepared bytes digest",
                    ));
                }
                if self.decision_receipt_digest.is_none() {
                    return Err(ValidationError::new(
                        "a prepared egress receipt must link its decision receipt",
                    ));
                }
            }
            EgressAdmissionOutcomeV1::Withheld => {
                if self.prepared_bytes_digest.is_some() {
                    return Err(ValidationError::new(
                        "a withheld egress receipt cannot name prepared bytes",
                    ));
                }
                if self.decision_receipt_digest.is_none() {
                    return Err(ValidationError::new(
                        "a withheld egress receipt must link its decision receipt",
                    ));
                }
            }
            EgressAdmissionOutcomeV1::Failed => {
                if self.prepared_bytes_digest.is_some() {
                    return Err(ValidationError::new(
                        "a failed egress receipt cannot name prepared bytes",
                    ));
                }
            }
        }
        Ok(())
    }

    /// Deterministic content identity over canonical JSON.
    pub fn canonical_digest(&self) -> Result<Sha256Digest, ValidationError> {
        self.validate()?;
        let value = serde_json::to_value(self)
            .map_err(|e| ValidationError::new(format!("egress admission serialization: {e}")))?;
        let bytes = serde_json::to_vec(&value)
            .map_err(|e| ValidationError::new(format!("egress admission serialization: {e}")))?;
        sha256_digest(&bytes)
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum EgressTransportV1 {
    Http,
    WebSocket,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum EgressTransportObserverV1 {
    /// The Engine transport itself observed this attempt.
    EngineObserved,
    /// A calling host reported what it observed; this is not independently attested.
    HostReported,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum EgressTransportResultV1 {
    /// A response was observed. The status does not claim model consumption.
    ResponseObserved,
    /// No response was observed; request bytes may still have reached the peer.
    NoResponseObserved,
}

/// Bounded error classes only; raw transport errors may contain sensitive data.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum EgressTransportFailureV1 {
    Connect,
    Timeout,
    Cancelled,
    Other,
}

/// Append-only observation of one transport attempt, linked to its admission receipt.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct EgressTransportObservationV1 {
    #[serde(deserialize_with = "deserialize_schema_version")]
    pub schema_version: u32,
    pub admission_receipt_digest: Sha256Digest,
    /// One-based attempt number for this admission receipt.
    pub attempt: u32,
    pub transport: EgressTransportV1,
    pub observer: EgressTransportObserverV1,
    pub result: EgressTransportResultV1,
    /// Required for an HTTP response; optional for a WebSocket handshake/message.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub http_status: Option<u16>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub failure: Option<EgressTransportFailureV1>,
}

impl EgressTransportObservationV1 {
    pub fn validate(&self) -> Result<(), ValidationError> {
        validate_schema_version(self.schema_version)?;
        if self.attempt == 0 {
            return Err(ValidationError::new(
                "transport attempt numbers are one-based",
            ));
        }
        if self
            .http_status
            .is_some_and(|status| !(100..=599).contains(&status))
        {
            return Err(ValidationError::new(
                "observed HTTP status must be between 100 and 599",
            ));
        }
        match self.result {
            EgressTransportResultV1::ResponseObserved => {
                if self.failure.is_some() {
                    return Err(ValidationError::new(
                        "a response observation cannot include a transport failure",
                    ));
                }
                if self.transport == EgressTransportV1::Http && self.http_status.is_none() {
                    return Err(ValidationError::new(
                        "an observed HTTP response must include its status",
                    ));
                }
            }
            EgressTransportResultV1::NoResponseObserved => {
                if self.http_status.is_some() || self.failure.is_none() {
                    return Err(ValidationError::new(
                        "a no-response observation needs one bounded failure and no status",
                    ));
                }
            }
        }
        Ok(())
    }

    /// Check that this observation names the exact prepared admission record.
    pub fn validate_for(
        &self,
        admission: &EgressAdmissionReceiptV1,
    ) -> Result<(), ValidationError> {
        self.validate()?;
        admission.validate()?;
        if admission.outcome != EgressAdmissionOutcomeV1::Prepared {
            return Err(ValidationError::new(
                "transport observations require a prepared admission receipt",
            ));
        }
        if self.admission_receipt_digest != admission.canonical_digest()? {
            return Err(ValidationError::new(
                "transport observation does not match its admission receipt digest",
            ));
        }
        Ok(())
    }

    /// Deterministic content identity over canonical JSON.
    pub fn canonical_digest(&self) -> Result<Sha256Digest, ValidationError> {
        self.validate()?;
        let value = serde_json::to_value(self).map_err(|e| {
            ValidationError::new(format!("transport observation serialization: {e}"))
        })?;
        let bytes = serde_json::to_vec(&value).map_err(|e| {
            ValidationError::new(format!("transport observation serialization: {e}"))
        })?;
        sha256_digest(&bytes)
    }
}

fn sha256_digest(bytes: &[u8]) -> Result<Sha256Digest, ValidationError> {
    let mut digest = String::from("sha256:");
    for byte in Sha256::digest(bytes) {
        write!(&mut digest, "{byte:02x}")
            .map_err(|_| ValidationError::new("gateway digest encoding failed"))?;
    }
    Sha256Digest::new(digest)
}

#[cfg(test)]
#[path = "context_gateway_tests.rs"]
mod tests;