enact-core 0.0.2

Core agent runtime for Enact - Graph-Native AI agents
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
//! Role Profiles - Capability-based role definitions
//!
//! Implements role presets inspired by Antfarm:
//! - analysis: Explores and plans
//! - coding: Implements and tests
//! - verification: Validates work quality
//! - testing: Integration and E2E testing
//! - pr: Pull request management
//! - scanning: Security and compliance

use serde::{Deserialize, Serialize};
use std::collections::HashSet;
use std::str::FromStr;

/// Role capability (what the role CAN do)
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Capability {
    /// Read source code
    ReadCode,
    /// Write source code
    WriteSource,
    /// Explore project structure
    ExploreStructure,
    /// Execute shell commands
    ExecuteShell,
    /// Execute tests
    ExecuteTests,
    /// Git operations
    WriteGit,
    /// Read pull requests
    ReadPr,
    /// Write PR reviews
    WriteReview,
    /// Merge PRs
    MergePr,
    /// Use external tools
    UseTools,
    /// Use browser for visual testing
    UseBrowser,
}

impl FromStr for Capability {
    type Err = ();

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::parse(s).ok_or(())
    }
}

impl Capability {
    /// Parse capability from string
    pub fn parse(s: &str) -> Option<Self> {
        match s {
            "read:code" => Some(Capability::ReadCode),
            "write:source" => Some(Capability::WriteSource),
            "explore:structure" => Some(Capability::ExploreStructure),
            "execute:shell" => Some(Capability::ExecuteShell),
            "execute:tests" => Some(Capability::ExecuteTests),
            "write:git" => Some(Capability::WriteGit),
            "read:pr" => Some(Capability::ReadPr),
            "write:review" => Some(Capability::WriteReview),
            "merge:pr" => Some(Capability::MergePr),
            "use:tools" => Some(Capability::UseTools),
            "use:browser" => Some(Capability::UseBrowser),
            _ => None,
        }
    }

    /// Convert to string representation
    pub fn as_str(&self) -> &'static str {
        match self {
            Capability::ReadCode => "read:code",
            Capability::WriteSource => "write:source",
            Capability::ExploreStructure => "explore:structure",
            Capability::ExecuteShell => "execute:shell",
            Capability::ExecuteTests => "execute:tests",
            Capability::WriteGit => "write:git",
            Capability::ReadPr => "read:pr",
            Capability::WriteReview => "write:review",
            Capability::MergePr => "merge:pr",
            Capability::UseTools => "use:tools",
            Capability::UseBrowser => "use:browser",
        }
    }
}

/// Role restriction (what the role CANNOT do)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Restriction {
    /// Type of restriction
    #[serde(rename = "type")]
    pub restriction_type: RestrictionType,
    /// Action being restricted
    pub action: String,
}

/// Restriction types
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RestrictionType {
    /// Explicitly deny this action
    Deny,
    /// Require approval for this action
    RequireApproval,
    /// Log this action for audit
    Audit,
}

/// Predefined role profiles
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum RoleProfile {
    /// Analysis and planning
    Analysis,
    /// Coding and implementation
    Coding,
    /// Verification and validation
    Verification,
    /// Testing (integration and E2E)
    Testing,
    /// PR management
    Pr,
    /// Security scanning
    Scanning,
}

impl RoleProfile {
    /// Get the default capabilities for this role
    pub fn default_capabilities(&self) -> HashSet<Capability> {
        let mut caps = HashSet::new();

        match self {
            RoleProfile::Analysis => {
                caps.insert(Capability::ReadCode);
                caps.insert(Capability::ExploreStructure);
                caps.insert(Capability::ReadPr);
            }
            RoleProfile::Coding => {
                caps.insert(Capability::ReadCode);
                caps.insert(Capability::WriteSource);
                caps.insert(Capability::ExecuteShell);
                caps.insert(Capability::ExecuteTests);
                caps.insert(Capability::WriteGit);
                caps.insert(Capability::UseTools);
            }
            RoleProfile::Verification => {
                caps.insert(Capability::ReadCode);
                caps.insert(Capability::ExecuteTests);
                caps.insert(Capability::ReadPr);
                caps.insert(Capability::WriteReview);
            }
            RoleProfile::Testing => {
                caps.insert(Capability::ReadCode);
                caps.insert(Capability::ExecuteTests);
                caps.insert(Capability::UseBrowser);
                caps.insert(Capability::ExecuteShell);
            }
            RoleProfile::Pr => {
                caps.insert(Capability::ReadCode);
                caps.insert(Capability::ReadPr);
                caps.insert(Capability::WriteReview);
                caps.insert(Capability::WriteGit);
            }
            RoleProfile::Scanning => {
                caps.insert(Capability::ReadCode);
                caps.insert(Capability::ExecuteShell);
                caps.insert(Capability::ExploreStructure);
            }
        }

        caps
    }

    /// Get default restrictions for this role
    pub fn default_restrictions(&self) -> Vec<Restriction> {
        match self {
            RoleProfile::Analysis => vec![
                Restriction {
                    restriction_type: RestrictionType::Deny,
                    action: "write:source".to_string(),
                },
                Restriction {
                    restriction_type: RestrictionType::Deny,
                    action: "execute:shell".to_string(),
                },
            ],
            RoleProfile::Coding => vec![],
            RoleProfile::Verification => vec![
                Restriction {
                    restriction_type: RestrictionType::Deny,
                    action: "write:source".to_string(),
                },
                Restriction {
                    restriction_type: RestrictionType::Deny,
                    action: "write:git".to_string(),
                },
            ],
            RoleProfile::Testing => vec![Restriction {
                restriction_type: RestrictionType::Deny,
                action: "write:source".to_string(),
            }],
            RoleProfile::Pr => vec![
                Restriction {
                    restriction_type: RestrictionType::Deny,
                    action: "write:source".to_string(),
                },
                Restriction {
                    restriction_type: RestrictionType::Deny,
                    action: "merge:pr".to_string(),
                },
            ],
            RoleProfile::Scanning => vec![Restriction {
                restriction_type: RestrictionType::Deny,
                action: "write:source".to_string(),
            }],
        }
    }

    /// Get recommended model profile for this role
    pub fn recommended_model_profile(&self) -> &'static str {
        match self {
            RoleProfile::Analysis => "balanced",
            RoleProfile::Coding => "quality",
            RoleProfile::Verification => "deterministic",
            RoleProfile::Testing => "balanced",
            RoleProfile::Pr => "balanced",
            RoleProfile::Scanning => "deterministic",
        }
    }

    /// Get description of this role
    pub fn description(&self) -> &'static str {
        match self {
            RoleProfile::Analysis => "Explores codebase, analyzes requirements, and creates plans",
            RoleProfile::Coding => "Implements features, writes tests, and manages code",
            RoleProfile::Verification => "Validates implementation quality and correctness",
            RoleProfile::Testing => "Performs integration and end-to-end testing",
            RoleProfile::Pr => "Manages pull requests and code reviews",
            RoleProfile::Scanning => "Performs security and compliance scans",
        }
    }
}

/// Role definition in a workflow
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RoleDefinition {
    /// Role identifier
    pub id: String,
    /// Display name
    pub name: String,
    /// Base profile
    #[serde(default)]
    pub profile: Option<RoleProfile>,
    /// Description
    pub description: Option<String>,
    /// Workspace configuration
    #[serde(default)]
    pub workspace: Option<WorkspaceConfig>,
    /// Explicit capabilities (overrides profile)
    #[serde(default)]
    pub capabilities: Vec<String>,
    /// Explicit restrictions (overrides profile)
    #[serde(default)]
    pub restrictions: Vec<Restriction>,
    /// Model configuration
    #[serde(default)]
    pub model: Option<ModelConfig>,
}

impl RoleDefinition {
    /// Get effective capabilities (profile + overrides)
    pub fn effective_capabilities(&self) -> HashSet<Capability> {
        let mut caps = if let Some(profile) = self.profile {
            profile.default_capabilities()
        } else {
            HashSet::new()
        };

        // Add explicit capabilities
        for cap_str in &self.capabilities {
            if let Ok(cap) = cap_str.parse::<Capability>() {
                caps.insert(cap);
            }
        }

        caps
    }

    /// Get effective restrictions (profile + overrides)
    pub fn effective_restrictions(&self) -> Vec<Restriction> {
        let mut restrictions = if let Some(profile) = self.profile {
            profile.default_restrictions()
        } else {
            vec![]
        };

        // Add explicit restrictions
        restrictions.extend(self.restrictions.clone());

        restrictions
    }

    /// Check if role has a capability
    pub fn has_capability(&self, cap: &Capability) -> bool {
        self.effective_capabilities().contains(cap)
    }

    /// Check if role is restricted from an action
    pub fn is_restricted(&self, action: &str) -> bool {
        self.effective_restrictions()
            .iter()
            .any(|r| r.action == action)
    }
}

/// Workspace configuration for a role
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkspaceConfig {
    /// Base directory for agent files
    pub base_dir: String,
    /// Files to include in workspace
    #[serde(default)]
    pub files: Vec<String>,
    /// Skills available to this role
    #[serde(default)]
    pub skills: Vec<String>,
}

/// Model configuration for a role
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ModelConfig {
    /// Model identifier
    pub model: Option<String>,
    /// Routing profile
    #[serde(default)]
    pub profile: Option<String>,
    /// Maximum tokens
    #[serde(default)]
    pub max_tokens: Option<usize>,
    /// Temperature
    #[serde(default)]
    pub temperature: Option<f32>,
}

/// Role registry for managing role definitions
pub struct RoleRegistry {
    roles: std::collections::HashMap<String, RoleDefinition>,
}

impl RoleRegistry {
    /// Create a new empty registry
    pub fn new() -> Self {
        Self {
            roles: std::collections::HashMap::new(),
        }
    }

    /// Register a role
    pub fn register(&mut self, role: RoleDefinition) {
        self.roles.insert(role.id.clone(), role);
    }

    /// Get a role by ID
    pub fn get(&self, id: &str) -> Option<&RoleDefinition> {
        self.roles.get(id)
    }

    /// Load roles from workflow definition
    pub fn load_from_workflow(&mut self, roles: Vec<RoleDefinition>) {
        for role in roles {
            self.register(role);
        }
    }
}

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

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

    #[test]
    fn test_analysis_profile() {
        let profile = RoleProfile::Analysis;
        let caps = profile.default_capabilities();

        assert!(caps.contains(&Capability::ReadCode));
        assert!(caps.contains(&Capability::ExploreStructure));
        assert!(!caps.contains(&Capability::WriteSource));

        let restrictions = profile.default_restrictions();
        assert!(restrictions.iter().any(|r| r.action == "write:source"));
    }

    #[test]
    fn test_coding_profile() {
        let profile = RoleProfile::Coding;
        let caps = profile.default_capabilities();

        assert!(caps.contains(&Capability::WriteSource));
        assert!(caps.contains(&Capability::ExecuteTests));

        let restrictions = profile.default_restrictions();
        assert!(restrictions.is_empty());
    }

    #[test]
    fn test_verification_profile() {
        let profile = RoleProfile::Verification;
        let restrictions = profile.default_restrictions();

        assert!(restrictions.iter().any(|r| r.action == "write:source"));
        assert!(restrictions.iter().any(|r| r.action == "write:git"));
    }

    #[test]
    fn test_role_definition_override() {
        let role = RoleDefinition {
            id: "custom".to_string(),
            name: "Custom Role".to_string(),
            profile: Some(RoleProfile::Analysis),
            description: None,
            workspace: None,
            capabilities: vec!["write:source".to_string()],
            restrictions: vec![],
            model: None,
        };

        // Should have analysis capabilities plus the override
        let caps = role.effective_capabilities();
        assert!(caps.contains(&Capability::ReadCode));
        assert!(caps.contains(&Capability::WriteSource)); // Added via override
    }

    #[test]
    fn test_capability_parsing() {
        assert_eq!(
            "read:code".parse::<Capability>().unwrap(),
            Capability::ReadCode
        );
        assert_eq!(
            "write:source".parse::<Capability>().unwrap(),
            Capability::WriteSource
        );
        assert!("invalid:cap".parse::<Capability>().is_err());
    }
}