aegis-runtime-mv
Native Rust agent runtime: Axum WebSocket/SSE/REST gateway, heartbeat scheduler, dependency-aware task workflow, SQLite storage. Attachment of AienOS. Pre-alpha.
Brought by drakestapleton
aegis-runtime-mv / src / heartbeat.rs
| 1 | use chrono::Utc; |
| 2 | use futures_util::FutureExt; |
| 3 | use serde::{Deserialize, Serialize}; |
| 4 | use std::panic::AssertUnwindSafe; |
| 5 | use std::sync::atomic::{AtomicU64, Ordering}; |
| 6 | use std::sync::Arc; |
| 7 | use std::time::Duration; |
| 8 | use tokio::process::Command; |
| 9 | use tokio::sync::{broadcast, Mutex}; |
| 10 | use tracing::{info, warn}; |
| 11 | |
| 12 | use crate::inference::InferenceEngine; |
| 13 | use crate::persistence::Database; |
| 14 | use crate::security::WorkspaceCapability; |
| 15 | |
| 16 | const HEALTH_ACTION_TIMEOUT: Duration = Duration::from_secs(15); |
| 17 | |
| 18 | async fn http_model_health(endpoint: &str) -> Result<bool, reqwest::Error> { |
| 19 | let client = reqwest::Client::builder() |
| 20 | .connect_timeout(HEALTH_ACTION_TIMEOUT) |
| 21 | .timeout(HEALTH_ACTION_TIMEOUT) |
| 22 | .build()?; |
| 23 | Ok(client.get(endpoint).send().await?.status().is_success()) |
| 24 | } |
| 25 | |
| 26 | #[derive(Serialize, Deserialize, Clone, Debug)] |
| 27 | pub struct PulseReceipt { |
| 28 | pub tick_id: u64, |
| 29 | pub timestamp: String, |
| 30 | pub status: &'static str, |
| 31 | pub tasks_scanned: usize, |
| 32 | pub actions_dispatched: usize, |
| 33 | pub notes: String, |
| 34 | } |
| 35 | |
| 36 | pub struct HeartbeatEngine { |
| 37 | interval_secs: u64, |
| 38 | tick_counter: AtomicU64, |
| 39 | db: Arc<Database>, |
| 40 | inference: Option<Arc<dyn InferenceEngine>>, |
| 41 | workspace: Arc<WorkspaceCapability>, |
| 42 | is_running: Mutex<bool>, |
| 43 | tx_pulse: broadcast::Sender<PulseReceipt>, |
| 44 | } |
| 45 | |
| 46 | impl HeartbeatEngine { |
| 47 | pub fn new(interval_secs: u64, db: Arc<Database>) -> Self { |
| 48 | let (tx, _) = broadcast::channel(128); |
| 49 | Self { |
| 50 | interval_secs, |
| 51 | tick_counter: AtomicU64::new(0), |
| 52 | db, |
| 53 | inference: None, |
| 54 | workspace: Arc::new(WorkspaceCapability::detect()), |
| 55 | is_running: Mutex::new(false), |
| 56 | tx_pulse: tx, |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | pub fn with_inference( |
| 61 | interval_secs: u64, |
| 62 | db: Arc<Database>, |
| 63 | inference: Arc<dyn InferenceEngine>, |
| 64 | ) -> Self { |
| 65 | let (tx, _) = broadcast::channel(128); |
| 66 | Self { |
| 67 | interval_secs, |
| 68 | tick_counter: AtomicU64::new(0), |
| 69 | db, |
| 70 | inference: Some(inference), |
| 71 | workspace: Arc::new(WorkspaceCapability::detect()), |
| 72 | is_running: Mutex::new(false), |
| 73 | tx_pulse: tx, |
| 74 | } |
| 75 | } |
| 76 | |
| 77 | pub fn interval_secs(&self) -> u64 { |
| 78 | self.interval_secs |
| 79 | } |
| 80 | |
| 81 | pub fn tick_count(&self) -> u64 { |
| 82 | self.tick_counter.load(Ordering::Relaxed) |
| 83 | } |
| 84 | |
| 85 | pub fn with_workspace( |
| 86 | interval_secs: u64, |
| 87 | db: Arc<Database>, |
| 88 | workspace: WorkspaceCapability, |
| 89 | ) -> Self { |
| 90 | let (tx, _) = broadcast::channel(128); |
| 91 | Self { |
| 92 | interval_secs, |
| 93 | tick_counter: AtomicU64::new(0), |
| 94 | db, |
| 95 | inference: None, |
| 96 | workspace: Arc::new(workspace), |
| 97 | is_running: Mutex::new(false), |
| 98 | tx_pulse: tx, |
| 99 | } |
| 100 | } |
| 101 | |
| 102 | pub fn subscribe(&self) -> broadcast::Receiver<PulseReceipt> { |
| 103 | self.tx_pulse.subscribe() |
| 104 | } |
| 105 | |
| 106 | pub async fn pulse_once(&self) -> PulseReceipt { |
| 107 | let tick = self.tick_counter.fetch_add(1, Ordering::SeqCst) + 1; |
| 108 | let now = Utc::now().to_rfc3339(); |
| 109 | |
| 110 | let mut degraded = match self.db.recover_abandoned_tasks() { |
| 111 | Ok(recovered) => recovered != 0, |
| 112 | Err(error) => { |
| 113 | warn!("Heartbeat could not recover abandoned claims: {}", error); |
| 114 | true |
| 115 | } |
| 116 | }; |
| 117 | degraded |= match self.db.retry_task_outcomes() { |
| 118 | Ok(summary) => summary.failed != 0, |
| 119 | Err(error) => { |
| 120 | warn!( |
| 121 | "Heartbeat retained finalization or transcript export for retry: {}", |
| 122 | error |
| 123 | ); |
| 124 | true |
| 125 | } |
| 126 | }; |
| 127 | let pending_tasks = match self.db.list_pending_tasks() { |
| 128 | Ok(tasks) => tasks, |
| 129 | Err(e) => { |
| 130 | degraded = true; |
| 131 | warn!( |
| 132 | "Heartbeat pulse #{} could not list pending tasks: {}", |
| 133 | tick, e |
| 134 | ); |
| 135 | Vec::new() |
| 136 | } |
| 137 | }; |
| 138 | let tasks_count = pending_tasks.len(); |
| 139 | let mut actions = 0; |
| 140 | |
| 141 | for task in pending_tasks { |
| 142 | // Another pulse may have taken this task since the list was read. |
| 143 | let claim = match self.db.claim_task(&task.id) { |
| 144 | Ok(Some(claim)) => claim, |
| 145 | Ok(None) => continue, |
| 146 | Err(e) => { |
| 147 | degraded = true; |
| 148 | warn!("Heartbeat could not claim task {}: {}", task.id, e); |
| 149 | continue; |
| 150 | } |
| 151 | }; |
| 152 | let execution = self.db.hold_claim(claim); |
| 153 | |
| 154 | let action = async { |
| 155 | match task.task_type.as_str() { |
| 156 | // "max_health" is the former name, kept so tasks already queued under it still run. |
| 157 | "model_health" | "max_health" => { |
| 158 | let health = async { |
| 159 | if let Some(ref inf) = self.inference { |
| 160 | inf.check_health().await |
| 161 | } else { |
| 162 | http_model_health("http://127.0.0.1:18006/v1/models") |
| 163 | .await |
| 164 | .unwrap_or(false) |
| 165 | } |
| 166 | }; |
| 167 | let is_healthy = tokio::time::timeout(HEALTH_ACTION_TIMEOUT, health) |
| 168 | .await |
| 169 | .map_err(|_| { |
| 170 | "Model health deadline exceeded: outcome unknown".to_string() |
| 171 | })?; |
| 172 | |
| 173 | if is_healthy { |
| 174 | Ok("Local model seat verified ACTIVE on port 18006".to_string()) |
| 175 | } else { |
| 176 | Err("Local model seat unreachable or offline on port 18006".to_string()) |
| 177 | } |
| 178 | } |
| 179 | "build_monitor" | "shell_exec" => { |
| 180 | let cmd_to_run = if task.payload.is_empty() { |
| 181 | "echo 'empty build task'" |
| 182 | } else { |
| 183 | &task.payload |
| 184 | }; |
| 185 | |
| 186 | match self |
| 187 | .workspace |
| 188 | .dispatch_shell_gated(cmd_to_run, None, 15) |
| 189 | .await |
| 190 | { |
| 191 | Ok(stdout) => Ok(format!("Exit code 0: {}", stdout.trim())), |
| 192 | Err(e) => Err(format!("Execution failure: {}", e)), |
| 193 | } |
| 194 | } |
| 195 | "consolidate_memory" => { |
| 196 | let crumb_key = format!("consolidation_tick_{}", tick); |
| 197 | self.db |
| 198 | .store_crumb( |
| 199 | &crumb_key, |
| 200 | "Episodic memory consolidated into WAL", |
| 201 | "heartbeat", |
| 202 | ) |
| 203 | .map(|()| "Memory crumbs recorded".to_string()) |
| 204 | .map_err(|e| format!("Memory consolidation failure: {}", e)) |
| 205 | } |
| 206 | "system_telemetry" => Ok("System telemetry nominal: GB10 aarch64".to_string()), |
| 207 | _ => Err(format!("Unknown task type: {}", task.task_type)), |
| 208 | } |
| 209 | }; |
| 210 | let outcome = AssertUnwindSafe(action) |
| 211 | .catch_unwind() |
| 212 | .await |
| 213 | .unwrap_or_else(|_| Err("Task action panicked: outcome unknown".into())); |
| 214 | |
| 215 | degraded |= outcome.is_err(); |
| 216 | execution.finish(outcome); |
| 217 | actions += 1; |
| 218 | } |
| 219 | degraded |= match self.db.retry_task_outcomes() { |
| 220 | Ok(summary) => summary.failed != 0, |
| 221 | Err(error) => { |
| 222 | warn!( |
| 223 | "Heartbeat retained finalization or transcript export for retry: {}", |
| 224 | error |
| 225 | ); |
| 226 | true |
| 227 | } |
| 228 | }; |
| 229 | |
| 230 | let mut receipt = PulseReceipt { |
| 231 | tick_id: tick, |
| 232 | timestamp: now, |
| 233 | status: if degraded { "degraded" } else { "nominal" }, |
| 234 | tasks_scanned: tasks_count, |
| 235 | actions_dispatched: actions, |
| 236 | notes: format!( |
| 237 | "Autonomous tick #{} scanned {} pending tasks, dispatched {} actions", |
| 238 | tick, tasks_count, actions |
| 239 | ), |
| 240 | }; |
| 241 | |
| 242 | if let Err(error) = self.db.record_heartbeat_tick(&mut receipt) { |
| 243 | receipt.status = "degraded"; |
| 244 | receipt |
| 245 | .notes |
| 246 | .push_str(&format!("; receipt persistence failed: {}", error)); |
| 247 | } |
| 248 | let _ = self.tx_pulse.send(receipt.clone()); |
| 249 | |
| 250 | // Record operational pulse event to the Crumb ledger (.crumb) |
| 251 | let crumb_bin = if let Ok(home) = std::env::var("HOME") { |
| 252 | let candidate = std::path::PathBuf::from(home).join(".local/bin/spark-crumbs"); |
| 253 | if candidate.exists() { |
| 254 | candidate.to_string_lossy().to_string() |
| 255 | } else { |
| 256 | "spark-crumbs".to_string() |
| 257 | } |
| 258 | } else { |
| 259 | "spark-crumbs".to_string() |
| 260 | }; |
| 261 | let _ = Command::new(&crumb_bin) |
| 262 | .args([ |
| 263 | "record", |
| 264 | "--agent", |
| 265 | "AEGIS", |
| 266 | "--action", |
| 267 | "heartbeat:pulse", |
| 268 | "--target", |
| 269 | "aegis-heartbeat", |
| 270 | "--intent", |
| 271 | "Sovereign runtime heartbeat pulse", |
| 272 | "--vector", |
| 273 | &format!( |
| 274 | "Tick #{} {} | tasks: {} | actions: {}", |
| 275 | tick, receipt.status, tasks_count, actions |
| 276 | ), |
| 277 | ".", |
| 278 | ]) |
| 279 | .output() |
| 280 | .await; |
| 281 | |
| 282 | receipt |
| 283 | } |
| 284 | |
| 285 | pub async fn start_loop(self: Arc<Self>) { |
| 286 | let mut running = self.is_running.lock().await; |
| 287 | if *running { |
| 288 | return; |
| 289 | } |
| 290 | *running = true; |
| 291 | drop(running); |
| 292 | |
| 293 | let engine = self.clone(); |
| 294 | tokio::spawn(async move { |
| 295 | info!( |
| 296 | "AEGIS autonomous heartbeat loop started (period: {}s)", |
| 297 | engine.interval_secs |
| 298 | ); |
| 299 | let mut interval = tokio::time::interval(Duration::from_secs(engine.interval_secs)); |
| 300 | loop { |
| 301 | interval.tick().await; |
| 302 | let receipt = engine.pulse_once().await; |
| 303 | info!( |
| 304 | "Heartbeat pulse #{}: {} tasks scanned, {} actions", |
| 305 | receipt.tick_id, receipt.tasks_scanned, receipt.actions_dispatched |
| 306 | ); |
| 307 | } |
| 308 | }); |
| 309 | } |
| 310 | } |
| 311 | |
| 312 | #[cfg(test)] |
| 313 | mod tests { |
| 314 | use super::*; |
| 315 | use crate::inference::{ChatStream, ChatTurnResponse}; |
| 316 | use serde_json::Value; |
| 317 | |
| 318 | struct HealthyProbe; |
| 319 | #[async_trait::async_trait] |
| 320 | impl InferenceEngine for HealthyProbe { |
| 321 | fn model_id(&self) -> String { |
| 322 | "test-health".into() |
| 323 | } |
| 324 | fn endpoint(&self) -> String { |
| 325 | "test-only".into() |
| 326 | } |
| 327 | async fn generate_with_tokens( |
| 328 | &self, |
| 329 | _: &str, |
| 330 | _: Option<&str>, |
| 331 | _: Option<f32>, |
| 332 | _: Option<u32>, |
| 333 | ) -> Result<String, Box<dyn std::error::Error + Send + Sync>> { |
| 334 | unreachable!() |
| 335 | } |
| 336 | async fn generate_chat( |
| 337 | &self, |
| 338 | _: &[Value], |
| 339 | _: Option<f32>, |
| 340 | _: Option<u32>, |
| 341 | ) -> Result<String, Box<dyn std::error::Error + Send + Sync>> { |
| 342 | unreachable!() |
| 343 | } |
| 344 | async fn generate_chat_with_tools( |
| 345 | &self, |
| 346 | _: &[Value], |
| 347 | _: Option<&[Value]>, |
| 348 | _: Option<f32>, |
| 349 | _: Option<u32>, |
| 350 | ) -> Result<ChatTurnResponse, Box<dyn std::error::Error + Send + Sync>> { |
| 351 | unreachable!() |
| 352 | } |
| 353 | async fn stream_chat( |
| 354 | &self, |
| 355 | _: &[Value], |
| 356 | _: Option<f32>, |
| 357 | _: Option<u32>, |
| 358 | ) -> Result<ChatStream, Box<dyn std::error::Error + Send + Sync>> { |
| 359 | unreachable!() |
| 360 | } |
| 361 | async fn check_health(&self) -> bool { |
| 362 | tokio::task::yield_now().await; |
| 363 | true |
| 364 | } |
| 365 | } |
| 366 | |
| 367 | #[tokio::test] |
| 368 | async fn test_http_health_client_deadline() { |
| 369 | use tokio::io::AsyncReadExt; |
| 370 | let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); |
| 371 | let endpoint = format!("http://{}", listener.local_addr().unwrap()); |
| 372 | let accepted = Arc::new(tokio::sync::Notify::new()); |
| 373 | let server_accepted = accepted.clone(); |
| 374 | let server = tokio::spawn(async move { |
| 375 | let (mut socket, _) = listener.accept().await.unwrap(); |
| 376 | let mut request = [0; 1024]; |
| 377 | assert!(socket.read(&mut request).await.unwrap() != 0); |
| 378 | server_accepted.notify_one(); |
| 379 | std::future::pending::<()>().await; |
| 380 | drop(socket); |
| 381 | }); |
| 382 | let client = tokio::spawn(async move { http_model_health(&endpoint).await }); |
| 383 | tokio::time::timeout(Duration::from_secs(2), accepted.notified()) |
| 384 | .await |
| 385 | .unwrap(); |
| 386 | tokio::time::pause(); |
| 387 | tokio::time::advance(HEALTH_ACTION_TIMEOUT).await; |
| 388 | tokio::time::resume(); |
| 389 | let result = tokio::time::timeout(Duration::from_secs(2), client).await; |
| 390 | server.abort(); |
| 391 | let error = result |
| 392 | .expect("HTTP client must have its own request deadline") |
| 393 | .unwrap() |
| 394 | .unwrap_err(); |
| 395 | assert!(error.is_timeout()); |
| 396 | } |
| 397 | |
| 398 | #[tokio::test] |
| 399 | async fn test_heartbeat_pulse_and_task_execution() { |
| 400 | let db = Arc::new(Database::open_in_memory().unwrap()); |
| 401 | db.create_task("hb1", "system_telemetry", "check").unwrap(); |
| 402 | db.create_task("hb2", "consolidate_memory", "sync").unwrap(); |
| 403 | db.create_task("hb3", "shell_exec", "git status").unwrap(); |
| 404 | |
| 405 | let engine = HeartbeatEngine::new(60, db.clone()); |
| 406 | let receipt = engine.pulse_once().await; |
| 407 | |
| 408 | assert_eq!(receipt.tick_id, 1); |
| 409 | assert_eq!(receipt.tasks_scanned, 3); |
| 410 | assert_eq!(receipt.actions_dispatched, 3); |
| 411 | assert_eq!(receipt.status, "nominal"); |
| 412 | |
| 413 | let remaining = db.list_pending_tasks().unwrap(); |
| 414 | assert_eq!(remaining.len(), 0); |
| 415 | } |
| 416 | |
| 417 | #[tokio::test] |
| 418 | async fn test_overlapping_pulses_run_a_task_once() { |
| 419 | let db = Arc::new(Database::open_in_memory().unwrap()); |
| 420 | // Uses the former task name on purpose, so the legacy alias stays covered. |
| 421 | db.create_task("hb_once", "max_health", "check").unwrap(); |
| 422 | |
| 423 | // The first pulse awaits the health probe while the second one lists |
| 424 | // tasks, so both see the task unless the first one claimed it. |
| 425 | let engine = HeartbeatEngine::with_inference(60, db.clone(), Arc::new(HealthyProbe)); |
| 426 | let (a, b) = tokio::join!(engine.pulse_once(), engine.pulse_once()); |
| 427 | |
| 428 | assert_eq!(a.actions_dispatched + b.actions_dispatched, 1); |
| 429 | assert!(db.list_pending_tasks().unwrap().is_empty()); |
| 430 | } |
| 431 | |
| 432 | #[tokio::test] |
| 433 | async fn test_heartbeat_prohibited_root_command_rejection() { |
| 434 | let db = Arc::new(Database::open_in_memory().unwrap()); |
| 435 | db.create_task("hb_sec", "shell_exec", "cd /etc && ls") |
| 436 | .unwrap(); |
| 437 | |
| 438 | let engine = HeartbeatEngine::new(60, db.clone()); |
| 439 | let receipt = engine.pulse_once().await; |
| 440 | |
| 441 | assert_eq!(receipt.tick_id, 1); |
| 442 | assert_eq!(receipt.tasks_scanned, 1); |
| 443 | assert_eq!(receipt.actions_dispatched, 1); |
| 444 | |
| 445 | let remaining = db.list_pending_tasks().unwrap(); |
| 446 | assert_eq!(remaining.len(), 0); |
| 447 | } |
| 448 | } |