Skip to main content

oxios_kernel/
supervisor.rs

1//! Supervisor: agent lifecycle management.
2//!
3//! The supervisor handles forking, executing, monitoring, and
4//! terminating agent instances. It is the "init" of Oxios.
5//!
6//! When an agent is forked and executed, the supervisor delegates
7//! the actual tool-calling loop to the [`AgentRuntime`].
8//!
9//! # Agent Pool & Session Persistence
10//!
11//! Agents are retained in an [`AgentPool`] after execution for:
12//! - **Session continuation** via `Agent::continue_with()` — multi-turn
13//!   conversations without re-creating the agent.
14//! - **State export/import** — serialize agent conversation history to
15//!   JSON for crash recovery, migration, or debugging.
16//! - **Provider rate limiting** — all agents share a [`ProviderPool`] to
17//!   respect per-provider RPM/concurrency limits.
18
19use anyhow::Result;
20use async_trait::async_trait;
21use chrono::Utc;
22use oxi_sdk::Agent;
23use oxios_ouroboros::{Directive, ExecEnv};
24use parking_lot::RwLock;
25use std::collections::HashMap;
26use std::sync::Arc;
27use std::sync::atomic::{AtomicBool, Ordering};
28use tokio::task::JoinHandle;
29
30use crate::agent_runtime::AgentRuntime;
31use crate::config::AgentLogConfig;
32use crate::event_bus::EventBus;
33use crate::resilience::classify;
34use crate::resource_monitor::ResourceMonitor;
35use crate::session_context::SessionContext;
36use crate::state_store::StateStore;
37use crate::types::{AgentId, AgentInfo, AgentStatus};
38
39use oxios_ouroboros::ExecutionResult;
40
41#[cfg(feature = "sqlite-memory")]
42use crate::agent_log_db::AgentLogDb;
43
44/// Tracks the runtime handles needed to cancel a running agent.
45struct AgentHandle {
46    /// Flag set on `kill()` to cooperatively signal cancellation.
47    cancelled: Arc<AtomicBool>,
48    /// The tokio task running the agent execution. Aborted on `kill()`.
49    task: JoinHandle<()>,
50}
51
52/// Pool of live `Agent` instances, keyed by AgentId.
53///
54/// Retains agents after execution for:
55/// - **State persistence** — `export_state()` serializes conversation history
56///   to JSON for crash recovery, migration, or debugging.
57/// - **State restoration** — `import_state()` restores a previous session.
58#[derive(Default)]
59pub struct AgentPool {
60    agents: RwLock<HashMap<AgentId, Arc<Agent>>>,
61}
62
63impl AgentPool {
64    /// Create an empty agent pool.
65    pub fn new() -> Self {
66        Self {
67            agents: RwLock::new(HashMap::new()),
68        }
69    }
70
71    /// Insert an agent into the pool.
72    pub fn insert(&self, id: AgentId, agent: Arc<Agent>) {
73        self.agents.write().insert(id, agent);
74    }
75
76    /// Get a pooled agent by ID.
77    pub fn get(&self, id: &AgentId) -> Option<Arc<Agent>> {
78        self.agents.read().get(id).cloned()
79    }
80
81    /// Remove an agent from the pool.
82    pub fn remove(&self, id: &AgentId) -> Option<Arc<Agent>> {
83        self.agents.write().remove(id)
84    }
85
86    /// Export an agent's state as JSON.
87    ///
88    /// Returns `None` if the agent is not in the pool or export fails.
89    pub fn export_state(&self, id: &AgentId) -> Option<serde_json::Value> {
90        self.agents
91            .read()
92            .get(id)
93            .and_then(|agent| agent.export_state().ok())
94    }
95
96    /// Import agent state from JSON.
97    ///
98    /// Returns `false` if the agent is not in the pool or import fails.
99    pub fn import_state(&self, id: &AgentId, state: serde_json::Value) -> bool {
100        if let Some(agent) = self.agents.read().get(id) {
101            agent.import_state(state).is_ok()
102        } else {
103            false
104        }
105    }
106
107    /// Number of agents currently in the pool.
108    pub fn len(&self) -> usize {
109        self.agents.read().len()
110    }
111
112    /// Whether the pool is empty.
113    pub fn is_empty(&self) -> bool {
114        self.agents.read().is_empty()
115    }
116}
117
118/// Supervisor trait for managing agent lifecycles.
119#[async_trait]
120pub trait Supervisor: Send + Sync {
121    /// Start executing an agent.
122    async fn exec(&self, id: AgentId) -> Result<()>;
123
124    /// Fork a new agent from a Directive and ExecEnv (RFC-027).
125    ///
126    /// Reads the goal / project_id from the unified-intent Directive.
127    async fn fork_directive(&self, directive: &Directive, env: &ExecEnv) -> Result<AgentId>;
128
129    /// Fork and execute an agent with a Directive + ExecEnv, running to completion.
130    ///
131    /// Dispatches to `AgentRuntime::execute_directive_with_session`.
132    async fn run_with_directive(
133        &self,
134        id: AgentId,
135        directive: &Directive,
136        env: &ExecEnv,
137    ) -> Result<ExecutionResult>;
138
139    /// Wait for an agent to complete and return its final status.
140    async fn wait(&self, id: AgentId) -> Result<AgentStatus>;
141
142    /// Terminate an agent.
143    async fn kill(&self, id: AgentId) -> Result<()>;
144
145    /// List all known agents.
146    async fn list(&self) -> Result<Vec<AgentInfo>>;
147}
148
149/// Basic in-memory supervisor implementation with AgentRuntime integration.
150pub struct BasicSupervisor {
151    agents: RwLock<HashMap<AgentId, AgentInfo>>,
152    /// Per-agent cancellation tokens and join handles for task abortion.
153    handles: RwLock<HashMap<AgentId, AgentHandle>>,
154    /// Pool of live Agent instances for session continuation.
155    agent_pool: AgentPool,
156    event_bus: EventBus,
157    runtime: Arc<AgentRuntime>,
158    resource_monitor: Option<Arc<ResourceMonitor>>,
159    /// Session context for proactive recall timing (RFC-020).
160    /// Shared across all agent executions within this supervisor's lifetime
161    /// so that RecallTiming can track message count and topic changes.
162    /// Uses tokio::sync::RwLock (not parking_lot) so the guard is Send,
163    /// allowing it to be held across .await in tokio::spawn.
164    session_context: Arc<tokio::sync::RwLock<SessionContext>>,
165    /// Filesystem state store for agent persistence (JSON files).
166    state_store: Option<Arc<StateStore>>,
167    /// SQLite-backed agent history query index.
168    #[cfg(feature = "sqlite-memory")]
169    agent_log_db: Option<Arc<AgentLogDb>>,
170    /// Agent log retention configuration.
171    agent_log_config: AgentLogConfig,
172}
173
174impl BasicSupervisor {
175    /// Creates a new supervisor with the given event bus and agent runtime.
176    pub fn new(event_bus: EventBus, runtime: AgentRuntime) -> Self {
177        Self {
178            agents: RwLock::new(HashMap::new()),
179            handles: RwLock::new(HashMap::new()),
180            agent_pool: AgentPool::new(),
181            event_bus,
182            runtime: Arc::new(runtime),
183            resource_monitor: None,
184            session_context: Arc::new(tokio::sync::RwLock::new(SessionContext::new())),
185            state_store: None,
186            #[cfg(feature = "sqlite-memory")]
187            agent_log_db: None,
188            agent_log_config: AgentLogConfig::default(),
189        }
190    }
191
192    /// Attach a filesystem state store for agent history persistence.
193    pub fn set_state_store(&mut self, store: Arc<StateStore>) {
194        self.state_store = Some(store);
195    }
196
197    /// Attach a SQLite-backed agent history log database.
198    #[cfg(feature = "sqlite-memory")]
199    pub fn set_agent_log_db(&mut self, db: Arc<AgentLogDb>) {
200        self.agent_log_db = Some(db);
201    }
202
203    /// Set agent log retention configuration.
204    pub fn set_agent_log_config(&mut self, config: AgentLogConfig) {
205        self.agent_log_config = config;
206    }
207
208    /// Attach a resource monitor for agent count tracking.
209    pub fn set_resource_monitor(&mut self, rm: Arc<ResourceMonitor>) {
210        self.resource_monitor = Some(rm);
211    }
212
213    /// Update the resource monitor with current active agent count.
214    fn update_agent_count(&self) {
215        if let Some(ref rm) = self.resource_monitor {
216            let count = self.agents.read().len();
217            rm.set_active_agents(count);
218        }
219    }
220
221    /// Access the agent pool for session continuation.
222    pub fn pool(&self) -> &AgentPool {
223        &self.agent_pool
224    }
225}
226
227#[async_trait]
228impl Supervisor for BasicSupervisor {
229    async fn fork_directive(&self, directive: &Directive, env: &ExecEnv) -> Result<AgentId> {
230        let id = AgentId::new_v4();
231        let info = AgentInfo {
232            id,
233            name: directive.goal.clone(),
234            status: AgentStatus::Starting,
235            created_at: Utc::now(),
236            project_id: env.project_id,
237            started_at: None,
238            completed_at: None,
239            error: None,
240            steps_completed: 0,
241            steps_total: None,
242            tool_calls: vec![],
243            tokens_input: 0,
244            tokens_output: 0,
245            cost_usd: 0.0,
246            model_id: String::new(),
247            session_id: None,
248        };
249
250        {
251            let mut agents = self.agents.write();
252            agents.insert(id, info);
253        }
254
255        self.update_agent_count();
256
257        let _ = self
258            .event_bus
259            .publish(crate::event_bus::KernelEvent::AgentCreated {
260                id,
261                name: directive.goal.clone(),
262            });
263
264        tracing::info!(agent_id = %id, "Forked new agent from directive");
265        Ok(id)
266    }
267
268    async fn exec(&self, id: AgentId) -> Result<()> {
269        {
270            let mut agents = self.agents.write();
271            match agents.get_mut(&id) {
272                Some(agent) => {
273                    agent.status = AgentStatus::Running;
274                }
275                None => anyhow::bail!("Agent {id} not found"),
276            }
277        }
278
279        self.update_agent_count();
280
281        let _ = self
282            .event_bus
283            .publish(crate::event_bus::KernelEvent::AgentStarted { id });
284        tracing::info!(agent_id = %id, "Agent execution started");
285
286        Ok(())
287    }
288
289    async fn run_with_directive(
290        &self,
291        id: AgentId,
292        directive: &Directive,
293        env: &ExecEnv,
294    ) -> Result<ExecutionResult> {
295        // Mark as running.
296        {
297            let mut agents = self.agents.write();
298            match agents.get_mut(&id) {
299                Some(agent) => {
300                    agent.status = AgentStatus::Running;
301                    agent.started_at = Some(Utc::now());
302                }
303                None => anyhow::bail!("Agent {id} not found"),
304            }
305        }
306
307        let _ = self
308            .event_bus
309            .publish(crate::event_bus::KernelEvent::AgentStarted { id });
310
311        tracing::info!(agent_id = %id, "Running agent task from directive");
312
313        // Spawn the execution as a tokio task so we can track and abort it.
314        let cancelled = Arc::new(AtomicBool::new(false));
315        let runtime = Arc::clone(&self.runtime);
316        let directive = directive.clone();
317        let env = env.clone();
318
319        // Share the session context so RecallTiming persists across directives.
320        // Uses tokio::sync::RwLock so the guard is Send-safe across .await.
321        let session_ctx = self.session_context.clone();
322
323        let (done_tx, done_rx) = tokio::sync::oneshot::channel::<Result<ExecutionResult>>();
324        let cancelled_done = cancelled.clone();
325        let handle: JoinHandle<()> = tokio::spawn(async move {
326            // Check for cancellation before starting.
327            let result = if cancelled_done.load(Ordering::Relaxed) {
328                Ok(ExecutionResult {
329                    output: "Agent cancelled before execution".into(),
330                    steps_completed: 0,
331                    success: false,
332                    tool_calls: vec![],
333                    tokens_input: 0,
334                    tokens_output: 0,
335                    model_id: String::new(),
336                    failure_class: None, // cancellation, not a provider failure
337                    restore_state: None,
338                    reasoning_text: String::new(),
339                })
340            } else {
341                let mut ctx = session_ctx.write().await;
342                runtime
343                    .execute_directive(id, &directive, &env, &mut ctx)
344                    .await
345            };
346            // Receiver gone (run_with_directive returned early) → ignore error.
347            let _ = done_tx.send(result);
348        });
349
350        // Store the handle so kill() can abort the task.
351        {
352            let mut handles = self.handles.write();
353            handles.insert(
354                id,
355                AgentHandle {
356                    cancelled,
357                    task: handle,
358                },
359            );
360        }
361
362        // Await completion via the oneshot channel. If kill() aborts the task
363        // (or it panics), done_tx is dropped and this returns Err — treat as
364        // cancellation.
365        let result = match done_rx.await {
366            Ok(res) => res,
367            Err(_) => {
368                let mut handles = self.handles.write();
369                handles.remove(&id);
370                Ok(ExecutionResult {
371                    output: "Agent task aborted".into(),
372                    steps_completed: 0,
373                    success: false,
374                    tool_calls: vec![],
375                    tokens_input: 0,
376                    tokens_output: 0,
377                    model_id: String::new(),
378                    failure_class: None, // abort (kill/panic), not a provider failure
379                    restore_state: None,
380                    reasoning_text: String::new(),
381                })
382            }
383        };
384
385        // Natural completion — remove the handle.
386        {
387            let mut handles = self.handles.write();
388            handles.remove(&id);
389        }
390
391        match result {
392            Ok(result) => {
393                tracing::info!(
394                    agent_id = %id,
395                    success = result.success,
396                    steps = result.steps_completed,
397                    "Agent task completed (directive)"
398                );
399
400                {
401                    let mut agents = self.agents.write();
402                    if let Some(agent) = agents.get_mut(&id) {
403                        agent.status = if result.success {
404                            AgentStatus::Completed
405                        } else {
406                            AgentStatus::Failed
407                        };
408                        agent.completed_at = Some(Utc::now());
409                        agent.steps_completed = result.steps_completed;
410                        agent.tool_calls = result
411                            .tool_calls
412                            .iter()
413                            .map(|tc| crate::types::ToolCallRecord {
414                                tool: tc.tool.clone(),
415                                input: tc.input.clone(),
416                                output: tc.output.clone(),
417                                duration_ms: tc.duration_ms,
418                                is_error: tc.is_error,
419                                tool_call_id: tc.tool_call_id.clone(),
420                                timestamp: tc.timestamp,
421                            })
422                            .collect();
423                        agent.tokens_input = result.tokens_input;
424                        agent.tokens_output = result.tokens_output;
425                        agent.model_id = result.model_id.clone();
426                        agent.cost_usd = if !result.model_id.is_empty() {
427                            crate::kernel_handle::engine_api::estimate_cost(
428                                &result.model_id,
429                                result.tokens_input,
430                                result.tokens_output,
431                            )
432                        } else {
433                            0.0
434                        };
435                        if !result.success {
436                            agent.error = Some(result.output.clone());
437                        }
438                    }
439                }
440
441                let _ = self
442                    .event_bus
443                    .publish(crate::event_bus::KernelEvent::AgentStopped {
444                        id,
445                        success: result.success,
446                    });
447                self.update_agent_count();
448
449                // Persist to agent history log (async, non-blocking)
450                self.persist_agent(id).await;
451
452                Ok(result)
453            }
454            Err(e) => {
455                tracing::error!(agent_id = %id, error = %e, "Agent task failed (directive)");
456
457                {
458                    let mut agents = self.agents.write();
459                    if let Some(agent) = agents.get_mut(&id) {
460                        agent.status = AgentStatus::Failed;
461                        agent.completed_at = Some(Utc::now());
462                        agent.error = Some(e.to_string());
463                    }
464                }
465
466                let _ = self
467                    .event_bus
468                    .publish(crate::event_bus::KernelEvent::AgentFailed {
469                        id,
470                        error: e.to_string(),
471                    });
472                self.update_agent_count();
473
474                // Persist to agent history log (async, non-blocking)
475                self.persist_agent(id).await;
476
477                Ok(ExecutionResult {
478                    output: format!("Agent failed: {e}"),
479                    steps_completed: 0,
480                    success: false,
481                    tool_calls: vec![],
482                    tokens_input: 0,
483                    tokens_output: 0,
484                    model_id: String::new(),
485                    reasoning_text: String::new(),
486                    // (P2 RecoveryCoordinator, gateway user-facing
487                    // messages) can see whether this is a transient
488                    // retry, a quota/auth that needs provider swap,
489                    // context overflow, etc. Conservative: Unknown
490                    // when no pattern matches.
491                    failure_class: Some(classify(&e)),
492                    restore_state: e
493                        .downcast_ref::<crate::resilience::AgentRunError>()
494                        .and_then(|err| err.restore_state.clone()),
495                })
496            }
497        }
498    }
499
500    async fn wait(&self, id: AgentId) -> Result<AgentStatus> {
501        let agents = self.agents.read();
502        match agents.get(&id) {
503            Some(info) => Ok(info.status),
504            None => anyhow::bail!("Agent {id} not found"),
505        }
506    }
507
508    async fn kill(&self, id: AgentId) -> Result<()> {
509        // Cancel and abort the running task, if any.
510        {
511            let mut handles = self.handles.write();
512            if let Some(agent_handle) = handles.remove(&id) {
513                agent_handle.cancelled.store(true, Ordering::Relaxed);
514                agent_handle.task.abort();
515                tracing::info!(agent_id = %id, "Agent task aborted");
516            }
517        }
518
519        {
520            let mut agents = self.agents.write();
521            if let Some(agent) = agents.get_mut(&id) {
522                agent.status = AgentStatus::Stopped;
523                agent.completed_at = Some(Utc::now());
524            } else {
525                anyhow::bail!("Agent {id} not found");
526            }
527        }
528
529        let _ = self
530            .event_bus
531            .publish(crate::event_bus::KernelEvent::AgentStopped { id, success: false });
532        self.update_agent_count();
533
534        // Persist to agent history log (async, non-blocking)
535        self.persist_agent(id).await;
536
537        tracing::info!(agent_id = %id, "Agent killed");
538        Ok(())
539    }
540
541    async fn list(&self) -> Result<Vec<AgentInfo>> {
542        let agents = self.agents.read();
543        Ok(agents.values().cloned().collect())
544    }
545}
546
547impl BasicSupervisor {
548    /// Persist a terminated agent to both filesystem JSON and SQLite.
549    /// Non-blocking: spawns a tokio task for the actual persistence.
550    async fn persist_agent(&self, id: AgentId) {
551        // Snapshot the agent info from the in-memory map
552        let info = {
553            let agents = self.agents.read();
554            agents.get(&id).cloned()
555        };
556
557        let Some(info) = info else { return };
558
559        // 1. Filesystem JSON (source of truth)
560        if let Some(ref store) = self.state_store {
561            let store = store.clone();
562            let info = info.clone();
563            let max_entries = self.agent_log_config.max_entries;
564            let ttl_hours = self.agent_log_config.ttl_hours;
565            let batch_size = self.agent_log_config.prune_batch_size;
566            tokio::spawn(async move {
567                let _ = store
568                    .save_json("agents", &id.to_string(), &info)
569                    .await
570                    .inspect_err(|e| tracing::warn!(agent_id = %id, error = %e, "Failed to persist agent to filesystem"));
571
572                // Prune old records (async, best-effort)
573                if max_entries > 0 || ttl_hours > 0 {
574                    let _ = store
575                        .prune_agents_by_config(max_entries, ttl_hours, batch_size)
576                        .await
577                        .inspect_err(|e| tracing::warn!(error = %e, "Failed to prune agent log"));
578                }
579            });
580        }
581
582        // 2. SQLite (query index)
583        #[cfg(feature = "sqlite-memory")]
584        if let Some(ref db) = self.agent_log_db {
585            let db = db.clone();
586            let info = info.clone();
587            let config = self.agent_log_config.clone();
588            tokio::spawn(async move {
589                let _ = db
590                    .upsert_agent(&info)
591                    .inspect_err(|e| tracing::warn!(agent_id = %id, error = %e, "Failed to upsert agent to SQLite"));
592
593                // Prune old records
594                let _ = db
595                    .prune(&config)
596                    .inspect_err(|e| tracing::warn!(error = %e, "Failed to prune agent SQLite"));
597            });
598        }
599    }
600}
601
602/// A no-op supervisor used during KernelBuilder::build() to break the
603/// KernelHandle → AgentRuntime → Supervisor → KernelHandle cycle.
604///
605/// AgentApi.supervisor is only used for list/kill operations, not during
606/// tool registration, so this placeholder is safe during build time.
607pub struct NoOpSupervisor;
608
609#[async_trait::async_trait]
610impl Supervisor for NoOpSupervisor {
611    async fn exec(&self, _id: AgentId) -> Result<()> {
612        Err(anyhow::anyhow!(
613            "NoOpSupervisor: exec not available during build"
614        ))
615    }
616    async fn fork_directive(&self, _directive: &Directive, _env: &ExecEnv) -> Result<AgentId> {
617        Err(anyhow::anyhow!(
618            "NoOpSupervisor: fork_directive not available during build"
619        ))
620    }
621    async fn run_with_directive(
622        &self,
623        _id: AgentId,
624        _directive: &Directive,
625        _env: &ExecEnv,
626    ) -> Result<ExecutionResult> {
627        Err(anyhow::anyhow!(
628            "NoOpSupervisor: run_with_directive not available during build"
629        ))
630    }
631    async fn wait(&self, _id: AgentId) -> Result<AgentStatus> {
632        Err(anyhow::anyhow!(
633            "NoOpSupervisor: wait not available during build"
634        ))
635    }
636    async fn kill(&self, _id: AgentId) -> Result<()> {
637        Err(anyhow::anyhow!(
638            "NoOpSupervisor: kill not available during build"
639        ))
640    }
641    async fn list(&self) -> Result<Vec<AgentInfo>> {
642        Ok(Vec::new())
643    }
644}
645
646#[cfg(test)]
647mod tests {
648    use super::*;
649    use crate::event_bus::EventBus;
650    use crate::types::AgentStatus;
651
652    // Note: MockProvider no longer needed — OxiosEngine handles provider resolution.
653    // The engine resolves models internally, so tests just use OxiosEngine::new().
654
655    /// Helper to create a real BasicSupervisor wired to a real EventBus.
656    async fn make_supervisor() -> BasicSupervisor {
657        let event_bus = EventBus::new(64);
658
659        // Build a mock KernelHandle with temp dirs.
660        let tmp = std::env::temp_dir().join(format!("oxios-test-{}", uuid::Uuid::new_v4()));
661        let _ = std::fs::create_dir_all(&tmp);
662
663        let state_store_2 =
664            Arc::new(crate::state_store::StateStore::new(tmp.join("state")).expect("state store"));
665        let state_store = state_store_2.clone();
666        let memory_manager = Arc::new({
667            let mut mm = crate::memory::MemoryManager::new(state_store.clone());
668            mm.set_git_layer(Arc::new(
669                crate::git_layer::GitLayer::new(tmp.join("git"), false).expect("git layer"),
670            ));
671            mm
672        });
673
674        let kernel_handle = Arc::new(crate::KernelHandle::new(
675            crate::kernel_handle::StateApi::new(state_store),
676            crate::kernel_handle::AgentApi::new(
677                Arc::new(crate::supervisor::NoOpSupervisor),
678                Arc::new(crate::budget::BudgetManager::new()),
679                memory_manager.clone(),
680                Some(event_bus.clone()),
681            ),
682            crate::kernel_handle::SecurityApi::new(
683                Arc::new(parking_lot::Mutex::new(crate::auth::AuthManager::new())),
684                Arc::new(oxi_sdk::observability::AuditTrail::new(100)),
685                Arc::new(parking_lot::Mutex::new(
686                    crate::access_manager::AccessManager::new(),
687                )),
688                Arc::new(
689                    crate::state_store::StateStore::new(tmp.join("state2")).expect("state store 2"),
690                ),
691            ),
692            crate::kernel_handle::PersonaApi::new(Arc::new(crate::persona::PersonaManager::new())),
693            crate::kernel_handle::ExtensionApi::new(Arc::new(crate::skill::SkillManager::new(
694                tmp.join("skills"),
695                tmp.join("share/skills"),
696            ))),
697            crate::kernel_handle::McpApi::new(Arc::new(crate::mcp::McpBridge::new())),
698            crate::kernel_handle::InfraApi::new(
699                Arc::new(
700                    crate::git_layer::GitLayer::new(tmp.join("git"), false).expect("git layer"),
701                ),
702                Arc::new(crate::cron::CronScheduler::new(
703                    Arc::new(
704                        crate::state_store::StateStore::new(tmp.join("cron")).expect("cron state"),
705                    ),
706                    60,
707                )),
708                Arc::new(crate::resource_monitor::ResourceMonitor::new(60, 100)),
709                EventBus::new(64),
710                crate::config::OxiosConfig::default(),
711                std::time::Instant::now(),
712            ),
713            None,
714            crate::kernel_handle::ExecApi::new(
715                Arc::new(parking_lot::RwLock::new(
716                    crate::config::ExecConfig::default(),
717                )),
718                Arc::new(parking_lot::Mutex::new(
719                    crate::access_manager::AccessManager::new(),
720                )),
721            ),
722            crate::kernel_handle::A2aApi::new(Arc::new(crate::a2a::A2AProtocol::new(
723                EventBus::new(64),
724            ))),
725            crate::kernel_handle::EngineApi::new(
726                Arc::new(parking_lot::RwLock::new(
727                    crate::config::OxiosConfig::default(),
728                )),
729                tmp.join("config.toml"),
730                Arc::new(crate::kernel_handle::RoutingStats::new()),
731                Arc::new(crate::engine::EngineHandle::new(Arc::new(
732                    crate::OxiosEngine::new("anthropic/claude-sonnet-4-20250514"),
733                ))),
734            ),
735            Arc::new(oxios_markdown::KnowledgeBase::new(tmp.join("knowledge")).unwrap()),
736            Arc::new(
737                crate::kernel_handle::KnowledgeLens::new(
738                    Arc::new(oxios_markdown::KnowledgeBase::new(tmp.join("knowledge")).unwrap()),
739                    memory_manager.clone(),
740                )
741                .unwrap(),
742            ),
743            crate::kernel_handle::MarketplaceApi::new(
744                Arc::new(crate::skill::clawhub::ClawHubInstaller::new(
745                    tmp.join("skills"),
746                    tmp.join("state"),
747                    None,
748                )),
749                Arc::new(
750                    crate::skill::clawhub::ClawHubClient::new(None).expect("valid ClawHub client"),
751                ),
752                Arc::new(crate::skill::skills_sh::SkillsShInstaller::new(
753                    tmp.join("skills"),
754                    None,
755                    None,
756                )),
757                Arc::new(
758                    crate::skill::skills_sh::SkillsShClient::new(None, None)
759                        .expect("valid Skills.sh client"),
760                ),
761            ),
762            None, // calendar (not configured in test)
763            None, // email (not configured in test)
764        ));
765
766        let engine = crate::OxiosEngine::new("mock/model");
767        let engine_handle = Arc::new(crate::engine::EngineHandle::new(Arc::new(engine)));
768        let runtime = AgentRuntime::new(engine_handle, kernel_handle, None);
769        BasicSupervisor::new(event_bus, runtime)
770    }
771
772    /// Helper to create a minimal (Directive, ExecEnv) pair for testing.
773    fn make_directive(goal: &str) -> (Directive, ExecEnv) {
774        (Directive::from_message(goal), ExecEnv::default())
775    }
776
777    #[tokio::test]
778    async fn test_fork_creates_agent() {
779        let supervisor = make_supervisor().await;
780        let (directive, env) = make_directive("Test agent");
781
782        let id = supervisor.fork_directive(&directive, &env).await.unwrap();
783
784        let agents = supervisor.list().await.unwrap();
785        assert_eq!(agents.len(), 1);
786        assert_eq!(agents[0].id, id);
787        assert_eq!(agents[0].name, "Test agent");
788        assert_eq!(agents[0].status, AgentStatus::Starting);
789    }
790
791    #[tokio::test]
792    async fn test_exec_updates_status_to_running() {
793        let supervisor = make_supervisor().await;
794        let (directive, env) = make_directive("Running agent");
795
796        let id = supervisor.fork_directive(&directive, &env).await.unwrap();
797        assert_eq!(supervisor.wait(id).await.unwrap(), AgentStatus::Starting);
798
799        supervisor.exec(id).await.unwrap();
800        assert_eq!(supervisor.wait(id).await.unwrap(), AgentStatus::Running);
801    }
802
803    #[tokio::test]
804    async fn test_kill_sets_stopped() {
805        let supervisor = make_supervisor().await;
806        let (directive, env) = make_directive("Doomed agent");
807
808        let id = supervisor.fork_directive(&directive, &env).await.unwrap();
809        supervisor.exec(id).await.unwrap();
810        assert_eq!(supervisor.wait(id).await.unwrap(), AgentStatus::Running);
811
812        supervisor.kill(id).await.unwrap();
813        assert_eq!(supervisor.wait(id).await.unwrap(), AgentStatus::Stopped);
814    }
815
816    #[tokio::test]
817    async fn test_kill_unknown_agent_returns_error() {
818        let supervisor = make_supervisor().await;
819        let unknown_id = uuid::Uuid::new_v4();
820
821        let result = supervisor.kill(unknown_id).await;
822        assert!(result.is_err());
823        assert!(result.unwrap_err().to_string().contains("not found"));
824    }
825
826    #[tokio::test]
827    async fn test_list_returns_all_agents() {
828        let supervisor = make_supervisor().await;
829
830        let (d1, e1) = make_directive("Agent 1");
831        let id1 = supervisor.fork_directive(&d1, &e1).await.unwrap();
832        let (d2, e2) = make_directive("Agent 2");
833        let id2 = supervisor.fork_directive(&d2, &e2).await.unwrap();
834        let (d3, e3) = make_directive("Agent 3");
835        let id3 = supervisor.fork_directive(&d3, &e3).await.unwrap();
836
837        let agents = supervisor.list().await.unwrap();
838        assert_eq!(agents.len(), 3);
839
840        let ids: std::collections::HashSet<AgentId> = agents.iter().map(|a| a.id).collect();
841        assert!(ids.contains(&id1));
842        assert!(ids.contains(&id2));
843        assert!(ids.contains(&id3));
844    }
845
846    #[tokio::test]
847    async fn test_exec_unknown_agent_returns_error() {
848        let supervisor = make_supervisor().await;
849        let unknown_id = uuid::Uuid::new_v4();
850
851        let result = supervisor.exec(unknown_id).await;
852        assert!(result.is_err());
853        assert!(result.unwrap_err().to_string().contains("not found"));
854    }
855
856    #[tokio::test]
857    async fn test_wait_unknown_agent_returns_error() {
858        let supervisor = make_supervisor().await;
859        let unknown_id = uuid::Uuid::new_v4();
860
861        let result = supervisor.wait(unknown_id).await;
862        assert!(result.is_err());
863        assert!(result.unwrap_err().to_string().contains("not found"));
864    }
865}