oxios-kernel 1.23.0

Oxios kernel: supervisor, event bus, state store
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
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
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
//! Integration tests for the Oxios kernel.
//!
//! Tests the main kernel components using mock implementations:
//! - Orchestrator with mock OuroborosProtocol and mock Supervisor
//! - StateStore markdown/JSON read/write
//! - EventBus publish/subscribe
//! - Gateway routing with mock channel

#[path = "common/mod.rs"]
mod common;

use std::collections::HashMap;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};

use async_trait::async_trait;

use oxios_gateway::channel::Channel;
use oxios_gateway::gateway::Gateway;
use oxios_gateway::message::{IncomingMessage, OutgoingMessage};
use oxios_kernel::a2a::A2AProtocol;
use oxios_kernel::access_manager::{AccessManager, AgentPermissions};
use oxios_kernel::agent_lifecycle::AgentLifecycleManager;
use oxios_kernel::config::OrchestratorConfig;
use oxios_kernel::event_bus::{EventBus, KernelEvent};
use oxios_kernel::orchestrator::Orchestrator;
use oxios_kernel::state_store::StateStore;
use oxios_kernel::supervisor::Supervisor;
use oxios_ouroboros::{Directive, ExecEnv, ExecutionResult};

use oxios_kernel::types::{AgentId, AgentInfo, AgentStatus};

// ---------------------------------------------------------------------------
// Mock Supervisor
// ---------------------------------------------------------------------------

/// Mock supervisor that tracks agent creation without actually running agents.
struct MockSupervisor {
    agents: parking_lot::RwLock<HashMap<AgentId, AgentInfo>>,
    fork_called: AtomicUsize,
    run_called: AtomicUsize,
    event_bus: EventBus,
}

impl MockSupervisor {
    fn new(event_bus: EventBus) -> Self {
        Self {
            agents: parking_lot::RwLock::new(HashMap::new()),
            fork_called: AtomicUsize::new(0),
            run_called: AtomicUsize::new(0),
            event_bus,
        }
    }
}

#[async_trait]
impl Supervisor for MockSupervisor {
    async fn exec(&self, id: AgentId) -> anyhow::Result<()> {
        let mut agents = self.agents.write();
        match agents.get_mut(&id) {
            Some(a) => a.status = AgentStatus::Running,
            None => anyhow::bail!("Agent {id} not found"),
        }
        Ok(())
    }

    async fn fork_directive(
        &self,
        directive: &Directive,
        _env: &ExecEnv,
    ) -> anyhow::Result<AgentId> {
        self.fork_called.fetch_add(1, Ordering::SeqCst);
        let id = AgentId::new_v4();
        let info = AgentInfo {
            id,
            name: directive.goal.clone(),
            status: AgentStatus::Starting,
            created_at: chrono::Utc::now(),
            project_id: None,
            started_at: None,
            completed_at: None,
            error: None,
            steps_completed: 0,
            steps_total: None,
            tool_calls: vec![],
            tokens_input: 0,
            tokens_output: 0,
            cost_usd: 0.0,
            model_id: String::new(),
            session_id: None,
        };
        {
            let mut agents = self.agents.write();
            agents.insert(id, info);
        }
        let _ = self.event_bus.publish(KernelEvent::AgentCreated {
            id,
            name: directive.goal.clone(),
        });
        Ok(id)
    }

    async fn run_with_directive(
        &self,
        id: AgentId,
        _directive: &Directive,
        _env: &ExecEnv,
    ) -> anyhow::Result<ExecutionResult> {
        self.run_called.fetch_add(1, Ordering::SeqCst);
        {
            let mut agents = self.agents.write();
            if let Some(a) = agents.get_mut(&id) {
                a.status = AgentStatus::Idle;
            }
        }
        let _ = self.event_bus.publish(KernelEvent::AgentStarted { id });
        let _ = self
            .event_bus
            .publish(KernelEvent::AgentStopped { id, success: true });
        Ok(ExecutionResult {
            output: "Mock agent completed".into(),
            steps_completed: 3,
            success: true,
            tool_calls: vec![],
            tokens_input: 0,
            tokens_output: 0,
            model_id: String::new(),
            failure_class: None,
            restore_state: None,
            reasoning_text: String::new(),
        })
    }

    async fn wait(&self, id: AgentId) -> anyhow::Result<AgentStatus> {
        let agents = self.agents.read();
        match agents.get(&id) {
            Some(a) => Ok(a.status),
            None => anyhow::bail!("Agent {id} not found"),
        }
    }

    async fn kill(&self, id: AgentId) -> anyhow::Result<()> {
        let mut agents = self.agents.write();
        if let Some(a) = agents.get_mut(&id) {
            a.status = AgentStatus::Stopped;
        }
        Ok(())
    }

    async fn list(&self) -> anyhow::Result<Vec<AgentInfo>> {
        let agents = self.agents.read();
        Ok(agents.values().cloned().collect())
    }
}

// ---------------------------------------------------------------------------
// Mock Channel
// ---------------------------------------------------------------------------

/// Mock channel that captures outgoing messages for verification.
struct MockChannel {
    outgoing: tokio::sync::Mutex<Vec<OutgoingMessage>>,
    incoming_rx: tokio::sync::Mutex<Option<tokio::sync::mpsc::Receiver<IncomingMessage>>>,
}

impl MockChannel {
    fn new(buffer: usize) -> Self {
        let (_tx, rx) = tokio::sync::mpsc::channel(buffer);
        Self {
            outgoing: tokio::sync::Mutex::new(Vec::new()),
            incoming_rx: tokio::sync::Mutex::new(Some(rx)),
        }
    }
}

#[async_trait]
impl Channel for MockChannel {
    fn name(&self) -> &str {
        "mock"
    }

    async fn start(
        &self,
        _tx: tokio::sync::mpsc::Sender<oxios_gateway::GatewayInbox>,
        mut shutdown: tokio::sync::watch::Receiver<bool>,
    ) -> anyhow::Result<tokio::task::JoinHandle<()>> {
        // Take the receiver so it can't be started twice.
        self.incoming_rx.lock().await.take();
        let handle = tokio::spawn(async move {
            // Just wait for shutdown.
            let _ = shutdown.changed().await;
        });
        Ok(handle)
    }

    async fn send(&self, msg: OutgoingMessage) -> anyhow::Result<()> {
        self.outgoing.lock().await.push(msg);
        Ok(())
    }
}

// ===========================================================================
// Tests
// ===========================================================================

// --- EventBus tests ---

#[tokio::test]
async fn test_event_bus_publish_subscribe() {
    let bus = EventBus::new(16);
    let mut rx = bus.subscribe();

    bus.publish(KernelEvent::AgentCreated {
        id: uuid::Uuid::new_v4(),
        name: "test-agent".into(),
    })
    .unwrap();

    let event = rx.recv().await.unwrap();
    match event {
        KernelEvent::AgentCreated { .. } => {}
        other => panic!("Expected AgentCreated, got {other:?}"),
    }
}

#[tokio::test]
async fn test_event_bus_multiple_subscribers() {
    let bus = EventBus::new(16);
    let mut rx1 = bus.subscribe();
    let mut rx2 = bus.subscribe();

    bus.publish(KernelEvent::AgentCreated {
        id: uuid::Uuid::new_v4(),
        name: "test-agent".into(),
    })
    .unwrap();

    let e1 = rx1.recv().await.unwrap();
    let e2 = rx2.recv().await.unwrap();

    assert!(matches!(e1, KernelEvent::AgentCreated { .. }));
    assert!(matches!(e2, KernelEvent::AgentCreated { .. }));
}

#[tokio::test]
async fn test_event_bus_no_subscribers_ok() {
    let bus = EventBus::new(16);
    // Should not panic when publishing with no subscribers.
    bus.publish(KernelEvent::AgentCreated {
        id: uuid::Uuid::new_v4(),
        name: "test-agent".into(),
    })
    .unwrap();
}

// --- StateStore tests ---

#[tokio::test]
async fn test_state_store_save_load_markdown() {
    let tmp = common::setup_tempdir();
    let store = StateStore::new(tmp.path().to_path_buf()).unwrap();

    store
        .save_markdown("memory", "test-note", "Hello, world!")
        .await
        .unwrap();

    let loaded = store.load_markdown("memory", "test-note").await.unwrap();
    assert_eq!(loaded, Some("Hello, world!".to_string()));
}

#[tokio::test]
async fn test_state_store_load_nonexistent() {
    let tmp = common::setup_tempdir();
    let store = StateStore::new(tmp.path().to_path_buf()).unwrap();

    let loaded = store.load_markdown("memory", "nope").await.unwrap();
    assert_eq!(loaded, None);
}

#[tokio::test]
async fn test_state_store_list_category() {
    let tmp = common::setup_tempdir();
    let store = StateStore::new(tmp.path().to_path_buf()).unwrap();

    store
        .save_markdown("notes", "alpha", "alpha content")
        .await
        .unwrap();
    store
        .save_markdown("notes", "beta", "beta content")
        .await
        .unwrap();

    let names = store.list_category("notes").await.unwrap();
    assert_eq!(names, vec!["alpha", "beta"]);
}

#[tokio::test]
async fn test_state_store_save_load_json() {
    let tmp = common::setup_tempdir();
    let store = StateStore::new(tmp.path().to_path_buf()).unwrap();

    let data = serde_json::json!({
        "name": "test",
        "value": 42
    });

    store.save_json("config", "test", &data).await.unwrap();
    let loaded: Option<serde_json::Value> = store.load_json("config", "test").await.unwrap();
    assert_eq!(loaded, Some(data));
}

#[tokio::test]
async fn test_state_store_path_traversal_blocked() {
    let tmp = common::setup_tempdir();
    let store = StateStore::new(tmp.path().to_path_buf()).unwrap();

    // Category traversal should be blocked.
    let result = store.save_markdown("../etc", "shadow", "hacked").await;
    assert!(result.is_err());

    // Name traversal should be blocked.
    let result = store.save_markdown("memory", "../shadow", "hacked").await;
    assert!(result.is_err());

    // Slash in category is allowed (sub-directory categories like memory/knowledge).
    let result = store.save_markdown("foo/bar", "test", "content").await;
    assert!(result.is_ok());

    // Backslash should be blocked.
    let result = store.save_markdown("foo\\bar", "test", "content").await;
    assert!(result.is_err());

    // Empty category should be blocked.
    let result = store.save_markdown("", "test", "content").await;
    assert!(result.is_err());

    // Leading slash should be blocked.
    let result = store.save_markdown("/foo", "test", "content").await;
    assert!(result.is_err());

    // Trailing slash should be blocked.
    let result = store.save_markdown("foo/", "test", "content").await;
    assert!(result.is_err());

    // Double slash should be blocked.
    let result = store.save_markdown("foo//bar", "test", "content").await;
    assert!(result.is_err());
}

fn make_evolution_config(max_iterations: u32) -> OrchestratorConfig {
    OrchestratorConfig {
        max_evolution_iterations: max_iterations,
        min_evaluation_score: 0.8,
    }
}

// --- Orchestrator tests ---

#[tokio::test]
async fn test_orchestrator_happy_path() {
    let supervisor = Arc::new(MockSupervisor::new(EventBus::new(64)));
    let event_bus = EventBus::new(64);
    let tmp = common::setup_tempdir();
    let state_store = Arc::new(StateStore::new(tmp.path().to_path_buf()).unwrap());

    let (orchestrator, _mock) =
        common::build_test_orchestrator(supervisor.clone(), state_store, event_bus);

    let result = orchestrator
        .handle_unified(
            "test-user",
            "Do something useful",
            None,
            None,
            None,
            None, // RFC-032: role
            None, // model_override
            "test-req",
        )
        .await
        .unwrap();

    assert!(result.session_id.is_some());
    assert_eq!(result.phase_reached, "execute");
    assert_eq!(result.evaluation_passed, None);
    assert!(!result.response.is_empty());

    // Verify supervisor was called.
    assert_eq!(supervisor.fork_called.load(Ordering::SeqCst), 1);
    assert_eq!(supervisor.run_called.load(Ordering::SeqCst), 1);
}

#[tokio::test]
async fn test_orchestrator_events_published() {
    let event_bus = EventBus::new(64);
    let mut rx = event_bus.subscribe();
    let tmp = common::setup_tempdir();
    let state_store = Arc::new(StateStore::new(tmp.path().to_path_buf()).unwrap());

    let supervisor = Arc::new(MockSupervisor::new(event_bus.clone()));
    let (orchestrator, _mock) =
        common::build_test_orchestrator(supervisor, state_store, event_bus.clone());

    // Run orchestration in background.
    let handle = tokio::spawn(async move {
        orchestrator
            .handle_unified(
                "test-user",
                "Check events",
                None,
                None,
                None,
                None, // RFC-032: role
                None, // model_override
                "test-req",
            )
            .await
    });

    // Collect events with timeout.
    let mut agent_events = 0;
    let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(5);

    loop {
        let evt = tokio::select! {
            evt = rx.recv() => evt.unwrap(),
            _ = tokio::time::sleep_until(deadline) => break,
        };
        match evt {
            KernelEvent::AgentCreated { .. }
            | KernelEvent::AgentStarted { .. }
            | KernelEvent::AgentStopped { .. } => {
                agent_events += 1;
            }
            _ => {}
        }
        if agent_events >= 2 {
            break;
        }
    }

    // Should have at least AgentCreated + AgentStarted + AgentStopped events.
    assert!(
        agent_events >= 2,
        "Expected at least 2 agent events, got {agent_events}"
    );

    // Ensure the orchestration completed.
    let _ = handle.await.unwrap();
}

// --- Gateway routing test ---

#[tokio::test]
async fn test_gateway_routes_message_through_orchestrator() {
    let event_bus = EventBus::new(64);
    let tmp = common::setup_tempdir();
    let state_store = Arc::new(StateStore::new(tmp.path().to_path_buf()).unwrap());

    let supervisor = Arc::new(MockSupervisor::new(event_bus.clone()));

    let a2a = Arc::new(A2AProtocol::new(event_bus.clone()));
    let access_manager = Arc::new(parking_lot::Mutex::new(AccessManager::new()));
    let orchestrator = Arc::new({
        let lifecycle = AgentLifecycleManager::new(
            supervisor,
            access_manager.clone(),
            a2a.clone(),
            event_bus.clone(),
            300,
            vec![],
            true,
            "/tmp/oxios-test-workspace".to_string(),
        );
        Orchestrator::with_config(
            event_bus.clone(),
            state_store,
            lifecycle,
            make_evolution_config(0),
        )
    });

    let gateway = Gateway::new(orchestrator);
    let mock_channel = Box::new(MockChannel::new(16));

    // Register the mock channel (start() will be called internally).
    gateway.register(mock_channel).await.unwrap();
    assert_eq!(gateway.channel_names().await, vec!["mock"]);

    // Test that channel registration works and the gateway can send_to.
    let outgoing = OutgoingMessage::new("mock", "test-user", "Hello from gateway");
    let result = gateway.send_to("mock", outgoing).await;
    assert!(result.is_ok());

    // Clean shutdown.
    gateway.signal_shutdown();
}

#[tokio::test]
async fn test_gateway_unknown_channel() {
    let event_bus = EventBus::new(64);
    let tmp = common::setup_tempdir();
    let state_store = Arc::new(StateStore::new(tmp.path().to_path_buf()).unwrap());

    let supervisor = Arc::new(MockSupervisor::new(event_bus.clone()));

    let a2a = Arc::new(A2AProtocol::new(event_bus.clone()));
    let access_manager = Arc::new(parking_lot::Mutex::new(AccessManager::new()));
    let orchestrator = Arc::new({
        let lifecycle = AgentLifecycleManager::new(
            supervisor,
            access_manager.clone(),
            a2a.clone(),
            event_bus.clone(),
            300,
            vec![],
            true,
            "/tmp/oxios-test-workspace".to_string(),
        );
        Orchestrator::with_config(
            event_bus.clone(),
            state_store,
            lifecycle,
            make_evolution_config(0),
        )
    });

    let gateway = Gateway::new(orchestrator);

    // Sending to a non-existent channel should succeed (logged as warning).
    let outgoing = OutgoingMessage::new("nonexistent", "test-user", "Test");
    let result = gateway.send_to("nonexistent", outgoing).await;
    // send_to succeeds even if channel doesn't exist — just logs a warning.
    assert!(result.is_ok());
}

// ===========================================================================
// Orchestrator Integration
// ===========================================================================

use std::sync::atomic::AtomicU32;

/// Mock supervisor with agent tracking for orchestrator integration tests.
struct TrackingSupervisor {
    agents: parking_lot::RwLock<HashMap<AgentId, AgentInfo>>,
    event_bus: EventBus,
    runs: AtomicU32,
}

impl TrackingSupervisor {
    fn new(event_bus: EventBus) -> Self {
        Self {
            agents: parking_lot::RwLock::new(HashMap::new()),
            event_bus,
            runs: AtomicU32::new(0),
        }
    }
}

#[async_trait]
impl Supervisor for TrackingSupervisor {
    async fn exec(&self, id: AgentId) -> anyhow::Result<()> {
        let mut agents = self.agents.write();
        if let Some(a) = agents.get_mut(&id) {
            a.status = AgentStatus::Running;
        }
        Ok(())
    }

    async fn fork_directive(
        &self,
        directive: &Directive,
        _env: &ExecEnv,
    ) -> anyhow::Result<AgentId> {
        let id = AgentId::new_v4();
        let info = AgentInfo {
            id,
            name: directive.goal.clone(),
            status: AgentStatus::Starting,
            created_at: chrono::Utc::now(),
            project_id: None,
            started_at: None,
            completed_at: None,
            error: None,
            steps_completed: 0,
            steps_total: None,
            tool_calls: vec![],
            tokens_input: 0,
            tokens_output: 0,
            cost_usd: 0.0,
            model_id: String::new(),
            session_id: None,
        };
        {
            let mut agents = self.agents.write();
            agents.insert(id, info);
        }
        let _ = self.event_bus.publish(KernelEvent::AgentCreated {
            id,
            name: directive.goal.clone(),
        });
        Ok(id)
    }

    async fn run_with_directive(
        &self,
        id: AgentId,
        _directive: &Directive,
        _env: &ExecEnv,
    ) -> anyhow::Result<ExecutionResult> {
        self.runs.fetch_add(1, Ordering::SeqCst);

        {
            let mut agents = self.agents.write();
            if let Some(a) = agents.get_mut(&id) {
                a.status = AgentStatus::Idle;
            }
        }
        let _ = self.event_bus.publish(KernelEvent::AgentStarted { id });
        let _ = self
            .event_bus
            .publish(KernelEvent::AgentStopped { id, success: true });
        Ok(ExecutionResult {
            output: "Task completed".into(),
            steps_completed: 1,
            success: true,
            tool_calls: vec![],
            tokens_input: 0,
            tokens_output: 0,
            model_id: String::new(),
            failure_class: None,
            restore_state: None,
            reasoning_text: String::new(),
        })
    }

    async fn wait(&self, id: AgentId) -> anyhow::Result<AgentStatus> {
        let agents = self.agents.read();
        match agents.get(&id) {
            Some(a) => Ok(a.status),
            None => anyhow::bail!("Agent {id} not found"),
        }
    }

    async fn kill(&self, id: AgentId) -> anyhow::Result<()> {
        let mut agents = self.agents.write();
        if let Some(a) = agents.get_mut(&id) {
            a.status = AgentStatus::Stopped;
        }
        Ok(())
    }

    async fn list(&self) -> anyhow::Result<Vec<AgentInfo>> {
        let agents = self.agents.read();
        Ok(agents.values().cloned().collect())
    }
}

#[tokio::test]
async fn test_orchestrator_routes_to_supervisor() {
    let event_bus = EventBus::new(64);
    let tmp = common::setup_tempdir();
    let state_store = Arc::new(StateStore::new(tmp.path().to_path_buf()).unwrap());

    let supervisor = Arc::new(TrackingSupervisor::new(event_bus.clone()));

    let (orchestrator, _mock) =
        common::build_test_orchestrator(supervisor, state_store, event_bus.clone());

    let result = orchestrator
        .handle_unified(
            "test-user",
            "Build a simple thing",
            None,
            None,
            None,
            None, // RFC-032: role
            None, // model_override
            "test-req",
        )
        .await
        .unwrap();

    assert!(result.session_id.is_some());
    assert_eq!(result.phase_reached, "execute");
}

// ===========================================================================
// Access Manager Enforcing Permissions
// ===========================================================================

#[tokio::test]
async fn test_access_manager_blocks_dangerous_tools() {
    let mut access = AccessManager::new();

    // Create a restrictive permission set (no dangerous tools).
    let mut perms = AgentPermissions::for_new_agent("safe-agent");
    perms.allowed_tools.clear(); // Start with nothing.
    perms.allow_tool("read"); // Only safe tools.
    perms.allow_tool("grep");
    access.set_permissions(perms);

    // Verify dangerous tools are blocked.
    assert!(!access.can_use_tool("safe-agent", "bash")); // bash not allowed.
    assert!(!access.can_use_tool("safe-agent", "rm")); // rm not allowed.
    assert!(!access.can_use_tool("safe-agent", "sudo")); // sudo not allowed.
    assert!(access.can_use_tool("safe-agent", "read")); // read is allowed.
    assert!(access.can_use_tool("safe-agent", "grep")); // grep is allowed.

    // Unknown agent gets no tools.
    assert!(!access.can_use_tool("unknown-agent", "read"));
}

#[tokio::test]
async fn test_access_manager_enforces_path_restrictions() {
    let mut access = AccessManager::new();

    let mut perms = AgentPermissions::for_new_agent("file-agent");
    perms.allowed_paths = vec![
        "/workspace/**".to_string(),
        "/home/user/projects/**".to_string(),
    ];
    perms.denied_paths = vec![
        "/workspace/secrets/**".to_string(),
        "/workspace/.oxios/**".to_string(),
    ];
    access.set_permissions(perms);

    // Allowed paths.
    assert!(access.can_access_path("file-agent", "/workspace/file.txt"));
    assert!(access.can_access_path("file-agent", "/workspace/subdir/code.rs"));
    assert!(access.can_access_path("file-agent", "/home/user/projects/app/main.rs"));

    // Blocked: outside allowed paths.
    assert!(!access.can_access_path("file-agent", "/etc/passwd"));
    assert!(!access.can_access_path("file-agent", "/root/.ssh/id_rsa"));

    // Blocked: denied pattern matches.
    assert!(!access.can_access_path("file-agent", "/workspace/secrets/api-key.txt"));
    assert!(!access.can_access_path("file-agent", "/workspace/.oxios/config.toml"));
}

#[tokio::test]
async fn test_access_manager_audit_log_on_denied_access() {
    let mut access = AccessManager::new();

    let perms = AgentPermissions::for_new_agent("audited-agent");
    access.set_permissions(perms);

    // Attempt denied operations.
    access.can_use_tool("audited-agent", "network"); // not in allowed set.
    access.can_access_path("audited-agent", "/etc/shadow"); // path not allowed.

    let log = access.audit_log();
    assert_eq!(log.len(), 2);

    // Both should be marked as denied.
    assert!(!log[0].allowed);
    assert!(!log[1].allowed);

    // Check reason is recorded.
    assert!(log[0].reason.is_some());
    assert!(log[1].reason.is_some());

    // Check denied_actions filter.
    let denied = access.denied_actions();
    assert_eq!(denied.len(), 2);
}

#[tokio::test]
async fn test_access_manager_network_and_fork_permissions() {
    let mut access = AccessManager::new();

    // Agent with network but no fork.
    let mut perms = AgentPermissions::for_new_agent("web-agent");
    perms.enable_network();
    // can_fork stays false by default.
    access.set_permissions(perms);

    assert!(access.can_access_network("web-agent"));
    assert!(!access.can_fork("web-agent"));

    // Agent with fork but no network.
    let mut perms2 = AgentPermissions::for_new_agent("fork-agent");
    perms2.enable_forking();
    // network_access stays false.
    access.set_permissions(perms2);

    assert!(!access.can_access_network("fork-agent"));
    assert!(access.can_fork("fork-agent"));

    // Agent with execution time and memory limits.
    let mut perms3 = AgentPermissions::for_new_agent("limited-agent");
    perms3.max_execution_time_secs = 60;
    perms3.max_memory_mb = 256;
    access.set_permissions(perms3);

    assert!(access.can_execute_for("limited-agent", 30));
    assert!(access.can_execute_for("limited-agent", 60));
    assert!(!access.can_execute_for("limited-agent", 61));
    assert!(access.can_use_memory("limited-agent", 128));
    assert!(!access.can_use_memory("limited-agent", 257));
}

#[tokio::test]
async fn test_access_manager_permission_lifecycle() {
    let mut access = AccessManager::new();

    // Create permissions.
    access.set_permissions(AgentPermissions::for_new_agent("lifecycle-agent"));

    // Check agent is listed.
    assert!(
        access
            .list_agents()
            .contains(&"lifecycle-agent".to_string())
    );

    // Grant a tool.
    let perms = access.get_or_create_permissions("lifecycle-agent");
    perms.allow_tool("custom-tool");

    // Verify tool is now allowed.
    assert!(access.can_use_tool("lifecycle-agent", "custom-tool"));

    // Remove permissions.
    access.remove_permissions("lifecycle-agent");

    // Agent no longer listed.
    assert!(
        !access
            .list_agents()
            .contains(&"lifecycle-agent".to_string())
    );

    // All access denied for removed agent.
    assert!(!access.can_use_tool("lifecycle-agent", "custom-tool"));
    assert!(!access.can_access_path("lifecycle-agent", "/workspace/test.txt"));
    assert!(!access.can_access_network("lifecycle-agent"));
}