Skip to main content

omega_cognitive_kernel/l1/
sandbox.rs

1#[allow(unused_imports)]
2use crate::prelude::*;
3
4use crate::error::Result;
5use crate::types::CognitivePatch;
6use uuid::Uuid;
7
8#[derive(Debug)]
9/// Report of validation.
10pub struct ValidationReport {
11    /// Whether accepted is enabled or active.
12    pub accepted: bool,
13    /// Message for this value.
14    pub message: String,
15    /// Identifier for the patch.
16    pub patch_id: Uuid,
17}
18
19/// Data structure representing code sandbox.
20pub struct CodeSandbox {
21    /// Maximum risk permitted by the active policy.
22    pub max_risk: f64,
23    /// Collection of forbidden keywords.
24    pub forbidden_keywords: Vec<String>,
25}
26
27impl Default for CodeSandbox {
28    fn default() -> Self {
29        Self {
30            max_risk: 0.65,
31            forbidden_keywords: vec![
32                "std::process".into(),
33                "std::fs".into(),
34                "unsafe".into(),
35                "include!".into(),
36                "Command::".into(),
37            ],
38        }
39    }
40}
41
42impl CodeSandbox {
43    /// Validates this value and reports any violated constraints.
44    pub fn validate(&self, patch: &CognitivePatch) -> Result<ValidationReport> {
45        if patch.risk_level > self.max_risk {
46            return Ok(ValidationReport {
47                accepted: false,
48                message: format!(
49                    "risk {:.2} exceeds max_risk {:.2}",
50                    patch.risk_level, self.max_risk
51                ),
52                patch_id: patch.patch_id,
53            });
54        }
55
56        for kw in &self.forbidden_keywords {
57            if patch.code.contains(kw) {
58                return Ok(ValidationReport {
59                    accepted: false,
60                    message: format!("forbidden keyword detected: {}", kw),
61                    patch_id: patch.patch_id,
62                });
63            }
64        }
65
66        if patch.code.len() > 12_000 {
67            return Ok(ValidationReport {
68                accepted: false,
69                message: "code too long".into(),
70                patch_id: patch.patch_id,
71            });
72        }
73
74        if let Some(msg) = patch.effect.validate_bounds() {
75            return Ok(ValidationReport {
76                accepted: false,
77                message: format!("effect rejected: {msg}"),
78                patch_id: patch.patch_id,
79            });
80        }
81
82        Ok(ValidationReport {
83            accepted: true,
84            message: "accepted".into(),
85            patch_id: patch.patch_id,
86        })
87    }
88}
89
90#[cfg(test)]
91mod tests {
92    use super::*;
93
94    fn make_patch(code: &str, risk: f64) -> CognitivePatch {
95        CognitivePatch {
96            patch_id: crate::new_uuid(),
97            description: "test".into(),
98            code: code.into(),
99            target_module: "cognitive_rules".into(),
100            expected_effect: "test".into(),
101            risk_level: risk,
102            created_at: crate::now_utc(),
103            effect: crate::types::RuleEffect::default(),
104        }
105    }
106
107    #[test]
108    fn accepts_safe_low_risk_patch() {
109        let sandbox = CodeSandbox::default();
110        let patch = make_patch("fn adjust_bias(err: f64) -> f64 { err * 0.9 }", 0.2);
111        assert!(sandbox.validate(&patch).unwrap().accepted);
112    }
113
114    #[test]
115    fn rejects_high_risk_patch() {
116        let sandbox = CodeSandbox::default();
117        let patch = make_patch("fn dangerous() {}", 0.9);
118        assert!(!sandbox.validate(&patch).unwrap().accepted);
119    }
120
121    #[test]
122    fn rejects_forbidden_keyword() {
123        let sandbox = CodeSandbox::default();
124        let patch = make_patch("use std::process::Command;", 0.1);
125        assert!(!sandbox.validate(&patch).unwrap().accepted);
126    }
127
128    #[test]
129    fn rejects_bad_effect_damping() {
130        let sandbox = CodeSandbox::default();
131        let mut patch = make_patch("fn ok() {}", 0.1);
132        patch.effect.error_damping = 9.0;
133        let report = sandbox.validate(&patch).unwrap();
134        assert!(!report.accepted);
135        assert!(report.message.contains("effect rejected"));
136    }
137
138    #[test]
139    fn rejects_unknown_action_preference() {
140        let sandbox = CodeSandbox::default();
141        let mut patch = make_patch("fn ok() {}", 0.1);
142        patch
143            .effect
144            .action_preference
145            .insert("launch_missiles".into(), 1.0);
146        assert!(!sandbox.validate(&patch).unwrap().accepted);
147    }
148
149    #[test]
150    fn rejects_out_of_bounds_explore_bonus() {
151        let sandbox = CodeSandbox::default();
152        let mut patch = make_patch("fn ok() {}", 0.1);
153        patch.effect.explore_bonus = 5.0;
154        let report = sandbox.validate(&patch).unwrap();
155        assert!(!report.accepted);
156        assert!(report.message.contains("explore_bonus"));
157    }
158
159    #[test]
160    fn rejects_out_of_bounds_risk_tolerance() {
161        let sandbox = CodeSandbox::default();
162        let mut patch = make_patch("fn ok() {}", 0.1);
163        patch.effect.risk_tolerance = 0.01;
164        let report = sandbox.validate(&patch).unwrap();
165        assert!(!report.accepted);
166        assert!(report.message.contains("risk_tolerance"));
167    }
168
169    #[test]
170    fn sanitize_clamps_new_fields() {
171        let mut effect = crate::types::RuleEffect {
172            error_damping: 0.5,
173            action_preference: Default::default(),
174            min_uncertainty: 0.1,
175            explore_bonus: 3.0,
176            risk_tolerance: 0.05,
177        };
178        effect = effect.sanitize();
179        assert!(effect.explore_bonus <= 1.5);
180        assert!(effect.risk_tolerance >= 0.15);
181    }
182}