selfware 0.6.1

Your personal AI workshop — software you own, software that lasts
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
//! Guardrail Engine
//!
//! Core engine for evaluating guardrail conditions and enforcing policies.

use super::types::*;
use crate::errors::{SafetyError, SelfwareError};
use crate::observability::telemetry;
use regex::Regex;
use std::collections::HashMap;
use std::sync::OnceLock;
use tracing::{debug, info, warn};

/// Engine for evaluating guardrail conditions
pub struct GuardrailEngine {
    /// Compiled regex patterns for condition evaluation
    patterns: HashMap<String, Regex>,
    /// Enable detailed logging
    verbose: bool,
}

impl Default for GuardrailEngine {
    fn default() -> Self {
        Self::new()
    }
}

impl GuardrailEngine {
    /// Create a new guardrail engine
    pub fn new() -> Self {
        Self {
            patterns: HashMap::new(),
            verbose: false,
        }
    }

    /// Create a verbose engine with detailed logging
    pub fn new_verbose() -> Self {
        Self {
            patterns: HashMap::new(),
            verbose: true,
        }
    }

    /// Evaluate a single condition against a context
    pub fn evaluate_condition(
        &self,
        condition: &Condition,
        context: &GuardrailContext,
    ) -> EvaluationResult {
        match condition {
            Condition::Inline(expr) => self.evaluate_inline_expression(expr, context),
            Condition::Code { language, content } => {
                self.evaluate_code_condition(language, content, context)
            }
            Condition::Composite {
                operator,
                conditions,
            } => self.evaluate_composite_condition(*operator, conditions, context),
        }
    }

    /// Evaluate an inline expression (simple pattern matching)
    pub fn evaluate_inline_expression(
        &self,
        expr: &str,
        context: &GuardrailContext,
    ) -> EvaluationResult {
        let expr = expr.trim();

        // Handle negation
        if let Some(stripped) = expr.strip_prefix('!') {
            let inner = &stripped.trim();
            match self.evaluate_inline_expression(inner, context) {
                EvaluationResult::Pass => EvaluationResult::Fail {
                    reason: format!("Negated condition '{inner}' was true"),
                },
                EvaluationResult::Fail { .. } => EvaluationResult::Pass,
                error => error,
            }
        }
        // Handle contains check: "output.contains('pattern')"
        else if let Some(caps) = get_contains_pattern().captures(expr) {
            let source = caps.get(1).map(|m| m.as_str()).unwrap_or("");
            let pattern = caps.get(3).map(|m| m.as_str()).unwrap_or("");
            self.evaluate_contains(source, pattern, context)
        }
        // Handle regex match: "output.matches('regex')"
        else if let Some(caps) = get_matches_pattern().captures(expr) {
            let source = caps.get(1).map(|m| m.as_str()).unwrap_or("");
            let pattern = caps.get(3).map(|m| m.as_str()).unwrap_or("");
            self.evaluate_matches(source, pattern, context)
        }
        // Handle comparison: "value > 10"
        else if let Some(caps) = get_comparison_pattern().captures(expr) {
            let left = caps.get(1).map(|m| m.as_str()).unwrap_or("");
            let op = caps.get(2).map(|m| m.as_str()).unwrap_or("");
            let right = caps.get(3).map(|m| m.as_str()).unwrap_or("");
            self.evaluate_comparison(left, op, right, context)
        }
        // Handle equality check
        else if let Some(caps) = get_equality_pattern().captures(expr) {
            let left = caps.get(1).map(|m| m.as_str()).unwrap_or("");
            let op = caps.get(2).map(|m| m.as_str()).unwrap_or("");
            let right = caps.get(3).map(|m| m.as_str()).unwrap_or("");
            self.evaluate_equality(left, op, right, context)
        }
        // Handle simple boolean: "true" or "false"
        else if expr == "true" {
            EvaluationResult::Pass
        } else if expr == "false" {
            EvaluationResult::Fail {
                reason: "Condition is false".to_string(),
            }
        }
        // Handle variable existence check
        else if expr.starts_with("exists:") {
            let var_path = expr.strip_prefix("exists:").unwrap_or("").trim();
            self.evaluate_exists(var_path, context)
        }
        // Unknown expression format - try as truthy check
        else {
            match self.resolve_value(expr, context) {
                Some(val) => {
                    if Self::is_truthy(&val) {
                        EvaluationResult::Pass
                    } else {
                        EvaluationResult::Fail {
                            reason: format!("'{expr}' evaluated to falsy value: {val}"),
                        }
                    }
                }
                None => EvaluationResult::Error {
                    message: format!("Could not resolve expression: '{expr}'"),
                },
            }
        }
    }

    /// Evaluate a code block condition
    pub fn evaluate_code_condition(
        &self,
        language: &str,
        content: &str,
        context: &GuardrailContext,
    ) -> EvaluationResult {
        match language.to_lowercase().as_str() {
            "rust" | "rs" => self.evaluate_rust_code(content, context),
            "json" => self.evaluate_json_logic(content, context),
            "regex" | "regexp" => self.evaluate_regex_pattern(content, context),
            _ => EvaluationResult::Error {
                message: format!("Unsupported condition language: '{language}'"),
            },
        }
    }

    /// Evaluate composite conditions with AND/OR logic
    fn evaluate_composite_condition(
        &self,
        operator: LogicalOperator,
        conditions: &[Condition],
        context: &GuardrailContext,
    ) -> EvaluationResult {
        if conditions.is_empty() {
            return EvaluationResult::Pass; // Empty composite passes
        }

        let mut fail_reasons = Vec::new();

        match operator {
            LogicalOperator::And => {
                // All conditions must pass
                for cond in conditions {
                    match self.evaluate_condition(cond, context) {
                        EvaluationResult::Pass => continue,
                        fail @ EvaluationResult::Fail { .. } => return fail,
                        error @ EvaluationResult::Error { .. } => return error,
                    }
                }
                EvaluationResult::Pass
            }
            LogicalOperator::Or => {
                // At least one condition must pass
                for cond in conditions {
                    match self.evaluate_condition(cond, context) {
                        EvaluationResult::Pass => return EvaluationResult::Pass,
                        EvaluationResult::Fail { reason } => fail_reasons.push(reason),
                        error @ EvaluationResult::Error { .. } => return error,
                    }
                }
                EvaluationResult::Fail {
                    reason: format!("All OR conditions failed: {}", fail_reasons.join("; ")),
                }
            }
        }
    }

    /// Evaluate contains check
    fn evaluate_contains(
        &self,
        source: &str,
        pattern: &str,
        context: &GuardrailContext,
    ) -> EvaluationResult {
        let source_value = match self.resolve_value(source, context) {
            Some(v) => v,
            None => {
                return EvaluationResult::Error {
                    message: format!("Could not resolve source: '{source}'"),
                }
            }
        };

        let source_string = source_value.to_string();
        let source_str = source_value.as_str().unwrap_or(&source_string);
        let pattern_owned = pattern.to_string();
        let pattern_str = pattern.trim_matches('\'').trim_matches('"');

        if source_str.contains(pattern_str) {
            EvaluationResult::Pass
        } else {
            EvaluationResult::Fail {
                reason: format!("'{source}' does not contain '{pattern}'"),
            }
        }
    }

    /// Evaluate regex matches
    fn evaluate_matches(
        &self,
        source: &str,
        pattern: &str,
        context: &GuardrailContext,
    ) -> EvaluationResult {
        let source_value = match self.resolve_value(source, context) {
            Some(v) => v,
            None => {
                return EvaluationResult::Error {
                    message: format!("Could not resolve source: '{source}'"),
                }
            }
        };

        let source_string = source_value.to_string();
        let source_str = source_value.as_str().unwrap_or(&source_string);
        let pattern = pattern.trim_matches('\'').trim_matches('"');

        match Regex::new(pattern) {
            Ok(regex) => {
                if regex.is_match(source_str) {
                    EvaluationResult::Pass
                } else {
                    EvaluationResult::Fail {
                        reason: format!("'{source}' does not match pattern '{pattern}'"),
                    }
                }
            }
            Err(e) => EvaluationResult::Error {
                message: format!("Invalid regex pattern '{pattern}': {e}"),
            },
        }
    }

    /// Evaluate numeric comparison
    fn evaluate_comparison(
        &self,
        left: &str,
        op: &str,
        right: &str,
        context: &GuardrailContext,
    ) -> EvaluationResult {
        let left_val = match self.resolve_value(left, context) {
            Some(v) => v,
            None => {
                return EvaluationResult::Error {
                    message: format!("Could not resolve left operand: '{left}'"),
                }
            }
        };

        let left_num = match left_val.as_f64() {
            Some(n) => n,
            None => {
                return EvaluationResult::Error {
                    message: format!("Left operand '{left}' is not a number"),
                }
            }
        };

        let right_num: f64 = match right.trim().parse() {
            Ok(n) => n,
            Err(_) => {
                // Try to resolve as a variable
                match self.resolve_value(right, context) {
                    Some(v) => match v.as_f64() {
                        Some(n) => n,
                        None => {
                            return EvaluationResult::Error {
                                message: format!("Right operand '{right}' is not a number"),
                            }
                        }
                    },
                    None => {
                        return EvaluationResult::Error {
                            message: format!("Could not resolve right operand: '{right}'"),
                        }
                    }
                }
            }
        };

        let result = match op {
            ">" => left_num > right_num,
            ">=" => left_num >= right_num,
            "<" => left_num < right_num,
            "<=" => left_num <= right_num,
            _ => {
                return EvaluationResult::Error {
                    message: format!("Unknown comparison operator: '{op}'"),
                }
            }
        };

        if result {
            EvaluationResult::Pass
        } else {
            EvaluationResult::Fail {
                reason: format!("{left_num} {op} {right_num} is false"),
            }
        }
    }

    /// Evaluate equality check
    fn evaluate_equality(
        &self,
        left: &str,
        op: &str,
        right: &str,
        context: &GuardrailContext,
    ) -> EvaluationResult {
        let left_val = match self.resolve_value(left, context) {
            Some(v) => v,
            None => {
                return EvaluationResult::Error {
                    message: format!("Could not resolve left operand: '{left}'"),
                }
            }
        };

        let right_val = if right.starts_with('\'') || right.starts_with('"') {
            serde_json::Value::String(right.trim_matches('\'').trim_matches('"').to_string())
        } else {
            // Try to resolve as variable first
            match self.resolve_value(right, context) {
                Some(v) => v,
                None => {
                    // Try parsing as number
                    if let Ok(n) = right.trim().parse::<i64>() {
                        serde_json::Value::Number(n.into())
                    } else if let Ok(n) = right.trim().parse::<f64>() {
                        serde_json::Number::from_f64(n)
                            .map(serde_json::Value::Number)
                            .unwrap_or_else(|| serde_json::Value::String(right.to_string()))
                    } else {
                        serde_json::Value::String(right.to_string())
                    }
                }
            }
        };

        let equal = left_val == right_val;
        let result = match op {
            "==" => equal,
            "!=" => !equal,
            _ => {
                return EvaluationResult::Error {
                    message: format!("Unknown equality operator: '{op}'"),
                }
            }
        };

        if result {
            EvaluationResult::Pass
        } else {
            EvaluationResult::Fail {
                reason: format!("'{left}' ({left_val}) {op} '{right}' ({right_val}) is false"),
            }
        }
    }

    /// Evaluate variable existence
    fn evaluate_exists(&self, var_path: &str, context: &GuardrailContext) -> EvaluationResult {
        match self.resolve_value(var_path, context) {
            Some(_) => EvaluationResult::Pass,
            None => EvaluationResult::Fail {
                reason: format!("Variable '{var_path}' does not exist"),
            },
        }
    }

    /// Evaluate Rust-like pseudocode
    fn evaluate_rust_code(&self, code: &str, context: &GuardrailContext) -> EvaluationResult {
        // Convert Rust-like code to inline expressions
        // This is a simplified evaluator for common patterns
        let code = code.trim();

        // Handle let bindings and expressions
        // For now, we evaluate the last expression line
        let lines: Vec<&str> = code.lines().collect();
        if lines.is_empty() {
            return EvaluationResult::Error {
                message: "Empty Rust code block".to_string(),
            };
        }

        // Evaluate every non-let, non-comment line as a boolean condition.
        // All such lines must pass for the guard to pass; this correctly
        // handles multi-line Rust conditions rather than only the last line.
        for line in lines.iter() {
            let line = line.trim();
            if line.is_empty() || line.starts_with("//") {
                continue;
            }
            if line.starts_with("let ") {
                // let bindings are not boolean conditions — skip them.
                continue;
            }
            let result = self.evaluate_inline_expression(line, context);
            if !result.is_pass() {
                return result;
            }
        }

        // No inline expression failed (or none were present) → pass.
        EvaluationResult::Pass
    }

    /// Evaluate JSON logic
    ///
    /// Supports a subset of JSON Logic operators:
    /// - Comparison: "==", "!=", ">", "<", ">=", "<="
    /// - Logic: "and", "or", "!" (not)
    /// - Existence: "exists" (check if value exists in context)
    /// - Regex: "match" (regex pattern matching)
    /// - Context access: "var" (access context variables)
    pub fn evaluate_json_logic(&self, logic: &str, context: &GuardrailContext) -> EvaluationResult {
        // Try to parse as JSON
        let json_value: serde_json::Value = match serde_json::from_str(logic.trim()) {
            Ok(v) => v,
            Err(e) => {
                // Not valid JSON - try to evaluate as inline expression
                return self.evaluate_inline_expression(logic, context);
            }
        };

        self.evaluate_json_value(&json_value, context)
    }

    /// Recursively evaluate a JSON value as JSON Logic
    fn evaluate_json_value(
        &self,
        value: &serde_json::Value,
        context: &GuardrailContext,
    ) -> EvaluationResult {
        match value {
            serde_json::Value::Object(map) => {
                if map.is_empty() {
                    return EvaluationResult::Pass;
                }
                // JSON Logic operators are single-key objects
                if let Some((op, args)) = map.iter().next() {
                    return self.evaluate_json_operator(op, args, context);
                }
                EvaluationResult::Pass
            }
            serde_json::Value::Bool(b) => {
                if *b {
                    EvaluationResult::Pass
                } else {
                    EvaluationResult::Fail {
                        reason: "Boolean condition is false".to_string(),
                    }
                }
            }
            serde_json::Value::String(s) => {
                // Treat as inline expression
                self.evaluate_inline_expression(s, context)
            }
            _ => EvaluationResult::Error {
                message: format!("Unsupported JSON Logic value: {:?}", value),
            },
        }
    }

    /// Evaluate a JSON Logic operator
    fn evaluate_json_operator(
        &self,
        op: &str,
        args: &serde_json::Value,
        context: &GuardrailContext,
    ) -> EvaluationResult {
        match op {
            // Comparison operators
            "==" | "===" => self.evaluate_json_comparison(args, context, |a, b| a == b, "=="),
            "!=" | "!==" => self.evaluate_json_comparison(args, context, |a, b| a != b, "!="),
            ">" => self.evaluate_json_numeric_comparison(args, context, |a, b| a > b, ">"),
            ">=" => self.evaluate_json_numeric_comparison(args, context, |a, b| a >= b, ">="),
            "<" => self.evaluate_json_numeric_comparison(args, context, |a, b| a < b, "<"),
            "<=" => self.evaluate_json_numeric_comparison(args, context, |a, b| a <= b, "<="),

            // Logic operators
            "and" | "&&" => self.evaluate_json_and(args, context),
            "or" | "||" => self.evaluate_json_or(args, context),
            "!" | "not" => self.evaluate_json_not(args, context),

            // String operators
            "contains" => self.evaluate_json_contains(args, context),
            "match" => self.evaluate_json_match(args, context),

            // Existence check
            "exists" => self.evaluate_json_exists(args, context),
            "var" => self.evaluate_json_var(args, context),

            // Unknown operator
            _ => EvaluationResult::Error {
                message: format!("Unknown JSON Logic operator: '{}'", op),
            },
        }
    }

    /// Evaluate JSON Logic comparison (== and !=)
    fn evaluate_json_comparison(
        &self,
        args: &serde_json::Value,
        context: &GuardrailContext,
        compare: fn(&serde_json::Value, &serde_json::Value) -> bool,
        op_name: &str,
    ) -> EvaluationResult {
        let arr = match args.as_array() {
            Some(a) if a.len() >= 2 => a,
            _ => {
                return EvaluationResult::Error {
                    message: format!("'{}' requires 2 arguments", op_name),
                }
            }
        };

        let left = self.resolve_json_value(&arr[0], context);
        let right = self.resolve_json_value(&arr[1], context);

        if compare(&left, &right) {
            EvaluationResult::Pass
        } else {
            EvaluationResult::Fail {
                reason: format!("{} {} {} is false", left, op_name, right),
            }
        }
    }

    /// Evaluate JSON Logic numeric comparison (>, >=, <, <=)
    fn evaluate_json_numeric_comparison(
        &self,
        args: &serde_json::Value,
        context: &GuardrailContext,
        compare: fn(f64, f64) -> bool,
        op_name: &str,
    ) -> EvaluationResult {
        let arr = match args.as_array() {
            Some(a) if a.len() >= 2 => a,
            _ => {
                return EvaluationResult::Error {
                    message: format!("'{}' requires 2 numeric arguments", op_name),
                }
            }
        };

        let left_val = self.resolve_json_value(&arr[0], context);
        let right_val = self.resolve_json_value(&arr[1], context);

        let left_num = match left_val.as_f64() {
            Some(n) => n,
            None => {
                return EvaluationResult::Error {
                    message: format!("Left operand '{}' is not a number", left_val),
                }
            }
        };

        let right_num = match right_val.as_f64() {
            Some(n) => n,
            None => {
                return EvaluationResult::Error {
                    message: format!("Right operand '{}' is not a number", right_val),
                }
            }
        };

        if compare(left_num, right_num) {
            EvaluationResult::Pass
        } else {
            EvaluationResult::Fail {
                reason: format!("{} {} {} is false", left_num, op_name, right_num),
            }
        }
    }

    /// Evaluate JSON Logic AND
    fn evaluate_json_and(
        &self,
        args: &serde_json::Value,
        context: &GuardrailContext,
    ) -> EvaluationResult {
        let arr = match args.as_array() {
            Some(a) => a,
            None => {
                // Single argument
                return self.evaluate_json_value(args, context);
            }
        };

        for (i, arg) in arr.iter().enumerate() {
            match self.evaluate_json_value(arg, context) {
                EvaluationResult::Pass => continue,
                fail @ EvaluationResult::Fail { .. } => {
                    return EvaluationResult::Fail {
                        reason: format!("AND condition {} failed: {:?}", i, fail),
                    }
                }
                error => return error,
            }
        }
        EvaluationResult::Pass
    }

    /// Evaluate JSON Logic OR
    fn evaluate_json_or(
        &self,
        args: &serde_json::Value,
        context: &GuardrailContext,
    ) -> EvaluationResult {
        let arr = match args.as_array() {
            Some(a) => a,
            None => {
                return self.evaluate_json_value(args, context);
            }
        };

        let mut fail_reasons = Vec::new();
        for arg in arr.iter() {
            match self.evaluate_json_value(arg, context) {
                EvaluationResult::Pass => return EvaluationResult::Pass,
                EvaluationResult::Fail { reason } => fail_reasons.push(reason),
                error => return error,
            }
        }
        EvaluationResult::Fail {
            reason: format!("All OR conditions failed: {}", fail_reasons.join("; ")),
        }
    }

    /// Evaluate JSON Logic NOT
    fn evaluate_json_not(
        &self,
        args: &serde_json::Value,
        context: &GuardrailContext,
    ) -> EvaluationResult {
        let result = self.evaluate_json_value(args, context);
        match result {
            EvaluationResult::Pass => EvaluationResult::Fail {
                reason: "NOT condition: inner was true".to_string(),
            },
            EvaluationResult::Fail { .. } => EvaluationResult::Pass,
            error => error,
        }
    }

    /// Evaluate JSON Logic contains
    fn evaluate_json_contains(
        &self,
        args: &serde_json::Value,
        context: &GuardrailContext,
    ) -> EvaluationResult {
        let arr = match args.as_array() {
            Some(a) if a.len() >= 2 => a,
            _ => {
                return EvaluationResult::Error {
                    message: "'contains' requires [source, pattern] arguments".to_string(),
                }
            }
        };

        let source = self.resolve_json_value(&arr[0], context);
        let pattern = self.resolve_json_value(&arr[1], context);

        let source_owned = source.to_string();
        let pattern_owned = pattern.to_string();
        let source_str = source.as_str().unwrap_or(&source_owned);
        let pattern_str = pattern.as_str().unwrap_or(&pattern_owned);

        if source_str.contains(pattern_str) {
            EvaluationResult::Pass
        } else {
            EvaluationResult::Fail {
                reason: format!("'{}' does not contain '{}'", source_str, pattern_str),
            }
        }
    }

    /// Evaluate JSON Logic regex match
    fn evaluate_json_match(
        &self,
        args: &serde_json::Value,
        context: &GuardrailContext,
    ) -> EvaluationResult {
        let arr = match args.as_array() {
            Some(a) if a.len() >= 2 => a,
            _ => {
                return EvaluationResult::Error {
                    message: "'match' requires [source, pattern] arguments".to_string(),
                }
            }
        };

        let source = self.resolve_json_value(&arr[0], context);
        let pattern = self.resolve_json_value(&arr[1], context);

        let source_owned = source.to_string();
        let pattern_owned = pattern.to_string();
        let source_str = source.as_str().unwrap_or(&source_owned);
        let pattern_str = pattern.as_str().unwrap_or(&pattern_owned);

        match Regex::new(pattern_str) {
            Ok(regex) => {
                if regex.is_match(source_str) {
                    EvaluationResult::Pass
                } else {
                    EvaluationResult::Fail {
                        reason: format!(
                            "'{}' does not match pattern '{}'",
                            source_str, pattern_str
                        ),
                    }
                }
            }
            Err(e) => EvaluationResult::Error {
                message: format!("Invalid regex pattern '{}': {}", pattern_str, e),
            },
        }
    }

    /// Evaluate JSON Logic exists
    fn evaluate_json_exists(
        &self,
        args: &serde_json::Value,
        context: &GuardrailContext,
    ) -> EvaluationResult {
        let var_path = match args {
            serde_json::Value::String(s) => s.as_str(),
            _ => {
                return EvaluationResult::Error {
                    message: "'exists' requires a variable path string".to_string(),
                }
            }
        };

        match self.resolve_value(var_path, context) {
            Some(_) => EvaluationResult::Pass,
            None => EvaluationResult::Fail {
                reason: format!("Variable '{}' does not exist", var_path),
            },
        }
    }

    /// Evaluate JSON Logic var (resolve value from context)
    fn evaluate_json_var(
        &self,
        args: &serde_json::Value,
        context: &GuardrailContext,
    ) -> EvaluationResult {
        let var_path = match args {
            serde_json::Value::String(s) => s.as_str(),
            _ => {
                return EvaluationResult::Error {
                    message: "'var' requires a variable path string".to_string(),
                }
            }
        };

        // Try standard resolution, then fallback to state lookup
        let value = self
            .resolve_value(var_path, context)
            .or_else(|| context.state.get(var_path).cloned());

        match value {
            Some(val) => {
                if Self::is_truthy(&val) {
                    EvaluationResult::Pass
                } else {
                    EvaluationResult::Fail {
                        reason: format!("Variable '{}' is falsy", var_path),
                    }
                }
            }
            None => EvaluationResult::Fail {
                reason: format!("Variable '{}' does not exist", var_path),
            },
        }
    }

    /// Resolve a JSON value (either literal or context reference)
    fn resolve_json_value(
        &self,
        value: &serde_json::Value,
        context: &GuardrailContext,
    ) -> serde_json::Value {
        match value {
            serde_json::Value::Object(map) if map.contains_key("var") => {
                // It's a var reference
                let var_path = match map.get("var") {
                    Some(serde_json::Value::String(s)) => s.as_str(),
                    Some(v) => return v.clone(),
                    None => return serde_json::Value::Null,
                };
                // First try standard resolution, then fallback to state lookup
                self.resolve_value(var_path, context)
                    .or_else(|| context.state.get(var_path).cloned())
                    .unwrap_or(serde_json::Value::Null)
            }
            serde_json::Value::Object(map) if map.len() == 1 => {
                // Might be another operator - evaluate it
                match self.evaluate_json_value(value, context) {
                    EvaluationResult::Pass => serde_json::Value::Bool(true),
                    EvaluationResult::Fail { .. } => serde_json::Value::Bool(false),
                    EvaluationResult::Error { message } => {
                        serde_json::Value::String(format!("error: {}", message))
                    }
                }
            }
            serde_json::Value::String(s) => {
                // Try to resolve as variable (standard and state fallback), otherwise return as string literal
                self.resolve_value(s, context)
                    .or_else(|| context.state.get(s).cloned())
                    .unwrap_or_else(|| serde_json::Value::String(s.clone()))
            }
            _ => value.clone(),
        }
    }

    /// Evaluate regex pattern directly
    fn evaluate_regex_pattern(
        &self,
        pattern: &str,
        context: &GuardrailContext,
    ) -> EvaluationResult {
        // Use agent_output as default source for regex patterns
        let source = context
            .agent_output
            .as_ref()
            .or(context.tool_output.as_ref())
            .map(|s| s.as_str())
            .unwrap_or("");

        match Regex::new(pattern.trim()) {
            Ok(regex) => {
                if regex.is_match(source) {
                    EvaluationResult::Pass
                } else {
                    EvaluationResult::Fail {
                        reason: format!("Pattern '{pattern}' did not match"),
                    }
                }
            }
            Err(e) => EvaluationResult::Error {
                message: format!("Invalid regex pattern: {e}"),
            },
        }
    }

    /// Resolve a value from the context using dot notation (e.g., "state.count")
    fn resolve_value(&self, path: &str, context: &GuardrailContext) -> Option<serde_json::Value> {
        let parts: Vec<&str> = path.split('.').collect();
        if parts.is_empty() {
            return None;
        }

        let root = match parts[0] {
            "state" => parts.get(1).and_then(|k| context.state.get(*k)).cloned(),
            "agent_outputs" => parts
                .get(1)
                .and_then(|k| context.agent_outputs.get(*k))
                .map(|s| serde_json::Value::String(s.clone())),
            "workflow_inputs" => parts
                .get(1)
                .and_then(|k| context.workflow_inputs.get(*k))
                .cloned(),
            "args" => {
                // Special 'args' accessor for common patterns
                if parts.len() >= 2 {
                    match parts[1] {
                        "state" => parts.get(2).and_then(|k| context.state.get(*k)).cloned(),
                        "agent_outputs" => parts
                            .get(2)
                            .and_then(|k| context.agent_outputs.get(*k))
                            .map(|s| serde_json::Value::String(s.clone())),
                        "agent_output" => {
                            context.agent_output.clone().map(serde_json::Value::String)
                        }
                        "tool_input" => context.tool_input.clone().map(serde_json::Value::String),
                        "tool_output" => context.tool_output.clone().map(serde_json::Value::String),
                        _ => None,
                    }
                } else {
                    None
                }
            }
            "agent_output" => context.agent_output.clone().map(serde_json::Value::String),
            "tool_input" => context.tool_input.clone().map(serde_json::Value::String),
            "tool_output" => context.tool_output.clone().map(serde_json::Value::String),
            _ => None,
        };

        // Handle nested access for remaining parts
        if parts.len() > 2 && parts[0] != "args" {
            let mut current = root?;
            for part in &parts[2..] {
                current = current.get(part)?.clone();
            }
            Some(current)
        } else {
            root
        }
    }

    /// Check if a JSON value is truthy
    fn is_truthy(value: &serde_json::Value) -> bool {
        match value {
            serde_json::Value::Bool(b) => *b,
            serde_json::Value::Number(n) => n.as_f64().map(|f| f != 0.0).unwrap_or(false),
            serde_json::Value::String(s) => !s.is_empty(),
            serde_json::Value::Array(a) => !a.is_empty(),
            serde_json::Value::Object(o) => !o.is_empty(),
            serde_json::Value::Null => false,
        }
    }
}

// Static regex patterns (compiled once)
static CONTAINS_PATTERN: OnceLock<Regex> = OnceLock::new();
static MATCHES_PATTERN: OnceLock<Regex> = OnceLock::new();
static COMPARISON_PATTERN: OnceLock<Regex> = OnceLock::new();
static EQUALITY_PATTERN: OnceLock<Regex> = OnceLock::new();

fn get_contains_pattern() -> &'static Regex {
    CONTAINS_PATTERN.get_or_init(|| {
        Regex::new(r#"([\w.]+)\.contains\((["'])(.+?)["']\)"#).expect("Invalid regex")
    })
}

fn get_matches_pattern() -> &'static Regex {
    MATCHES_PATTERN.get_or_init(|| {
        Regex::new(r#"([\w.]+)\.matches\((["'])(.+?)["']\)"#).expect("Invalid regex")
    })
}

fn get_comparison_pattern() -> &'static Regex {
    COMPARISON_PATTERN
        .get_or_init(|| Regex::new(r"(\w+(?:\.\w+)*)\s*([><]=?)\s*(.+)$").expect("Invalid regex"))
}

fn get_equality_pattern() -> &'static Regex {
    EQUALITY_PATTERN
        .get_or_init(|| Regex::new(r"(\w+(?:\.\w+)*)\s*([!=]=)\s*(.+)$").expect("Invalid regex"))
}

#[cfg(test)]
#[path = "../../../tests/unit/swl/guardrails/engine/engine_test.rs"]
mod tests;