lean-ctx-ocla 1.0.0

Open Context & Token Lifecycle Architecture — the stable, provider-neutral contract boundary (14 traits, canonical types, token envelopes) shared between lean-ctx-core (OSS) and lean-ctx-enterprise (proprietary).
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
//! # Data Classification
//! Fields are annotated with sensitivity levels:
//! - `[PII]` — personally identifiable or workspace-identifying data, requires redaction before cross-boundary transmission
//! - `[INTERNAL]` — business-sensitive data, visible to operators but not external parties
//! - `[PUBLIC]` — safe for any consumer

use std::cell::RefCell;
use std::collections::BTreeMap;

use serde::{Deserialize, Serialize};
use thiserror::Error;

pub const OCLA_API_VERSION: &str = "ocla/v1";
pub const CANONICAL_TOKEN_ENVELOPE_SCHEMA_VERSION: u16 = 1;
pub const AGENT_ENVELOPE_SCHEMA_VERSION: u16 = 1;

pub type OclaResult<T> = Result<T, OclaError>;

/// Replaces the first two user/workspace path components with redaction markers.
#[must_use]
pub fn redact_path(path: &str) -> String {
    let mut components = path
        .split('/')
        .filter(|component| !component.is_empty())
        .collect::<Vec<_>>();

    if matches!(components.first(), Some(&"Users" | &"home")) {
        components.remove(0);
    }

    components
        .iter()
        .enumerate()
        .map(|(index, component)| {
            if index < 2 {
                "***".to_string()
            } else {
                (*component).to_string()
            }
        })
        .collect::<Vec<_>>()
        .join("/")
}

/// Retains only an identifier's first eight characters for correlation.
#[must_use]
pub fn redact_id(id: &str) -> String {
    format!("{}...", id.chars().take(8).collect::<String>())
}

/// Stable identifiers required to join decisions across interception surfaces.
/// Payload bytes intentionally never belong in this contract.
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct OclaRequestContext {
    /// [PII] Request identifier that can correlate a user's activity.
    pub request_id: String,
    /// [PII] Session identifier.
    pub session_id: String,
    /// [PII] Agent identifier.
    pub agent_id: String,
    /// [PII] Content reference that can identify workspace data.
    pub content_ref: String,
    /// [PII] Tenant identifier.
    pub tenant_id: Option<String>,
    /// [PII] Trace identifier that correlates requests across boundaries.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub trace_id: String,
}

thread_local! {
    static CURRENT_REQUEST_CONTEXT: RefCell<Option<OclaRequestContext>> = const {
        RefCell::new(None)
    };
}

fn generate_trace_id() -> String {
    let mut bytes = [0_u8; 16];
    getrandom::fill(&mut bytes).expect("CSPRNG unavailable");
    bytes[6] = (bytes[6] & 0x0f) | 0x40;
    bytes[8] = (bytes[8] & 0x3f) | 0x80;
    let uuid = format!(
        "{:02x}{:02x}{:02x}{:02x}-{:02x}{:02x}-{:02x}{:02x}-{:02x}{:02x}-{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}",
        bytes[0],
        bytes[1],
        bytes[2],
        bytes[3],
        bytes[4],
        bytes[5],
        bytes[6],
        bytes[7],
        bytes[8],
        bytes[9],
        bytes[10],
        bytes[11],
        bytes[12],
        bytes[13],
        bytes[14],
        bytes[15]
    );
    format!("tr-{uuid}")
}

#[derive(Deserialize)]
#[serde(untagged)]
enum RequiredNullableString {
    Value(String),
    Null(()),
}

impl RequiredNullableString {
    fn into_option(self) -> Option<String> {
        match self {
            Self::Value(value) => Some(value),
            Self::Null(()) => None,
        }
    }
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct WireContext {
    /// [PII] Request identifier that can correlate a user's activity.
    request_id: String,
    /// [PII] Session identifier.
    session_id: String,
    /// [PII] Agent identifier.
    agent_id: String,
    /// [PII] Content reference that can identify workspace data.
    content_ref: String,
    /// [PII] Tenant identifier.
    tenant_id: RequiredNullableString,
    /// [PII] Trace identifier that correlates requests across boundaries.
    #[serde(default)]
    trace_id: Option<String>,
}

impl<'de> Deserialize<'de> for OclaRequestContext {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let wire = WireContext::deserialize(deserializer)?;
        Ok(Self::new(
            wire.request_id,
            wire.session_id,
            wire.agent_id,
            wire.content_ref,
            wire.tenant_id.into_option(),
            wire.trace_id,
        ))
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TokenEnvelopeSurface {
    Mcp,
    Proxy,
    Shell,
    Agent,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TokenFlowDirection {
    Input,
    Output,
}

/// Provider-neutral token accounting. Each field reflects a distinct lifecycle
/// stage and prevents a cache or delivery mechanism from being double-counted.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct TokenBalanceV1 {
    /// [INTERNAL] Token count before materialization.
    pub original_tokens: u64,
    /// [INTERNAL] Token count after materialization.
    pub materialized_tokens: u64,
    /// [INTERNAL] Token count delivered to the consumer.
    pub delivered_tokens: u64,
    /// [INTERNAL] Token count billed by the provider.
    pub provider_billed_tokens: u64,
}

impl TokenBalanceV1 {
    pub fn validate(&self) -> OclaResult<()> {
        if self.materialized_tokens > self.original_tokens {
            return Err(OclaError::InvalidRequest(
                "materialized_tokens exceeds original_tokens".into(),
            ));
        }
        if self.delivered_tokens > self.materialized_tokens {
            return Err(OclaError::InvalidRequest(
                "delivered_tokens exceeds materialized_tokens".into(),
            ));
        }
        Ok(())
    }
}

/// Canonical, payload-free representation of a token decision at any engine
/// boundary. Provider adapters project into this type before ledger, policy or
/// external SDK code observes the request.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CanonicalTokenEnvelopeV1 {
    /// [PUBLIC] OCLA schema version.
    pub schema_version: u16,
    /// [PII] Request context containing correlation identifiers.
    pub context: OclaRequestContext,
    /// [PUBLIC] Interception surface name.
    pub surface: TokenEnvelopeSurface,
    /// [PUBLIC] Token-flow direction.
    pub direction: TokenFlowDirection,
    /// [PUBLIC] Provider name.
    pub provider: String,
    /// [INTERNAL] Model name.
    pub model: String,
    /// [INTERNAL] Token-accounting metrics.
    pub token_balance: TokenBalanceV1,
    /// [INTERNAL] Internal route reference.
    pub route_ref: Option<String>,
    /// [INTERNAL] Internal policy reference.
    pub policy_ref: Option<String>,
    /// [PII] Idempotency key that correlates requests.
    pub idempotency_key: String,
}

impl CanonicalTokenEnvelopeV1 {
    pub fn validate(&self) -> OclaResult<()> {
        if self.schema_version != CANONICAL_TOKEN_ENVELOPE_SCHEMA_VERSION {
            return Err(OclaError::UnsupportedVersion(
                self.schema_version.to_string(),
            ));
        }
        self.context.validate()?;
        self.token_balance.validate()?;
        for (label, value) in [
            ("provider", &self.provider),
            ("model", &self.model),
            ("idempotency_key", &self.idempotency_key),
        ] {
            if value.trim().is_empty() {
                return Err(OclaError::InvalidRequest(format!("{label} is required")));
            }
        }
        Ok(())
    }
}

impl OclaRequestContext {
    #[must_use]
    pub fn new(
        request_id: String,
        session_id: String,
        agent_id: String,
        content_ref: String,
        tenant_id: Option<String>,
        trace_id: Option<String>,
    ) -> Self {
        Self {
            request_id,
            session_id,
            agent_id,
            content_ref,
            tenant_id,
            trace_id: trace_id.unwrap_or_else(generate_trace_id),
        }
    }

    pub fn scope<R>(&self, operation: impl FnOnce() -> R) -> R {
        CURRENT_REQUEST_CONTEXT.with(|current| {
            let previous = current.replace(Some(self.clone()));
            let result = operation();
            current.replace(previous);
            result
        })
    }

    pub fn current_trace_id() -> Option<String> {
        CURRENT_REQUEST_CONTEXT.with(|current| {
            current
                .borrow()
                .as_ref()
                .map(|context| context.trace_id.clone())
        })
    }

    pub fn current_request_id() -> Option<String> {
        CURRENT_REQUEST_CONTEXT.with(|current| {
            current
                .borrow()
                .as_ref()
                .map(|context| context.request_id.clone())
        })
    }

    pub fn current_session_id() -> Option<String> {
        CURRENT_REQUEST_CONTEXT.with(|current| {
            current
                .borrow()
                .as_ref()
                .map(|context| context.session_id.clone())
        })
    }

    pub fn validate(&self) -> OclaResult<()> {
        for (label, value) in [
            ("request_id", &self.request_id),
            ("session_id", &self.session_id),
            ("agent_id", &self.agent_id),
            ("content_ref", &self.content_ref),
            ("trace_id", &self.trace_id),
        ] {
            if value.trim().is_empty() {
                return Err(OclaError::InvalidRequest(format!("{label} is required")));
            }
        }
        Ok(())
    }
}

#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum OclaCapabilityKind {
    ObservationHook,
    UsageSink,
    MetricsExporter,
    SavingsLedger,
    IntentClassifier,
    OutcomeTracker,
    CompressionProvider,
    ResponseOptimizer,
    ModelRouter,
    EfficiencyAnalyzer,
    ConfigTuner,
    ExperimentRunner,
    ConnectorScheduler,
    AgentGateway,
    DeliveryRegistry,
}

impl OclaCapabilityKind {
    pub const ALL: [Self; 15] = [
        Self::ObservationHook,
        Self::UsageSink,
        Self::MetricsExporter,
        Self::SavingsLedger,
        Self::IntentClassifier,
        Self::OutcomeTracker,
        Self::CompressionProvider,
        Self::ResponseOptimizer,
        Self::ModelRouter,
        Self::EfficiencyAnalyzer,
        Self::ConfigTuner,
        Self::ExperimentRunner,
        Self::ConnectorScheduler,
        Self::AgentGateway,
        Self::DeliveryRegistry,
    ];
}

/// Fail behavior when a subsystem cannot evaluate policy.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum FailMode {
    Open,
    Closed,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum OclaCapabilityStatus {
    Available,
    Degraded,
    Unavailable,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct OclaCapability {
    /// [PUBLIC] Capability name.
    pub kind: OclaCapabilityKind,
    /// [PUBLIC] Supported API version string.
    pub api_version: String,
    /// [PUBLIC] Capability availability status.
    pub status: OclaCapabilityStatus,
    /// [INTERNAL] Named operating limits, e.g. `max_input_tokens` or `max_fanout`.
    pub limits: BTreeMap<String, u64>,
}

impl OclaCapability {
    #[must_use]
    pub fn available(kind: OclaCapabilityKind) -> Self {
        Self {
            kind,
            api_version: OCLA_API_VERSION.to_string(),
            status: OclaCapabilityStatus::Available,
            limits: BTreeMap::new(),
        }
    }
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct Observation {
    /// [PII] Request context containing correlation identifiers.
    pub context: OclaRequestContext,
    /// [PUBLIC] Observation name.
    pub name: String,
    /// [PII] Observation attributes, which may contain user or workspace identifiers.
    pub attributes: BTreeMap<String, String>,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct UsageRecord {
    /// [PII] Request context containing correlation identifiers.
    pub context: OclaRequestContext,
    /// [INTERNAL] Model name.
    pub model: String,
    /// [INTERNAL] Input token count.
    pub input_tokens: u64,
    /// [INTERNAL] Output token count.
    pub output_tokens: u64,
    /// [INTERNAL] Provider-billed token count.
    pub provider_billed_tokens: u64,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct MetricPoint {
    /// [PII] Request context containing correlation identifiers.
    pub context: OclaRequestContext,
    /// [PUBLIC] Metric name.
    pub name: String,
    /// [INTERNAL] Metric value.
    pub value_milli: i64,
    /// [PII] Metric dimensions, which may contain user or workspace identifiers.
    pub dimensions: BTreeMap<String, String>,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct SavingsEvidence {
    /// [PII] Request context containing correlation identifiers.
    pub context: OclaRequestContext,
    /// [INTERNAL] Original token count.
    pub original_tokens: u64,
    /// [INTERNAL] Delivered token count.
    pub delivered_tokens: u64,
    /// [INTERNAL] Internal quality reference.
    pub quality_ref: Option<String>,
    /// [INTERNAL] Internal evidence reference.
    pub evidence_ref: String,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct IntentRequest {
    /// [PII] Request context containing correlation identifiers.
    pub context: OclaRequestContext,
    /// [INTERNAL] Candidate intent labels derived from a request.
    pub candidate_intents: Vec<String>,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct IntentDecision {
    /// [INTERNAL] Selected request intent.
    pub intent: String,
    /// [INTERNAL] Decision confidence metric.
    pub confidence_milli: u16,
    /// [INTERNAL] Internal rationale reference.
    pub rationale_ref: Option<String>,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct Outcome {
    /// [PII] Request context containing correlation identifiers.
    pub context: OclaRequestContext,
    /// [INTERNAL] Whether the user accepted the outcome.
    pub accepted: Option<bool>,
    /// [INTERNAL] Outcome quality metric.
    pub quality_score_milli: Option<u16>,
    /// [INTERNAL] Internal outcome reference.
    pub outcome_ref: Option<String>,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct CompressionRequest {
    /// [PII] Request context containing correlation identifiers.
    pub context: OclaRequestContext,
    /// [PII] Source reference that can identify workspace content.
    pub source_ref: String,
    /// [INTERNAL] Source token count.
    pub source_tokens: u64,
    /// [INTERNAL] Requested target token count.
    pub target_tokens: u64,
    /// [INTERNAL] Internal quality-policy reference.
    pub quality_policy_ref: Option<String>,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct CompressionResult {
    /// [PII] Delivered-content reference that can identify workspace data.
    pub delivered_ref: String,
    /// [INTERNAL] Delivered token count.
    pub delivered_tokens: u64,
    /// [INTERNAL] Internal recovery reference.
    pub recovery_ref: Option<String>,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct ResponseOptimizationRequest {
    /// [PII] Request context containing correlation identifiers.
    pub context: OclaRequestContext,
    /// [PII] Response reference that can identify workspace content.
    pub response_ref: String,
    /// [INTERNAL] Original token count.
    pub original_tokens: u64,
    /// [INTERNAL] Requested target token count.
    pub target_tokens: u64,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct ResponseOptimizationResult {
    /// [PII] Response reference that can identify workspace content.
    pub response_ref: String,
    /// [INTERNAL] Delivered token count.
    pub delivered_tokens: u64,
    /// [INTERNAL] Internal recovery reference.
    pub recovery_ref: Option<String>,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct ModelRouteRequest {
    /// [PII] Request context containing correlation identifiers.
    pub context: OclaRequestContext,
    /// [INTERNAL] Candidate model names.
    pub candidate_models: Vec<String>,
    /// [INTERNAL] Maximum permitted cost metric.
    pub maximum_cost_micros: Option<u64>,
    /// [INTERNAL] Maximum permitted latency metric.
    pub maximum_latency_ms: Option<u64>,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct RoutingDecision {
    /// [INTERNAL] Selected model name.
    pub model: String,
    /// [PUBLIC] Provider name.
    pub provider: String,
    /// [INTERNAL] Reasoning budget token count.
    pub reasoning_budget_tokens: u64,
    /// [INTERNAL] Internal decision reference.
    pub decision_ref: String,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct EfficiencySample {
    /// [PII] Request context containing correlation identifiers.
    pub context: OclaRequestContext,
    /// [INTERNAL] Original token count.
    pub original_tokens: u64,
    /// [INTERNAL] Delivered token count.
    pub delivered_tokens: u64,
    /// [INTERNAL] Whether the user accepted the result.
    pub accepted: Option<bool>,
    /// [INTERNAL] Cache-hit metric.
    #[serde(default)]
    pub cache_hits: u64,
    /// [INTERNAL] Cache-read metric.
    #[serde(default)]
    pub cache_reads: u64,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct EfficiencyAnalysis {
    /// [INTERNAL] Efficiency metric.
    pub etpao_milli: Option<u64>,
    /// [INTERNAL] Duplicate-content metric.
    pub duplicate_ratio_milli: u16,
    /// [INTERNAL] Compression-rate metric.
    #[serde(default)]
    pub compression_rate_milli: u16,
    /// [INTERNAL] Cache-hit-rate metric.
    #[serde(default)]
    pub cache_hit_rate_milli: u16,
    /// [INTERNAL] Internal recommendation references.
    pub recommendation_refs: Vec<String>,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct ConfigTuningRequest {
    /// [PII] Request context containing correlation identifiers.
    pub context: OclaRequestContext,
    /// [INTERNAL] Internal configuration reference.
    pub config_ref: String,
    /// [INTERNAL] Internal objective reference.
    pub objective_ref: String,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct ConfigProposal {
    /// [INTERNAL] Internal proposal reference.
    pub proposal_ref: String,
    /// [INTERNAL] Internal rollback reference.
    pub rollback_ref: String,
    /// [INTERNAL] Approval workflow state.
    pub requires_approval: bool,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
/// Holdout configuration for experiments.
pub struct HoldoutConfig {
    /// [INTERNAL] Percentage of traffic to hold out (0-100).
    pub holdout_pct: u8,
    /// [INTERNAL] Deterministic assignment seed for reproducibility.
    pub assignment_seed: String,
    /// [INTERNAL] Maximum number of samples before stopping.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_samples: Option<u64>,
}

/// Stop conditions that can terminate an experiment early.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct ExperimentStopConditions {
    /// [INTERNAL] Stop if this many samples are collected.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_samples: Option<u64>,
    /// [INTERNAL] Stop if improvement over control is below this threshold.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub min_improvement_pct: Option<u8>,
    /// [INTERNAL] Stop after this many seconds.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_duration_secs: Option<u64>,
}

/// Extended experiment result with holdout data.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ExperimentOutcome {
    /// [INTERNAL] Internal experiment reference.
    pub experiment_ref: String,
    /// [INTERNAL] Treatment sample count.
    pub treatment_samples: u64,
    /// [INTERNAL] Control sample count.
    pub control_samples: u64,
    /// [INTERNAL] Treatment metric.
    pub treatment_metric: f64,
    /// [INTERNAL] Control metric.
    pub control_metric: f64,
    /// [INTERNAL] Improvement metric.
    pub improvement_pct: f64,
    /// [INTERNAL] Internal experiment stop reason.
    pub stopped_reason: Option<String>,
    /// [INTERNAL] Statistical significance state.
    pub is_significant: bool,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct ExperimentRequest {
    /// [PII] Request context containing correlation identifiers.
    pub context: OclaRequestContext,
    /// [INTERNAL] Internal experiment reference.
    pub experiment_ref: String,
    /// [PII] Cohort reference that can identify a user group.
    pub cohort_ref: String,
    /// [INTERNAL] Experiment holdout configuration.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub holdout: Option<HoldoutConfig>,
    /// [INTERNAL] Experiment stop conditions.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub stop_conditions: Option<ExperimentStopConditions>,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct ExperimentResult {
    /// [INTERNAL] Internal experiment reference.
    pub experiment_ref: String,
    /// [INTERNAL] Internal outcome reference.
    pub outcome_ref: String,
    /// [INTERNAL] Internal rollback reference.
    pub rollback_ref: Option<String>,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct ConnectorJob {
    /// [PII] Request context containing correlation identifiers.
    pub context: OclaRequestContext,
    /// [INTERNAL] Connector identifier.
    pub connector_id: String,
    /// [PII] Payload reference that can identify workspace content.
    pub payload_ref: String,
    /// [INTERNAL] Deadline metric in milliseconds.
    pub deadline_ms: Option<u64>,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct ScheduledJob {
    /// [INTERNAL] Internal job reference.
    pub job_ref: String,
    /// [INTERNAL] Internal queue reference.
    pub queue_ref: String,
}

/// Cross-agent delivery record: tracks that file content was read by an agent.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct DeliveryRecord {
    /// [INTERNAL] Content-derived digest.
    pub blake3: [u8; 12],
    /// [PII] File path.
    pub path: String,
    /// [INTERNAL] File line-count metric.
    pub line_count: u32,
    /// [INTERNAL] File token-count metric.
    pub token_count: u64,
    /// [PII] Agent identifier.
    pub agent_id: String,
    /// [PII] Conversation identifier.
    pub conversation_id: String,
    /// [INTERNAL] Read timestamp.
    pub read_at: u64,
    /// [INTERNAL] File modification timestamp.
    pub mtime: u64,
    /// [INTERNAL] Freshness state.
    pub fresh: bool,
}

/// Entry for recording a new delivery.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct DeliveryEntry {
    /// [INTERNAL] Content-derived digest.
    pub blake3: [u8; 12],
    /// [PII] File path.
    pub path: String,
    /// [INTERNAL] File line-count metric.
    pub line_count: u32,
    /// [INTERNAL] File token-count metric.
    pub token_count: u64,
    /// [PII] Agent identifier.
    pub agent_id: String,
    /// [PII] Conversation identifier.
    pub conversation_id: String,
    /// [INTERNAL] File modification timestamp.
    pub mtime: u64,
}

/// Result of an idempotent delivery-record attempt.
#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
pub struct DeliveryRecordResult {
    /// The existing record already represented the same source version.
    pub already_recorded: bool,
    /// An existing record was refreshed because its source version changed.
    pub updated: bool,
}

/// Statistics for the delivery registry.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct DeliveryStats {
    /// [INTERNAL] Registry entry count.
    pub total_entries: usize,
    /// [INTERNAL] Stub-delivery count.
    pub stubs_served: u64,
    /// [INTERNAL] Token-savings metric.
    pub tokens_saved: u64,
    /// [INTERNAL] Unique-path count.
    pub unique_paths: usize,
    /// [INTERNAL] Unique-agent count.
    pub unique_agents: usize,
}

/// Canonical, payload-free admission contract for one A2A relay.
///
/// `budget_tokens` is an authorization ceiling, never observed delivery or
/// savings evidence. A transport must create its own measured token envelope
/// only after it actually materializes and delivers the handoff.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AgentEnvelope {
    /// [PUBLIC] Agent-envelope schema version.
    pub schema_version: u16,
    /// [PII] Content-derived relay identifier for idempotent admission and event joins.
    pub relay_id: String,
    /// [PII] Request context containing correlation identifiers.
    pub context: OclaRequestContext,
    /// [PII] Sending agent identifier.
    pub from_agent_id: String,
    /// [PII] Receiving agent identifier.
    pub to_agent_id: String,
    /// [PII] Capsule reference that can identify workspace content.
    pub capsule_ref: String,
    /// [INTERNAL] Authorized token budget.
    pub budget_tokens: u64,
}

impl AgentEnvelope {
    /// Assigns the deterministic identity after all relay fields are set.
    pub fn assign_relay_id(&mut self) -> OclaResult<()> {
        self.relay_id = self.computed_relay_id()?;
        Ok(())
    }

    /// Derives a stable relay ID without including payload bytes or the ID itself.
    pub fn computed_relay_id(&self) -> OclaResult<String> {
        let mut canonical = self.clone();
        canonical.relay_id = "agent-relay:pending".to_string();
        let bytes = serde_json::to_vec(&canonical).map_err(|error| {
            OclaError::InvalidRequest(format!("cannot serialize agent relay: {error}"))
        })?;
        Ok(format!("agent-relay:{}", blake3::hash(&bytes).to_hex()))
    }

    pub fn validate(&self) -> OclaResult<()> {
        if self.schema_version != AGENT_ENVELOPE_SCHEMA_VERSION {
            return Err(OclaError::UnsupportedVersion(
                self.schema_version.to_string(),
            ));
        }
        self.context.validate()?;
        for (label, value) in [
            ("from_agent_id", &self.from_agent_id),
            ("to_agent_id", &self.to_agent_id),
        ] {
            valid_agent_id(value)
                .then_some(())
                .ok_or_else(|| OclaError::InvalidRequest(format!("invalid {label}")))?;
        }
        if self.context.agent_id != self.from_agent_id {
            return Err(OclaError::InvalidRequest(
                "context agent_id must match from_agent_id".to_string(),
            ));
        }
        valid_digest_ref("capsule", "capsule:", &self.capsule_ref)?;
        valid_digest_ref("relay", "agent-relay:", &self.relay_id)?;
        if self.budget_tokens == 0 {
            return Err(OclaError::InvalidRequest(
                "agent relay budget_tokens must be greater than zero".to_string(),
            ));
        }
        if self.relay_id != self.computed_relay_id()? {
            return Err(OclaError::InvalidRequest(
                "agent relay_id does not match canonical relay content".to_string(),
            ));
        }
        Ok(())
    }
}

fn valid_agent_id(value: &str) -> bool {
    !value.is_empty() && value.len() <= 256 && value.bytes().all(|byte| byte.is_ascii_graphic())
}

fn valid_digest_ref(label: &str, prefix: &str, value: &str) -> OclaResult<()> {
    let digest = value.strip_prefix(prefix).ok_or_else(|| {
        OclaError::InvalidRequest(format!("{label}_ref must use {prefix}BLAKE3-hex form"))
    })?;
    (digest.len() == 64
        && digest.bytes().all(|byte| {
            byte.is_ascii_digit() || (byte.is_ascii_lowercase() && byte.is_ascii_hexdigit())
        }))
    .then_some(())
    .ok_or_else(|| OclaError::InvalidRequest(format!("invalid {label}_ref")))
}

#[derive(Debug, Error)]
pub enum OclaError {
    #[error("invalid OCLA request: {0}")]
    InvalidRequest(String),
    #[error("OCLA capability {0:?} is unavailable")]
    Unavailable(OclaCapabilityKind),
    #[error("OCLA capability {0:?} rejected the request: {1}")]
    Rejected(OclaCapabilityKind, String),
    #[error("unsupported OCLA contract version: {0}")]
    UnsupportedVersion(String),
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
pub enum MessagePriority {
    Low,
    #[default]
    Normal,
    High,
    Critical,
}

impl MessagePriority {
    pub fn parse_str(s: &str) -> Self {
        match s.to_lowercase().as_str() {
            "low" => Self::Low,
            "high" => Self::High,
            "critical" => Self::Critical,
            _ => Self::Normal,
        }
    }
}

impl std::fmt::Display for MessagePriority {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Low => write!(f, "low"),
            Self::Normal => write!(f, "normal"),
            Self::High => write!(f, "high"),
            Self::Critical => write!(f, "critical"),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
pub enum PrivacyLevel {
    Public,
    #[default]
    Team,
    Private,
}

impl PrivacyLevel {
    pub fn parse_str(s: &str) -> Self {
        match s.to_lowercase().as_str() {
            "public" => Self::Public,
            "private" => Self::Private,
            _ => Self::Team,
        }
    }

    pub fn allows_access(&self, requester_is_sender: bool, requester_is_recipient: bool) -> bool {
        match self {
            Self::Public | Self::Team => true,
            Self::Private => requester_is_sender || requester_is_recipient,
        }
    }
}

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

    #[test]
    fn redact_path_masks_user_and_workspace_components() {
        assert_eq!(
            redact_path("/Users/alice/projects/my-app/src/main.rs"),
            "***/***/my-app/src/main.rs"
        );
    }

    #[test]
    fn redact_id_retains_only_a_short_correlation_prefix() {
        assert_eq!(redact_id("agent-0123456789"), "agent-01...");
    }

    #[test]
    fn contract_has_exactly_fifteen_discoverable_capabilities() {
        assert_eq!(OclaCapabilityKind::ALL.len(), 15);
        let capability = OclaCapability::available(OclaCapabilityKind::AgentGateway);
        assert_eq!(capability.api_version, OCLA_API_VERSION);
        assert_eq!(capability.status, OclaCapabilityStatus::Available);
    }

    #[test]
    fn request_context_rejects_incomplete_lineage() {
        let context = OclaRequestContext {
            request_id: "request".into(),
            session_id: String::new(),
            agent_id: "agent".into(),
            content_ref: "blake3:content".into(),
            tenant_id: None,
            trace_id: "tr-test".into(),
        };
        assert!(matches!(
            context.validate(),
            Err(OclaError::InvalidRequest(_))
        ));
    }

    #[test]
    fn wire_context_requires_an_explicit_nullable_tenant_id() {
        let missing = r#"{
            "request_id":"request",
            "session_id":"session",
            "agent_id":"agent",
            "content_ref":"blake3:content"
        }"#;
        assert!(serde_json::from_str::<WireContext>(missing).is_err());

        let explicit_null = r#"{
            "request_id":"request",
            "session_id":"session",
            "agent_id":"agent",
            "content_ref":"blake3:content",
            "tenant_id":null
        }"#;
        let context = serde_json::from_str::<WireContext>(explicit_null).expect("explicit null");
        assert!(matches!(
            context.tenant_id,
            RequiredNullableString::Null(())
        ));

        let explicit_value = r#"{
            "request_id":"request",
            "session_id":"session",
            "agent_id":"agent",
            "content_ref":"blake3:content",
            "tenant_id":"tenant"
        }"#;
        let context = serde_json::from_str::<WireContext>(explicit_value).expect("tenant string");
        assert!(matches!(
            context.tenant_id,
            RequiredNullableString::Value(ref value) if value == "tenant"
        ));

        let wrong_type = r#"{
            "request_id":"request",
            "session_id":"session",
            "agent_id":"agent",
            "content_ref":"blake3:content",
            "tenant_id":42
        }"#;
        assert!(serde_json::from_str::<WireContext>(wrong_type).is_err());
    }

    #[test]
    fn request_context_generates_or_preserves_trace_id() {
        let generated = OclaRequestContext::new(
            "request".into(),
            "session".into(),
            "agent".into(),
            "blake3:content".into(),
            None,
            None,
        );
        assert!(generated.trace_id.starts_with("tr-"));
        assert_eq!(generated.trace_id.len(), 39);

        let mut provided = serde_json::json!({
            "request_id": "request",
            "session_id": "session",
            "agent_id": "agent",
            "content_ref": "blake3:content",
            "tenant_id": null
        });
        provided["trace_id"] = serde_json::Value::String("tr-provided".into());
        let preserved: OclaRequestContext =
            serde_json::from_value(provided).expect("context preserves trace");
        assert_eq!(preserved.trace_id, "tr-provided");
    }

    #[test]
    fn agent_envelope_is_canonical_and_rejects_lineage_or_budget_drift() {
        let mut envelope = AgentEnvelope {
            schema_version: AGENT_ENVELOPE_SCHEMA_VERSION,
            relay_id: "agent-relay:pending".to_string(),
            context: OclaRequestContext {
                request_id: "request".into(),
                session_id: "session".into(),
                agent_id: "owner-agent".into(),
                content_ref: "blake3:content".into(),
                tenant_id: None,
                trace_id: "tr-test".into(),
            },
            from_agent_id: "owner-agent".into(),
            to_agent_id: "reviewer-agent".into(),
            capsule_ref: format!("capsule:{}", "a".repeat(64)),
            budget_tokens: 900,
        };
        envelope.assign_relay_id().expect("relay identity assigns");
        envelope.validate().expect("canonical relay validates");

        let mut wire = serde_json::to_value(&envelope).expect("relay serializes");
        wire.as_object_mut()
            .expect("relay is an object")
            .insert("unexpected".to_string(), serde_json::Value::Bool(true));
        assert!(serde_json::from_value::<AgentEnvelope>(wire).is_err());

        envelope.budget_tokens = 0;
        assert!(matches!(
            envelope.validate(),
            Err(OclaError::InvalidRequest(_))
        ));
    }
}