spec-ai 0.6.12

A framework for building AI agents with structured outputs, policy enforcement, and execution tracking
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
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};

use crate::spec_ai_config::persistence::Persistence;

/// Represents the effect of a policy rule
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum PolicyEffect {
    Allow,
    Deny,
}

/// A single policy rule matching (agent, action, resource) tuples
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PolicyRule {
    /// Agent name pattern (supports wildcards: "*")
    pub agent: String,
    /// Action pattern (e.g., "tool_call", "file_write", "bash")
    pub action: String,
    /// Resource pattern (e.g., tool name, file path - supports wildcards: "*")
    pub resource: String,
    /// Effect to apply when rule matches
    pub effect: PolicyEffect,
}

impl PolicyRule {
    /// Check if this rule matches the given agent, action, and resource
    pub fn matches(&self, agent: &str, action: &str, resource: &str) -> bool {
        wildcard_match(&self.agent, agent)
            && wildcard_match(&self.action, action)
            && wildcard_match(&self.resource, resource)
    }
}

/// Container for all policy rules
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct PolicySet {
    pub rules: Vec<PolicyRule>,
}

/// Result of policy evaluation
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PolicyDecision {
    /// Action is allowed
    Allow,
    /// Action is denied with a reason
    Deny(String),
}

/// Policy engine that evaluates actions against stored rules
#[derive(Debug, Clone)]
pub struct PolicyEngine {
    policy_set: PolicySet,
}

impl PolicyEngine {
    /// Create a new policy engine with an empty policy set
    pub fn new() -> Self {
        Self {
            policy_set: PolicySet::default(),
        }
    }

    /// Create a policy engine with the given policy set
    pub fn with_policy_set(policy_set: PolicySet) -> Self {
        Self { policy_set }
    }

    /// Load policies from persistence layer
    /// Policies are stored in the policy_cache table with key "policies"
    pub fn load_from_persistence(persistence: &Persistence) -> Result<Self> {
        match persistence.policy_get("policies")? {
            Some(entry) => {
                let policy_set: PolicySet = serde_json::from_value(entry.value)
                    .context("deserializing policy set from cache")?;
                Ok(Self::with_policy_set(policy_set))
            }
            None => {
                // No policies stored yet, return empty engine
                Ok(Self::new())
            }
        }
    }

    /// Save current policy set to persistence
    pub fn save_to_persistence(&self, persistence: &Persistence) -> Result<()> {
        let value = serde_json::to_value(&self.policy_set).context("serializing policy set")?;
        persistence.policy_upsert("policies", &value)?;
        Ok(())
    }

    /// Reload policies from persistence
    pub fn reload(&mut self, persistence: &Persistence) -> Result<()> {
        let engine = Self::load_from_persistence(persistence)?;
        self.policy_set = engine.policy_set;
        Ok(())
    }

    /// Evaluate a policy decision for the given agent, action, and resource
    /// Rules are evaluated in order, and the first matching rule determines the decision
    /// If no rules match, the default is to deny with a reason
    pub fn check(&self, agent: &str, action: &str, resource: &str) -> PolicyDecision {
        for rule in &self.policy_set.rules {
            if rule.matches(agent, action, resource) {
                return match rule.effect {
                    PolicyEffect::Allow => PolicyDecision::Allow,
                    PolicyEffect::Deny => PolicyDecision::Deny(format!(
                        "Policy denies {} action {} on resource {}",
                        agent, action, resource
                    )),
                };
            }
        }

        // Default: deny if no rule matches
        PolicyDecision::Deny(format!(
            "No policy rule matches agent '{}', action '{}', resource '{}' (default deny)",
            agent, action, resource
        ))
    }

    /// Get the number of rules in the policy set
    pub fn rule_count(&self) -> usize {
        self.policy_set.rules.len()
    }

    /// Add a rule to the policy set
    pub fn add_rule(&mut self, rule: PolicyRule) {
        self.policy_set.rules.push(rule);
    }

    /// Get a reference to the policy set
    pub fn policy_set(&self) -> &PolicySet {
        &self.policy_set
    }
}

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

/// Simple wildcard matching
/// Supports "*" as a wildcard that matches any string
fn wildcard_match(pattern: &str, text: &str) -> bool {
    if pattern == "*" {
        return true;
    }

    // If pattern contains wildcards, do more complex matching
    if pattern.contains('*') {
        // Split pattern by '*' and check if text contains all parts in order
        let parts: Vec<&str> = pattern.split('*').collect();
        let mut text_pos = 0;

        for (i, part) in parts.iter().enumerate() {
            if part.is_empty() {
                continue;
            }

            if let Some(pos) = text[text_pos..].find(part) {
                text_pos += pos + part.len();
            } else {
                return false;
            }

            // If this is not the last part and not followed by wildcard at pattern end,
            // ensure part is found
            if i == parts.len() - 1 && !pattern.ends_with('*') {
                // Last part must be at the end
                return text.ends_with(part);
            }
        }

        // If pattern starts with '*', first part can be anywhere
        // If pattern ends with '*', last part can be anywhere (already handled)
        if !pattern.starts_with('*') && !parts.is_empty() && !parts[0].is_empty() {
            return text.starts_with(parts[0]);
        }

        true
    } else {
        // No wildcards, exact match
        pattern == text
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_wildcard_match_exact() {
        assert!(wildcard_match("hello", "hello"));
        assert!(!wildcard_match("hello", "world"));
        assert!(!wildcard_match("hello", "hello_world"));
    }

    #[test]
    fn test_wildcard_match_star() {
        assert!(wildcard_match("*", "anything"));
        assert!(wildcard_match("*", ""));
        assert!(wildcard_match("*", "foo/bar/baz"));
    }

    #[test]
    fn test_wildcard_match_prefix() {
        assert!(wildcard_match("hello*", "hello"));
        assert!(wildcard_match("hello*", "hello_world"));
        assert!(wildcard_match("hello*", "hello123"));
        assert!(!wildcard_match("hello*", "hi_world"));
    }

    #[test]
    fn test_wildcard_match_suffix() {
        assert!(wildcard_match("*world", "world"));
        assert!(wildcard_match("*world", "hello_world"));
        assert!(!wildcard_match("*world", "world_hello"));
    }

    #[test]
    fn test_wildcard_match_middle() {
        assert!(wildcard_match("hello*world", "helloworld"));
        assert!(wildcard_match("hello*world", "hello_beautiful_world"));
        assert!(!wildcard_match("hello*world", "hello"));
        assert!(!wildcard_match("hello*world", "world"));
    }

    #[test]
    fn test_wildcard_match_multiple() {
        assert!(wildcard_match("/etc/*/*.conf", "/etc/nginx/nginx.conf"));
        assert!(wildcard_match("/etc/*/*.conf", "/etc/apache2/apache2.conf"));
        assert!(!wildcard_match(
            "/etc/*/*.conf",
            "/etc/nginx/sites-available/default"
        ));
    }

    #[test]
    fn test_policy_rule_matches() {
        let rule = PolicyRule {
            agent: "coder".to_string(),
            action: "tool_call".to_string(),
            resource: "echo".to_string(),
            effect: PolicyEffect::Allow,
        };

        assert!(rule.matches("coder", "tool_call", "echo"));
        assert!(!rule.matches("assistant", "tool_call", "echo"));
        assert!(!rule.matches("coder", "file_write", "echo"));
        assert!(!rule.matches("coder", "tool_call", "calculator"));
    }

    #[test]
    fn test_policy_rule_wildcard_agent() {
        let rule = PolicyRule {
            agent: "*".to_string(),
            action: "tool_call".to_string(),
            resource: "echo".to_string(),
            effect: PolicyEffect::Allow,
        };

        assert!(rule.matches("coder", "tool_call", "echo"));
        assert!(rule.matches("assistant", "tool_call", "echo"));
        assert!(rule.matches("any_agent", "tool_call", "echo"));
    }

    #[test]
    fn test_policy_rule_wildcard_resource() {
        let rule = PolicyRule {
            agent: "coder".to_string(),
            action: "tool_call".to_string(),
            resource: "*".to_string(),
            effect: PolicyEffect::Allow,
        };

        assert!(rule.matches("coder", "tool_call", "echo"));
        assert!(rule.matches("coder", "tool_call", "calculator"));
        assert!(rule.matches("coder", "tool_call", "any_tool"));
    }

    #[test]
    fn test_policy_engine_allow() {
        let mut engine = PolicyEngine::new();
        engine.add_rule(PolicyRule {
            agent: "coder".to_string(),
            action: "tool_call".to_string(),
            resource: "echo".to_string(),
            effect: PolicyEffect::Allow,
        });

        assert_eq!(
            engine.check("coder", "tool_call", "echo"),
            PolicyDecision::Allow
        );
    }

    #[test]
    fn test_policy_engine_deny() {
        let mut engine = PolicyEngine::new();
        engine.add_rule(PolicyRule {
            agent: "coder".to_string(),
            action: "bash".to_string(),
            resource: "/etc/*".to_string(),
            effect: PolicyEffect::Deny,
        });

        match engine.check("coder", "bash", "/etc/passwd") {
            PolicyDecision::Deny(_) => {}
            _ => panic!("Expected deny decision"),
        }
    }

    #[test]
    fn test_policy_engine_first_match_wins() {
        let mut engine = PolicyEngine::new();
        // First rule: deny all bash
        engine.add_rule(PolicyRule {
            agent: "*".to_string(),
            action: "bash".to_string(),
            resource: "*".to_string(),
            effect: PolicyEffect::Deny,
        });
        // Second rule: allow bash for coder (should never be reached)
        engine.add_rule(PolicyRule {
            agent: "coder".to_string(),
            action: "bash".to_string(),
            resource: "*".to_string(),
            effect: PolicyEffect::Allow,
        });

        // First rule should win
        match engine.check("coder", "bash", "/tmp/test.sh") {
            PolicyDecision::Deny(_) => {}
            _ => panic!("Expected deny decision from first rule"),
        }
    }

    #[test]
    fn test_policy_engine_default_deny() {
        let engine = PolicyEngine::new();

        // No rules, should deny by default
        match engine.check("agent", "action", "resource") {
            PolicyDecision::Deny(reason) => {
                assert!(reason.contains("No policy rule matches"));
            }
            _ => panic!("Expected default deny"),
        }
    }

    #[test]
    fn test_policy_engine_rule_count() {
        let mut engine = PolicyEngine::new();
        assert_eq!(engine.rule_count(), 0);

        engine.add_rule(PolicyRule {
            agent: "*".to_string(),
            action: "*".to_string(),
            resource: "*".to_string(),
            effect: PolicyEffect::Allow,
        });
        assert_eq!(engine.rule_count(), 1);
    }

    #[test]
    fn test_policy_serialization() {
        let policy_set = PolicySet {
            rules: vec![
                PolicyRule {
                    agent: "coder".to_string(),
                    action: "tool_call".to_string(),
                    resource: "echo".to_string(),
                    effect: PolicyEffect::Allow,
                },
                PolicyRule {
                    agent: "*".to_string(),
                    action: "bash".to_string(),
                    resource: "/etc/*".to_string(),
                    effect: PolicyEffect::Deny,
                },
            ],
        };

        // Serialize and deserialize
        let json = serde_json::to_value(&policy_set).unwrap();
        let deserialized: PolicySet = serde_json::from_value(json).unwrap();

        assert_eq!(deserialized.rules.len(), 2);
        assert_eq!(deserialized.rules[0].agent, "coder");
        assert_eq!(deserialized.rules[1].effect, PolicyEffect::Deny);
    }

    #[test]
    fn test_policy_persistence() {
        use crate::spec_ai_config::test_utils::create_test_db;

        let persistence = create_test_db();

        // Create engine with some rules
        let mut engine = PolicyEngine::new();
        engine.add_rule(PolicyRule {
            agent: "coder".to_string(),
            action: "tool_call".to_string(),
            resource: "echo".to_string(),
            effect: PolicyEffect::Allow,
        });
        engine.add_rule(PolicyRule {
            agent: "*".to_string(),
            action: "bash".to_string(),
            resource: "*".to_string(),
            effect: PolicyEffect::Deny,
        });

        // Save to persistence
        engine.save_to_persistence(&persistence).unwrap();

        // Load from persistence
        let loaded = PolicyEngine::load_from_persistence(&persistence).unwrap();
        assert_eq!(loaded.rule_count(), 2);

        // Verify rules work
        assert_eq!(
            loaded.check("coder", "tool_call", "echo"),
            PolicyDecision::Allow
        );
        match loaded.check("coder", "bash", "/tmp/test.sh") {
            PolicyDecision::Deny(_) => {}
            _ => panic!("Expected deny"),
        }
    }

    #[test]
    fn test_policy_reload() {
        use crate::spec_ai_config::test_utils::create_test_db;

        let persistence = create_test_db();

        // Create and save initial engine
        let mut engine = PolicyEngine::new();
        engine.add_rule(PolicyRule {
            agent: "coder".to_string(),
            action: "tool_call".to_string(),
            resource: "echo".to_string(),
            effect: PolicyEffect::Allow,
        });
        engine.save_to_persistence(&persistence).unwrap();

        // Create new engine with different rules
        let mut engine2 = PolicyEngine::new();
        engine2.add_rule(PolicyRule {
            agent: "*".to_string(),
            action: "*".to_string(),
            resource: "*".to_string(),
            effect: PolicyEffect::Deny,
        });
        engine2.save_to_persistence(&persistence).unwrap();

        // Reload first engine - should get new rules
        engine.reload(&persistence).unwrap();
        assert_eq!(engine.rule_count(), 1);

        // Should have the deny-all rule now
        match engine.check("coder", "tool_call", "echo") {
            PolicyDecision::Deny(_) => {}
            _ => panic!("Expected deny after reload"),
        }
    }

    #[test]
    fn test_load_empty_persistence() {
        use crate::spec_ai_config::test_utils::create_test_db;

        let persistence = create_test_db();

        // Load from empty persistence - should get empty engine
        let engine = PolicyEngine::load_from_persistence(&persistence).unwrap();
        assert_eq!(engine.rule_count(), 0);

        // Should deny by default
        match engine.check("agent", "action", "resource") {
            PolicyDecision::Deny(_) => {}
            _ => panic!("Expected default deny"),
        }
    }
}