oatf 0.4.0

Rust SDK for the Open Agent Threat Format (OATF)
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
//! OATF document types per the format specification §2.
//!
//! All struct fields follow the specification naming. Extension fields (`x-*` prefixed)
//! are captured via `#[serde(flatten)] IndexMap<String, Value>` on types that support them,
//! preserving insertion order so that `serialize` can emit them in their original position.

use indexmap::IndexMap;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use serde_json::Value;
use std::collections::HashMap;

use crate::enums::*;

// ─── §2.2 Document ──────────────────────────────────────────────────────────

/// The top-level container for a parsed OATF document.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Document {
    /// OATF format version string (e.g., `"0.1"`).
    pub oatf: String,
    /// Optional JSON Schema URI for editor validation.
    #[serde(rename = "$schema", skip_serializing_if = "Option::is_none")]
    pub schema: Option<String>,
    /// The attack description and all contained structures.
    pub attack: Attack,
    /// Whether `oatf` was the first key in the original YAML (for W-001).
    #[serde(skip)]
    pub oatf_is_first_key: bool,
}

// ─── §2.3 Attack ─────────────────────────────────────────────────────────────

/// The attack envelope containing metadata, execution, and indicators.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Attack {
    /// Unique attack identifier.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<String>,
    /// Human-readable attack name.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// Document version number (integer).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub version: Option<i64>,
    /// Document lifecycle status.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status: Option<Status>,
    /// ISO 8601 creation date.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub created: Option<String>,
    /// ISO 8601 last-modified date.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub modified: Option<String>,
    /// Author name or identifier.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub author: Option<String>,
    /// Human-readable attack description.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// Grace period duration string (e.g., `"30d"`) for responsible disclosure.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub grace_period: Option<String>,
    /// Attack severity (scalar string or object with level + confidence).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub severity: Option<Severity>,
    /// Categories of harm caused by this attack.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub impact: Option<Vec<Impact>>,
    /// OATF taxonomy classification.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub classification: Option<Classification>,
    /// External references (URLs, papers, advisories).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub references: Option<Vec<Reference>>,
    /// Execution plan describing the attack phases and actors.
    pub execution: Execution,
    /// Detection indicators for this attack.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub indicators: Option<Vec<Indicator>>,
    /// Verdict correlation configuration.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub correlation: Option<Correlation>,
    /// Extension fields (`x-*` prefixed).
    #[serde(flatten)]
    pub extensions: IndexMap<String, Value>,
}

// ─── §2.3a Correlation ───────────────────────────────────────────────────────

/// Configuration for how indicator verdicts combine into an attack-level result.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Correlation {
    /// Correlation logic (`any` or `all`). Defaults to `any` at evaluation time.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub logic: Option<CorrelationLogic>,
}

// ─── §2.4 Severity ───────────────────────────────────────────────────────────

/// Severity can be either a scalar string or an object form.
/// During deserialization, a bare string like "high" is accepted.
/// After normalization, always in object form.
#[derive(Clone, Debug)]
pub enum Severity {
    /// Shorthand scalar form (e.g., `"high"`). Normalized to `Object` by N-003.
    Scalar(SeverityLevel),
    /// Full object form with level and optional confidence.
    Object {
        /// Severity level classification.
        level: SeverityLevel,
        /// Confidence percentage (0–100), if specified.
        confidence: Option<i64>,
    },
}

impl Serialize for Severity {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        use serde::ser::SerializeMap;
        match self {
            Severity::Scalar(level) => level.serialize(serializer),
            Severity::Object { level, confidence } => {
                let mut map = serializer.serialize_map(None)?;
                map.serialize_entry("level", level)?;
                if let Some(c) = confidence {
                    map.serialize_entry("confidence", c)?;
                }
                map.end()
            }
        }
    }
}

impl<'de> Deserialize<'de> for Severity {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let value = Value::deserialize(deserializer)?;
        match &value {
            Value::String(s) => {
                let level: SeverityLevel = serde_json::from_value(Value::String(s.clone()))
                    .map_err(serde::de::Error::custom)?;
                Ok(Severity::Scalar(level))
            }
            Value::Object(map) => {
                let level_val = map.get("level").ok_or_else(|| {
                    serde::de::Error::custom("severity object must have 'level' field")
                })?;
                let level: SeverityLevel =
                    serde_json::from_value(level_val.clone()).map_err(serde::de::Error::custom)?;
                let confidence = match map.get("confidence") {
                    Some(v) if v.is_null() => None,
                    Some(v) => Some(v.as_i64().ok_or_else(|| {
                        serde::de::Error::custom(format!(
                            "severity.confidence must be an integer, got {}",
                            v
                        ))
                    })?),
                    None => None,
                };
                Ok(Severity::Object { level, confidence })
            }
            _ => Err(serde::de::Error::custom(
                "severity must be a string or object",
            )),
        }
    }
}

// ─── §2.5 Classification ────────────────────────────────────────────────────

/// OATF taxonomy classification with optional framework mappings.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Classification {
    /// OATF taxonomy category.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub category: Option<Category>,
    /// Mappings to external security frameworks (MITRE ATT&CK, etc.).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mappings: Option<Vec<FrameworkMapping>>,
    /// Free-form tags for categorization.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tags: Option<Vec<String>>,
}

// ─── §2.6 Execution ─────────────────────────────────────────────────────────

/// Execution plan describing how the attack is carried out.
///
/// Exactly one of `state`, `phases`, or `actors` must be present (three
/// mutually exclusive execution forms). After normalization, only `actors` is set.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Execution {
    /// Protocol mode for single-phase form (e.g., `"mcp/sse"`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mode: Option<String>,
    /// Single-phase execution state (JSON object). Mutually exclusive with `phases`/`actors`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub state: Option<Value>,
    /// Multi-phase execution form. Mutually exclusive with `state`/`actors`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub phases: Option<Vec<Phase>>,
    /// Multi-actor execution form (canonical). Mutually exclusive with `state`/`phases`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub actors: Option<Vec<Actor>>,
    /// Extension fields (`x-*` prefixed).
    #[serde(flatten)]
    pub extensions: IndexMap<String, Value>,
}

// ─── §2.6a Actor ─────────────────────────────────────────────────────────────

/// An actor in the multi-actor execution form, representing a protocol participant.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Actor {
    /// Actor name identifier (e.g., `"attacker"`, `"victim"`).
    pub name: String,
    /// Protocol mode (e.g., `"mcp/sse"`, `"a2a"`).
    pub mode: String,
    /// Ordered list of execution phases for this actor.
    pub phases: Vec<Phase>,
    /// Extension fields (`x-*` prefixed).
    #[serde(flatten)]
    pub extensions: IndexMap<String, Value>,
}

// ─── §2.7 Phase ──────────────────────────────────────────────────────────────

/// An execution phase within an actor's plan.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Phase {
    /// Phase name identifier.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// Human-readable phase description.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// Protocol mode override for this phase.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mode: Option<String>,
    /// Phase execution state (JSON object describing protocol messages).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub state: Option<Value>,
    /// Data extractors applied to protocol messages during this phase.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub extractors: Option<Vec<Extractor>>,
    /// Actions executed when this phase begins.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub on_enter: Option<Vec<Action>>,
    /// Trigger condition that advances to the next phase.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub trigger: Option<Trigger>,
    /// Extension fields (`x-*` prefixed).
    #[serde(flatten)]
    pub extensions: IndexMap<String, Value>,
}

// ─── §2.7a Action ────────────────────────────────────────────────────────────

/// An entry action executed when a phase begins.
/// Tagged union with known variants + catch-all for binding-specific actions.
#[derive(Clone, Debug)]
pub enum Action {
    /// Send a protocol message.
    Send {
        /// Method name.
        method: String,
        /// Optional parameters.
        params: Option<Value>,
        /// Extension fields (`x-*` prefixed).
        extensions: IndexMap<String, Value>,
    },
    /// Emit a log message.
    Log {
        /// Log message text.
        message: String,
        /// Log level (defaults to `info`).
        level: Option<LogLevel>,
        /// Extension fields (`x-*` prefixed).
        extensions: IndexMap<String, Value>,
    },
    /// Binding-specific action with a single unknown key.
    BindingSpecific {
        /// The action key name.
        key: String,
        /// The action value.
        value: Value,
        /// Extension fields (`x-*` prefixed).
        extensions: IndexMap<String, Value>,
    },
}

impl Serialize for Action {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        use serde::ser::SerializeMap;
        match self {
            Action::Send {
                method,
                params,
                extensions,
                ..
            } => {
                let mut outer = serializer.serialize_map(None)?;
                let mut inner = serde_json::Map::new();
                inner.insert("method".to_string(), Value::String(method.clone()));
                if let Some(p) = params {
                    inner.insert("params".to_string(), p.clone());
                }
                outer.serialize_entry("send", &Value::Object(inner))?;
                for (k, v) in extensions {
                    outer.serialize_entry(k, v)?;
                }
                outer.end()
            }
            Action::Log {
                message,
                level,
                extensions,
                ..
            } => {
                let mut outer = serializer.serialize_map(None)?;
                let mut inner = serde_json::Map::new();
                inner.insert("message".to_string(), Value::String(message.clone()));
                if let Some(l) = level {
                    inner.insert(
                        "level".to_string(),
                        serde_json::to_value(l).unwrap_or(Value::Null),
                    );
                }
                outer.serialize_entry("log", &Value::Object(inner))?;
                for (k, v) in extensions {
                    outer.serialize_entry(k, v)?;
                }
                outer.end()
            }
            Action::BindingSpecific {
                key,
                value,
                extensions,
                ..
            } => {
                let mut map = serializer.serialize_map(None)?;
                map.serialize_entry(key, value)?;
                for (k, v) in extensions {
                    map.serialize_entry(k, v)?;
                }
                map.end()
            }
        }
    }
}

impl<'de> Deserialize<'de> for Action {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let map: serde_json::Map<String, Value> = serde_json::Map::deserialize(deserializer)?;

        let mut extensions = IndexMap::new();
        let mut action_key = None;
        let mut action_value = None;
        let mut non_ext_key_count = 0usize;

        for (k, v) in &map {
            if k.starts_with("x-") {
                extensions.insert(k.clone(), v.clone());
            } else {
                non_ext_key_count += 1;
                if action_key.is_none() {
                    action_key = Some(k.clone());
                    action_value = Some(v.clone());
                }
            }
        }

        if non_ext_key_count != 1 {
            return Err(serde::de::Error::custom(format!(
                "action must have exactly 1 non-extension key, found {}",
                non_ext_key_count
            )));
        }

        let key = action_key
            .ok_or_else(|| serde::de::Error::custom("action object must have at least one key"))?;
        let value = action_value
            .ok_or_else(|| serde::de::Error::custom("action object must have a value"))?;

        match key.as_str() {
            "send" => {
                let obj = value
                    .as_object()
                    .ok_or_else(|| serde::de::Error::custom("send must be an object"))?;
                for field in obj.keys() {
                    if field != "method" && field != "params" {
                        return Err(serde::de::Error::custom(format!(
                            "send has unknown field '{}'",
                            field
                        )));
                    }
                }
                let method = obj
                    .get("method")
                    .and_then(|v| v.as_str())
                    .ok_or_else(|| serde::de::Error::custom("send requires 'method'"))?
                    .to_string();
                let params = obj.get("params").cloned();
                Ok(Action::Send {
                    method,
                    params,
                    extensions,
                })
            }
            "log" => {
                let obj = value
                    .as_object()
                    .ok_or_else(|| serde::de::Error::custom("log must be an object"))?;
                for field in obj.keys() {
                    if field != "message" && field != "level" {
                        return Err(serde::de::Error::custom(format!(
                            "log has unknown field '{}'",
                            field
                        )));
                    }
                }
                let message = obj
                    .get("message")
                    .and_then(|v| v.as_str())
                    .ok_or_else(|| serde::de::Error::custom("log requires 'message'"))?
                    .to_string();
                let level = obj
                    .get("level")
                    .map(|v| serde_json::from_value(v.clone()))
                    .transpose()
                    .map_err(serde::de::Error::custom)?;
                Ok(Action::Log {
                    message,
                    level,
                    extensions,
                })
            }
            _ => Ok(Action::BindingSpecific {
                key,
                value,
                extensions,
            }),
        }
    }
}

// ─── §2.8 Trigger ────────────────────────────────────────────────────────────

/// Condition that advances execution to the next phase.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Trigger {
    /// Protocol event name (e.g., `"mcp:tool_call"`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub event: Option<String>,
    /// Number of matching events required before advancing.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub count: Option<i64>,
    /// Predicate that the event payload must satisfy.
    #[serde(rename = "match", skip_serializing_if = "Option::is_none")]
    pub match_predicate: Option<MatchPredicate>,
    /// Duration string (e.g., `"5s"`) after which the trigger times out.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub after: Option<String>,
}

// ─── §2.8a ProtocolEvent ─────────────────────────────────────────────────────

/// A protocol event observed during execution.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ProtocolEvent {
    /// The event type (e.g., `"tools/call"`, `"message/send"`, `"run_started"`).
    pub event_type: String,
    /// The event payload. Evaluated against `trigger.match` predicates via `evaluate_predicate`.
    pub content: Value,
}

// ─── §2.8b TriggerResult ────────────────────────────────────────────────────

/// Result of evaluating a trigger against an event.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum TriggerResult {
    /// The trigger condition was met and execution should advance.
    Advanced {
        /// Why the trigger advanced.
        reason: AdvanceReason,
    },
    /// The trigger condition was not met.
    NotAdvanced,
}

// ─── §2.8c TriggerState ─────────────────────────────────────────────────────

/// Mutable per-trigger state tracked across successive `evaluate_trigger` calls.
///
/// The caller should create one `TriggerState` per trigger and pass it by
/// mutable reference on every evaluation. The SDK increments `event_count`
/// only when the incoming event fully matches (base event type + predicate),
/// which prevents the over-count bug inherent in external counting.
#[derive(Clone, Debug, Default)]
pub struct TriggerState {
    /// Number of events that have fully matched so far.
    pub event_count: u64,
}

// ─── §2.9 Extractor ─────────────────────────────────────────────────────────

/// A data extractor that captures values from protocol messages.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Extractor {
    /// Variable name to bind the extracted value to.
    pub name: String,
    /// Whether to extract from request or response.
    pub source: ExtractorSource,
    /// Extraction method (JSONPath or regex).
    #[serde(rename = "type")]
    pub extractor_type: ExtractorType,
    /// JSONPath expression or regex pattern.
    pub selector: String,
}

// ─── §2.10 MatchPredicate ───────────────────────────────────────────────────

/// A match predicate is a map from dot-path field references to conditions.
pub type MatchPredicate = HashMap<String, MatchEntry>;

/// Either a scalar Value (equality check) or a MatchCondition object.
#[derive(Clone, Debug)]
pub enum MatchEntry {
    /// Direct value equality comparison.
    Scalar(Value),
    /// Operator-based condition (contains, regex, etc.).
    Condition(MatchCondition),
}

impl Serialize for MatchEntry {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        match self {
            MatchEntry::Scalar(v) => v.serialize(serializer),
            MatchEntry::Condition(c) => c.serialize(serializer),
        }
    }
}

impl<'de> Deserialize<'de> for MatchEntry {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let value = Value::deserialize(deserializer)?;
        match &value {
            Value::Object(map) => {
                // Check if it looks like a MatchCondition (has operator keys)
                if map
                    .keys()
                    .any(|k| MATCH_OPERATOR_KEYS.contains(&k.as_str()))
                {
                    let cond: MatchCondition =
                        serde_json::from_value(value).map_err(serde::de::Error::custom)?;
                    Ok(MatchEntry::Condition(cond))
                } else {
                    Ok(MatchEntry::Scalar(value))
                }
            }
            _ => Ok(MatchEntry::Scalar(value)),
        }
    }
}

// ─── §2.11 MatchCondition ───────────────────────────────────────────────────

/// The set of recognized match-condition operator key names.
///
/// Used to distinguish a MatchCondition object from a bare-value equality
/// check during deserialization of `MatchEntry`, `Condition`, and
/// `PatternMatch.condition`.
pub static MATCH_OPERATOR_KEYS: &[&str] = &[
    "contains",
    "starts_with",
    "ends_with",
    "regex",
    "any_of",
    "gt",
    "lt",
    "gte",
    "lte",
    "exists",
];

/// Operator-based match condition for field comparison.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct MatchCondition {
    /// String containment check.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub contains: Option<String>,
    /// String prefix check.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub starts_with: Option<String>,
    /// String suffix check.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ends_with: Option<String>,
    /// Regular expression match.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub regex: Option<String>,
    /// Value must be one of the given values.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub any_of: Option<Vec<Value>>,
    /// Greater-than numeric comparison.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub gt: Option<f64>,
    /// Less-than numeric comparison.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub lt: Option<f64>,
    /// Greater-than-or-equal numeric comparison.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub gte: Option<f64>,
    /// Less-than-or-equal numeric comparison.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub lte: Option<f64>,
    /// Field existence check.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub exists: Option<bool>,
}

// ─── §2.12 Indicator ────────────────────────────────────────────────────────

/// A detection indicator that matches against protocol messages.
///
/// Exactly one of `pattern`, `expression`, or `semantic` should be present.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Indicator {
    /// Unique indicator identifier (used in verdict reporting).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<String>,
    /// Protocol this indicator applies to (e.g., `"mcp"`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub protocol: Option<String>,
    /// Protocol operation name (e.g., `"tools/call"`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub surface: Option<String>,
    /// Target path within the protocol message.
    pub target: String,
    /// Actor name this indicator is scoped to.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub actor: Option<String>,
    /// Message direction filter.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub direction: Option<Direction>,
    /// Detection method hint.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub method: Option<IndicatorMethod>,
    /// Human-readable indicator description.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// Pattern-based detection (target + condition matching).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pattern: Option<PatternMatch>,
    /// CEL expression-based detection.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub expression: Option<ExpressionMatch>,
    /// Semantic/intent-based detection.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub semantic: Option<SemanticMatch>,
    /// Outcome tier this indicator detects (§6.5).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tier: Option<String>,
    /// Confidence percentage (0–100) for this indicator.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub confidence: Option<i64>,
    /// Indicator-level severity override.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub severity: Option<SeverityLevel>,
    /// Known false-positive descriptions.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub false_positives: Option<Vec<String>>,
    /// Extension fields (`x-*` prefixed).
    #[serde(flatten)]
    pub extensions: IndexMap<String, Value>,
}

// ─── §2.13 PatternMatch ─────────────────────────────────────────────────────

/// A pattern match indicator. Supports standard and shorthand form.
/// In standard form: has `target` and `condition`.
/// In shorthand form: has operator keys directly (e.g., `contains`, `regex`).
#[derive(Clone, Debug)]
pub struct PatternMatch {
    /// JSONPath target to match against.
    pub target: Option<String>,
    /// Condition to evaluate against the resolved target value.
    pub condition: Option<Condition>,
    // Shorthand operator fields (before normalization)
    /// Shorthand: string containment check.
    pub contains: Option<String>,
    /// Shorthand: string prefix check.
    pub starts_with: Option<String>,
    /// Shorthand: string suffix check.
    pub ends_with: Option<String>,
    /// Shorthand: regular expression match.
    pub regex: Option<String>,
    /// Shorthand: value must be one of the given values.
    pub any_of: Option<Vec<Value>>,
    /// Shorthand: greater-than numeric comparison.
    pub gt: Option<f64>,
    /// Shorthand: less-than numeric comparison.
    pub lt: Option<f64>,
    /// Shorthand: greater-than-or-equal numeric comparison.
    pub gte: Option<f64>,
    /// Shorthand: less-than-or-equal numeric comparison.
    pub lte: Option<f64>,
}

impl PatternMatch {
    /// Returns true if this pattern is in shorthand form (has direct operator keys).
    pub fn is_shorthand(&self) -> bool {
        self.condition.is_none() && self.is_shorthand_fields_present()
    }

    /// Returns true if any shorthand operator field is present.
    pub fn is_shorthand_fields_present(&self) -> bool {
        self.contains.is_some()
            || self.starts_with.is_some()
            || self.ends_with.is_some()
            || self.regex.is_some()
            || self.any_of.is_some()
            || self.gt.is_some()
            || self.lt.is_some()
            || self.gte.is_some()
            || self.lte.is_some()
    }
}

impl Serialize for PatternMatch {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        use serde::ser::SerializeMap;
        let mut map = serializer.serialize_map(None)?;
        if let Some(ref t) = self.target {
            map.serialize_entry("target", t)?;
        }
        if let Some(ref c) = self.condition {
            map.serialize_entry("condition", c)?;
        }
        // Shorthand fields (only present before normalization)
        if let Some(ref v) = self.contains {
            map.serialize_entry("contains", v)?;
        }
        if let Some(ref v) = self.starts_with {
            map.serialize_entry("starts_with", v)?;
        }
        if let Some(ref v) = self.ends_with {
            map.serialize_entry("ends_with", v)?;
        }
        if let Some(ref v) = self.regex {
            map.serialize_entry("regex", v)?;
        }
        if let Some(ref v) = self.any_of {
            map.serialize_entry("any_of", v)?;
        }
        if let Some(v) = self.gt {
            map.serialize_entry("gt", &v)?;
        }
        if let Some(v) = self.lt {
            map.serialize_entry("lt", &v)?;
        }
        if let Some(v) = self.gte {
            map.serialize_entry("gte", &v)?;
        }
        if let Some(v) = self.lte {
            map.serialize_entry("lte", &v)?;
        }
        map.end()
    }
}

impl<'de> Deserialize<'de> for PatternMatch {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let value = Value::deserialize(deserializer)?;
        let map = value
            .as_object()
            .ok_or_else(|| serde::de::Error::custom("pattern must be an object"))?;

        let parse_opt_string = |key: &str| -> Result<Option<String>, D::Error> {
            match map.get(key) {
                None | Some(Value::Null) => Ok(None),
                Some(Value::String(s)) => Ok(Some(s.clone())),
                Some(v) => Err(serde::de::Error::custom(format!(
                    "pattern.{} must be a string, got {}",
                    key, v
                ))),
            }
        };

        let parse_opt_number = |key: &str| -> Result<Option<f64>, D::Error> {
            match map.get(key) {
                None | Some(Value::Null) => Ok(None),
                Some(v) => v.as_f64().map(Some).ok_or_else(|| {
                    serde::de::Error::custom(format!("pattern.{} must be a number, got {}", key, v))
                }),
            }
        };

        let target = match map.get("target") {
            None | Some(Value::Null) => None,
            Some(Value::String(s)) => Some(s.clone()),
            Some(v) => {
                return Err(serde::de::Error::custom(format!(
                    "pattern.target must be a string, got {}",
                    v
                )));
            }
        };

        let condition = match map.get("condition") {
            Some(v) => Some(Condition::from_value(v.clone()).map_err(serde::de::Error::custom)?),
            None => None,
        };

        // Shorthand operator fields
        let contains = parse_opt_string("contains")?;
        let starts_with = parse_opt_string("starts_with")?;
        let ends_with = parse_opt_string("ends_with")?;
        let regex = parse_opt_string("regex")?;
        let any_of = match map.get("any_of") {
            None | Some(Value::Null) => None,
            Some(Value::Array(arr)) => Some(arr.clone()),
            Some(v) => {
                return Err(serde::de::Error::custom(format!(
                    "pattern.any_of must be an array, got {}",
                    v
                )));
            }
        };
        let gt = parse_opt_number("gt")?;
        let lt = parse_opt_number("lt")?;
        let gte = parse_opt_number("gte")?;
        let lte = parse_opt_number("lte")?;

        Ok(PatternMatch {
            target,
            condition,
            contains,
            starts_with,
            ends_with,
            regex,
            any_of,
            gt,
            lt,
            gte,
            lte,
        })
    }
}

/// A Condition is either a bare Value (equality) or a MatchCondition object.
#[derive(Clone, Debug)]
pub enum Condition {
    /// Direct value equality comparison.
    Equality(Value),
    /// Operator-based condition.
    Operators(MatchCondition),
}

impl Condition {
    pub fn from_value(v: Value) -> Result<Self, String> {
        match &v {
            Value::Object(map) => {
                if map
                    .keys()
                    .any(|k| MATCH_OPERATOR_KEYS.contains(&k.as_str()))
                {
                    let cond: MatchCondition = serde_json::from_value(v)
                        .map_err(|e| format!("invalid pattern.condition object: {}", e))?;
                    Ok(Condition::Operators(cond))
                } else {
                    Ok(Condition::Equality(v))
                }
            }
            _ => Ok(Condition::Equality(v)),
        }
    }
}

impl Serialize for Condition {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        match self {
            Condition::Equality(v) => v.serialize(serializer),
            Condition::Operators(c) => c.serialize(serializer),
        }
    }
}

// ─── §2.14 ExpressionMatch ──────────────────────────────────────────────────

/// A CEL expression-based detection indicator.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ExpressionMatch {
    /// CEL expression to evaluate.
    pub cel: String,
    /// Variable bindings: name → JSONPath.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub variables: Option<HashMap<String, String>>,
}

// ─── §2.15 SemanticMatch ────────────────────────────────────────────────────

/// A semantic/intent-based detection indicator.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct SemanticMatch {
    /// JSONPath target to extract text from.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub target: Option<String>,
    /// Natural-language intent description to match against.
    pub intent: String,
    /// Classification hint for the semantic evaluator.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub intent_class: Option<SemanticIntentClass>,
    /// Similarity threshold (0.0–1.0); defaults to 0.7.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub threshold: Option<f64>,
    /// Positive and negative examples for few-shot guidance.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub examples: Option<SemanticExamples>,
}

// ─── §2.16 SemanticExamples ─────────────────────────────────────────────────

/// Positive and negative examples for semantic matching guidance.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct SemanticExamples {
    /// Examples that should match the intent.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub positive: Option<Vec<String>>,
    /// Examples that should not match the intent.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub negative: Option<Vec<String>>,
}

// ─── §2.17 Reference ────────────────────────────────────────────────────────

/// An external reference (URL, paper, advisory).
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Reference {
    /// Reference URL.
    pub url: String,
    /// Human-readable title.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,
    /// Human-readable description.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

// ─── §2.18 FrameworkMapping ─────────────────────────────────────────────────

/// A mapping to an external security framework (e.g., MITRE ATT&CK).
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct FrameworkMapping {
    /// Framework name (e.g., `"MITRE ATT&CK"`).
    pub framework: String,
    /// Framework-specific identifier (e.g., `"T1059"`).
    pub id: String,
    /// Human-readable technique/entry name.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// URL to the framework entry.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub url: Option<String>,
    /// Relationship type (primary or related).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub relationship: Option<Relationship>,
}

// ─── §2.19 Verdict Types ────────────────────────────────────────────────────

/// Result of evaluating a single indicator against a protocol message.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct IndicatorVerdict {
    /// Identifier of the evaluated indicator.
    pub indicator_id: String,
    /// Evaluation result.
    pub result: IndicatorResult,
    /// ISO 8601 timestamp of the evaluation.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub timestamp: Option<String>,
    /// Supporting evidence (e.g., matched value, error message).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub evidence: Option<String>,
    /// Source that produced this verdict.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub source: Option<String>,
}

/// Attack-level verdict computed from indicator verdicts.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct AttackVerdict {
    /// Identifier of the evaluated attack.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub attack_id: Option<String>,
    /// Overall attack result.
    pub result: AttackResult,
    /// Highest tier among matched indicators.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_tier: Option<Tier>,
    /// Individual indicator verdicts.
    pub indicator_verdicts: Vec<IndicatorVerdict>,
    /// Summary counts of indicator results.
    pub evaluation_summary: EvaluationSummary,
    /// ISO 8601 timestamp of the verdict.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub timestamp: Option<String>,
    /// Source that produced this verdict.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub source: Option<String>,
}

/// Summary counts of indicator evaluation results.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct EvaluationSummary {
    /// Number of indicators that matched.
    pub matched: i64,
    /// Number of indicators that did not match.
    pub not_matched: i64,
    /// Number of indicators that errored.
    pub error: i64,
    /// Number of indicators that were skipped.
    pub skipped: i64,
}

// ─── §2.23 SynthesizeBlock ──────────────────────────────────────────────────

/// An LLM synthesis block for generating adversarial content.
/// Reserved for a future version; no normative semantics in v0.1.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct SynthesizeBlock {
    /// Prompt template for the generation provider.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub prompt: Option<String>,
}

// ─── §2.24 ResponseEntry ────────────────────────────────────────────────────

/// A conditional response entry in a phase's state.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ResponseEntry {
    /// Predicate that selects this response (matched against the request).
    #[serde(rename = "when", skip_serializing_if = "Option::is_none")]
    pub when: Option<MatchPredicate>,
    /// LLM synthesis block for dynamic content generation.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub synthesize: Option<SynthesizeBlock>,
    /// Protocol-specific static content fields (MCP content, A2A messages, etc.).
    #[serde(flatten)]
    pub extra: IndexMap<String, Value>,
}