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
//! Guardrail Types
//!
//! Core types for guardrail enforcement in SWL workflows.

use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// Type of guardrail trigger point
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum GuardrailType {
    /// Check before agent execution
    #[serde(rename = "pre_agent")]
    PreAgent,
    /// Check after agent execution
    #[serde(rename = "post_agent")]
    PostAgent,
    /// Check before tool execution
    #[serde(rename = "pre_tool")]
    PreTool,
    /// Check after tool execution
    #[serde(rename = "post_tool")]
    PostTool,
    /// Check before workflow execution
    #[serde(rename = "pre_workflow")]
    PreWorkflow,
    /// Check after workflow execution
    #[serde(rename = "post_workflow")]
    PostWorkflow,
}

impl std::fmt::Display for GuardrailType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            GuardrailType::PreAgent => write!(f, "pre_agent"),
            GuardrailType::PostAgent => write!(f, "post_agent"),
            GuardrailType::PreTool => write!(f, "pre_tool"),
            GuardrailType::PostTool => write!(f, "post_tool"),
            GuardrailType::PreWorkflow => write!(f, "pre_workflow"),
            GuardrailType::PostWorkflow => write!(f, "post_workflow"),
        }
    }
}

impl GuardrailType {
    /// Parse from string representation
    pub fn parse_str(s: &str) -> Option<Self> {
        match s {
            "pre_agent" => Some(GuardrailType::PreAgent),
            "post_agent" => Some(GuardrailType::PostAgent),
            "pre_tool" => Some(GuardrailType::PreTool),
            "post_tool" => Some(GuardrailType::PostTool),
            "pre_workflow" => Some(GuardrailType::PreWorkflow),
            "post_workflow" => Some(GuardrailType::PostWorkflow),
            _ => None,
        }
    }

    /// All guardrail types
    pub fn all() -> Vec<Self> {
        vec![
            GuardrailType::PreAgent,
            GuardrailType::PostAgent,
            GuardrailType::PreTool,
            GuardrailType::PostTool,
            GuardrailType::PreWorkflow,
            GuardrailType::PostWorkflow,
        ]
    }
}

/// Action to take when guardrail condition is violated
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum ViolationAction {
    /// Block the operation and fail
    #[serde(rename = "block")]
    Block,
    /// Log warning but continue
    #[serde(rename = "warn")]
    Warn,
    /// Log silently
    #[serde(rename = "log")]
    Log,
    /// Alert (notify external system)
    #[serde(rename = "alert")]
    Alert,
}

impl std::fmt::Display for ViolationAction {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ViolationAction::Block => write!(f, "block"),
            ViolationAction::Warn => write!(f, "warn"),
            ViolationAction::Log => write!(f, "log"),
            ViolationAction::Alert => write!(f, "alert"),
        }
    }
}

impl ViolationAction {
    /// Parse from string representation
    pub fn parse_str(s: &str) -> Option<Self> {
        match s {
            "block" => Some(ViolationAction::Block),
            "warn" => Some(ViolationAction::Warn),
            "log" => Some(ViolationAction::Log),
            "alert" => Some(ViolationAction::Alert),
            _ => None,
        }
    }
}

/// Logical operator for combining conditions
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub enum LogicalOperator {
    /// All conditions must be true
    #[serde(rename = "and")]
    #[default]
    And,
    /// At least one condition must be true
    #[serde(rename = "or")]
    Or,
}

/// A condition that can be evaluated
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum Condition {
    /// Simple inline expression
    Inline(String),
    /// Code block in a specific language
    Code { language: String, content: String },
    /// Composite condition with logical operator
    Composite {
        operator: LogicalOperator,
        conditions: Vec<Condition>,
    },
}

/// Guardrail definition for enforcement
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct GuardrailDef {
    /// Unique name for the guardrail
    pub name: String,
    /// Type of trigger point
    #[serde(rename = "type")]
    pub guardrail_type: GuardrailType,
    /// Condition to evaluate
    pub condition: Condition,
    /// Action to take on violation
    pub on_violation: ViolationAction,
    /// Optional description
    #[serde(default)]
    pub description: Option<String>,
    /// Optional severity level
    #[serde(default)]
    pub severity: Option<GuardrailSeverity>,
    /// Optional tags for categorization
    #[serde(default)]
    pub tags: Vec<String>,
}

/// Severity level for guardrail violations
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default, Serialize, Deserialize)]
pub enum GuardrailSeverity {
    #[serde(rename = "info")]
    Info,
    #[serde(rename = "low")]
    Low,
    #[serde(rename = "medium")]
    #[default]
    Medium,
    #[serde(rename = "high")]
    High,
    #[serde(rename = "critical")]
    Critical,
}

impl std::fmt::Display for GuardrailSeverity {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            GuardrailSeverity::Info => write!(f, "info"),
            GuardrailSeverity::Low => write!(f, "low"),
            GuardrailSeverity::Medium => write!(f, "medium"),
            GuardrailSeverity::High => write!(f, "high"),
            GuardrailSeverity::Critical => write!(f, "critical"),
        }
    }
}

/// Context for evaluating guardrail conditions
#[derive(Debug, Clone, Default)]
pub struct GuardrailContext {
    /// Current state values
    pub state: HashMap<String, serde_json::Value>,
    /// Agent outputs (for post-agent checks)
    pub agent_outputs: HashMap<String, String>,
    /// Current agent name (if applicable)
    pub current_agent: Option<String>,
    /// Current tool name (if applicable)
    pub current_tool: Option<String>,
    /// Tool input arguments (for pre-tool checks)
    pub tool_input: Option<String>,
    /// Tool output (for post-tool checks)
    pub tool_output: Option<String>,
    /// Workflow inputs
    pub workflow_inputs: HashMap<String, serde_json::Value>,
    /// Current agent output (for post-agent checks)
    pub agent_output: Option<String>,
}

impl GuardrailContext {
    /// Create a new empty context
    pub fn new() -> Self {
        Self::default()
    }

    /// Add state value
    pub fn with_state(
        mut self,
        key: impl Into<String>,
        value: impl Into<serde_json::Value>,
    ) -> Self {
        self.state.insert(key.into(), value.into());
        self
    }

    /// Add agent output
    pub fn with_agent_output(
        mut self,
        agent: impl Into<String>,
        output: impl Into<String>,
    ) -> Self {
        let agent_name = agent.into();
        let output_str = output.into();
        self.agent_outputs
            .insert(agent_name.clone(), output_str.clone());
        self.current_agent = Some(agent_name);
        self.agent_output = Some(output_str);
        self
    }

    /// Set current agent
    pub fn with_current_agent(mut self, agent: impl Into<String>) -> Self {
        self.current_agent = Some(agent.into());
        self
    }

    /// Set current tool
    pub fn with_current_tool(mut self, tool: impl Into<String>) -> Self {
        self.current_tool = Some(tool.into());
        self
    }

    /// Set tool input
    pub fn with_tool_input(mut self, input: impl Into<String>) -> Self {
        self.tool_input = Some(input.into());
        self
    }

    /// Add workflow input
    pub fn with_workflow_input(
        mut self,
        key: impl Into<String>,
        value: impl Into<serde_json::Value>,
    ) -> Self {
        self.workflow_inputs.insert(key.into(), value.into());
        self
    }

    /// Convert to JSON for condition evaluation
    pub fn to_json(&self) -> serde_json::Value {
        let mut map = serde_json::Map::new();

        map.insert(
            "state".to_string(),
            serde_json::to_value(&self.state).unwrap_or_default(),
        );
        map.insert(
            "agent_outputs".to_string(),
            serde_json::to_value(&self.agent_outputs).unwrap_or_default(),
        );
        map.insert(
            "workflow_inputs".to_string(),
            serde_json::to_value(&self.workflow_inputs).unwrap_or_default(),
        );

        if let Some(agent) = &self.current_agent {
            map.insert("current_agent".to_string(), agent.clone().into());
        }
        if let Some(tool) = &self.current_tool {
            map.insert("current_tool".to_string(), tool.clone().into());
        }
        if let Some(input) = &self.tool_input {
            map.insert("tool_input".to_string(), input.clone().into());
        }
        if let Some(output) = &self.tool_output {
            map.insert("tool_output".to_string(), output.clone().into());
        }
        if let Some(output) = &self.agent_output {
            map.insert("agent_output".to_string(), output.clone().into());
        }

        serde_json::Value::Object(map)
    }
}

/// Result of guardrail evaluation
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum EvaluationResult {
    /// Condition passed (no violation)
    Pass,
    /// Condition failed (violation detected)
    Fail { reason: String },
    /// Evaluation could not be completed
    Error { message: String },
}

impl EvaluationResult {
    /// Check if the evaluation passed
    pub fn is_pass(&self) -> bool {
        matches!(self, EvaluationResult::Pass)
    }

    /// Check if the evaluation failed
    pub fn is_fail(&self) -> bool {
        matches!(self, EvaluationResult::Fail { .. })
    }

    /// Check if there was an error
    pub fn is_error(&self) -> bool {
        matches!(self, EvaluationResult::Error { .. })
    }
}

/// Outcome of checking a guardrail
#[derive(Debug, Clone)]
pub struct GuardrailOutcome {
    /// Name of the guardrail
    pub guardrail_name: String,
    /// Type of guardrail
    pub guardrail_type: GuardrailType,
    /// Evaluation result
    pub result: EvaluationResult,
    /// Action that was or should be taken
    pub action: ViolationAction,
    /// Timestamp of evaluation
    pub timestamp: std::time::Instant,
    /// Duration of evaluation
    pub evaluation_duration_ms: u64,
}

/// Summary of guardrail check results
#[derive(Debug, Clone, Default)]
pub struct GuardrailSummary {
    /// Total number of guardrails checked
    pub total_checked: usize,
    /// Number of passed checks
    pub passed: usize,
    /// Number of failed checks (violations)
    pub failed: usize,
    /// Number of evaluation errors
    pub errors: usize,
    /// Number of blocked operations
    pub blocked: usize,
    /// Number of warnings issued
    pub warnings: usize,
    /// Detailed outcomes
    pub outcomes: Vec<GuardrailOutcome>,
}

impl GuardrailSummary {
    /// Check if any violations should block execution
    pub fn should_block(&self) -> bool {
        self.outcomes
            .iter()
            .any(|o| matches!(o.action, ViolationAction::Block) && o.result.is_fail())
    }

    /// Get all blocking violations
    pub fn blocking_violations(&self) -> Vec<&GuardrailOutcome> {
        self.outcomes
            .iter()
            .filter(|o| matches!(o.action, ViolationAction::Block) && o.result.is_fail())
            .collect()
    }

    /// Get all warnings
    pub fn warnings(&self) -> Vec<&GuardrailOutcome> {
        self.outcomes
            .iter()
            .filter(|o| matches!(o.action, ViolationAction::Warn) && o.result.is_fail())
            .collect()
    }
}

/// Telemetry event for guardrail evaluation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GuardrailTelemetryEvent {
    /// Event timestamp (ISO 8601)
    pub timestamp: String,
    /// Guardrail name
    pub guardrail_name: String,
    /// Guardrail type
    pub guardrail_type: String,
    /// Evaluation result (pass/fail/error)
    pub result: String,
    /// Action taken
    pub action: String,
    /// Evaluation duration in milliseconds
    pub duration_ms: u64,
    /// Optional error message
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error_message: Option<String>,
    /// Optional failure reason
    #[serde(skip_serializing_if = "Option::is_none")]
    pub failure_reason: Option<String>,
    /// Current agent (if applicable)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub agent_name: Option<String>,
    /// Current tool (if applicable)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tool_name: Option<String>,
    /// Workflow name
    #[serde(skip_serializing_if = "Option::is_none")]
    pub workflow_name: Option<String>,
}

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