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
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
489
490
491
492
493
494
495
//! Step Contract - I/O validation and status parsing
//!
//! Implements the strict step I/O contract from Antfarm patterns:
//! - STATUS: done|retry|blocked
//! - Typed key/value outputs
//! - Strict expects validation with actionable failure reasons

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

/// Step execution status
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum StepStatus {
    /// Step completed successfully
    Done,
    /// Step needs to be retried
    Retry,
    /// Step is blocked and requires escalation
    Blocked,
}

impl StepStatus {
    /// Parse status from string
    pub fn parse(s: &str) -> Result<Self> {
        match s.trim().to_lowercase().as_str() {
            "done" => Ok(StepStatus::Done),
            "retry" => Ok(StepStatus::Retry),
            "blocked" => Ok(StepStatus::Blocked),
            _ => Err(anyhow!(
                "Invalid status: {}. Expected: done, retry, or blocked",
                s
            )),
        }
    }

    /// Convert to string
    pub fn as_str(&self) -> &'static str {
        match self {
            StepStatus::Done => "done",
            StepStatus::Retry => "retry",
            StepStatus::Blocked => "blocked",
        }
    }
}

/// Expected output field definition
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExpectedField {
    /// Field name (e.g., "REPO", "BRANCH")
    pub name: String,
    /// Field type
    #[serde(rename = "type")]
    pub field_type: FieldType,
    /// Whether this field is required
    #[serde(default = "default_true")]
    pub required: bool,
    /// Optional validation pattern (regex)
    pub pattern: Option<String>,
    /// Optional enum values for validation
    #[serde(default)]
    pub enum_values: Vec<String>,
}

fn default_true() -> bool {
    true
}

/// Field types for validation
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum FieldType {
    /// String value
    String,
    /// Integer value
    Integer,
    /// Floating point value
    Float,
    /// Boolean value
    Boolean,
    /// JSON object or array
    Json,
    /// Array of strings
    StringArray,
}

/// Contract expectation definition
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ContractExpectation {
    /// Expected status
    pub status: StepStatus,
    /// Expected output fields
    #[serde(default)]
    pub outputs: Vec<ExpectedField>,
}

/// Failure handling configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "action", rename_all = "snake_case")]
pub enum FailureAction {
    /// Retry the step
    Retry {
        /// Maximum number of retries
        max_retries: u32,
        /// Optional step to retry (defaults to current)
        #[serde(default)]
        retry_target: Option<String>,
        /// Field name containing feedback for retry
        #[serde(default)]
        feedback_field: Option<String>,
        /// Action when retries exhausted
        #[serde(default)]
        on_exhausted: Option<Box<FailureAction>>,
    },
    /// Escalate to human
    Escalate {
        /// Who to escalate to
        to: String,
    },
    /// Skip to next step
    Skip,
    /// Fail the workflow
    Fail,
}

/// Step contract definition
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StepContract {
    /// Expected outputs
    pub expects: ContractExpectation,
    /// Failure handling
    #[serde(default)]
    pub on_failure: Option<FailureAction>,
}

/// Parsed step output
#[derive(Debug, Clone)]
pub struct ParsedOutput {
    /// Execution status
    pub status: StepStatus,
    /// Parsed key-value pairs
    pub fields: HashMap<String, serde_json::Value>,
    /// Raw output text (for debugging)
    pub raw_output: String,
}

/// Contract parser for step outputs
pub struct ContractParser;

impl ContractParser {
    /// Parse step output according to contract
    pub fn parse(output: &str, contract: &StepContract) -> Result<ParsedOutput> {
        // Extract STATUS line
        let status = Self::extract_status(output)?;

        // Parse key-value pairs
        let fields = Self::parse_fields(output)?;

        // Validate against contract
        if status == contract.expects.status {
            Self::validate_fields(&fields, &contract.expects.outputs)?;
        }

        Ok(ParsedOutput {
            status,
            fields,
            raw_output: output.to_string(),
        })
    }

    /// Extract STATUS from output
    fn extract_status(output: &str) -> Result<StepStatus> {
        for line in output.lines() {
            let line = line.trim();
            if let Some(status_str) = line.strip_prefix("STATUS:") {
                return StepStatus::parse(status_str.trim());
            }
        }

        Err(anyhow!(
            "Missing STATUS field. Expected: STATUS: done|retry|blocked\n\nOutput:\n{}",
            output
        ))
    }

    /// Parse key-value pairs from output
    fn parse_fields(output: &str) -> Result<HashMap<String, serde_json::Value>> {
        let mut fields = HashMap::new();

        for line in output.lines() {
            let line = line.trim();

            // Skip empty lines and comments
            if line.is_empty() || line.starts_with('#') {
                continue;
            }

            // Look for KEY: value pattern
            if let Some(pos) = line.find(':') {
                let key = line[..pos].trim();
                let value = line[pos + 1..].trim();

                // Skip if it's a status line (handled separately)
                if key == "STATUS" {
                    continue;
                }

                // Try to parse as JSON if it looks like JSON
                let parsed_value = if (value.starts_with('[') && value.ends_with(']'))
                    || (value.starts_with('{') && value.ends_with('}'))
                {
                    serde_json::from_str(value)
                        .unwrap_or_else(|_| serde_json::Value::String(value.to_string()))
                } else {
                    serde_json::Value::String(value.to_string())
                };

                fields.insert(key.to_string(), parsed_value);
            }
        }

        Ok(fields)
    }

    /// Validate fields against expected definitions
    fn validate_fields(
        fields: &HashMap<String, serde_json::Value>,
        expected: &[ExpectedField],
    ) -> Result<()> {
        let mut errors = Vec::new();

        for field_def in expected {
            let field_name = &field_def.name;

            match fields.get(field_name) {
                Some(value) => {
                    // Validate type
                    if let Err(e) = Self::validate_type(value, &field_def.field_type) {
                        errors.push(format!(
                            "Field '{}' type mismatch: expected {}, got error: {}",
                            field_name,
                            format!("{:?}", field_def.field_type).to_lowercase(),
                            e
                        ));
                    }

                    // Validate pattern if specified
                    if let Some(pattern) = &field_def.pattern {
                        let value_str = match value {
                            serde_json::Value::String(s) => s.clone(),
                            other => other.to_string(),
                        };

                        let regex = regex::Regex::new(pattern).context("Invalid pattern regex")?;

                        if !regex.is_match(&value_str) {
                            errors.push(format!(
                                "Field '{}' value '{}' does not match pattern '{}'",
                                field_name, value_str, pattern
                            ));
                        }
                    }

                    // Validate enum values if specified
                    if !field_def.enum_values.is_empty() {
                        let value_str = match value {
                            serde_json::Value::String(s) => s.clone(),
                            other => other.to_string(),
                        };

                        if !field_def.enum_values.contains(&value_str) {
                            errors.push(format!(
                                "Field '{}' value '{}' not in allowed values: {:?}",
                                field_name, value_str, field_def.enum_values
                            ));
                        }
                    }
                }
                None => {
                    if field_def.required {
                        errors.push(format!(
                            "Missing required field: {} (type: {:?})",
                            field_name, field_def.field_type
                        ));
                    }
                }
            }
        }

        if errors.is_empty() {
            Ok(())
        } else {
            Err(anyhow!(
                "Contract validation failed:\n{}",
                errors.join("\n")
            ))
        }
    }

    /// Validate a value matches expected type
    fn validate_type(value: &serde_json::Value, expected: &FieldType) -> Result<()> {
        match expected {
            FieldType::String => {
                if !value.is_string() {
                    return Err(anyhow!("Expected string, got {}", value));
                }
            }
            FieldType::Integer => {
                if !value.is_i64() && !value.is_u64() {
                    return Err(anyhow!("Expected integer, got {}", value));
                }
            }
            FieldType::Float => {
                if !value.is_f64() && !value.is_i64() && !value.is_u64() {
                    return Err(anyhow!("Expected number, got {}", value));
                }
            }
            FieldType::Boolean => {
                if !value.is_boolean() {
                    return Err(anyhow!("Expected boolean, got {}", value));
                }
            }
            FieldType::Json => {
                // Any JSON value is valid
            }
            FieldType::StringArray => {
                if let serde_json::Value::Array(arr) = value {
                    for (i, item) in arr.iter().enumerate() {
                        if !item.is_string() {
                            return Err(anyhow!(
                                "Expected string array, but item {} is {}",
                                i,
                                item
                            ));
                        }
                    }
                } else {
                    return Err(anyhow!("Expected array, got {}", value));
                }
            }
        }

        Ok(())
    }

    /// Get feedback field value from output
    pub fn get_feedback(output: &str, field_name: &str) -> Option<String> {
        let fields = Self::parse_fields(output).ok()?;
        fields.get(field_name).map(|v| v.to_string())
    }
}

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

    #[test]
    fn test_parse_status() {
        let output = "STATUS: done\nREPO: /path/to/repo";
        let status = ContractParser::extract_status(output).unwrap();
        assert_eq!(status, StepStatus::Done);

        let output = "STATUS: retry\nISSUES: something went wrong";
        let status = ContractParser::extract_status(output).unwrap();
        assert_eq!(status, StepStatus::Retry);

        let output = "STATUS: blocked\nREASON: need permission";
        let status = ContractParser::extract_status(output).unwrap();
        assert_eq!(status, StepStatus::Blocked);
    }

    #[test]
    fn test_parse_fields() {
        let output = r#"
STATUS: done
REPO: /path/to/repo
BRANCH: feature-branch
COUNT: 42
"#;

        let fields = ContractParser::parse_fields(output).unwrap();
        assert_eq!(
            fields.get("REPO").unwrap().as_str().unwrap(),
            "/path/to/repo"
        );
        assert_eq!(
            fields.get("BRANCH").unwrap().as_str().unwrap(),
            "feature-branch"
        );
        assert_eq!(fields.get("COUNT").unwrap().as_str().unwrap(), "42");
    }

    #[test]
    fn test_parse_json_field() {
        let output = r#"
STATUS: done
STORIES_JSON: [{"id": 1, "title": "Story 1"}, {"id": 2, "title": "Story 2"}]
"#;

        let fields = ContractParser::parse_fields(output).unwrap();
        let stories = fields.get("STORIES_JSON").unwrap();
        assert!(stories.is_array());
        assert_eq!(stories.as_array().unwrap().len(), 2);
    }

    #[test]
    fn test_validate_contract() {
        let contract = StepContract {
            expects: ContractExpectation {
                status: StepStatus::Done,
                outputs: vec![
                    ExpectedField {
                        name: "REPO".to_string(),
                        field_type: FieldType::String,
                        required: true,
                        pattern: None,
                        enum_values: vec![],
                    },
                    ExpectedField {
                        name: "BRANCH".to_string(),
                        field_type: FieldType::String,
                        required: true,
                        pattern: None,
                        enum_values: vec![],
                    },
                ],
            },
            on_failure: None,
        };

        let output = r#"
STATUS: done
REPO: /path/to/repo
BRANCH: feature-branch
"#;

        let result = ContractParser::parse(output, &contract);
        assert!(result.is_ok());

        let parsed = result.unwrap();
        assert_eq!(parsed.status, StepStatus::Done);
        assert_eq!(
            parsed.fields.get("REPO").unwrap().as_str().unwrap(),
            "/path/to/repo"
        );
    }

    #[test]
    fn test_validate_missing_field() {
        let contract = StepContract {
            expects: ContractExpectation {
                status: StepStatus::Done,
                outputs: vec![
                    ExpectedField {
                        name: "REPO".to_string(),
                        field_type: FieldType::String,
                        required: true,
                        pattern: None,
                        enum_values: vec![],
                    },
                    ExpectedField {
                        name: "BRANCH".to_string(),
                        field_type: FieldType::String,
                        required: true,
                        pattern: None,
                        enum_values: vec![],
                    },
                ],
            },
            on_failure: None,
        };

        let output = r#"
STATUS: done
REPO: /path/to/repo
"#;

        let result = ContractParser::parse(output, &contract);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("BRANCH"));
    }

    #[test]
    fn test_get_feedback() {
        let output = r#"
STATUS: retry
ISSUES: The test is failing due to missing imports
"#;

        let feedback = ContractParser::get_feedback(output, "ISSUES");
        assert!(feedback.is_some());
        assert!(feedback.unwrap().contains("missing imports"));
    }
}