selfware 0.6.3

Your personal AI workshop — software you own, software that lasts
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
//! Guardrail Integration Tests
//!
//! Integration tests for the guardrail enforcement system.

use super::{enforcer::GuardrailEnforcer, engine::GuardrailEngine, types::*};
use crate::swl::parser::ast::{CodeBlock, CodeLanguage, GuardCondition, Guardrail};

/// Test helper to create a simple inline guardrail
fn create_inline_guardrail(
    name: &str,
    guardrail_type: GuardrailType,
    condition: &str,
    action: ViolationAction,
) -> GuardrailDef {
    GuardrailDef {
        name: name.to_string(),
        guardrail_type,
        condition: Condition::Inline(condition.to_string()),
        on_violation: action,
        description: None,
        severity: None,
        tags: Vec::new(),
    }
}

/// Test helper to create a code block guardrail
fn create_code_guardrail(
    name: &str,
    guardrail_type: GuardrailType,
    code: &str,
    action: ViolationAction,
) -> GuardrailDef {
    GuardrailDef {
        name: name.to_string(),
        guardrail_type,
        condition: Condition::Code {
            language: "rust".to_string(),
            content: code.to_string(),
        },
        on_violation: action,
        description: None,
        severity: None,
        tags: Vec::new(),
    }
}

#[tokio::test]
async fn test_pre_agent_guardrail_blocks_execution() {
    let mut enforcer = GuardrailEnforcer::new();

    // Register a guardrail that always blocks
    enforcer.register_guardrail(create_inline_guardrail(
        "always_block",
        GuardrailType::PreAgent,
        "false",
        ViolationAction::Block,
    ));

    let ctx = GuardrailContext::new().with_current_agent("test_agent");

    let summary = enforcer.check(GuardrailType::PreAgent, &ctx).await.unwrap();

    assert!(summary.should_block());
    assert_eq!(summary.blocked, 1);
    assert_eq!(summary.failed, 1);
}

#[tokio::test]
async fn test_post_agent_guardrail_detects_critical_issues() {
    let mut enforcer = GuardrailEnforcer::new();

    // Register a guardrail that blocks on critical issues
    enforcer.register_guardrail(create_inline_guardrail(
        "block_critical",
        GuardrailType::PostAgent,
        "!agent_output.contains('[CRITICAL]')",
        ViolationAction::Block,
    ));

    // Test with critical output - should block
    let ctx = GuardrailContext::new()
        .with_agent_output("agent1", "Found [CRITICAL] security vulnerability");

    let summary = enforcer
        .check(GuardrailType::PostAgent, &ctx)
        .await
        .unwrap();

    assert!(summary.should_block());
    assert_eq!(summary.blocked, 1);

    // Test with safe output - should pass
    let ctx = GuardrailContext::new().with_agent_output("agent1", "All checks passed successfully");

    let summary = enforcer
        .check(GuardrailType::PostAgent, &ctx)
        .await
        .unwrap();

    assert!(!summary.should_block());
    assert_eq!(summary.passed, 1);
}

#[tokio::test]
async fn test_pre_tool_guardrail_blocks_dangerous_commands() {
    let mut enforcer = GuardrailEnforcer::new();

    // Register a guardrail that blocks rm -rf
    enforcer.register_guardrail(create_inline_guardrail(
        "no_rm_rf",
        GuardrailType::PreTool,
        "!tool_input.contains('rm -rf')",
        ViolationAction::Block,
    ));

    // Test with dangerous command - should block
    let ctx = GuardrailContext::new()
        .with_current_tool("shell")
        .with_tool_input("rm -rf /");

    let summary = enforcer.check(GuardrailType::PreTool, &ctx).await.unwrap();

    assert!(summary.should_block());

    // Test with safe command - should pass
    let ctx = GuardrailContext::new()
        .with_current_tool("shell")
        .with_tool_input("ls -la");

    let summary = enforcer.check(GuardrailType::PreTool, &ctx).await.unwrap();

    assert!(!summary.should_block());
}

#[tokio::test]
async fn test_warn_action_does_not_block() {
    let mut enforcer = GuardrailEnforcer::new();

    // Register a guardrail with warn action
    enforcer.register_guardrail(create_inline_guardrail(
        "warn_only",
        GuardrailType::PostAgent,
        "false",
        ViolationAction::Warn,
    ));

    let ctx = GuardrailContext::new().with_agent_output("agent1", "some output");

    let summary = enforcer
        .check(GuardrailType::PostAgent, &ctx)
        .await
        .unwrap();

    // Should fail but not block
    assert!(!summary.should_block());
    assert_eq!(summary.warnings, 1);
    assert_eq!(summary.failed, 1);
}

#[tokio::test]
async fn test_composite_and_conditions() {
    let engine = GuardrailEngine::new();

    let condition = Condition::Composite {
        operator: LogicalOperator::And,
        conditions: vec![
            Condition::Inline("true".to_string()),
            Condition::Inline("true".to_string()),
            Condition::Inline("true".to_string()),
        ],
    };

    let ctx = GuardrailContext::new();
    let result = engine.evaluate_condition(&condition, &ctx);

    assert!(result.is_pass());
}

#[tokio::test]
async fn test_composite_and_conditions_fail() {
    let engine = GuardrailEngine::new();

    let condition = Condition::Composite {
        operator: LogicalOperator::And,
        conditions: vec![
            Condition::Inline("true".to_string()),
            Condition::Inline("false".to_string()),
            Condition::Inline("true".to_string()),
        ],
    };

    let ctx = GuardrailContext::new();
    let result = engine.evaluate_condition(&condition, &ctx);

    assert!(result.is_fail());
}

#[tokio::test]
async fn test_composite_or_conditions() {
    let engine = GuardrailEngine::new();

    let condition = Condition::Composite {
        operator: LogicalOperator::Or,
        conditions: vec![
            Condition::Inline("false".to_string()),
            Condition::Inline("true".to_string()),
            Condition::Inline("false".to_string()),
        ],
    };

    let ctx = GuardrailContext::new();
    let result = engine.evaluate_condition(&condition, &ctx);

    assert!(result.is_pass());
}

#[tokio::test]
async fn test_composite_or_conditions_all_fail() {
    let engine = GuardrailEngine::new();

    let condition = Condition::Composite {
        operator: LogicalOperator::Or,
        conditions: vec![
            Condition::Inline("false".to_string()),
            Condition::Inline("false".to_string()),
        ],
    };

    let ctx = GuardrailContext::new();
    let result = engine.evaluate_condition(&condition, &ctx);

    assert!(result.is_fail());
}

#[tokio::test]
async fn test_state_based_conditions() {
    let engine = GuardrailEngine::new();

    let condition = Condition::Inline("state.count > 5".to_string());

    let ctx = GuardrailContext::new().with_state("count", 10);

    let result = engine.evaluate_condition(&condition, &ctx);
    assert!(result.is_pass());

    let ctx = GuardrailContext::new().with_state("count", 3);

    let result = engine.evaluate_condition(&condition, &ctx);
    assert!(result.is_fail());
}

#[tokio::test]
async fn test_no_secrets_in_output_guardrail() {
    let engine = GuardrailEngine::new();

    let condition = Condition::Composite {
        operator: LogicalOperator::And,
        conditions: vec![
            Condition::Inline("!agent_output.contains('password:')".to_string()),
            Condition::Inline("!agent_output.contains('api_key:')".to_string()),
            Condition::Inline("!agent_output.contains('secret:')".to_string()),
        ],
    };

    // Test with safe output — no secrets present, all checks pass
    let ctx = GuardrailContext::new().with_agent_output("agent1", "The configuration is valid.");

    let result = engine.evaluate_condition(&condition, &ctx);
    assert!(result.is_pass());

    // Test with secret in output — api_key: present, check fails
    let ctx = GuardrailContext::new()
        .with_agent_output("agent1", "The api_key: sk-abc123 is configured.");

    let result = engine.evaluate_condition(&condition, &ctx);
    assert!(result.is_fail());
}

#[tokio::test]
async fn test_regex_pattern_matching() {
    let engine = GuardrailEngine::new();

    // Test with regex language code block
    let condition = Condition::Code {
        language: "regex".to_string(),
        content: r"\[CRITICAL\]|\[HIGH\]".to_string(),
    };

    let ctx = GuardrailContext::new().with_agent_output("agent1", "Found [HIGH] priority issue");

    let result = engine.evaluate_condition(&condition, &ctx);
    assert!(result.is_pass()); // Regex matches, so condition passes

    let ctx = GuardrailContext::new().with_agent_output("agent1", "All checks passed");

    let result = engine.evaluate_condition(&condition, &ctx);
    assert!(result.is_fail()); // Regex doesn't match, so condition fails
}

#[tokio::test]
async fn test_enforcer_from_ast_guardrails() {
    let mut enforcer = GuardrailEnforcer::new();

    let ast_guardrails = vec![Guardrail {
        name: Some("test_guardrail".to_string()),
        guardrail_type: Some("post_agent".to_string()),
        condition: GuardCondition::Inline("!agent_output.contains('ERROR')".to_string()),
        on_violation: "block".to_string(),
    }];

    enforcer.register_guardrails(&ast_guardrails);

    let ctx = GuardrailContext::new().with_agent_output("agent1", "Something ERROR happened");

    let summary = enforcer
        .check(GuardrailType::PostAgent, &ctx)
        .await
        .unwrap();

    assert!(summary.should_block());
}

#[tokio::test]
async fn test_guardrail_telemetry_collection() {
    let mut enforcer = GuardrailEnforcer::new();

    enforcer.register_guardrail(create_inline_guardrail(
        "telemetry_test",
        GuardrailType::PreAgent,
        "true",
        ViolationAction::Log,
    ));

    let ctx = GuardrailContext::new().with_current_agent("test_agent");

    enforcer.check(GuardrailType::PreAgent, &ctx).await.unwrap();

    let telemetry = enforcer.get_telemetry_events().await;
    assert_eq!(telemetry.len(), 1);
    assert_eq!(telemetry[0].guardrail_name, "telemetry_test");
    assert_eq!(telemetry[0].result, "pass");
}

#[tokio::test]
async fn test_multiple_guardrail_types() {
    let mut enforcer = GuardrailEnforcer::new();

    // Register guardrails for different types
    enforcer.register_guardrail(create_inline_guardrail(
        "pre_workflow_check",
        GuardrailType::PreWorkflow,
        "true",
        ViolationAction::Log,
    ));

    enforcer.register_guardrail(create_inline_guardrail(
        "pre_agent_check",
        GuardrailType::PreAgent,
        "true",
        ViolationAction::Log,
    ));

    enforcer.register_guardrail(create_inline_guardrail(
        "post_agent_check",
        GuardrailType::PostAgent,
        "true",
        ViolationAction::Log,
    ));

    let ctx = GuardrailContext::new();

    let pre_workflow_summary = enforcer
        .check(GuardrailType::PreWorkflow, &ctx)
        .await
        .unwrap();
    assert_eq!(pre_workflow_summary.total_checked, 1);

    let pre_agent_summary = enforcer.check(GuardrailType::PreAgent, &ctx).await.unwrap();
    assert_eq!(pre_agent_summary.total_checked, 1);

    let post_agent_summary = enforcer
        .check(GuardrailType::PostAgent, &ctx)
        .await
        .unwrap();
    assert_eq!(post_agent_summary.total_checked, 1);
}

#[test]
fn test_guardrail_context_json_conversion() {
    let ctx = GuardrailContext::new()
        .with_state("count", 42)
        .with_state("name", "test")
        .with_current_agent("my_agent")
        .with_agent_output("my_agent", "output data")
        .with_workflow_input("prompt", "test prompt");

    let json = ctx.to_json();

    assert!(json.get("state").is_some());
    assert!(json.get("current_agent").is_some());
    assert!(json.get("agent_output").is_some());
    assert!(json.get("workflow_inputs").is_some());
    assert!(json.get("agent_outputs").is_some());

    let state = json.get("state").unwrap();
    assert_eq!(state.get("count").unwrap().as_i64(), Some(42));
    assert_eq!(state.get("name").unwrap().as_str(), Some("test"));
}