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
//! Execution primitives per SDK spec §5.1–§5.11.
//!
//! Shared utility operations used by both entry points and evaluation.

use crate::enums::AdvanceReason;
use crate::error::{Diagnostic, DiagnosticSeverity, ParseError, ParseErrorKind};
use crate::types::*;
use regex::Regex;
use serde_json::Value;
use std::collections::HashMap;
use std::time::Duration;

/// Compile a user-supplied regex with size limits to prevent ReDoS.
pub(crate) fn compile_user_regex(pattern: &str) -> Result<Regex, regex::Error> {
    regex::RegexBuilder::new(pattern)
        .size_limit(1 << 20) // 1 MB compiled size
        .dfa_size_limit(1 << 20) // 1 MB DFA size
        .build()
}

// Re-export extract_protocol from event_registry (§5.9)
pub use crate::event_registry::extract_protocol;

// ─── §5.1.1 resolve_simple_path ─────────────────────────────────────────────

/// Resolves a simple dot-path against a value tree.
///
/// Returns the single value at the path, or `None` if any segment fails to
/// resolve. Empty path returns the root value.
pub fn resolve_simple_path(path: &str, value: &Value) -> Option<Value> {
    if path.is_empty() {
        return Some(value.clone());
    }

    let mut current = value;
    for segment in path.split('.') {
        match current.as_object() {
            Some(obj) => match obj.get(segment) {
                Some(v) => current = v,
                None => return None,
            },
            None => return None,
        }
    }
    Some(current.clone())
}

// ─── §5.1.2 resolve_wildcard_path ───────────────────────────────────────────

/// Resolves a wildcard dot-path against a value tree.
///
/// Returns all values that match, potentially expanding across array elements
/// via `[*]` wildcards. Returns an empty vec if the path does not match.
/// Empty path returns the root value as a single-element list.
pub fn resolve_wildcard_path(path: &str, value: &Value) -> Vec<Value> {
    if path.is_empty() {
        return vec![value.clone()];
    }

    let segments = match split_wildcard_segments(path) {
        Some(s) => s,
        None => return vec![],
    };

    let mut current = vec![value.clone()];

    for seg in &segments {
        if current.is_empty() {
            break;
        }
        let mut next = Vec::new();
        for val in &current {
            if seg.wildcard {
                // First access the field name, then fan out
                let target = if seg.name.is_empty() {
                    val.clone()
                } else {
                    match val.as_object().and_then(|o| o.get(&seg.name)) {
                        Some(v) => v.clone(),
                        None => continue,
                    }
                };
                if let Some(arr) = target.as_array() {
                    next.extend(arr.iter().cloned());
                }
            } else if let Some(v) = val.as_object().and_then(|o| o.get(&seg.name)) {
                next.push(v.clone());
            }
        }
        current = next;
    }

    current
}

struct WildcardSegment {
    name: String,
    wildcard: bool,
}

/// Check whether a character is valid within a dot-path segment.
/// Segments may contain ASCII alphanumerics, underscores, and hyphens.
fn is_path_segment_char(c: char) -> bool {
    c.is_ascii_alphanumeric() || c == '_' || c == '-'
}

/// Parse a wildcard dot-path into segments, validating syntax and character set.
///
/// This is the single shared parser used by both the validator
/// (`is_valid_wildcard_dot_path`) and the runtime resolver
/// (`resolve_wildcard_path`). Returns `None` for any syntax error.
fn split_wildcard_segments(path: &str) -> Option<Vec<WildcardSegment>> {
    let mut segments = Vec::new();
    let mut current = String::new();
    let chars: Vec<char> = path.chars().collect();
    let mut i = 0;
    let mut expect_segment = true; // tracks whether we need a new segment name next

    while i < chars.len() {
        match chars[i] {
            '.' => {
                if !current.is_empty() {
                    segments.push(WildcardSegment {
                        name: current.clone(),
                        wildcard: false,
                    });
                    current.clear();
                } else if !expect_segment {
                    // Previous token was [*] which already consumed the dot — this is fine
                } else {
                    return None; // leading dot or double dot
                }
                expect_segment = true;
                i += 1;
            }
            '[' => {
                // Must be [*]
                if i + 2 < chars.len() && chars[i + 1] == '*' && chars[i + 2] == ']' {
                    // [*] at the start of the path is invalid
                    if current.is_empty() && segments.is_empty() {
                        return None;
                    }
                    segments.push(WildcardSegment {
                        name: current.clone(),
                        wildcard: true,
                    });
                    current.clear();
                    i += 3;
                    expect_segment = false;
                    // After [*], must be . or end
                    if i < chars.len() {
                        if chars[i] == '.' {
                            expect_segment = true;
                            i += 1;
                        } else {
                            return None;
                        }
                    }
                } else if i + 1 < chars.len() && chars[i + 1] == '-' {
                    return None; // Negative index
                } else {
                    return None; // Invalid bracket content
                }
            }
            c if is_path_segment_char(c) => {
                current.push(c);
                i += 1;
            }
            _ => {
                return None; // Invalid character
            }
        }
    }

    if !current.is_empty() {
        segments.push(WildcardSegment {
            name: current,
            wildcard: false,
        });
    } else if expect_segment && !segments.is_empty() {
        // Trailing dot (expect_segment is true but nothing followed)
        return None;
    }

    Some(segments)
}

/// Validate wildcard dot-path syntax per §5.1.2.
///
/// Accepts paths like `tools[*].name`, `content`, or `""` (root).
/// Rejects invalid characters, leading/trailing dots, double dots,
/// numeric indices, and leading wildcards.
pub fn is_valid_wildcard_dot_path(path: &str) -> bool {
    if path.is_empty() {
        return true;
    }
    split_wildcard_segments(path).is_some()
}

/// Validate simple dot-path syntax per §5.1.1.
/// No wildcards or numeric indices allowed.
pub fn is_valid_simple_dot_path(path: &str) -> bool {
    if path.is_empty() {
        return true;
    }
    for seg in path.split('.') {
        if seg.is_empty() {
            return false;
        }
        if !seg.chars().all(is_path_segment_char) {
            return false;
        }
    }
    true
}

// ─── §5.2 parse_duration ────────────────────────────────────────────────────

/// Parses a duration string in either shorthand or ISO 8601 format.
///
/// Accepted: `30s`, `5m`, `1h`, `2d`, `PT30S`, `PT5M`, `PT1H`, `P2D`,
/// `P1DT12H30M15S`, etc.
pub fn parse_duration(input: &str) -> Result<Duration, ParseError> {
    if input.is_empty() {
        return Err(duration_error("empty duration string"));
    }

    if input.starts_with('P') {
        parse_iso_duration(input)
    } else {
        parse_shorthand_duration(input)
    }
}

fn parse_shorthand_duration(input: &str) -> Result<Duration, ParseError> {
    if input.len() < 2 {
        return Err(duration_error(&format!(
            "invalid shorthand duration: '{}'",
            input
        )));
    }

    // Split before the last character safely (handles multi-byte chars)
    let split_pos = input
        .char_indices()
        .next_back()
        .map(|(i, _)| i)
        .unwrap_or(0);
    let (num_str, unit) = input.split_at(split_pos);
    let n: u64 = num_str
        .parse()
        .map_err(|_| duration_error(&format!("invalid shorthand duration: '{}'", input)))?;

    let secs = match unit {
        "s" => Some(n),
        "m" => n.checked_mul(60),
        "h" => n.checked_mul(3600),
        "d" => n.checked_mul(86400),
        _ => {
            return Err(duration_error(&format!(
                "unknown duration unit: '{}'",
                unit
            )));
        }
    };

    let secs =
        secs.ok_or_else(|| duration_error(&format!("duration value too large: '{}'", input)))?;

    Ok(Duration::from_secs(secs))
}

fn parse_iso_duration(input: &str) -> Result<Duration, ParseError> {
    let rest = &input[1..]; // strip leading 'P'
    let mut total_secs: u64 = 0;

    let (date_part, time_part) = if let Some(t_pos) = rest.find('T') {
        (&rest[..t_pos], Some(&rest[t_pos + 1..]))
    } else {
        (rest, None)
    };

    // Parse date component (only D supported)
    if !date_part.is_empty() {
        if let Some(num_str) = date_part.strip_suffix('D') {
            let n: u64 = num_str
                .parse()
                .map_err(|_| duration_error(&format!("invalid ISO duration: '{}'", input)))?;
            total_secs = n
                .checked_mul(86400)
                .and_then(|v| total_secs.checked_add(v))
                .ok_or_else(|| duration_error(&format!("duration value too large: '{}'", input)))?;
        } else {
            return Err(duration_error(&format!(
                "invalid ISO duration: '{}'",
                input
            )));
        }
    }

    // Parse time components (H, M, S)
    if let Some(time) = time_part {
        if time.is_empty() {
            return Err(duration_error(&format!(
                "invalid ISO duration: '{}'",
                input
            )));
        }
        let mut remaining = time;
        // Hours
        if let Some(h_pos) = remaining.find('H') {
            let n: u64 = remaining[..h_pos]
                .parse()
                .map_err(|_| duration_error(&format!("invalid ISO duration: '{}'", input)))?;
            total_secs = n
                .checked_mul(3600)
                .and_then(|v| total_secs.checked_add(v))
                .ok_or_else(|| duration_error(&format!("duration value too large: '{}'", input)))?;
            remaining = &remaining[h_pos + 1..];
        }
        // Minutes
        if let Some(m_pos) = remaining.find('M') {
            let n: u64 = remaining[..m_pos]
                .parse()
                .map_err(|_| duration_error(&format!("invalid ISO duration: '{}'", input)))?;
            total_secs = n
                .checked_mul(60)
                .and_then(|v| total_secs.checked_add(v))
                .ok_or_else(|| duration_error(&format!("duration value too large: '{}'", input)))?;
            remaining = &remaining[m_pos + 1..];
        }
        // Seconds
        if let Some(s_pos) = remaining.find('S') {
            let n: u64 = remaining[..s_pos]
                .parse()
                .map_err(|_| duration_error(&format!("invalid ISO duration: '{}'", input)))?;
            total_secs = total_secs
                .checked_add(n)
                .ok_or_else(|| duration_error(&format!("duration value too large: '{}'", input)))?;
            remaining = &remaining[s_pos + 1..];
        }
        if !remaining.is_empty() {
            return Err(duration_error(&format!(
                "invalid ISO duration: '{}'",
                input
            )));
        }
    }

    // Must have at least some duration component
    if date_part.is_empty() && time_part.is_none() {
        return Err(duration_error(&format!(
            "invalid ISO duration: '{}'",
            input
        )));
    }

    Ok(Duration::from_secs(total_secs))
}

fn duration_error(message: &str) -> ParseError {
    ParseError {
        kind: ParseErrorKind::Syntax,
        message: message.to_string(),
        path: None,
        line: None,
        column: None,
    }
}

// ─── §5.3 evaluate_condition ────────────────────────────────────────────────

/// Evaluates a condition against a resolved value.
///
/// If `condition` is a bare value, performs deep equality comparison.
/// If `condition` is a `MatchCondition` object, evaluates each present operator
/// — all must match (AND logic).
pub fn evaluate_condition(condition: &Condition, value: &Value) -> bool {
    match condition {
        Condition::Equality(expected) => values_deep_equal(value, expected),
        Condition::Operators(cond) => evaluate_match_condition(cond, value),
    }
}

/// Evaluate a MatchCondition (set of operators) against a value with AND logic.
pub fn evaluate_match_condition(cond: &MatchCondition, value: &Value) -> bool {
    // Each present operator must pass (AND logic)
    // Coerce value to string once for all string operators.
    // For strings this is a clone; for numbers/bools/null/objects/arrays it
    // produces a canonical text representation (e.g. "42", "true", compact JSON).
    let need_string_op = cond.contains.is_some()
        || cond.starts_with.is_some()
        || cond.ends_with.is_some()
        || cond.regex.is_some();

    if need_string_op {
        let text = value_to_string(value);

        if let Some(ref s) = cond.contains
            && !text.contains(s.as_str())
        {
            return false;
        }
        if let Some(ref s) = cond.starts_with
            && !text.starts_with(s.as_str())
        {
            return false;
        }
        if let Some(ref s) = cond.ends_with
            && !text.ends_with(s.as_str())
        {
            return false;
        }
        if let Some(ref pattern) = cond.regex {
            if let Ok(re) = compile_user_regex(pattern) {
                if !re.is_match(&text) {
                    return false;
                }
            } else {
                return false; // invalid regex → false
            }
        }
    }

    if let Some(ref items) = cond.any_of
        && !items.iter().any(|item| values_deep_equal(value, item))
    {
        return false;
    }

    if let Some(threshold) = cond.gt {
        match value.as_f64() {
            Some(v) if v > threshold => {}
            _ => return false,
        }
    }

    if let Some(threshold) = cond.lt {
        match value.as_f64() {
            Some(v) if v < threshold => {}
            _ => return false,
        }
    }

    if let Some(threshold) = cond.gte {
        match value.as_f64() {
            Some(v) if v >= threshold => {}
            _ => return false,
        }
    }

    if let Some(threshold) = cond.lte {
        match value.as_f64() {
            Some(v) if v <= threshold => {}
            _ => return false,
        }
    }

    // exists is handled by evaluate_predicate, not here
    true
}

/// Deep equality comparison per SDK spec §5.3.
///
/// Integer 42 equals float 42.0; object key order is irrelevant;
/// arrays compare element-wise by position and length.
fn values_deep_equal(a: &Value, b: &Value) -> bool {
    match (a, b) {
        (Value::Null, Value::Null) => true,
        (Value::Bool(a), Value::Bool(b)) => a == b,
        (Value::Number(a), Value::Number(b)) => match (a.as_f64(), b.as_f64()) {
            (Some(fa), Some(fb)) => fa == fb,
            _ => a == b,
        },
        (Value::String(a), Value::String(b)) => a == b,
        (Value::Array(a), Value::Array(b)) => {
            a.len() == b.len() && a.iter().zip(b.iter()).all(|(a, b)| values_deep_equal(a, b))
        }
        (Value::Object(a), Value::Object(b)) => {
            if a.len() != b.len() {
                return false;
            }
            a.iter()
                .all(|(k, v)| b.get(k).is_some_and(|bv| values_deep_equal(v, bv)))
        }
        _ => false,
    }
}

// ─── §5.4 evaluate_predicate ────────────────────────────────────────────────

/// Evaluates a match predicate against a value. All entries combined with AND.
///
/// For each `(path, condition)` entry:
/// - Resolve the path via `resolve_simple_path`
/// - Handle `exists` operator at the path-resolution level
/// - Evaluate remaining condition operators against resolved value
///
/// Empty predicate → true.
pub fn evaluate_predicate(predicate: &MatchPredicate, value: &Value) -> bool {
    for (path, entry) in predicate {
        let resolved = resolve_simple_path(path, value);

        match entry {
            MatchEntry::Scalar(expected) => match &resolved {
                Some(val) => {
                    if !values_deep_equal(val, expected) {
                        return false;
                    }
                }
                None => return false,
            },
            MatchEntry::Condition(cond) => {
                match cond {
                    MatchCondition {
                        exists: Some(false),
                        ..
                    } => {
                        // exists: false — path should NOT resolve
                        if resolved.is_some() {
                            return false;
                        }
                        // §5.4: exists: false with no other operators → true;
                        // exists: false with other operators → false
                        let has_other_ops = cond.contains.is_some()
                            || cond.starts_with.is_some()
                            || cond.ends_with.is_some()
                            || cond.regex.is_some()
                            || cond.any_of.is_some()
                            || cond.gt.is_some()
                            || cond.lt.is_some()
                            || cond.gte.is_some()
                            || cond.lte.is_some();
                        if has_other_ops {
                            return false;
                        }
                    }
                    MatchCondition {
                        exists: Some(true), ..
                    } => {
                        // exists: true — path MUST resolve
                        let Some(val) = &resolved else {
                            return false;
                        };
                        if !evaluate_match_condition_excluding_exists(cond, val) {
                            return false;
                        }
                    }
                    _ => {
                        // No exists operator
                        match &resolved {
                            Some(val) => {
                                if !evaluate_match_condition(cond, val) {
                                    return false;
                                }
                            }
                            None => return false,
                        }
                    }
                }
            }
        }
    }
    true
}

/// Evaluate all operators in a MatchCondition except `exists`.
fn evaluate_match_condition_excluding_exists(cond: &MatchCondition, value: &Value) -> bool {
    // Build a temporary MatchCondition without exists
    let without_exists = MatchCondition {
        contains: cond.contains.clone(),
        starts_with: cond.starts_with.clone(),
        ends_with: cond.ends_with.clone(),
        regex: cond.regex.clone(),
        any_of: cond.any_of.clone(),
        gt: cond.gt,
        lt: cond.lt,
        gte: cond.gte,
        lte: cond.lte,
        exists: None,
    };
    evaluate_match_condition(&without_exists, value)
}

// ─── §5.5 interpolate_template ──────────────────────────────────────────────

/// Resolves template expressions in a string.
///
/// Returns the interpolated string and any diagnostics (W-004 warnings for
/// undefined references).
pub fn interpolate_template(
    template: &str,
    extractors: &HashMap<String, String>,
    request: Option<&Value>,
    response: Option<&Value>,
) -> (String, Vec<Diagnostic>) {
    let mut diagnostics = Vec::new();

    // Step 1: Replace \{{ with placeholder
    const PLACEHOLDER: &str = "\x00ESCAPED_OPEN_BRACE\x00";
    let working = template.replace("\\{{", PLACEHOLDER);

    // Step 2-3: Find and replace all {{...}} expressions
    let mut result = String::new();
    let mut remaining = working.as_str();

    while let Some(start) = remaining.find("{{") {
        result.push_str(&remaining[..start]);

        let after_open = &remaining[start + 2..];
        if let Some(end) = after_open.find("}}") {
            let expr = &after_open[..end];

            // Resolution order:
            // a. Check extractors map
            if let Some(val) = extractors.get(expr) {
                result.push_str(val);
            }
            // b. If starts with "request." and request is Some
            else if let Some(rest) = expr.strip_prefix("request.") {
                if let Some(req) = request {
                    match resolve_simple_path(rest, req) {
                        Some(v) => result.push_str(&value_to_string(&v)),
                        None => {
                            diagnostics.push(w004_diagnostic(expr));
                        }
                    }
                } else {
                    diagnostics.push(w004_diagnostic(expr));
                }
            }
            // c. If starts with "response." and response is Some
            else if let Some(rest) = expr.strip_prefix("response.") {
                if let Some(resp) = response {
                    match resolve_simple_path(rest, resp) {
                        Some(v) => result.push_str(&value_to_string(&v)),
                        None => {
                            diagnostics.push(w004_diagnostic(expr));
                        }
                    }
                } else {
                    diagnostics.push(w004_diagnostic(expr));
                }
            }
            // d. Otherwise, empty string + W-004
            else {
                diagnostics.push(w004_diagnostic(expr));
            }

            remaining = &after_open[end + 2..];
        } else {
            // Unclosed {{ — just pass through
            result.push_str("{{");
            remaining = after_open;
        }
    }
    result.push_str(remaining);

    // Step 4: Restore placeholders to literal {{
    let final_result = result.replace(PLACEHOLDER, "{{");

    (final_result, diagnostics)
}

fn value_to_string(v: &Value) -> String {
    match v {
        Value::String(s) => s.clone(),
        Value::Null => "null".to_string(),
        Value::Bool(b) => b.to_string(),
        Value::Number(n) => n.to_string(),
        // Objects and arrays serialize to compact JSON with keys sorted
        // lexicographically per spec §5.3.
        _ => {
            serde_json::to_string(&sort_keys(v)).unwrap_or_else(|_| "<unserializable>".to_string())
        }
    }
}

const MAX_VALUE_DEPTH: usize = 128;

/// Recursively sort object keys lexicographically for canonical JSON output.
fn sort_keys(v: &Value) -> Value {
    sort_keys_inner(v, 0)
}

fn sort_keys_inner(v: &Value, depth: usize) -> Value {
    if depth > MAX_VALUE_DEPTH {
        return v.clone();
    }
    match v {
        Value::Object(map) => {
            let mut sorted: serde_json::Map<String, Value> = serde_json::Map::new();
            let mut keys: Vec<&String> = map.keys().collect();
            keys.sort();
            for k in keys {
                sorted.insert(k.clone(), sort_keys_inner(&map[k], depth + 1));
            }
            Value::Object(sorted)
        }
        Value::Array(arr) => {
            Value::Array(arr.iter().map(|v| sort_keys_inner(v, depth + 1)).collect())
        }
        _ => v.clone(),
    }
}

fn w004_diagnostic(expr: &str) -> Diagnostic {
    Diagnostic {
        severity: DiagnosticSeverity::Warning,
        code: "W-004".to_string(),
        path: None,
        message: format!("unresolvable template reference: '{}'", expr),
    }
}

// ─── §5.5a interpolate_value ─────────────────────────────────────────────────

/// Recursively walks a JSON value tree and interpolates template expressions
/// in all string leaves that contain `{{`.
///
/// Returns a new `Value` with all templates resolved and aggregated diagnostics.
pub fn interpolate_value(
    value: &Value,
    extractors: &HashMap<String, String>,
    request: Option<&Value>,
    response: Option<&Value>,
) -> (Value, Vec<Diagnostic>) {
    let mut diagnostics = Vec::new();
    let result = interpolate_value_inner(value, extractors, request, response, &mut diagnostics, 0);
    (result, diagnostics)
}

fn interpolate_value_inner(
    value: &Value,
    extractors: &HashMap<String, String>,
    request: Option<&Value>,
    response: Option<&Value>,
    diagnostics: &mut Vec<Diagnostic>,
    depth: usize,
) -> Value {
    if depth > MAX_VALUE_DEPTH {
        return value.clone();
    }
    match value {
        Value::String(s) => {
            if s.contains("{{") {
                let (interpolated, diags) = interpolate_template(s, extractors, request, response);
                diagnostics.extend(diags);
                Value::String(interpolated)
            } else {
                value.clone()
            }
        }
        Value::Object(map) => {
            let new_map: serde_json::Map<String, Value> = map
                .iter()
                .map(|(k, v)| {
                    let new_v = interpolate_value_inner(
                        v,
                        extractors,
                        request,
                        response,
                        diagnostics,
                        depth + 1,
                    );
                    (k.clone(), new_v)
                })
                .collect();
            Value::Object(new_map)
        }
        Value::Array(arr) => {
            let new_arr: Vec<Value> = arr
                .iter()
                .map(|v| {
                    interpolate_value_inner(
                        v,
                        extractors,
                        request,
                        response,
                        diagnostics,
                        depth + 1,
                    )
                })
                .collect();
            Value::Array(new_arr)
        }
        // Null, Bool, Number — pass through unchanged
        _ => value.clone(),
    }
}

// ─── §5.6 evaluate_extractor ────────────────────────────────────────────────

/// Applies an extractor to a message, capturing a value.
///
/// - `json_path`: Evaluate JSONPath; return first match serialized to compact JSON.
/// - `regex`: Evaluate regex; return first capture group value.
///
/// The `direction` parameter indicates whether the message is a request or
/// response. If it does not match the extractor's `source` field, `None` is
/// returned immediately (the extractor does not apply to this direction).
///
/// Returns `None` for no match. `Some("")` is a valid result.
pub fn evaluate_extractor(
    extractor: &Extractor,
    message: &Value,
    direction: crate::enums::ExtractorSource,
) -> Option<String> {
    if extractor.source != direction {
        return None;
    }
    match extractor.extractor_type {
        crate::enums::ExtractorType::JsonPath => {
            evaluate_extractor_jsonpath(&extractor.selector, message)
        }
        crate::enums::ExtractorType::Regex => {
            evaluate_extractor_regex(&extractor.selector, message)
        }
    }
}

fn evaluate_extractor_jsonpath(selector: &str, message: &Value) -> Option<String> {
    let path = serde_json_path::JsonPath::parse(selector).ok()?;
    let node_list = path.query(message);
    let first = node_list.first()?;
    Some(extractor_value_to_string(first))
}

/// Like `value_to_string` but without key sorting — preserves insertion order
/// for extractors where the spec doesn't mandate canonical key ordering.
fn extractor_value_to_string(v: &Value) -> String {
    match v {
        Value::String(s) => s.clone(),
        Value::Null => "null".to_string(),
        Value::Bool(b) => b.to_string(),
        Value::Number(n) => n.to_string(),
        _ => serde_json::to_string(v).unwrap_or_else(|_| "<unserializable>".to_string()),
    }
}

fn evaluate_extractor_regex(selector: &str, message: &Value) -> Option<String> {
    let text = extractor_value_to_string(message);
    let re = compile_user_regex(selector).ok()?;
    let caps = re.captures(&text)?;

    // Must have at least one capture group; return first group
    if caps.len() < 2 {
        return None; // no capture groups
    }
    caps.get(1).map(|m| m.as_str().to_string())
}

// ─── §5.7 select_response ───────────────────────────────────────────────────

/// Selects the first matching response entry from an ordered list.
///
/// First-match-wins for entries with `when` predicates. Falls back to
/// the default entry (no `when`) if no predicate-bearing entry matches.
pub fn select_response<'a>(
    entries: &'a [ResponseEntry],
    request: &Value,
) -> Option<&'a ResponseEntry> {
    let mut default_entry: Option<&ResponseEntry> = None;

    for entry in entries {
        match &entry.when {
            Some(predicate) => {
                if evaluate_predicate(predicate, request) {
                    return Some(entry);
                }
            }
            None => {
                if default_entry.is_none() {
                    default_entry = Some(entry);
                }
            }
        }
    }

    default_entry
}

// ─── §5.8 evaluate_trigger ──────────────────────────────────────────────────

/// Evaluates whether a trigger condition is satisfied for phase advancement.
///
/// `state` is a mutable reference to per-trigger state that persists across
/// calls. The SDK increments `state.event_count` only when the incoming event
/// fully matches (event type + predicate).
pub fn evaluate_trigger(
    trigger: &Trigger,
    event: Option<&ProtocolEvent>,
    elapsed: Duration,
    state: &mut TriggerState,
) -> TriggerResult {
    // 1. Check timeout
    if let Some(after) = &trigger.after
        && let Ok(timeout) = parse_duration(after)
        && elapsed >= timeout
    {
        return TriggerResult::Advanced {
            reason: AdvanceReason::Timeout,
        };
    }

    // 2. Check event match
    if let (Some(trigger_event), Some(ev)) = (&trigger.event, event) {
        if trigger_event != &ev.event_type {
            return TriggerResult::NotAdvanced;
        }

        // 3. Check match predicate if present
        if let Some(predicate) = &trigger.match_predicate
            && !evaluate_predicate(predicate, &ev.content)
        {
            return TriggerResult::NotAdvanced;
        }

        // 4. Full match — increment count, then check threshold
        state.event_count += 1;
        // Defensive clamp for callers that bypass validate(): count must be >= 1.
        let required_count = trigger.count.unwrap_or(1).max(1) as u64;
        if state.event_count >= required_count {
            return TriggerResult::Advanced {
                reason: AdvanceReason::EventMatched,
            };
        }
    }

    TriggerResult::NotAdvanced
}

// ─── §5.10 compute_effective_state ──────────────────────────────────────────

/// Computes the effective state at a given phase by applying state inheritance.
///
/// Walk phases 0..=phase_index: if a phase defines `state`, that becomes
/// the current; if it omits `state`, the previous carries forward.
pub fn compute_effective_state(phases: &[Phase], phase_index: usize) -> Value {
    let mut effective = Value::Null;

    for (i, phase) in phases.iter().enumerate() {
        if i > phase_index {
            break;
        }
        if let Some(state) = &phase.state {
            effective = state.clone();
        }
    }

    effective
}