aa-runtime 0.0.1-alpha.9

Tokio async runtime wrapper and lifecycle management for Agent Assembly
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
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
//! Orchestrator that ties together sliding window, PID lineage, and config.
//!
//! The [`CorrelationEngine`] is the main entry point for the causal correlation
//! subsystem. It is intentionally synchronous — the caller (the Tokio event
//! loop in aa-runtime) handles channel I/O; the engine handles pure logic.

use std::collections::HashSet;

use uuid::Uuid;

use super::config::CorrelationConfig;
use super::event::CorrelationEvent;
use super::outcome::{CausalCorrelation, CorrelationOutcome};
use super::pid::PidLineage;
use super::window::SlidingWindow;

/// Maps a syscall name to an action keyword category.
///
/// Returns the canonical action keyword that corresponds to the given syscall,
/// allowing the correlation algorithm to match an intent's `action_keyword`
/// against an observed syscall. Returns `None` for unknown syscalls.
fn syscall_to_keyword(syscall: &str) -> Option<&'static str> {
    match syscall {
        "unlink" | "unlinkat" | "rmdir" => Some("file_delete"),
        "openat" | "open" | "creat" => Some("file_write"),
        "read" | "readv" | "pread64" => Some("file_read"),
        "rename" | "renameat" | "renameat2" => Some("file_rename"),
        "connect" => Some("network_connect"),
        "sendto" | "sendmsg" | "write" => Some("network_send"),
        "execve" | "execveat" => Some("process_exec"),
        "fork" | "clone" | "clone3" => Some("process_spawn"),
        "kill" | "tkill" | "tgkill" => Some("process_signal"),
        "chmod" | "fchmod" | "fchmodat" => Some("file_permission"),
        "chown" | "fchown" | "fchownat" | "lchown" => Some("file_owner"),
        _ => None,
    }
}

/// The causal correlation engine.
///
/// Ingests intent events (from LLM responses) and action events (from eBPF
/// kernel probes), stores them in a sliding time window, and produces
/// [`CorrelationOutcome`] results by matching intents to actions using PID
/// lineage and configurable time windows.
#[derive(Debug)]
pub struct CorrelationEngine {
    config: CorrelationConfig,
    window: SlidingWindow,
    lineage: PidLineage,
}

impl CorrelationEngine {
    /// Create a new correlation engine with the given configuration.
    pub fn new(config: CorrelationConfig) -> Self {
        let window = SlidingWindow::new(config.window_ms, config.max_window_size);
        Self {
            config,
            window,
            lineage: PidLineage::new(),
        }
    }

    /// Ingest a correlation event into the sliding window.
    ///
    /// This is a synchronous operation — no I/O, just an insertion into the
    /// in-memory window.
    pub fn ingest(&mut self, event: CorrelationEvent) {
        self.window.insert(event);
    }

    /// Run the correlation algorithm over the current window contents.
    ///
    /// For each action, finds the best matching intent by:
    /// 1. Keyword match — the intent's `action_keyword` must equal the syscall's
    ///    canonical keyword (via [`syscall_to_keyword`]).
    /// 2. PID lineage — the intent PID and action PID must belong to the same
    ///    causal group (via [`PidLineage::is_same_family`]).
    /// 3. Temporal ordering — the intent must precede the action.
    ///
    /// Among matching intents, the closest in time is selected (smallest delta).
    /// Correlation strength decays linearly from 1.0 at delta=0 to 0.0 at the
    /// window boundary.
    ///
    /// Returns all correlation outcomes: matched pairs, unexpected actions
    /// (no matching intent), and intents without a subsequent action.
    pub fn correlate(&self) -> Vec<CorrelationOutcome> {
        let intents = self.window.intents();
        let actions = self.window.actions();

        let mut results = Vec::new();
        let mut matched_intent_ids: HashSet<Uuid> = HashSet::new();
        let mut matched_action_ids: HashSet<Uuid> = HashSet::new();

        for action in &actions {
            let action_keyword = match syscall_to_keyword(&action.syscall) {
                Some(kw) => kw,
                None => continue,
            };

            let mut best_intent: Option<(&super::event::IntentEvent, u64)> = None;

            for intent in &intents {
                // Keyword must match.
                if intent.action_keyword != action_keyword {
                    continue;
                }
                // Intent must precede the action.
                if intent.timestamp_ms >= action.timestamp_ms {
                    continue;
                }
                // PIDs must be in the same causal group.
                if !self.lineage.is_same_family(intent.pid, action.pid) {
                    continue;
                }

                let delta = action.timestamp_ms - intent.timestamp_ms;
                match &best_intent {
                    Some((_, best_delta)) if delta >= *best_delta => {}
                    _ => best_intent = Some((intent, delta)),
                }
            }

            if let Some((intent, delta)) = best_intent {
                let strength = 1.0 - (delta as f64 / self.config.window_ms as f64).min(1.0);
                results.push(CorrelationOutcome::Matched(CausalCorrelation {
                    intent_event_id: intent.event_id,
                    action_event_id: action.event_id,
                    correlation_strength: strength,
                    time_delta_ms: delta,
                }));
                matched_intent_ids.insert(intent.event_id);
                matched_action_ids.insert(action.event_id);
            }
        }

        // Actions with no matching intent → UnexpectedAction.
        for action in &actions {
            if syscall_to_keyword(&action.syscall).is_none() {
                continue;
            }
            if !matched_action_ids.contains(&action.event_id) {
                results.push(CorrelationOutcome::UnexpectedAction {
                    action_event_id: action.event_id,
                });
            }
        }

        // Intents with no matching action → IntentWithoutAction.
        for intent in &intents {
            if !matched_intent_ids.contains(&intent.event_id) {
                results.push(CorrelationOutcome::IntentWithoutAction {
                    intent_event_id: intent.event_id,
                });
            }
        }

        results
    }

    /// Evict events older than the configured time window.
    ///
    /// Should be called periodically by the runtime at `config.eviction_interval_ms`.
    pub fn evict(&mut self, now_ms: u64) {
        self.window.evict(now_ms);
    }

    /// Register a PID parent-child relationship for lineage tracking.
    pub fn register_pid(&mut self, child_pid: u32, parent_pid: u32) {
        self.lineage.register(child_pid, parent_pid);
    }

    /// Returns a reference to the current configuration.
    pub fn config(&self) -> &CorrelationConfig {
        &self.config
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::correlation::event::{ActionEvent, IntentEvent};
    use uuid::Uuid;

    #[test]
    fn engine_constructs_with_default_config() {
        let engine = CorrelationEngine::new(CorrelationConfig::default());
        assert_eq!(engine.config().window_ms, 5_000);
    }

    #[test]
    fn ingest_adds_event_to_window() {
        let mut engine = CorrelationEngine::new(CorrelationConfig::default());
        let event = CorrelationEvent::Intent(IntentEvent {
            event_id: Uuid::new_v4(),
            timestamp_ms: 1000,
            pid: 1,
            intent_text: "test".to_string(),
            action_keyword: "test".to_string(),
        });
        engine.ingest(event);
        // Window is not directly accessible, but we can verify no panic occurred
        // and eviction works after ingest.
        engine.evict(2000);
    }

    #[test]
    fn register_pid_does_not_panic() {
        let mut engine = CorrelationEngine::new(CorrelationConfig::default());
        engine.register_pid(100, 1);
        engine.register_pid(200, 100);
    }

    #[test]
    fn evict_on_empty_engine_does_not_panic() {
        let mut engine = CorrelationEngine::new(CorrelationConfig::default());
        engine.evict(10_000);
    }

    #[test]
    fn syscall_to_keyword_maps_file_delete() {
        assert_eq!(syscall_to_keyword("unlink"), Some("file_delete"));
        assert_eq!(syscall_to_keyword("unlinkat"), Some("file_delete"));
        assert_eq!(syscall_to_keyword("rmdir"), Some("file_delete"));
    }

    #[test]
    fn syscall_to_keyword_maps_file_write() {
        assert_eq!(syscall_to_keyword("openat"), Some("file_write"));
        assert_eq!(syscall_to_keyword("open"), Some("file_write"));
        assert_eq!(syscall_to_keyword("creat"), Some("file_write"));
    }

    #[test]
    fn syscall_to_keyword_maps_network() {
        assert_eq!(syscall_to_keyword("connect"), Some("network_connect"));
        assert_eq!(syscall_to_keyword("sendto"), Some("network_send"));
    }

    #[test]
    fn syscall_to_keyword_maps_process() {
        assert_eq!(syscall_to_keyword("execve"), Some("process_exec"));
        assert_eq!(syscall_to_keyword("fork"), Some("process_spawn"));
        assert_eq!(syscall_to_keyword("kill"), Some("process_signal"));
    }

    #[test]
    fn syscall_to_keyword_returns_none_for_unknown() {
        assert_eq!(syscall_to_keyword("unknown_syscall"), None);
    }

    #[test]
    fn correlate_matches_intent_to_action_same_pid() {
        let mut engine = CorrelationEngine::new(CorrelationConfig::default());
        let intent_id = Uuid::new_v4();
        let action_id = Uuid::new_v4();

        engine.ingest(CorrelationEvent::Intent(IntentEvent {
            event_id: intent_id,
            timestamp_ms: 1000,
            pid: 1,
            intent_text: "delete /tmp/foo".to_string(),
            action_keyword: "file_delete".to_string(),
        }));
        engine.ingest(CorrelationEvent::Action(ActionEvent {
            event_id: action_id,
            timestamp_ms: 1500,
            pid: 1,
            syscall: "unlink".to_string(),
            details: "/tmp/foo".to_string(),
        }));

        let outcomes = engine.correlate();
        assert_eq!(outcomes.len(), 1);
        match &outcomes[0] {
            CorrelationOutcome::Matched(c) => {
                assert_eq!(c.intent_event_id, intent_id);
                assert_eq!(c.action_event_id, action_id);
                assert_eq!(c.time_delta_ms, 500);
                assert!(c.correlation_strength > 0.0);
                assert!(c.correlation_strength <= 1.0);
            }
            other => panic!("expected Matched, got {:?}", other),
        }
    }

    #[test]
    fn correlate_matches_intent_to_action_via_pid_lineage() {
        let mut engine = CorrelationEngine::new(CorrelationConfig::default());
        // PID 100 is a child of PID 1.
        engine.register_pid(100, 1);

        let intent_id = Uuid::new_v4();
        let action_id = Uuid::new_v4();

        engine.ingest(CorrelationEvent::Intent(IntentEvent {
            event_id: intent_id,
            timestamp_ms: 1000,
            pid: 1,
            intent_text: "exec /bin/ls".to_string(),
            action_keyword: "process_exec".to_string(),
        }));
        engine.ingest(CorrelationEvent::Action(ActionEvent {
            event_id: action_id,
            timestamp_ms: 1200,
            pid: 100,
            syscall: "execve".to_string(),
            details: "/bin/ls".to_string(),
        }));

        let outcomes = engine.correlate();
        assert_eq!(outcomes.len(), 1);
        assert!(matches!(&outcomes[0], CorrelationOutcome::Matched(c) if c.intent_event_id == intent_id));
    }

    #[test]
    fn correlate_picks_closest_intent() {
        let mut engine = CorrelationEngine::new(CorrelationConfig::default());
        let far_intent_id = Uuid::new_v4();
        let near_intent_id = Uuid::new_v4();
        let action_id = Uuid::new_v4();

        engine.ingest(CorrelationEvent::Intent(IntentEvent {
            event_id: far_intent_id,
            timestamp_ms: 1000,
            pid: 1,
            intent_text: "delete file".to_string(),
            action_keyword: "file_delete".to_string(),
        }));
        engine.ingest(CorrelationEvent::Intent(IntentEvent {
            event_id: near_intent_id,
            timestamp_ms: 1800,
            pid: 1,
            intent_text: "delete file".to_string(),
            action_keyword: "file_delete".to_string(),
        }));
        engine.ingest(CorrelationEvent::Action(ActionEvent {
            event_id: action_id,
            timestamp_ms: 2000,
            pid: 1,
            syscall: "unlink".to_string(),
            details: "/tmp/foo".to_string(),
        }));

        let outcomes = engine.correlate();
        // Should match the near intent (delta=200) not the far one (delta=1000).
        let matched: Vec<_> = outcomes
            .iter()
            .filter(|o| matches!(o, CorrelationOutcome::Matched(_)))
            .collect();
        assert_eq!(matched.len(), 1);
        match &matched[0] {
            CorrelationOutcome::Matched(c) => {
                assert_eq!(c.intent_event_id, near_intent_id);
                assert_eq!(c.time_delta_ms, 200);
            }
            _ => unreachable!(),
        }
    }

    #[test]
    fn correlate_strength_decays_with_time_delta() {
        let mut engine = CorrelationEngine::new(CorrelationConfig::default());

        engine.ingest(CorrelationEvent::Intent(IntentEvent {
            event_id: Uuid::new_v4(),
            timestamp_ms: 1000,
            pid: 1,
            intent_text: "delete".to_string(),
            action_keyword: "file_delete".to_string(),
        }));
        engine.ingest(CorrelationEvent::Action(ActionEvent {
            event_id: Uuid::new_v4(),
            timestamp_ms: 3500, // delta = 2500, window = 5000 → strength = 0.5
            pid: 1,
            syscall: "unlink".to_string(),
            details: "/tmp/foo".to_string(),
        }));

        let outcomes = engine.correlate();
        match &outcomes[0] {
            CorrelationOutcome::Matched(c) => {
                assert!((c.correlation_strength - 0.5).abs() < 0.01);
            }
            other => panic!("expected Matched, got {:?}", other),
        }
    }

    #[test]
    fn correlate_unexpected_action_when_no_intent() {
        let mut engine = CorrelationEngine::new(CorrelationConfig::default());
        let action_id = Uuid::new_v4();

        // Action with no preceding intent.
        engine.ingest(CorrelationEvent::Action(ActionEvent {
            event_id: action_id,
            timestamp_ms: 1000,
            pid: 1,
            syscall: "unlink".to_string(),
            details: "/tmp/foo".to_string(),
        }));

        let outcomes = engine.correlate();
        assert_eq!(outcomes.len(), 1);
        match &outcomes[0] {
            CorrelationOutcome::UnexpectedAction { action_event_id } => {
                assert_eq!(*action_event_id, action_id);
            }
            other => panic!("expected UnexpectedAction, got {:?}", other),
        }
    }

    #[test]
    fn correlate_unexpected_action_when_keyword_mismatch() {
        let mut engine = CorrelationEngine::new(CorrelationConfig::default());
        let action_id = Uuid::new_v4();

        // Intent for file_delete, but action is process_exec.
        engine.ingest(CorrelationEvent::Intent(IntentEvent {
            event_id: Uuid::new_v4(),
            timestamp_ms: 1000,
            pid: 1,
            intent_text: "delete file".to_string(),
            action_keyword: "file_delete".to_string(),
        }));
        engine.ingest(CorrelationEvent::Action(ActionEvent {
            event_id: action_id,
            timestamp_ms: 1500,
            pid: 1,
            syscall: "execve".to_string(),
            details: "/bin/sh".to_string(),
        }));

        let outcomes = engine.correlate();
        let unexpected: Vec<_> = outcomes
            .iter()
            .filter(|o| matches!(o, CorrelationOutcome::UnexpectedAction { .. }))
            .collect();
        assert_eq!(unexpected.len(), 1);
        match &unexpected[0] {
            CorrelationOutcome::UnexpectedAction { action_event_id } => {
                assert_eq!(*action_event_id, action_id);
            }
            _ => unreachable!(),
        }
    }

    #[test]
    fn correlate_unexpected_action_when_different_pid_family() {
        let mut engine = CorrelationEngine::new(CorrelationConfig::default());
        let action_id = Uuid::new_v4();

        // Intent from PID 1, action from PID 2 (unrelated).
        engine.ingest(CorrelationEvent::Intent(IntentEvent {
            event_id: Uuid::new_v4(),
            timestamp_ms: 1000,
            pid: 1,
            intent_text: "delete file".to_string(),
            action_keyword: "file_delete".to_string(),
        }));
        engine.ingest(CorrelationEvent::Action(ActionEvent {
            event_id: action_id,
            timestamp_ms: 1500,
            pid: 2,
            syscall: "unlink".to_string(),
            details: "/tmp/foo".to_string(),
        }));

        let outcomes = engine.correlate();
        let unexpected: Vec<_> = outcomes
            .iter()
            .filter(|o| matches!(o, CorrelationOutcome::UnexpectedAction { .. }))
            .collect();
        assert_eq!(unexpected.len(), 1);
    }

    #[test]
    fn correlate_intent_without_action_when_no_action() {
        let mut engine = CorrelationEngine::new(CorrelationConfig::default());
        let intent_id = Uuid::new_v4();

        // Intent with no subsequent action.
        engine.ingest(CorrelationEvent::Intent(IntentEvent {
            event_id: intent_id,
            timestamp_ms: 1000,
            pid: 1,
            intent_text: "delete file".to_string(),
            action_keyword: "file_delete".to_string(),
        }));

        let outcomes = engine.correlate();
        assert_eq!(outcomes.len(), 1);
        match &outcomes[0] {
            CorrelationOutcome::IntentWithoutAction { intent_event_id } => {
                assert_eq!(*intent_event_id, intent_id);
            }
            other => panic!("expected IntentWithoutAction, got {:?}", other),
        }
    }

    #[test]
    fn correlate_intent_without_action_when_action_precedes_intent() {
        let mut engine = CorrelationEngine::new(CorrelationConfig::default());
        let intent_id = Uuid::new_v4();

        // Action at t=1000, intent at t=2000 — action happened before intent.
        engine.ingest(CorrelationEvent::Action(ActionEvent {
            event_id: Uuid::new_v4(),
            timestamp_ms: 1000,
            pid: 1,
            syscall: "unlink".to_string(),
            details: "/tmp/foo".to_string(),
        }));
        engine.ingest(CorrelationEvent::Intent(IntentEvent {
            event_id: intent_id,
            timestamp_ms: 2000,
            pid: 1,
            intent_text: "delete file".to_string(),
            action_keyword: "file_delete".to_string(),
        }));

        let outcomes = engine.correlate();
        let intent_without: Vec<_> = outcomes
            .iter()
            .filter(|o| matches!(o, CorrelationOutcome::IntentWithoutAction { .. }))
            .collect();
        assert_eq!(intent_without.len(), 1);
        match &intent_without[0] {
            CorrelationOutcome::IntentWithoutAction { intent_event_id } => {
                assert_eq!(*intent_event_id, intent_id);
            }
            _ => unreachable!(),
        }
    }

    #[test]
    fn correlate_empty_window_returns_empty() {
        let engine = CorrelationEngine::new(CorrelationConfig::default());
        assert!(engine.correlate().is_empty());
    }

    #[test]
    fn eviction_removes_intent_preventing_match() {
        let mut engine = CorrelationEngine::new(CorrelationConfig::default());

        // Intent at t=1000.
        engine.ingest(CorrelationEvent::Intent(IntentEvent {
            event_id: Uuid::new_v4(),
            timestamp_ms: 1000,
            pid: 1,
            intent_text: "delete file".to_string(),
            action_keyword: "file_delete".to_string(),
        }));

        // Action at t=7000 (within window of 5000 from now=7000, but intent at
        // t=1000 is outside the window).
        let action_id = Uuid::new_v4();
        engine.ingest(CorrelationEvent::Action(ActionEvent {
            event_id: action_id,
            timestamp_ms: 7000,
            pid: 1,
            syscall: "unlink".to_string(),
            details: "/tmp/foo".to_string(),
        }));

        // Evict with now=7000 → cutoff=2000 → intent at 1000 is evicted.
        engine.evict(7000);

        let outcomes = engine.correlate();
        // Intent was evicted, so action is unexpected.
        let unexpected: Vec<_> = outcomes
            .iter()
            .filter(|o| matches!(o, CorrelationOutcome::UnexpectedAction { .. }))
            .collect();
        assert_eq!(unexpected.len(), 1);
        // No matched outcomes.
        let matched: Vec<_> = outcomes
            .iter()
            .filter(|o| matches!(o, CorrelationOutcome::Matched(_)))
            .collect();
        assert!(matched.is_empty());
    }
}