enact-core 0.0.1

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
//! Input Processor - Pre-execution content validation
//!
//! Input processors run BEFORE execution to validate and transform user input.
//! They detect potential issues like:
//! - PII in prompts (may need masking or blocking)
//! - Prompt injection attempts
//! - Prohibited content
//!
//! ## Architecture
//!
//! ```text
//! User Input
//!//!//! ┌──────────────────────────────────────────┐
//! │        INPUT PROCESSOR PIPELINE          │
//! │ ┌──────────┐ ┌──────────┐ ┌───────────┐ │
//! │ │ Content  │→│ Prompt   │→│   PII     │ │
//! │ │ Filter   │ │ Injection│ │ Detection │ │
//! │ └──────────┘ └──────────┘ └───────────┘ │
//! │      Pass/Block/Modify                   │
//! └──────────────────────────────────────────┘
//!//!     ▼ (if Pass)
//! ExecutionKernel
//! ```
//!
//! @see docs/TECHNICAL/17-GUARDRAILS-PROTECTION.md
//! @see docs/TECHNICAL/25-STREAM-PROCESSORS.md

use super::PolicyContext;
use async_trait::async_trait;
use std::sync::Arc;

/// Result of input processing
#[derive(Debug, Clone)]
pub enum InputProcessorResult {
    /// Input is safe, proceed with execution
    Pass,

    /// Input is blocked - do not execute
    Block {
        reason: String,
        /// The processor that blocked
        processor: String,
    },

    /// Input was modified (sanitized) - proceed with modified input
    Modify {
        original: String,
        modified: String,
        /// What was changed
        changes: Vec<String>,
    },
}

impl InputProcessorResult {
    /// Returns true if execution should proceed
    pub fn should_proceed(&self) -> bool {
        matches!(self, Self::Pass | Self::Modify { .. })
    }

    /// Returns true if input was blocked
    pub fn is_blocked(&self) -> bool {
        matches!(self, Self::Block { .. })
    }

    /// Get the input to use for execution (original or modified)
    pub fn effective_input<'a>(&'a self, original: &'a str) -> &'a str {
        match self {
            Self::Modify { modified, .. } => modified,
            _ => original,
        }
    }
}

/// Input Processor trait
///
/// Processors run BEFORE execution to validate/transform user input.
/// They MUST NOT have side effects beyond logging.
#[async_trait]
pub trait InputProcessor: Send + Sync {
    /// Processor name for logging/metrics
    fn name(&self) -> &str;

    /// Priority for ordering (lower = runs first)
    fn priority(&self) -> u32 {
        100 // Default priority
    }

    /// Process input before execution
    ///
    /// # Arguments
    /// * `input` - The user input to validate
    /// * `ctx` - Policy context (tenant, user, metadata)
    ///
    /// # Returns
    /// - `Pass` - Input is safe
    /// - `Block` - Input is blocked (don't execute)
    /// - `Modify` - Input was sanitized (use modified version)
    async fn process(
        &self,
        input: &str,
        ctx: &PolicyContext,
    ) -> anyhow::Result<InputProcessorResult>;
}

/// Input Processor Pipeline - chains multiple processors
pub struct InputProcessorPipeline {
    processors: Vec<Arc<dyn InputProcessor>>,
}

impl InputProcessorPipeline {
    /// Create a new empty pipeline
    pub fn new() -> Self {
        Self { processors: vec![] }
    }

    /// Add a processor to the pipeline
    pub fn add(mut self, processor: Arc<dyn InputProcessor>) -> Self {
        self.processors.push(processor);
        // Sort by priority (lower = first)
        self.processors.sort_by_key(|p| p.priority());
        self
    }

    /// Run all processors in sequence
    ///
    /// Processing stops on first Block.
    /// Modify results are chained (each processor sees the modified input).
    pub async fn process(
        &self,
        input: &str,
        ctx: &PolicyContext,
    ) -> anyhow::Result<InputProcessorResult> {
        let mut current_input = input.to_string();
        let mut all_changes: Vec<String> = vec![];
        let mut was_modified = false;

        for processor in &self.processors {
            let result = processor.process(&current_input, ctx).await?;

            match result {
                InputProcessorResult::Pass => {
                    // Continue to next processor
                    continue;
                }
                InputProcessorResult::Block { .. } => {
                    // Stop processing, return block
                    return Ok(result);
                }
                InputProcessorResult::Modify {
                    modified, changes, ..
                } => {
                    // Update input and continue
                    was_modified = true;
                    all_changes.extend(changes);
                    current_input = modified;
                }
            }
        }

        // All processors passed
        if was_modified {
            Ok(InputProcessorResult::Modify {
                original: input.to_string(),
                modified: current_input,
                changes: all_changes,
            })
        } else {
            Ok(InputProcessorResult::Pass)
        }
    }

    /// Check if the pipeline is empty
    pub fn is_empty(&self) -> bool {
        self.processors.is_empty()
    }

    /// Get the number of processors
    pub fn len(&self) -> usize {
        self.processors.len()
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use crate::policy::PolicyAction;
    use std::collections::HashMap;

    // Mock processor for testing
    struct MockPassProcessor;

    #[async_trait]
    impl InputProcessor for MockPassProcessor {
        fn name(&self) -> &str {
            "mock-pass"
        }

        async fn process(
            &self,
            _input: &str,
            _ctx: &PolicyContext,
        ) -> anyhow::Result<InputProcessorResult> {
            Ok(InputProcessorResult::Pass)
        }
    }

    struct MockBlockProcessor {
        reason: String,
    }

    #[async_trait]
    impl InputProcessor for MockBlockProcessor {
        fn name(&self) -> &str {
            "mock-block"
        }

        async fn process(
            &self,
            _input: &str,
            _ctx: &PolicyContext,
        ) -> anyhow::Result<InputProcessorResult> {
            Ok(InputProcessorResult::Block {
                reason: self.reason.clone(),
                processor: self.name().to_string(),
            })
        }
    }

    struct MockModifyProcessor {
        suffix: String,
    }

    #[async_trait]
    impl InputProcessor for MockModifyProcessor {
        fn name(&self) -> &str {
            "mock-modify"
        }

        async fn process(
            &self,
            input: &str,
            _ctx: &PolicyContext,
        ) -> anyhow::Result<InputProcessorResult> {
            Ok(InputProcessorResult::Modify {
                original: input.to_string(),
                modified: format!("{}{}", input, self.suffix),
                changes: vec![format!("Added suffix: {}", self.suffix)],
            })
        }
    }

    fn test_context() -> PolicyContext {
        PolicyContext {
            tenant_id: Some("test-tenant".to_string()),
            user_id: Some("test-user".to_string()),
            action: PolicyAction::StartExecution { graph_id: None },
            metadata: HashMap::new(),
        }
    }

    #[test]
    fn test_input_processor_result_should_proceed() {
        assert!(InputProcessorResult::Pass.should_proceed());
        assert!(InputProcessorResult::Modify {
            original: "a".to_string(),
            modified: "b".to_string(),
            changes: vec![],
        }
        .should_proceed());
        assert!(!InputProcessorResult::Block {
            reason: "test".to_string(),
            processor: "test".to_string(),
        }
        .should_proceed());
    }

    #[test]
    fn test_input_processor_result_is_blocked() {
        assert!(!InputProcessorResult::Pass.is_blocked());
        assert!(InputProcessorResult::Block {
            reason: "test".to_string(),
            processor: "test".to_string(),
        }
        .is_blocked());
    }

    #[test]
    fn test_input_processor_result_effective_input() {
        let original = "hello";

        // Pass returns original
        assert_eq!(
            InputProcessorResult::Pass.effective_input(original),
            "hello"
        );

        // Block returns original
        let block = InputProcessorResult::Block {
            reason: "blocked".to_string(),
            processor: "test".to_string(),
        };
        assert_eq!(block.effective_input(original), "hello");

        // Modify returns modified
        let modify = InputProcessorResult::Modify {
            original: "hello".to_string(),
            modified: "hello world".to_string(),
            changes: vec![],
        };
        assert_eq!(modify.effective_input(original), "hello world");
    }

    #[tokio::test]
    async fn test_pipeline_empty() {
        let pipeline = InputProcessorPipeline::new();
        assert!(pipeline.is_empty());
        assert_eq!(pipeline.len(), 0);

        let ctx = test_context();
        let result = pipeline.process("test input", &ctx).await.unwrap();
        assert!(matches!(result, InputProcessorResult::Pass));
    }

    #[tokio::test]
    async fn test_pipeline_pass_through() {
        let pipeline = InputProcessorPipeline::new().add(Arc::new(MockPassProcessor));

        let ctx = test_context();
        let result = pipeline.process("test input", &ctx).await.unwrap();
        assert!(matches!(result, InputProcessorResult::Pass));
    }

    #[tokio::test]
    async fn test_pipeline_block() {
        let pipeline = InputProcessorPipeline::new()
            .add(Arc::new(MockPassProcessor))
            .add(Arc::new(MockBlockProcessor {
                reason: "forbidden".to_string(),
            }));

        let ctx = test_context();
        let result = pipeline.process("test input", &ctx).await.unwrap();

        assert!(result.is_blocked());
        if let InputProcessorResult::Block { reason, processor } = result {
            assert_eq!(reason, "forbidden");
            assert_eq!(processor, "mock-block");
        }
    }

    #[tokio::test]
    async fn test_pipeline_modify() {
        let pipeline = InputProcessorPipeline::new().add(Arc::new(MockModifyProcessor {
            suffix: " [sanitized]".to_string(),
        }));

        let ctx = test_context();
        let result = pipeline.process("test input", &ctx).await.unwrap();

        if let InputProcessorResult::Modify {
            original,
            modified,
            changes,
        } = result
        {
            assert_eq!(original, "test input");
            assert_eq!(modified, "test input [sanitized]");
            assert_eq!(changes.len(), 1);
        } else {
            panic!("Expected Modify result");
        }
    }

    #[tokio::test]
    async fn test_pipeline_chained_modify() {
        let pipeline = InputProcessorPipeline::new()
            .add(Arc::new(MockModifyProcessor {
                suffix: " [a]".to_string(),
            }))
            .add(Arc::new(MockModifyProcessor {
                suffix: " [b]".to_string(),
            }));

        let ctx = test_context();
        let result = pipeline.process("input", &ctx).await.unwrap();

        if let InputProcessorResult::Modify {
            modified, changes, ..
        } = result
        {
            // Both modifications applied in sequence
            assert_eq!(modified, "input [a] [b]");
            assert_eq!(changes.len(), 2);
        } else {
            panic!("Expected Modify result");
        }
    }
}