From 467e4395135a77833163a60849b76ea49f5dde5d Mon Sep 17 00:00:00 2001 From: Boiko Oleg Date: Sat, 5 Sep 2026 07:19:47 +0300 Subject: [PATCH 01/46] feat(evolve): add event core and state manager --- sandbox_runtime/crates/sandbox-kernel/src/evolve/mod.rs | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 sandbox_runtime/crates/sandbox-kernel/src/evolve/mod.rs diff --git a/sandbox_runtime/crates/sandbox-kernel/src/evolve/mod.rs b/sandbox_runtime/crates/sandbox-kernel/src/evolve/mod.rs new file mode 100644 index 0000000..60d2b8b --- /dev/null +++ b/sandbox_runtime/crates/sandbox-kernel/src/evolve/mod.rs @@ -0,0 +1,9 @@ +pub mod event; +pub mod manager; +pub mod session; +pub mod state; + +pub use event::{EventSource, RiskLevel, SecurityEvent, SecurityEventType}; +pub use manager::{EvolveDecision, EvolveManager, EvolveStatus}; +pub use session::EvolveSession; +pub use state::{EvolveState, StateTransitionError}; From 6f5686dcd6c5382d9bbe69c39e26831a8d8fcaa3 Mon Sep 17 00:00:00 2001 From: Boiko Oleg Date: Sat, 5 Sep 2026 07:19:50 +0300 Subject: [PATCH 02/46] feat(evolve): add event core and state manager --- .../crates/sandbox-kernel/src/evolve/event.rs | 156 ++++++++++++++++++ 1 file changed, 156 insertions(+) create mode 100644 sandbox_runtime/crates/sandbox-kernel/src/evolve/event.rs diff --git a/sandbox_runtime/crates/sandbox-kernel/src/evolve/event.rs b/sandbox_runtime/crates/sandbox-kernel/src/evolve/event.rs new file mode 100644 index 0000000..cb32945 --- /dev/null +++ b/sandbox_runtime/crates/sandbox-kernel/src/evolve/event.rs @@ -0,0 +1,156 @@ +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::time::{SystemTime, UNIX_EPOCH}; + +static EVENT_SEQUENCE: AtomicU64 = AtomicU64::new(1); + +fn now_ms() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_millis() + .min(u64::MAX as u128) as u64 +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum EventSource { + Canary, + Filesystem, + Process, + Network, + Browser, + HttpProbe, + Policy, + System, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum SecurityEventType { + FileOpen, + FileRead, + FileWrite, + FileDelete, + ProcessSpawn, + ProcessExec, + ProcessExit, + NetworkConnect, + NetworkListen, + DnsAttempt, + CredentialAccess, + CanaryAccess, + Discovery, + PrivilegeAttempt, + PersistenceAttempt, + LateralMovementAttempt, + BrowserNavigation, + HttpRequest, + PolicyViolation, + EscapeAttempt, + ControlPlaneAccess, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "UPPERCASE")] +pub enum RiskLevel { + Low, + Medium, + High, + Critical, +} + +impl RiskLevel { + pub fn rank(self) -> u8 { + match self { + Self::Low => 0, + Self::Medium => 1, + Self::High => 2, + Self::Critical => 3, + } + } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct SecurityEvent { + pub event_id: String, + pub session_id: Option, + pub timestamp_ms: u64, + pub source: EventSource, + pub event_type: SecurityEventType, + pub process_id: Option, + pub parent_process_id: Option, + pub uid: Option, + pub resource: Option, + pub destination: Option, + pub command: Option, + pub arguments: Vec, + pub result: Option, + pub risk_hint: Option, + pub metadata: Value, +} + +impl SecurityEvent { + pub fn new(source: EventSource, event_type: SecurityEventType) -> Self { + let timestamp_ms = now_ms(); + let sequence = EVENT_SEQUENCE.fetch_add(1, Ordering::Relaxed); + + Self { + event_id: format!("evt-{timestamp_ms}-{sequence}"), + session_id: None, + timestamp_ms, + source, + event_type, + process_id: None, + parent_process_id: None, + uid: None, + resource: None, + destination: None, + command: None, + arguments: Vec::new(), + result: None, + risk_hint: None, + metadata: Value::Object(Default::default()), + } + } + + pub fn with_session_id(mut self, session_id: impl Into) -> Self { + self.session_id = Some(session_id.into()); + self + } + + pub fn with_resource(mut self, resource: impl Into) -> Self { + self.resource = Some(resource.into()); + self + } + + pub fn with_risk_hint(mut self, risk: RiskLevel) -> Self { + self.risk_hint = Some(risk); + self + } + + pub fn with_metadata(mut self, metadata: Value) -> Self { + self.metadata = metadata; + self + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn event_ids_are_unique() { + let first = SecurityEvent::new(EventSource::System, SecurityEventType::PolicyViolation); + let second = SecurityEvent::new(EventSource::System, SecurityEventType::PolicyViolation); + assert_ne!(first.event_id, second.event_id); + } + + #[test] + fn risk_rank_is_monotonic() { + assert!(RiskLevel::Critical.rank() > RiskLevel::High.rank()); + assert!(RiskLevel::High.rank() > RiskLevel::Medium.rank()); + assert!(RiskLevel::Medium.rank() > RiskLevel::Low.rank()); + } +} From 3390abcb3960e0b43f0eb59df2656cd672b48c6e Mon Sep 17 00:00:00 2001 From: Boiko Oleg Date: Sat, 5 Sep 2026 07:19:51 +0300 Subject: [PATCH 03/46] feat(evolve): add event core and state manager --- .../crates/sandbox-kernel/src/evolve/state.rs | 82 +++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 sandbox_runtime/crates/sandbox-kernel/src/evolve/state.rs diff --git a/sandbox_runtime/crates/sandbox-kernel/src/evolve/state.rs b/sandbox_runtime/crates/sandbox-kernel/src/evolve/state.rs new file mode 100644 index 0000000..092de37 --- /dev/null +++ b/sandbox_runtime/crates/sandbox-kernel/src/evolve/state.rs @@ -0,0 +1,82 @@ +use serde::{Deserialize, Serialize}; +use thiserror::Error; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "UPPERCASE")] +pub enum EvolveState { + Observe, + Suspect, + Engage, + Deceive, + Learn, + Adapt, + Isolate, +} + +impl Default for EvolveState { + fn default() -> Self { + Self::Observe + } +} + +impl EvolveState { + pub fn can_transition_to(self, next: Self) -> bool { + if next == Self::Isolate && self != Self::Isolate { + return true; + } + + matches!( + (self, next), + (Self::Observe, Self::Suspect) + | (Self::Suspect, Self::Observe) + | (Self::Suspect, Self::Engage) + | (Self::Engage, Self::Suspect) + | (Self::Engage, Self::Deceive) + | (Self::Deceive, Self::Learn) + | (Self::Learn, Self::Adapt) + | (Self::Adapt, Self::Observe) + ) + } +} + +#[derive(Debug, Error, PartialEq, Eq)] +pub enum StateTransitionError { + #[error("invalid Evolve state transition: {from:?} -> {to:?}")] + InvalidTransition { from: EvolveState, to: EvolveState }, +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn expected_pipeline_transitions_are_allowed() { + assert!(EvolveState::Observe.can_transition_to(EvolveState::Suspect)); + assert!(EvolveState::Suspect.can_transition_to(EvolveState::Engage)); + assert!(EvolveState::Engage.can_transition_to(EvolveState::Deceive)); + assert!(EvolveState::Deceive.can_transition_to(EvolveState::Learn)); + assert!(EvolveState::Learn.can_transition_to(EvolveState::Adapt)); + assert!(EvolveState::Adapt.can_transition_to(EvolveState::Observe)); + } + + #[test] + fn every_active_state_can_isolate() { + for state in [ + EvolveState::Observe, + EvolveState::Suspect, + EvolveState::Engage, + EvolveState::Deceive, + EvolveState::Learn, + EvolveState::Adapt, + ] { + assert!(state.can_transition_to(EvolveState::Isolate)); + } + } + + #[test] + fn unsafe_skip_is_rejected() { + assert!(!EvolveState::Observe.can_transition_to(EvolveState::Deceive)); + assert!(!EvolveState::Observe.can_transition_to(EvolveState::Adapt)); + assert!(!EvolveState::Isolate.can_transition_to(EvolveState::Observe)); + } +} From 4f6e10a7f357bc99437ded64341f5e589a3f886b Mon Sep 17 00:00:00 2001 From: Boiko Oleg Date: Sat, 5 Sep 2026 07:19:53 +0300 Subject: [PATCH 04/46] feat(evolve): add event core and state manager --- .../sandbox-kernel/src/evolve/session.rs | 60 +++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 sandbox_runtime/crates/sandbox-kernel/src/evolve/session.rs diff --git a/sandbox_runtime/crates/sandbox-kernel/src/evolve/session.rs b/sandbox_runtime/crates/sandbox-kernel/src/evolve/session.rs new file mode 100644 index 0000000..8635abb --- /dev/null +++ b/sandbox_runtime/crates/sandbox-kernel/src/evolve/session.rs @@ -0,0 +1,60 @@ +use super::{EvolveState, RiskLevel, SecurityEvent}; +use serde::{Deserialize, Serialize}; +use std::time::{SystemTime, UNIX_EPOCH}; + +fn now_ms() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_millis() + .min(u64::MAX as u128) as u64 +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct EvolveSession { + pub session_id: String, + pub created_at_ms: u64, + pub last_event_at_ms: u64, + pub state: EvolveState, + pub risk_level: RiskLevel, + pub event_refs: Vec, + pub process_roots: Vec, + pub active_deception_profile: Option, + pub shadow_path_id: Option, + pub attack_trace_id: Option, +} + +impl EvolveSession { + pub fn new(session_id: impl Into) -> Self { + let now = now_ms(); + Self { + session_id: session_id.into(), + created_at_ms: now, + last_event_at_ms: now, + state: EvolveState::Observe, + risk_level: RiskLevel::Low, + event_refs: Vec::new(), + process_roots: Vec::new(), + active_deception_profile: None, + shadow_path_id: None, + attack_trace_id: None, + } + } + + pub fn record_event(&mut self, event: &SecurityEvent) { + self.last_event_at_ms = event.timestamp_ms; + self.event_refs.push(event.event_id.clone()); + + if let Some(pid) = event.process_id { + if !self.process_roots.contains(&pid) { + self.process_roots.push(pid); + } + } + + if let Some(risk) = event.risk_hint { + if risk.rank() > self.risk_level.rank() { + self.risk_level = risk; + } + } + } +} From a68e6bb514fe78bcd8f91eef5e148877fd583982 Mon Sep 17 00:00:00 2001 From: Boiko Oleg Date: Sat, 5 Sep 2026 07:19:55 +0300 Subject: [PATCH 05/46] feat(evolve): add event core and state manager --- .../sandbox-kernel/src/evolve/manager.rs | 230 ++++++++++++++++++ 1 file changed, 230 insertions(+) create mode 100644 sandbox_runtime/crates/sandbox-kernel/src/evolve/manager.rs diff --git a/sandbox_runtime/crates/sandbox-kernel/src/evolve/manager.rs b/sandbox_runtime/crates/sandbox-kernel/src/evolve/manager.rs new file mode 100644 index 0000000..9400093 --- /dev/null +++ b/sandbox_runtime/crates/sandbox-kernel/src/evolve/manager.rs @@ -0,0 +1,230 @@ +use super::{ + EvolveSession, EvolveState, RiskLevel, SecurityEvent, StateTransitionError, +}; +use serde::Serialize; +use std::collections::{HashMap, VecDeque}; + +const DEFAULT_EVENT_CAPACITY: usize = 1024; +const DEFAULT_SESSION_ID: &str = "runtime-default"; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum EvolveDecision { + LegacyIsolate, + Observe, + EnhancedTelemetry, + Isolate, +} + +#[derive(Debug, Clone, Serialize)] +pub struct EvolveStatus { + pub enabled: bool, + pub state: EvolveState, + pub events_buffered: usize, + pub sessions: usize, +} + +pub struct EvolveManager { + enabled: bool, + state: EvolveState, + events: VecDeque, + sessions: HashMap, + event_capacity: usize, +} + +impl Default for EvolveManager { + fn default() -> Self { + Self::new() + } +} + +impl EvolveManager { + pub fn new() -> Self { + let mut sessions = HashMap::new(); + sessions.insert( + DEFAULT_SESSION_ID.to_string(), + EvolveSession::new(DEFAULT_SESSION_ID), + ); + + Self { + enabled: false, + state: EvolveState::Observe, + events: VecDeque::with_capacity(DEFAULT_EVENT_CAPACITY), + sessions, + event_capacity: DEFAULT_EVENT_CAPACITY, + } + } + + pub fn is_enabled(&self) -> bool { + self.enabled + } + + pub fn set_enabled(&mut self, enabled: bool) { + self.enabled = enabled; + } + + pub fn state(&self) -> EvolveState { + self.state + } + + pub fn status(&self) -> EvolveStatus { + EvolveStatus { + enabled: self.enabled, + state: self.state, + events_buffered: self.events.len(), + sessions: self.sessions.len(), + } + } + + pub fn recent_events(&self, limit: usize) -> Vec { + let limit = limit.min(self.events.len()); + self.events + .iter() + .rev() + .take(limit) + .cloned() + .collect::>() + .into_iter() + .rev() + .collect() + } + + pub fn transition(&mut self, next: EvolveState) -> Result<(), StateTransitionError> { + if !self.state.can_transition_to(next) { + return Err(StateTransitionError::InvalidTransition { + from: self.state, + to: next, + }); + } + + self.state = next; + Ok(()) + } + + pub fn mark_isolated(&mut self) { + if self.state != EvolveState::Isolate { + self.state = EvolveState::Isolate; + } + + for session in self.sessions.values_mut() { + session.state = EvolveState::Isolate; + } + } + + pub fn ingest_event(&mut self, mut event: SecurityEvent) -> EvolveDecision { + let session_id = event + .session_id + .clone() + .unwrap_or_else(|| DEFAULT_SESSION_ID.to_string()); + event.session_id = Some(session_id.clone()); + + let session = self + .sessions + .entry(session_id.clone()) + .or_insert_with(|| EvolveSession::new(session_id)); + session.record_event(&event); + + let risk = event.risk_hint.unwrap_or(RiskLevel::Low); + self.push_event(event); + + if !self.enabled { + return EvolveDecision::LegacyIsolate; + } + + match risk { + RiskLevel::Low => EvolveDecision::Observe, + RiskLevel::Medium => { + self.enter_suspect_state(); + EvolveDecision::EnhancedTelemetry + } + RiskLevel::High | RiskLevel::Critical => { + self.enter_suspect_state(); + + // Phase 8.1 intentionally fails closed here. The event pipeline is active, but + // Deception Fabric is not implemented yet, so high-risk behavior cannot safely be + // redirected and must still escalate to existing isolation. + EvolveDecision::Isolate + } + } + } + + fn enter_suspect_state(&mut self) { + if self.state == EvolveState::Observe { + let _ = self.transition(EvolveState::Suspect); + } + + if let Some(session) = self.sessions.get_mut(DEFAULT_SESSION_ID) { + if session.state == EvolveState::Observe { + session.state = EvolveState::Suspect; + } + } + } + + fn push_event(&mut self, event: SecurityEvent) { + if self.events.len() >= self.event_capacity { + self.events.pop_front(); + } + self.events.push_back(event); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::evolve::{EventSource, SecurityEventType}; + + #[test] + fn disabled_manager_preserves_legacy_isolation_decision() { + let mut manager = EvolveManager::new(); + let event = SecurityEvent::new(EventSource::Canary, SecurityEventType::CanaryAccess) + .with_risk_hint(RiskLevel::High); + + assert_eq!( + manager.ingest_event(event), + EvolveDecision::LegacyIsolate + ); + assert_eq!(manager.recent_events(10).len(), 1); + } + + #[test] + fn enabled_medium_risk_enters_suspect_without_isolation() { + let mut manager = EvolveManager::new(); + manager.set_enabled(true); + + let event = SecurityEvent::new(EventSource::Policy, SecurityEventType::PolicyViolation) + .with_risk_hint(RiskLevel::Medium); + + assert_eq!( + manager.ingest_event(event), + EvolveDecision::EnhancedTelemetry + ); + assert_eq!(manager.state(), EvolveState::Suspect); + } + + #[test] + fn enabled_high_risk_fails_closed_until_deception_exists() { + let mut manager = EvolveManager::new(); + manager.set_enabled(true); + + let event = SecurityEvent::new(EventSource::Canary, SecurityEventType::CanaryAccess) + .with_risk_hint(RiskLevel::High); + + assert_eq!(manager.ingest_event(event), EvolveDecision::Isolate); + assert_eq!(manager.state(), EvolveState::Suspect); + } + + #[test] + fn event_buffer_is_bounded() { + let mut manager = EvolveManager::new(); + manager.event_capacity = 2; + + for _ in 0..3 { + manager.ingest_event(SecurityEvent::new( + EventSource::System, + SecurityEventType::PolicyViolation, + )); + } + + assert_eq!(manager.recent_events(10).len(), 2); + } +} From bbc75edf63b0cf8055d53b829e25466bf8e5e83b Mon Sep 17 00:00:00 2001 From: Boiko Oleg Date: Sat, 5 Sep 2026 07:20:25 +0300 Subject: [PATCH 06/46] feat(evolve): export event core --- sandbox_runtime/crates/sandbox-kernel/src/lib.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/sandbox_runtime/crates/sandbox-kernel/src/lib.rs b/sandbox_runtime/crates/sandbox-kernel/src/lib.rs index df18f6f..88b8fe6 100644 --- a/sandbox_runtime/crates/sandbox-kernel/src/lib.rs +++ b/sandbox_runtime/crates/sandbox-kernel/src/lib.rs @@ -1,6 +1,7 @@ pub mod canary; pub mod containment; pub mod egress; +pub mod evolve; pub mod panic; pub mod privilege; pub mod tmux; @@ -9,6 +10,10 @@ pub mod watchdog; pub use canary::{CanaryManager, CanaryTrap}; pub use containment::{apply_runtime_containment, stop_tor_best_effort, ContainmentError}; pub use egress::{AuditMode, EgressConfig, EgressManager}; +pub use evolve::{ + EventSource, EvolveDecision, EvolveManager, EvolveSession, EvolveState, EvolveStatus, RiskLevel, + SecurityEvent, SecurityEventType, StateTransitionError, +}; pub use panic::KillSwitch; pub use privilege::{ audit_exec_identity, audit_identity_conflicts_with_reserved_runtime_uid, browser_exec_identity, From 222568b7875fd144d931c297e1bc71d9747bb7c7 Mon Sep 17 00:00:00 2001 From: Boiko Oleg Date: Sat, 5 Sep 2026 07:20:27 +0300 Subject: [PATCH 07/46] feat(evolve): route canary trips through event pipeline --- .../crates/sandbox-kernel/src/canary.rs | 106 +++++++++++++++--- 1 file changed, 93 insertions(+), 13 deletions(-) diff --git a/sandbox_runtime/crates/sandbox-kernel/src/canary.rs b/sandbox_runtime/crates/sandbox-kernel/src/canary.rs index 5e748f3..98337be 100644 --- a/sandbox_runtime/crates/sandbox-kernel/src/canary.rs +++ b/sandbox_runtime/crates/sandbox-kernel/src/canary.rs @@ -4,8 +4,10 @@ use std::sync::Arc; use std::time::Duration; use thiserror::Error; use tokio::fs; +use tokio::sync::mpsc::UnboundedSender; use tracing::{error, info}; +use crate::evolve::{EventSource, RiskLevel, SecurityEvent, SecurityEventType}; use crate::panic::KillSwitch; #[derive(Error, Debug)] @@ -27,6 +29,7 @@ pub struct CanaryManager { traps: Vec, is_armed: Arc, triggered_count: Arc, + event_sender: Option>, } impl Default for CanaryManager { @@ -41,10 +44,21 @@ impl CanaryManager { traps: Vec::new(), is_armed: Arc::new(AtomicBool::new(false)), triggered_count: Arc::new(AtomicUsize::new(0)), + event_sender: None, } } - /// Plants deceptive honeytoken files into the target filesystem + /// Creates a canary manager whose trip events are delegated to the Evolve event pipeline. + /// + /// If the receiver disappears, canary handling fails closed and falls back to KillSwitch. + pub fn with_event_sender(event_sender: UnboundedSender) -> Self { + Self { + event_sender: Some(event_sender), + ..Self::new() + } + } + + /// Plants deceptive honeytoken files into the target filesystem. pub async fn arm_canaries(&mut self, base_dir: &Path) -> Result, CanaryError> { let mut planted = Vec::new(); @@ -144,7 +158,6 @@ users: self.traps = planted.clone(); self.is_armed.store(true, Ordering::SeqCst); - // Spawn background file access monitor self.spawn_watcher(planted.clone()); info!("Armed {} canary honeytoken tripwires.", planted.len()); @@ -154,24 +167,34 @@ users: fn spawn_watcher(&self, traps: Vec) { let is_armed = self.is_armed.clone(); let triggered_count = self.triggered_count.clone(); + let event_sender = self.event_sender.clone(); tokio::spawn(async move { - info!("Canary inotify/access watcher loop started."); + info!("Canary metadata watcher loop started."); - // Record initial metadata timestamps and size - let mut initial_meta: Vec<(PathBuf, u64, Option)> = Vec::new(); + // Phase 8.1 keeps the existing metadata polling source and decouples its reaction. + // EVENT_MODEL.md tracks the later migration to fanotify/inotify. + let mut initial_meta: Vec<( + PathBuf, + String, + u64, + Option, + )> = Vec::new(); for trap in &traps { if let Ok(meta) = std::fs::metadata(&trap.file_path) { - let len = meta.len(); - let accessed = meta.accessed().ok(); - initial_meta.push((trap.file_path.clone(), len, accessed)); + initial_meta.push(( + trap.file_path.clone(), + trap.trap_type.clone(), + meta.len(), + meta.accessed().ok(), + )); } } while is_armed.load(Ordering::SeqCst) { tokio::time::sleep(Duration::from_millis(500)).await; - for (path, orig_len, orig_accessed) in &initial_meta { + for (path, trap_type, orig_len, orig_accessed) in &initial_meta { if let Ok(meta) = std::fs::metadata(path) { let current_len = meta.len(); let current_accessed = meta.accessed().ok(); @@ -183,10 +206,12 @@ users: }; if modified || accessed { - triggered_count.fetch_add(1, Ordering::SeqCst); - error!("TRIPWIRE TRIGGERED! Unauthorized access or modification on canary: {:?}", path); - let _ = - KillSwitch::trigger(&format!("Canary trap triggered: {:?}", path)); + handle_canary_trigger( + event_sender.as_ref(), + triggered_count.as_ref(), + path, + trap_type, + ); is_armed.store(false, Ordering::SeqCst); return; } @@ -209,10 +234,44 @@ users: } } +fn handle_canary_trigger( + event_sender: Option<&UnboundedSender>, + triggered_count: &AtomicUsize, + path: &Path, + trap_type: &str, +) { + triggered_count.fetch_add(1, Ordering::SeqCst); + error!( + "TRIPWIRE TRIGGERED! Unauthorized access or modification on canary: {:?}", + path + ); + + let event = SecurityEvent::new(EventSource::Canary, SecurityEventType::CanaryAccess) + .with_resource(path.to_string_lossy().into_owned()) + .with_risk_hint(RiskLevel::High) + .with_metadata(serde_json::json!({ + "trap_type": trap_type, + "legacy_reaction": "isolate" + })); + + if let Some(sender) = event_sender { + if sender.send(event).is_ok() { + return; + } + + error!("Evolve event receiver unavailable; falling back to emergency isolation."); + } + + // Compatibility/failure fallback. The daemon uses the event-driven path, but a standalone + // CanaryManager without an Evolve receiver must preserve the old fail-closed behavior. + let _ = KillSwitch::trigger(&format!("Canary trap triggered: {:?}", path)); +} + #[cfg(test)] mod tests { use super::*; use tempfile::TempDir; + use tokio::sync::mpsc; #[tokio::test] async fn test_arm_canaries() { @@ -228,4 +287,25 @@ mod tests { assert!(trap.file_path.exists()); } } + + #[tokio::test] + async fn trigger_emits_evolve_event_when_receiver_exists() { + let (sender, mut receiver) = mpsc::unbounded_channel(); + let triggered_count = AtomicUsize::new(0); + let path = Path::new("/workspace/.env.decoy"); + + handle_canary_trigger( + Some(&sender), + &triggered_count, + path, + "env_secrets", + ); + + let event = receiver.recv().await.expect("expected canary event"); + assert_eq!(triggered_count.load(Ordering::SeqCst), 1); + assert_eq!(event.source, EventSource::Canary); + assert_eq!(event.event_type, SecurityEventType::CanaryAccess); + assert_eq!(event.resource.as_deref(), Some("/workspace/.env.decoy")); + assert_eq!(event.risk_hint, Some(RiskLevel::High)); + } } From 7f0dd1e716f87576ce642dfb14d50844a18ed429 Mon Sep 17 00:00:00 2001 From: Boiko Oleg Date: Sat, 5 Sep 2026 07:20:54 +0300 Subject: [PATCH 08/46] feat(evolve): add daemon status and event routes --- .../sandbox-daemon/src/routes/evolve.rs | 54 +++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 sandbox_runtime/crates/sandbox-daemon/src/routes/evolve.rs diff --git a/sandbox_runtime/crates/sandbox-daemon/src/routes/evolve.rs b/sandbox_runtime/crates/sandbox-daemon/src/routes/evolve.rs new file mode 100644 index 0000000..70da2e9 --- /dev/null +++ b/sandbox_runtime/crates/sandbox-daemon/src/routes/evolve.rs @@ -0,0 +1,54 @@ +use axum::{extract::Query, http::StatusCode, Extension, Json}; +use serde::Deserialize; +use serde_json::json; +use std::sync::Arc; +use tokio::sync::Mutex; + +use sandbox_kernel::EvolveManager; + +#[derive(Debug, Deserialize)] +pub struct SetEvolveEnabledRequest { + pub enabled: bool, +} + +#[derive(Debug, Deserialize)] +pub struct EventsQuery { + pub limit: Option, +} + +pub async fn handle_set_enabled( + Extension(evolve_mgr): Extension>>, + Json(payload): Json, +) -> Result, (StatusCode, Json)> { + if payload.enabled && sandbox_kernel::KillSwitch::is_isolated() { + return Err(( + StatusCode::CONFLICT, + Json(json!({ + "error": "cannot enable Evolve while the runtime is isolated; recreate or reset the sandbox first" + })), + )); + } + + let mut manager = evolve_mgr.lock().await; + manager.set_enabled(payload.enabled); + Ok(Json(json!(manager.status()))) +} + +pub async fn handle_status( + Extension(evolve_mgr): Extension>>, +) -> Json { + let manager = evolve_mgr.lock().await; + Json(json!(manager.status())) +} + +pub async fn handle_events( + Extension(evolve_mgr): Extension>>, + Query(query): Query, +) -> Json { + let limit = query.limit.unwrap_or(100).min(1000); + let manager = evolve_mgr.lock().await; + Json(json!({ + "events": manager.recent_events(limit), + "limit": limit + })) +} From d46d40368ebf09c6cd1b6c5190ac24846a164129 Mon Sep 17 00:00:00 2001 From: Boiko Oleg Date: Sat, 5 Sep 2026 07:20:56 +0300 Subject: [PATCH 09/46] feat(evolve): register daemon evolve routes module --- sandbox_runtime/crates/sandbox-daemon/src/routes/mod.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/sandbox_runtime/crates/sandbox-daemon/src/routes/mod.rs b/sandbox_runtime/crates/sandbox-daemon/src/routes/mod.rs index 29ba0c3..c712568 100644 --- a/sandbox_runtime/crates/sandbox-daemon/src/routes/mod.rs +++ b/sandbox_runtime/crates/sandbox-daemon/src/routes/mod.rs @@ -2,6 +2,7 @@ pub mod background; pub mod browser; pub mod canary; pub mod egress; +pub mod evolve; pub mod exec; pub mod probe; pub mod tor; From 0364796f6c45bcfae2e20c5545a96d3c0a8536fa Mon Sep 17 00:00:00 2001 From: Boiko Oleg Date: Sat, 5 Sep 2026 07:20:58 +0300 Subject: [PATCH 10/46] feat(evolve): wire event pipeline into sandbox daemon --- .../crates/sandbox-daemon/src/main.rs | 84 ++++++++++++++++--- 1 file changed, 74 insertions(+), 10 deletions(-) diff --git a/sandbox_runtime/crates/sandbox-daemon/src/main.rs b/sandbox_runtime/crates/sandbox-daemon/src/main.rs index ba53a5c..698f797 100644 --- a/sandbox_runtime/crates/sandbox-daemon/src/main.rs +++ b/sandbox_runtime/crates/sandbox-daemon/src/main.rs @@ -7,10 +7,10 @@ use serde_json::json; use std::io::{Error as IoError, ErrorKind}; use std::net::SocketAddr; use std::sync::Arc; -use tokio::sync::Mutex; +use tokio::sync::{mpsc, Mutex}; use tower_http::cors::CorsLayer; use tower_http::trace::TraceLayer; -use tracing::{info, warn}; +use tracing::{error, info, warn}; use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt}; mod auth; @@ -20,7 +20,8 @@ use auth::{ratchet_auth_middleware, RatchetAuthState}; use sandbox_kernel::canary::CanaryManager; use sandbox_kernel::{ apply_runtime_containment, audit_identity_conflicts_with_reserved_runtime_uid, - configured_audit_exec_identity, EgressConfig, EgressManager, + configured_audit_exec_identity, EgressConfig, EgressManager, EvolveDecision, EvolveManager, + KillSwitch, }; fn validate_runtime_identity_contract() -> Result<(), Box> { @@ -99,11 +100,64 @@ async fn main() -> Result<(), Box> { ) .expect("Failed to initialize RatchetAuthState"); - let canary_mgr = Arc::new(Mutex::new(CanaryManager::new())); + let evolve_mgr = Arc::new(Mutex::new(EvolveManager::new())); + let (evolve_event_tx, mut evolve_event_rx) = mpsc::unbounded_channel(); + let canary_mgr = Arc::new(Mutex::new(CanaryManager::with_event_sender( + evolve_event_tx, + ))); + + // Canary and future sensors publish facts into the Evolve event pipeline. The Evolve manager + // decides the reaction. Until Deception Fabric exists, high-risk events intentionally retain + // the existing fail-closed isolation behavior. + let evolve_event_manager = evolve_mgr.clone(); + tokio::spawn(async move { + while let Some(event) = evolve_event_rx.recv().await { + let event_id = event.event_id.clone(); + let resource = event.resource.clone(); + let decision = { + let mut manager = evolve_event_manager.lock().await; + manager.ingest_event(event) + }; + + match decision { + EvolveDecision::Observe => { + info!(event_id = %event_id, "Evolve recorded low-risk security event"); + } + EvolveDecision::EnhancedTelemetry => { + warn!( + event_id = %event_id, + resource = ?resource, + "Evolve entered suspicious observation state" + ); + } + EvolveDecision::LegacyIsolate | EvolveDecision::Isolate => { + let reason = format!( + "Evolve security event requires isolation: event_id={event_id}, resource={resource:?}" + ); + match KillSwitch::trigger(&reason) { + Ok(()) => { + let mut manager = evolve_event_manager.lock().await; + manager.mark_isolated(); + } + Err(err) => { + // KillSwitch itself is responsible for fail-closed behavior when the + // kernel blackout cannot be installed. Keep a loud daemon-side trace. + error!( + event_id = %event_id, + error = %err, + "Evolve isolation request failed" + ); + } + } + } + } + } + }); let health_router = Router::new() .route("/health", get(handle_health)) - .layer(Extension(canary_mgr.clone())); + .layer(Extension(canary_mgr.clone())) + .layer(Extension(evolve_mgr.clone())); let protected_routes = Router::new() .route("/execute", post(routes::exec::handle_execute)) @@ -132,6 +186,12 @@ async fn main() -> Result<(), Box> { .route("/rotate_tor", post(routes::tor::handle_rotate_tor)) .route("/arm_canary", post(routes::canary::handle_arm_canary)) .route("/canary_status", get(routes::canary::handle_canary_status)) + .route( + "/evolve/enable", + post(routes::evolve::handle_set_enabled), + ) + .route("/evolve/status", get(routes::evolve::handle_status)) + .route("/evolve/events", get(routes::evolve::handle_events)) .route("/http_probe", post(routes::probe::handle_http_probe)) .route( "/browser_audit", @@ -141,7 +201,8 @@ async fn main() -> Result<(), Box> { auth_state.clone(), ratchet_auth_middleware, )) - .layer(Extension(canary_mgr)); + .layer(Extension(canary_mgr)) + .layer(Extension(evolve_mgr)); let app = Router::new() .merge(health_router) @@ -159,15 +220,18 @@ async fn main() -> Result<(), Box> { async fn handle_health( Extension(canary_mgr): Extension>>, + Extension(evolve_mgr): Extension>>, ) -> Json { - let mgr = canary_mgr.lock().await; + let canary = canary_mgr.lock().await; + let evolve = evolve_mgr.lock().await; Json(json!({ "status": "ok", "service": "sandbox-daemon", "version": "0.1.0", "isolated": sandbox_kernel::KillSwitch::is_isolated(), - "canary_armed": mgr.is_armed(), - "canary_traps_count": mgr.get_traps().len(), - "canary_triggered_count": mgr.triggered_count() + "canary_armed": canary.is_armed(), + "canary_traps_count": canary.get_traps().len(), + "canary_triggered_count": canary.triggered_count(), + "evolve": evolve.status() })) } From e34e4333d97c9ecda56c668f3d2ec517abf08598 Mon Sep 17 00:00:00 2001 From: Boiko Oleg Date: Sat, 5 Sep 2026 07:21:31 +0300 Subject: [PATCH 11/46] fix(evolve): scope legacy isolation to security tripwires --- .../sandbox-kernel/src/evolve/manager.rs | 27 ++++++++++++++----- 1 file changed, 21 insertions(+), 6 deletions(-) diff --git a/sandbox_runtime/crates/sandbox-kernel/src/evolve/manager.rs b/sandbox_runtime/crates/sandbox-kernel/src/evolve/manager.rs index 9400093..010bc7c 100644 --- a/sandbox_runtime/crates/sandbox-kernel/src/evolve/manager.rs +++ b/sandbox_runtime/crates/sandbox-kernel/src/evolve/manager.rs @@ -125,20 +125,26 @@ impl EvolveManager { session.record_event(&event); let risk = event.risk_hint.unwrap_or(RiskLevel::Low); + let event_type = event.event_type; self.push_event(event); if !self.enabled { - return EvolveDecision::LegacyIsolate; + return match event_type { + super::SecurityEventType::CanaryAccess => EvolveDecision::LegacyIsolate, + super::SecurityEventType::EscapeAttempt + | super::SecurityEventType::ControlPlaneAccess => EvolveDecision::Isolate, + _ => EvolveDecision::Observe, + }; } match risk { RiskLevel::Low => EvolveDecision::Observe, RiskLevel::Medium => { - self.enter_suspect_state(); + self.enter_suspect_state(&session_id); EvolveDecision::EnhancedTelemetry } RiskLevel::High | RiskLevel::Critical => { - self.enter_suspect_state(); + self.enter_suspect_state(&session_id); // Phase 8.1 intentionally fails closed here. The event pipeline is active, but // Deception Fabric is not implemented yet, so high-risk behavior cannot safely be @@ -148,12 +154,12 @@ impl EvolveManager { } } - fn enter_suspect_state(&mut self) { + fn enter_suspect_state(&mut self, session_id: &str) { if self.state == EvolveState::Observe { let _ = self.transition(EvolveState::Suspect); } - if let Some(session) = self.sessions.get_mut(DEFAULT_SESSION_ID) { + if let Some(session) = self.sessions.get_mut(session_id) { if session.state == EvolveState::Observe { session.state = EvolveState::Suspect; } @@ -174,7 +180,7 @@ mod tests { use crate::evolve::{EventSource, SecurityEventType}; #[test] - fn disabled_manager_preserves_legacy_isolation_decision() { + fn disabled_manager_preserves_canary_legacy_isolation_decision() { let mut manager = EvolveManager::new(); let event = SecurityEvent::new(EventSource::Canary, SecurityEventType::CanaryAccess) .with_risk_hint(RiskLevel::High); @@ -186,6 +192,15 @@ mod tests { assert_eq!(manager.recent_events(10).len(), 1); } + #[test] + fn disabled_manager_does_not_isolate_on_ordinary_telemetry() { + let mut manager = EvolveManager::new(); + let event = SecurityEvent::new(EventSource::Process, SecurityEventType::ProcessExec) + .with_risk_hint(RiskLevel::Low); + + assert_eq!(manager.ingest_event(event), EvolveDecision::Observe); + } + #[test] fn enabled_medium_risk_enters_suspect_without_isolation() { let mut manager = EvolveManager::new(); From a1528d5181fea0cb6d95d5db4107932fa3dd0aaa Mon Sep 17 00:00:00 2001 From: Boiko Oleg Date: Sat, 5 Sep 2026 07:25:50 +0300 Subject: [PATCH 12/46] feat(evolve): extend security event builders --- .../crates/sandbox-kernel/src/evolve/event.rs | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/sandbox_runtime/crates/sandbox-kernel/src/evolve/event.rs b/sandbox_runtime/crates/sandbox-kernel/src/evolve/event.rs index cb32945..9c889d6 100644 --- a/sandbox_runtime/crates/sandbox-kernel/src/evolve/event.rs +++ b/sandbox_runtime/crates/sandbox-kernel/src/evolve/event.rs @@ -125,6 +125,37 @@ impl SecurityEvent { self } + pub fn with_destination(mut self, destination: impl Into) -> Self { + self.destination = Some(destination.into()); + self + } + + pub fn with_command(mut self, command: impl Into) -> Self { + self.command = Some(command.into()); + self + } + + pub fn with_arguments(mut self, arguments: Vec) -> Self { + self.arguments = arguments; + self + } + + pub fn with_result(mut self, result: impl Into) -> Self { + self.result = Some(result.into()); + self + } + + pub fn with_process(mut self, process_id: u32, parent_process_id: Option) -> Self { + self.process_id = Some(process_id); + self.parent_process_id = parent_process_id; + self + } + + pub fn with_uid(mut self, uid: u32) -> Self { + self.uid = Some(uid); + self + } + pub fn with_risk_hint(mut self, risk: RiskLevel) -> Self { self.risk_hint = Some(risk); self From c3fe04dbc0885d9c3d999a9d698e4c536c877b38 Mon Sep 17 00:00:00 2001 From: Boiko Oleg Date: Sat, 5 Sep 2026 07:25:52 +0300 Subject: [PATCH 13/46] feat(evolve): add shared daemon event sink --- .../sandbox-daemon/src/evolve_events.rs | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 sandbox_runtime/crates/sandbox-daemon/src/evolve_events.rs diff --git a/sandbox_runtime/crates/sandbox-daemon/src/evolve_events.rs b/sandbox_runtime/crates/sandbox-daemon/src/evolve_events.rs new file mode 100644 index 0000000..166b522 --- /dev/null +++ b/sandbox_runtime/crates/sandbox-daemon/src/evolve_events.rs @@ -0,0 +1,33 @@ +use sandbox_kernel::SecurityEvent; +use tokio::sync::mpsc::UnboundedSender; +use tracing::warn; + +#[derive(Clone)] +pub struct EvolveEventSink { + sender: UnboundedSender, +} + +impl EvolveEventSink { + pub fn new(sender: UnboundedSender) -> Self { + Self { sender } + } + + pub fn sender(&self) -> UnboundedSender { + self.sender.clone() + } + + /// Best-effort telemetry delivery. + /// + /// Security enforcement must never depend on this return value. Route-level RoE checks + /// continue to deny locally, while canary has its own fail-closed fallback if the receiver + /// disappears. + pub fn emit(&self, event: SecurityEvent) -> bool { + let event_id = event.event_id.clone(); + if self.sender.send(event).is_ok() { + true + } else { + warn!(event_id = %event_id, "Evolve event receiver is unavailable"); + false + } + } +} From 2605f969ef62fe6e960bed57ec594c04e020fe31 Mon Sep 17 00:00:00 2001 From: Boiko Oleg Date: Sat, 5 Sep 2026 07:25:54 +0300 Subject: [PATCH 14/46] feat(evolve): expose event sink to daemon sensors --- sandbox_runtime/crates/sandbox-daemon/src/main.rs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/sandbox_runtime/crates/sandbox-daemon/src/main.rs b/sandbox_runtime/crates/sandbox-daemon/src/main.rs index 698f797..666c807 100644 --- a/sandbox_runtime/crates/sandbox-daemon/src/main.rs +++ b/sandbox_runtime/crates/sandbox-daemon/src/main.rs @@ -14,9 +14,11 @@ use tracing::{error, info, warn}; use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt}; mod auth; +mod evolve_events; mod routes; use auth::{ratchet_auth_middleware, RatchetAuthState}; +use evolve_events::EvolveEventSink; use sandbox_kernel::canary::CanaryManager; use sandbox_kernel::{ apply_runtime_containment, audit_identity_conflicts_with_reserved_runtime_uid, @@ -102,8 +104,9 @@ async fn main() -> Result<(), Box> { let evolve_mgr = Arc::new(Mutex::new(EvolveManager::new())); let (evolve_event_tx, mut evolve_event_rx) = mpsc::unbounded_channel(); + let evolve_event_sink = EvolveEventSink::new(evolve_event_tx); let canary_mgr = Arc::new(Mutex::new(CanaryManager::with_event_sender( - evolve_event_tx, + evolve_event_sink.sender(), ))); // Canary and future sensors publish facts into the Evolve event pipeline. The Evolve manager @@ -202,7 +205,8 @@ async fn main() -> Result<(), Box> { ratchet_auth_middleware, )) .layer(Extension(canary_mgr)) - .layer(Extension(evolve_mgr)); + .layer(Extension(evolve_mgr)) + .layer(Extension(evolve_event_sink)); let app = Router::new() .merge(health_router) From aaecf2812c1176b9a6676ec871c5eefe2c97b44b Mon Sep 17 00:00:00 2001 From: Boiko Oleg Date: Sat, 5 Sep 2026 07:26:49 +0300 Subject: [PATCH 15/46] feat(evolve): instrument synchronous execution events --- .../crates/sandbox-daemon/src/routes/exec.rs | 100 ++++++++++++++++-- 1 file changed, 90 insertions(+), 10 deletions(-) diff --git a/sandbox_runtime/crates/sandbox-daemon/src/routes/exec.rs b/sandbox_runtime/crates/sandbox-daemon/src/routes/exec.rs index c8cdff3..0b801a0 100644 --- a/sandbox_runtime/crates/sandbox-daemon/src/routes/exec.rs +++ b/sandbox_runtime/crates/sandbox-daemon/src/routes/exec.rs @@ -1,4 +1,4 @@ -use axum::{http::StatusCode, Json}; +use axum::{http::StatusCode, Extension, Json}; use serde::{Deserialize, Serialize}; use serde_json::json; #[cfg(unix)] @@ -9,10 +9,12 @@ use tokio::process::Command; use tokio::time::timeout; use tracing::{error, info, warn}; +use crate::evolve_events::EvolveEventSink; #[cfg(not(target_os = "windows"))] use sandbox_kernel::audit_exec_identity; use sandbox_kernel::tmux::TmuxManager; use sandbox_kernel::watchdog::{process_command_output, WatchdogResult}; +use sandbox_kernel::{EventSource, RiskLevel, SecurityEvent, SecurityEventType}; const SAFE_CHILD_PATH: &str = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"; @@ -21,6 +23,7 @@ pub struct ExecRequest { pub command: String, pub timeout_secs: Option, pub work_dir: Option, + pub evolve_session_id: Option, } #[derive(Debug, Serialize)] @@ -38,11 +41,40 @@ pub struct InteractiveTmuxRequest { pub input: String, } +fn emit_exec_event( + event_sink: &EvolveEventSink, + session_id: Option<&str>, + event_type: SecurityEventType, + command: &str, + work_dir: &str, + result: Option, + metadata: serde_json::Value, +) { + let mut event = SecurityEvent::new(EventSource::Process, event_type) + .with_command(command.to_string()) + .with_resource(work_dir.to_string()) + .with_risk_hint(RiskLevel::Low) + .with_metadata(metadata); + + if let Some(session_id) = session_id { + event = event.with_session_id(session_id.to_string()); + } + if let Some(result) = result { + event = event.with_result(result); + } + + event_sink.emit(event); +} + pub async fn handle_execute( + Extension(event_sink): Extension, Json(payload): Json, ) -> Result, (StatusCode, Json)> { - let timeout_duration = Duration::from_secs(payload.timeout_secs.unwrap_or(60)); + let timeout_secs = payload.timeout_secs.unwrap_or(60); + let timeout_duration = Duration::from_secs(timeout_secs); let work_dir = payload.work_dir.unwrap_or_else(|| "/workspace".to_string()); + let command_text = payload.command; + let evolve_session_id = payload.evolve_session_id; let cmd_id = format!( "exec_{}", std::time::SystemTime::now() @@ -51,27 +83,38 @@ pub async fn handle_execute( .as_millis() ); + emit_exec_event( + &event_sink, + evolve_session_id.as_deref(), + SecurityEventType::ProcessExec, + &command_text, + &work_dir, + Some("started".to_string()), + json!({ + "execution_mode": "sync", + "timeout_secs": timeout_secs, + "command_id": cmd_id + }), + ); + info!("Executing unprivileged audit command in '{}'", work_dir); #[cfg(target_os = "windows")] let mut cmd = { let mut c = Command::new("powershell"); - c.args(["-NoProfile", "-Command", &payload.command]); + c.args(["-NoProfile", "-Command", &command_text]); c }; #[cfg(not(target_os = "windows"))] let mut cmd = { let mut c = Command::new("/bin/sh"); - c.args(["-c", &payload.command]); + c.args(["-c", &command_text]); let (uid, gid) = audit_exec_identity(); #[cfg(unix)] { c.as_std_mut().uid(uid).gid(gid); } - // The daemon carries control-plane trust material in its environment. Agent-controlled - // children must receive a clean environment so BRIDGE_SESSION_KEY_HEX/HOST_PUBKEY_HEX and - // future daemon secrets can never be recovered with `env` or /proc/self/environ. c.env_clear(); c.env("HOME", "/tmp"); c.env("PATH", SAFE_CHILD_PATH); @@ -86,6 +129,15 @@ pub async fn handle_execute( let output = match timeout(timeout_duration, cmd.output()).await { Ok(Ok(output)) => output, Ok(Err(e)) => { + emit_exec_event( + &event_sink, + evolve_session_id.as_deref(), + SecurityEventType::ProcessExit, + &command_text, + &work_dir, + Some("spawn_error".to_string()), + json!({"command_id": cmd_id}), + ); error!("Command execution failed: {}", e); return Err(( StatusCode::INTERNAL_SERVER_ERROR, @@ -93,12 +145,22 @@ pub async fn handle_execute( )); } Err(_) => { + emit_exec_event( + &event_sink, + evolve_session_id.as_deref(), + SecurityEventType::ProcessExit, + &command_text, + &work_dir, + Some("timeout".to_string()), + json!({ + "command_id": cmd_id, + "timeout_secs": timeout_secs + }), + ); warn!("Command execution timed out after {:?}", timeout_duration); return Err(( StatusCode::GATEWAY_TIMEOUT, - Json( - json!({"error": format!("Command timed out after {}s", timeout_duration.as_secs())}), - ), + Json(json!({"error": format!("Command timed out after {}s", timeout_secs)})), )); } }; @@ -122,6 +184,21 @@ pub async fn handle_execute( log_file_path: None, }); + emit_exec_event( + &event_sink, + evolve_session_id.as_deref(), + SecurityEventType::ProcessExit, + &command_text, + &work_dir, + Some(format!("exit_code={exit_code}")), + json!({ + "command_id": cmd_id, + "is_truncated": watchdog_res.is_truncated, + "total_chars": watchdog_res.total_chars, + "log_file_path": watchdog_res.log_file_path + }), + ); + Ok(Json(ExecResponse { output: watchdog_res.output, exit_code, @@ -139,6 +216,9 @@ pub async fn handle_interactive_tmux( .unwrap_or_else(|| "audit_session".to_string()); info!("Sending interactive input to tmux session '{}'", session); + // Interactive input is intentionally not copied into Evolve telemetry because it may contain + // passwords, tokens or other secrets. Process-level tmux lifecycle remains observable through + // background session events. match TmuxManager::send_input(&session, &payload.input) { Ok(_) => Ok(Json(json!({"status": "success", "session": session}))), Err(e) => Err(( From 3cba00905ae8464b079fc65e6e02d8653cf3a3ae Mon Sep 17 00:00:00 2001 From: Boiko Oleg Date: Sat, 5 Sep 2026 07:26:53 +0300 Subject: [PATCH 16/46] feat(evolve): instrument background execution events --- .../sandbox-daemon/src/routes/background.rs | 77 ++++++++++++++++--- 1 file changed, 66 insertions(+), 11 deletions(-) diff --git a/sandbox_runtime/crates/sandbox-daemon/src/routes/background.rs b/sandbox_runtime/crates/sandbox-daemon/src/routes/background.rs index f0174ba..3be35d3 100644 --- a/sandbox_runtime/crates/sandbox-daemon/src/routes/background.rs +++ b/sandbox_runtime/crates/sandbox-daemon/src/routes/background.rs @@ -1,14 +1,17 @@ -use axum::{extract::Query, http::StatusCode, Json}; +use axum::{extract::Query, http::StatusCode, Extension, Json}; use serde::Deserialize; use serde_json::json; use tracing::info; +use crate::evolve_events::EvolveEventSink; use sandbox_kernel::tmux::TmuxManager; +use sandbox_kernel::{EventSource, RiskLevel, SecurityEvent, SecurityEventType}; #[derive(Debug, Deserialize)] pub struct StartBackgroundRequest { pub command: String, pub session: Option, + pub evolve_session_id: Option, } #[derive(Debug, Deserialize)] @@ -17,7 +20,28 @@ pub struct PollLogsQuery { pub last_lines: Option, } +fn emit_background_event( + event_sink: &EvolveEventSink, + session_id: &str, + event_type: SecurityEventType, + command: Option<&str>, + result: &str, +) { + let mut event = SecurityEvent::new(EventSource::Process, event_type) + .with_session_id(session_id.to_string()) + .with_result(result.to_string()) + .with_risk_hint(RiskLevel::Low) + .with_metadata(json!({"execution_mode": "tmux_background"})); + + if let Some(command) = command { + event = event.with_command(command.to_string()); + } + + event_sink.emit(event); +} + pub async fn handle_start_background( + Extension(event_sink): Extension, Json(payload): Json, ) -> Result, (StatusCode, Json)> { let session = payload.session.unwrap_or_else(|| { @@ -29,6 +53,9 @@ pub async fn handle_start_background( .as_secs() ) }); + let event_session_id = payload + .evolve_session_id + .unwrap_or_else(|| session.clone()); info!( "Starting background task in tmux session '{}': {}", @@ -36,15 +63,33 @@ pub async fn handle_start_background( ); match TmuxManager::start_session(&session, Some(&payload.command)) { - Ok(_) => Ok(Json(json!({ - "status": "started", - "session": session, - "command": payload.command - }))), - Err(e) => Err(( - StatusCode::INTERNAL_SERVER_ERROR, - Json(json!({"error": format!("Failed to start background task: {}", e)})), - )), + Ok(_) => { + emit_background_event( + &event_sink, + &event_session_id, + SecurityEventType::ProcessExec, + Some(&payload.command), + "started", + ); + Ok(Json(json!({ + "status": "started", + "session": session, + "command": payload.command + }))) + } + Err(e) => { + emit_background_event( + &event_sink, + &event_session_id, + SecurityEventType::ProcessExit, + Some(&payload.command), + "spawn_error", + ); + Err(( + StatusCode::INTERNAL_SERVER_ERROR, + Json(json!({"error": format!("Failed to start background task: {}", e)})), + )) + } } } @@ -70,6 +115,7 @@ pub async fn handle_poll_logs( } pub async fn handle_kill_background( + Extension(event_sink): Extension, Json(payload): Json, ) -> Result, (StatusCode, Json)> { let session = payload @@ -78,7 +124,16 @@ pub async fn handle_kill_background( .unwrap_or("audit_session"); match TmuxManager::kill_session(session) { - Ok(_) => Ok(Json(json!({"status": "killed", "session": session}))), + Ok(_) => { + emit_background_event( + &event_sink, + session, + SecurityEventType::ProcessExit, + None, + "killed", + ); + Ok(Json(json!({"status": "killed", "session": session}))) + } Err(e) => Err(( StatusCode::INTERNAL_SERVER_ERROR, Json(json!({"error": format!("Failed to kill session: {}", e)})), From 31371dc8f7e652b8e8b352e64f7d5348235dd269 Mon Sep 17 00:00:00 2001 From: Boiko Oleg Date: Sat, 5 Sep 2026 07:26:55 +0300 Subject: [PATCH 17/46] feat(evolve): instrument browser and policy events --- .../sandbox-daemon/src/routes/browser.rs | 84 ++++++++++++++++++- 1 file changed, 83 insertions(+), 1 deletion(-) diff --git a/sandbox_runtime/crates/sandbox-daemon/src/routes/browser.rs b/sandbox_runtime/crates/sandbox-daemon/src/routes/browser.rs index 20380d8..f5e2ded 100644 --- a/sandbox_runtime/crates/sandbox-daemon/src/routes/browser.rs +++ b/sandbox_runtime/crates/sandbox-daemon/src/routes/browser.rs @@ -1,4 +1,4 @@ -use axum::{http::StatusCode, Json}; +use axum::{http::StatusCode, Extension, Json}; use serde_json::Value; use std::process::Stdio; use std::time::Duration; @@ -6,7 +6,9 @@ use tokio::io::AsyncWriteExt; use tokio::process::Command; use tracing::{error, info}; +use crate::evolve_events::EvolveEventSink; use sandbox_kernel::browser_exec_identity; +use sandbox_kernel::{EventSource, RiskLevel, SecurityEvent, SecurityEventType}; const SAFE_CHILD_PATH: &str = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"; const TOR_BROWSER_PROXY: &str = "socks5://127.0.0.1:9050"; @@ -44,6 +46,55 @@ fn has_forbidden_authority_header(config: &Value) -> bool { }) } +fn evolve_session_id(config: &Value) -> Option<&str> { + config.get("evolve_session_id").and_then(Value::as_str) +} + +fn requested_url(config: &Value) -> Option<&str> { + config.get("url").and_then(Value::as_str) +} + +fn emit_browser_event( + event_sink: &EvolveEventSink, + config: &Value, + event_type: SecurityEventType, + risk: RiskLevel, + result: &str, +) { + let mut event = SecurityEvent::new(EventSource::Browser, event_type) + .with_result(result.to_string()) + .with_risk_hint(risk); + + if let Some(session_id) = evolve_session_id(config) { + event = event.with_session_id(session_id.to_string()); + } + if let Some(url) = requested_url(config) { + event = event.with_destination(url.to_string()); + } + + event_sink.emit(event); +} + +fn emit_browser_policy_violation( + event_sink: &EvolveEventSink, + config: &Value, + reason: &str, +) { + let mut event = SecurityEvent::new(EventSource::Policy, SecurityEventType::PolicyViolation) + .with_resource("browser_audit") + .with_result(reason.to_string()) + .with_risk_hint(RiskLevel::Medium); + + if let Some(session_id) = evolve_session_id(config) { + event = event.with_session_id(session_id.to_string()); + } + if let Some(url) = requested_url(config) { + event = event.with_destination(url.to_string()); + } + + event_sink.emit(event); +} + fn proxy_is_managed_tor(config: &Value) -> bool { config .get("proxy") @@ -55,9 +106,15 @@ fn proxy_is_managed_tor(config: &Value) -> bool { } pub async fn handle_browser_audit( + Extension(event_sink): Extension, Json(config): Json, ) -> Result, (StatusCode, Json)> { if !has_scope_hosts(&config) { + emit_browser_policy_violation( + &event_sink, + &config, + "browser request missing explicit RoE host allowlist", + ); return Err(( StatusCode::BAD_REQUEST, Json(serde_json::json!({ @@ -66,6 +123,11 @@ pub async fn handle_browser_audit( )); } if has_proxy(&config) && !proxy_is_managed_tor(&config) { + emit_browser_policy_violation( + &event_sink, + &config, + "browser attempted unmanaged proxy transport", + ); return Err(( StatusCode::BAD_REQUEST, Json(serde_json::json!({ @@ -74,6 +136,11 @@ pub async fn handle_browser_audit( )); } if has_forbidden_authority_header(&config) { + emit_browser_policy_violation( + &event_sink, + &config, + "browser attempted Host/:authority override", + ); return Err(( StatusCode::BAD_REQUEST, Json(serde_json::json!({ @@ -82,6 +149,14 @@ pub async fn handle_browser_audit( )); } + emit_browser_event( + &event_sink, + &config, + SecurityEventType::BrowserNavigation, + RiskLevel::Low, + "started", + ); + let config_bytes = serde_json::to_vec(&config).map_err(|e| { ( StatusCode::BAD_REQUEST, @@ -162,6 +237,13 @@ pub async fn handle_browser_audit( ) })?; + emit_browser_event( + &event_sink, + &config, + SecurityEventType::BrowserNavigation, + RiskLevel::Low, + "completed", + ); info!("Browser audit completed successfully"); Ok(Json(report)) } From 17e773386b921c3d1a512aec5d20918fe556b644 Mon Sep 17 00:00:00 2001 From: Boiko Oleg Date: Sat, 5 Sep 2026 07:26:57 +0300 Subject: [PATCH 18/46] feat(evolve): instrument HTTP probe and RoE events --- .../crates/sandbox-daemon/src/routes/probe.rs | 98 ++++++++++++++++++- 1 file changed, 97 insertions(+), 1 deletion(-) diff --git a/sandbox_runtime/crates/sandbox-daemon/src/routes/probe.rs b/sandbox_runtime/crates/sandbox-daemon/src/routes/probe.rs index 45821f1..a24733f 100644 --- a/sandbox_runtime/crates/sandbox-daemon/src/routes/probe.rs +++ b/sandbox_runtime/crates/sandbox-daemon/src/routes/probe.rs @@ -1,4 +1,4 @@ -use axum::{http::StatusCode, Json}; +use axum::{http::StatusCode, Extension, Json}; use reqwest::header::{HeaderMap, HeaderName, HeaderValue}; use serde::{Deserialize, Serialize}; use serde_json::json; @@ -7,6 +7,9 @@ use std::io::{Error as IoError, ErrorKind}; use std::time::{Duration, Instant}; use tracing::{error, info}; +use crate::evolve_events::EvolveEventSink; +use sandbox_kernel::{EventSource, RiskLevel, SecurityEvent, SecurityEventType}; + const TOR_BROWSER_PROXY: &str = "socks5://127.0.0.1:9050"; const TOR_HTTP_PROXY: &str = "socks5h://127.0.0.1:9050"; @@ -19,6 +22,7 @@ pub struct ProbeRequest { pub proxy: Option, pub timeout_secs: Option, pub allowed_hosts: Option>, + pub evolve_session_id: Option, } #[derive(Debug, Serialize)] @@ -73,11 +77,50 @@ fn has_forbidden_authority_header(headers: Option<&HashMap>) -> }) } +fn emit_probe_event( + event_sink: &EvolveEventSink, + payload: &ProbeRequest, + event_type: SecurityEventType, + source: EventSource, + risk: RiskLevel, + result: &str, +) { + let mut event = SecurityEvent::new(source, event_type) + .with_destination(payload.url.clone()) + .with_result(result.to_string()) + .with_risk_hint(risk) + .with_metadata(json!({ + "method": payload.method.as_deref().unwrap_or("GET").to_uppercase() + })); + + if let Some(session_id) = payload.evolve_session_id.as_deref() { + event = event.with_session_id(session_id.to_string()); + } + + event_sink.emit(event); +} + +fn emit_probe_policy_violation( + event_sink: &EvolveEventSink, + payload: &ProbeRequest, + reason: &str, +) { + emit_probe_event( + event_sink, + payload, + SecurityEventType::PolicyViolation, + EventSource::Policy, + RiskLevel::Medium, + reason, + ); +} + fn proxy_is_managed_tor(proxy: &str) -> bool { matches!(proxy.trim(), TOR_BROWSER_PROXY | TOR_HTTP_PROXY) } pub async fn handle_http_probe( + Extension(event_sink): Extension, Json(payload): Json, ) -> Result, (StatusCode, Json)> { let method_str = payload.method.as_deref().unwrap_or("GET").to_uppercase(); @@ -85,6 +128,11 @@ pub async fn handle_http_probe( let allowed_hosts = normalize_allowed_hosts(payload.allowed_hosts.clone()); if allowed_hosts.is_empty() { + emit_probe_policy_violation( + &event_sink, + &payload, + "HTTP probe missing explicit RoE host allowlist", + ); return Err(( StatusCode::BAD_REQUEST, Json(json!({ @@ -93,6 +141,11 @@ pub async fn handle_http_probe( )); } if has_forbidden_authority_header(payload.headers.as_ref()) { + emit_probe_policy_violation( + &event_sink, + &payload, + "HTTP probe attempted Host/:authority override", + ); return Err(( StatusCode::BAD_REQUEST, Json(json!({ @@ -102,6 +155,11 @@ pub async fn handle_http_probe( } if let Some(proxy) = payload.proxy.as_deref() { if !proxy_is_managed_tor(proxy) { + emit_probe_policy_violation( + &event_sink, + &payload, + "HTTP probe attempted unmanaged proxy transport", + ); return Err(( StatusCode::BAD_REQUEST, Json(json!({ @@ -118,12 +176,26 @@ pub async fn handle_http_probe( ) })?; if !url_matches_scope(&parsed_target, &allowed_hosts) { + emit_probe_policy_violation( + &event_sink, + &payload, + "HTTP probe URL is outside active RoE host scope", + ); return Err(( StatusCode::FORBIDDEN, Json(json!({"error": "Probe URL is outside the active RoE host scope"})), )); } + emit_probe_event( + &event_sink, + &payload, + SecurityEventType::HttpRequest, + EventSource::HttpProbe, + RiskLevel::Low, + "started", + ); + info!( "Sending HTTP probe: {} {} (proxy: {:?}, scope_hosts: {})", method_str, @@ -224,6 +296,21 @@ pub async fn handle_http_probe( let response = match req_builder.send().await { Ok(resp) => resp, Err(e) => { + if e.to_string().contains("outside active RoE scope") { + emit_probe_policy_violation( + &event_sink, + &payload, + "HTTP probe redirect attempted to leave active RoE host scope", + ); + } + emit_probe_event( + &event_sink, + &payload, + SecurityEventType::HttpRequest, + EventSource::HttpProbe, + RiskLevel::Low, + "request_failed", + ); error!("HTTP probe failed for {}: {}", payload.url, e); return Err(( StatusCode::BAD_GATEWAY, @@ -274,6 +361,15 @@ pub async fn handle_http_probe( _ => false, }; + emit_probe_event( + &event_sink, + &payload, + SecurityEventType::HttpRequest, + EventSource::HttpProbe, + RiskLevel::Low, + &format!("status={status}"), + ); + Ok(Json(ProbeResponse { status, headers: resp_headers, From 80ca53826b8d16f278f73d0e7659b129d0434771 Mon Sep 17 00:00:00 2001 From: Boiko Oleg Date: Sat, 5 Sep 2026 07:26:59 +0300 Subject: [PATCH 19/46] feat(evolve): record egress policy violations and isolation state --- .../sandbox-daemon/src/routes/egress.rs | 53 ++++++++++++++----- 1 file changed, 41 insertions(+), 12 deletions(-) diff --git a/sandbox_runtime/crates/sandbox-daemon/src/routes/egress.rs b/sandbox_runtime/crates/sandbox-daemon/src/routes/egress.rs index b7fd85b..bbfe080 100644 --- a/sandbox_runtime/crates/sandbox-daemon/src/routes/egress.rs +++ b/sandbox_runtime/crates/sandbox-daemon/src/routes/egress.rs @@ -1,12 +1,19 @@ -use axum::{http::StatusCode, Json}; +use axum::{http::StatusCode, Extension, Json}; use serde::Deserialize; use serde_json::json; +use std::sync::Arc; +use tokio::sync::Mutex; use tracing::{error, info, warn}; +use crate::evolve_events::EvolveEventSink; + use sandbox_kernel::containment::apply_runtime_containment_with_agent_allowlist; use sandbox_kernel::egress::{is_valid_ip_or_cidr, EgressConfig, EgressError, EgressManager}; use sandbox_kernel::panic::KillSwitch; use sandbox_kernel::stop_tor_best_effort; +use sandbox_kernel::{ + EventSource, EvolveManager, RiskLevel, SecurityEvent, SecurityEventType, +}; #[derive(Debug, Deserialize)] pub struct EmergencyIsolateRequest { @@ -21,6 +28,15 @@ pub struct ProvisionEgressRequest { pub agent_allowed_cidrs: Vec, } +fn emit_egress_policy_violation(event_sink: &EvolveEventSink, reason: &str) { + event_sink.emit( + SecurityEvent::new(EventSource::Policy, SecurityEventType::PolicyViolation) + .with_resource("egress_scope") + .with_result(reason.to_string()) + .with_risk_hint(RiskLevel::Medium), + ); +} + fn bad_request(message: impl Into) -> (StatusCode, Json) { ( StatusCode::BAD_REQUEST, @@ -53,6 +69,7 @@ fn validate_agent_allowlist( } pub async fn handle_provision_egress( + Extension(event_sink): Extension, Json(payload): Json, ) -> Result, (StatusCode, Json)> { let ProvisionEgressRequest { @@ -63,16 +80,19 @@ pub async fn handle_provision_egress( info!("Provisioning egress rules for mode: {:?}", config.mode); if config.proxy_enabled || config.proxy_target.is_some() { - return Err(bad_request( - "External upstream proxy containment is not implemented safely; only managed Tor is supported", - )); + let reason = + "External upstream proxy containment is not implemented safely; only managed Tor is supported"; + emit_egress_policy_violation(&event_sink, reason); + return Err(bad_request(reason)); } if config.tor_enabled && config.targets.is_empty() { - return Err(bad_request( - "Tor egress requires at least one explicit target; transport alone is not audit scope", - )); + let reason = + "Tor egress requires at least one explicit target; transport alone is not audit scope"; + emit_egress_policy_violation(&event_sink, reason); + return Err(bad_request(reason)); } if let Err(message) = validate_agent_allowlist(&config, &agent_allowed_cidrs) { + emit_egress_policy_violation(&event_sink, &message); return Err(bad_request(message)); } @@ -81,6 +101,10 @@ pub async fn handle_provision_egress( error!("Failed to apply egress rules: {}", e); let status = match e { EgressError::InvalidAddress(_) | EgressError::InvalidPolicy(_) => { + emit_egress_policy_violation( + &event_sink, + &format!("Rejected invalid egress policy: {e}"), + ); StatusCode::BAD_REQUEST } _ => StatusCode::INTERNAL_SERVER_ERROR, @@ -116,6 +140,7 @@ pub async fn handle_provision_egress( } pub async fn handle_emergency_isolate( + Extension(evolve_mgr): Extension>>, Json(payload): Json, ) -> Result, (StatusCode, Json)> { let reason = payload @@ -124,11 +149,15 @@ pub async fn handle_emergency_isolate( warn!("Emergency isolation request received: {}", reason); match KillSwitch::trigger(&reason) { - Ok(_) => Ok(Json(json!({ - "status": "isolated", - "reason": reason, - "is_isolated": true - }))), + Ok(_) => { + let mut manager = evolve_mgr.lock().await; + manager.mark_isolated(); + Ok(Json(json!({ + "status": "isolated", + "reason": reason, + "is_isolated": true + }))) + } Err(e) => Err(( StatusCode::INTERNAL_SERVER_ERROR, Json(json!({"error": format!("Failed to trigger kill switch: {}", e)})), From e681f8905b1bf18620fb7b90f042ab545ebc8a5e Mon Sep 17 00:00:00 2001 From: Boiko Oleg Date: Sat, 5 Sep 2026 07:27:31 +0300 Subject: [PATCH 20/46] fix(evolve): preserve probe payload for telemetry --- sandbox_runtime/crates/sandbox-daemon/src/routes/probe.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/sandbox_runtime/crates/sandbox-daemon/src/routes/probe.rs b/sandbox_runtime/crates/sandbox-daemon/src/routes/probe.rs index a24733f..d67981d 100644 --- a/sandbox_runtime/crates/sandbox-daemon/src/routes/probe.rs +++ b/sandbox_runtime/crates/sandbox-daemon/src/routes/probe.rs @@ -275,12 +275,12 @@ pub async fn handle_http_probe( } }; - if let Some(headers_map) = payload.headers { + if let Some(headers_map) = payload.headers.as_ref() { let mut header_map = HeaderMap::new(); for (k, v) in headers_map { if let (Ok(h_name), Ok(h_val)) = ( HeaderName::from_bytes(k.as_bytes()), - HeaderValue::from_str(&v), + HeaderValue::from_str(v), ) { header_map.insert(h_name, h_val); } @@ -288,8 +288,8 @@ pub async fn handle_http_probe( req_builder = req_builder.headers(header_map); } - if let Some(body_content) = payload.body { - req_builder = req_builder.body(body_content); + if let Some(body_content) = payload.body.as_ref() { + req_builder = req_builder.body(body_content.clone()); } let start_time = Instant::now(); From ded60de0a1d2bc3629b89e8899a504bd707762f0 Mon Sep 17 00:00:00 2001 From: Boiko Oleg Date: Sat, 5 Sep 2026 07:27:33 +0300 Subject: [PATCH 21/46] fix(evolve): avoid moving egress errors during classification --- sandbox_runtime/crates/sandbox-daemon/src/routes/egress.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sandbox_runtime/crates/sandbox-daemon/src/routes/egress.rs b/sandbox_runtime/crates/sandbox-daemon/src/routes/egress.rs index bbfe080..b9caaf2 100644 --- a/sandbox_runtime/crates/sandbox-daemon/src/routes/egress.rs +++ b/sandbox_runtime/crates/sandbox-daemon/src/routes/egress.rs @@ -99,7 +99,7 @@ pub async fn handle_provision_egress( let manager = EgressManager::new(); if let Err(e) = manager.apply_rules(&config) { error!("Failed to apply egress rules: {}", e); - let status = match e { + let status = match &e { EgressError::InvalidAddress(_) | EgressError::InvalidPolicy(_) => { emit_egress_policy_violation( &event_sink, From ffdc8c6c1fba514462a18709b70f09e963158417 Mon Sep 17 00:00:00 2001 From: Boiko Oleg Date: Sat, 5 Sep 2026 07:27:34 +0300 Subject: [PATCH 22/46] refactor(evolve): simplify suspect session transition --- .../crates/sandbox-kernel/src/evolve/manager.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/sandbox_runtime/crates/sandbox-kernel/src/evolve/manager.rs b/sandbox_runtime/crates/sandbox-kernel/src/evolve/manager.rs index 010bc7c..6060f9f 100644 --- a/sandbox_runtime/crates/sandbox-kernel/src/evolve/manager.rs +++ b/sandbox_runtime/crates/sandbox-kernel/src/evolve/manager.rs @@ -159,10 +159,10 @@ impl EvolveManager { let _ = self.transition(EvolveState::Suspect); } - if let Some(session) = self.sessions.get_mut(session_id) { - if session.state == EvolveState::Observe { - session.state = EvolveState::Suspect; - } + if let Some(session) = self.sessions.get_mut(session_id) + && session.state == EvolveState::Observe + { + session.state = EvolveState::Suspect; } } From 66f30ba7d0ac94354f74be464348b7961f43dc80 Mon Sep 17 00:00:00 2001 From: Boiko Oleg Date: Sat, 5 Sep 2026 07:27:36 +0300 Subject: [PATCH 23/46] test(evolve): cover daemon event sink delivery --- .../sandbox-daemon/src/evolve_events.rs | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/sandbox_runtime/crates/sandbox-daemon/src/evolve_events.rs b/sandbox_runtime/crates/sandbox-daemon/src/evolve_events.rs index 166b522..62ea2d6 100644 --- a/sandbox_runtime/crates/sandbox-daemon/src/evolve_events.rs +++ b/sandbox_runtime/crates/sandbox-daemon/src/evolve_events.rs @@ -31,3 +31,32 @@ impl EvolveEventSink { } } } + +#[cfg(test)] +mod tests { + use super::*; + use sandbox_kernel::{EventSource, SecurityEventType}; + use tokio::sync::mpsc; + + #[test] + fn sink_delivers_event_to_receiver() { + let (sender, mut receiver) = mpsc::unbounded_channel(); + let sink = EvolveEventSink::new(sender); + let event = + SecurityEvent::new(EventSource::Process, SecurityEventType::ProcessExec); + + assert!(sink.emit(event)); + assert!(receiver.try_recv().is_ok()); + } + + #[test] + fn sink_reports_closed_receiver_without_panicking() { + let (sender, receiver) = mpsc::unbounded_channel(); + drop(receiver); + let sink = EvolveEventSink::new(sender); + let event = + SecurityEvent::new(EventSource::System, SecurityEventType::PolicyViolation); + + assert!(!sink.emit(event)); + } +} From c72d5f4e0f87db3891c7f3b0ab5f575759b70f9a Mon Sep 17 00:00:00 2001 From: Boiko Oleg Date: Sat, 5 Sep 2026 07:28:20 +0300 Subject: [PATCH 24/46] feat(evolve): correlate canary triggers with behavioral sessions --- .../crates/sandbox-kernel/src/canary.rs | 22 ++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/sandbox_runtime/crates/sandbox-kernel/src/canary.rs b/sandbox_runtime/crates/sandbox-kernel/src/canary.rs index 98337be..357f2b1 100644 --- a/sandbox_runtime/crates/sandbox-kernel/src/canary.rs +++ b/sandbox_runtime/crates/sandbox-kernel/src/canary.rs @@ -60,6 +60,15 @@ impl CanaryManager { /// Plants deceptive honeytoken files into the target filesystem. pub async fn arm_canaries(&mut self, base_dir: &Path) -> Result, CanaryError> { + self.arm_canaries_for_session(base_dir, None).await + } + + /// Plants canaries and associates future trigger events with a behavioral Evolve session. + pub async fn arm_canaries_for_session( + &mut self, + base_dir: &Path, + session_id: Option, + ) -> Result, CanaryError> { let mut planted = Vec::new(); // 1. AWS Credentials Honeypot @@ -158,13 +167,13 @@ users: self.traps = planted.clone(); self.is_armed.store(true, Ordering::SeqCst); - self.spawn_watcher(planted.clone()); + self.spawn_watcher(planted.clone(), session_id); info!("Armed {} canary honeytoken tripwires.", planted.len()); Ok(planted) } - fn spawn_watcher(&self, traps: Vec) { + fn spawn_watcher(&self, traps: Vec, session_id: Option) { let is_armed = self.is_armed.clone(); let triggered_count = self.triggered_count.clone(); let event_sender = self.event_sender.clone(); @@ -211,6 +220,7 @@ users: triggered_count.as_ref(), path, trap_type, + session_id.as_deref(), ); is_armed.store(false, Ordering::SeqCst); return; @@ -239,6 +249,7 @@ fn handle_canary_trigger( triggered_count: &AtomicUsize, path: &Path, trap_type: &str, + session_id: Option<&str>, ) { triggered_count.fetch_add(1, Ordering::SeqCst); error!( @@ -246,13 +257,16 @@ fn handle_canary_trigger( path ); - let event = SecurityEvent::new(EventSource::Canary, SecurityEventType::CanaryAccess) + let mut event = SecurityEvent::new(EventSource::Canary, SecurityEventType::CanaryAccess) .with_resource(path.to_string_lossy().into_owned()) .with_risk_hint(RiskLevel::High) .with_metadata(serde_json::json!({ "trap_type": trap_type, "legacy_reaction": "isolate" })); + if let Some(session_id) = session_id { + event = event.with_session_id(session_id.to_string()); + } if let Some(sender) = event_sender { if sender.send(event).is_ok() { @@ -299,6 +313,7 @@ mod tests { &triggered_count, path, "env_secrets", + Some("audit-session-1"), ); let event = receiver.recv().await.expect("expected canary event"); @@ -306,6 +321,7 @@ mod tests { assert_eq!(event.source, EventSource::Canary); assert_eq!(event.event_type, SecurityEventType::CanaryAccess); assert_eq!(event.resource.as_deref(), Some("/workspace/.env.decoy")); + assert_eq!(event.session_id.as_deref(), Some("audit-session-1")); assert_eq!(event.risk_hint, Some(RiskLevel::High)); } } From 4c7883103edac00f62d4e1bd8b02b2eaec878384 Mon Sep 17 00:00:00 2001 From: Boiko Oleg Date: Sat, 5 Sep 2026 07:28:25 +0300 Subject: [PATCH 25/46] feat(evolve): accept canary session correlation --- sandbox_runtime/crates/sandbox-daemon/src/routes/canary.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/sandbox_runtime/crates/sandbox-daemon/src/routes/canary.rs b/sandbox_runtime/crates/sandbox-daemon/src/routes/canary.rs index edc44ed..89f6d21 100644 --- a/sandbox_runtime/crates/sandbox-daemon/src/routes/canary.rs +++ b/sandbox_runtime/crates/sandbox-daemon/src/routes/canary.rs @@ -11,6 +11,7 @@ use sandbox_kernel::canary::CanaryManager; #[derive(Debug, Deserialize)] pub struct ArmCanaryRequest { pub base_dir: Option, + pub evolve_session_id: Option, } pub async fn handle_arm_canary( @@ -24,7 +25,10 @@ pub async fn handle_arm_canary( ); let mut mgr = canary_mgr.lock().await; - match mgr.arm_canaries(&base_path).await { + match mgr + .arm_canaries_for_session(&base_path, payload.evolve_session_id) + .await + { Ok(traps) => { let traps_summary: Vec<_> = traps .iter() From 59de9153d9de60d19a2f105ecaa044f8ca33e10a Mon Sep 17 00:00:00 2001 From: Boiko Oleg Date: Sat, 5 Sep 2026 07:28:29 +0300 Subject: [PATCH 26/46] feat(evolve): propagate audit session correlation from host bridge --- src/mcp/bridge.ts | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/src/mcp/bridge.ts b/src/mcp/bridge.ts index b8f5406..367581c 100644 --- a/src/mcp/bridge.ts +++ b/src/mcp/bridge.ts @@ -1,6 +1,7 @@ import * as http from 'node:http'; import * as fs from 'node:fs'; import * as path from 'node:path'; +import { randomUUID } from 'node:crypto'; import { RatchetBridge } from './security/ratchet_bridge.js'; import { JailGuard } from './security/jail.js'; import { @@ -93,6 +94,7 @@ export class SandboxBridge { targetHosts: [], proxy: null, }; + private activeEvolveSessionId: string = randomUUID(); constructor(options?: { workspaceRoot?: string; @@ -262,6 +264,7 @@ export class SandboxBridge { }; const egressRes = await this.request('POST', '/provision_egress', payload); + this.activeEvolveSessionId = randomUUID(); this.activeNetworkScope = { mode: options.mode, targetHosts, @@ -312,6 +315,7 @@ export class SandboxBridge { const raw = await this.request('POST', '/execute', { command, timeout_secs: timeoutSecs, + evolve_session_id: this.activeEvolveSessionId, }); return { exit_code: raw.exit_code, @@ -333,7 +337,11 @@ export class SandboxBridge { command: string, session: string = 'background_scan' ): Promise<{ status: string; session: string; message: string }> { - return this.request('POST', '/start_background', { command, session }); + return this.request('POST', '/start_background', { + command, + session, + evolve_session_id: this.activeEvolveSessionId, + }); } public async pollLogs( @@ -361,6 +369,7 @@ export class SandboxBridge { ...options, proxy: networkPolicy.useTor ? TOR_BROWSER_PROXY : null, allowed_hosts: networkPolicy.allowedHosts, + evolve_session_id: this.activeEvolveSessionId, }); } @@ -374,6 +383,7 @@ export class SandboxBridge { body: options.body || '', proxy: networkPolicy.useTor ? TOR_HTTP_PROXY : null, allowed_hosts: networkPolicy.allowedHosts, + evolve_session_id: this.activeEvolveSessionId, }); } @@ -391,8 +401,11 @@ export class SandboxBridge { } } - public async armCanary(tokenLabel: string = 'default_audit_canary'): Promise { - return this.request('POST', '/arm_canary', { token_label: tokenLabel }); + public async armCanary(baseDir: string = '/workspace'): Promise { + return this.request('POST', '/arm_canary', { + base_dir: baseDir, + evolve_session_id: this.activeEvolveSessionId, + }); } public fsRead(relPath: string): { path: string; content: string } { @@ -422,6 +435,7 @@ export class SandboxBridge { await this.killSwitch('Reset called'); } this.activeNetworkScope = { mode: 'local', targetHosts: [], proxy: null }; + this.activeEvolveSessionId = randomUUID(); return { status: 'ok', message: 'Sandbox instance cleanly reset' }; } } From 14a2d41576761d8004b03a55115b9d5edad97ec5 Mon Sep 17 00:00:00 2001 From: Boiko Oleg Date: Sat, 5 Sep 2026 07:29:05 +0300 Subject: [PATCH 27/46] fix(evolve): invalidate stale canary watchers on rearm --- .../crates/sandbox-kernel/src/canary.rs | 40 ++++++++++++++++--- 1 file changed, 35 insertions(+), 5 deletions(-) diff --git a/sandbox_runtime/crates/sandbox-kernel/src/canary.rs b/sandbox_runtime/crates/sandbox-kernel/src/canary.rs index 357f2b1..cee28a0 100644 --- a/sandbox_runtime/crates/sandbox-kernel/src/canary.rs +++ b/sandbox_runtime/crates/sandbox-kernel/src/canary.rs @@ -1,5 +1,5 @@ use std::path::{Path, PathBuf}; -use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; use std::sync::Arc; use std::time::Duration; use thiserror::Error; @@ -29,6 +29,7 @@ pub struct CanaryManager { traps: Vec, is_armed: Arc, triggered_count: Arc, + watch_generation: Arc, event_sender: Option>, } @@ -44,6 +45,7 @@ impl CanaryManager { traps: Vec::new(), is_armed: Arc::new(AtomicBool::new(false)), triggered_count: Arc::new(AtomicUsize::new(0)), + watch_generation: Arc::new(AtomicU64::new(0)), event_sender: None, } } @@ -166,16 +168,23 @@ users: self.traps = planted.clone(); self.is_armed.store(true, Ordering::SeqCst); + let generation = self.watch_generation.fetch_add(1, Ordering::SeqCst) + 1; - self.spawn_watcher(planted.clone(), session_id); + self.spawn_watcher(planted.clone(), session_id, generation); info!("Armed {} canary honeytoken tripwires.", planted.len()); Ok(planted) } - fn spawn_watcher(&self, traps: Vec, session_id: Option) { + fn spawn_watcher( + &self, + traps: Vec, + session_id: Option, + generation: u64, + ) { let is_armed = self.is_armed.clone(); let triggered_count = self.triggered_count.clone(); + let watch_generation = self.watch_generation.clone(); let event_sender = self.event_sender.clone(); tokio::spawn(async move { @@ -200,7 +209,9 @@ users: } } - while is_armed.load(Ordering::SeqCst) { + while is_armed.load(Ordering::SeqCst) + && watch_generation.load(Ordering::SeqCst) == generation + { tokio::time::sleep(Duration::from_millis(500)).await; for (path, trap_type, orig_len, orig_accessed) in &initial_meta { @@ -222,7 +233,9 @@ users: trap_type, session_id.as_deref(), ); - is_armed.store(false, Ordering::SeqCst); + if watch_generation.load(Ordering::SeqCst) == generation { + is_armed.store(false, Ordering::SeqCst); + } return; } } @@ -242,6 +255,10 @@ users: pub fn get_traps(&self) -> &[CanaryTrap] { &self.traps } + + pub fn watch_generation(&self) -> u64 { + self.watch_generation.load(Ordering::SeqCst) + } } fn handle_canary_trigger( @@ -302,6 +319,19 @@ mod tests { } } + #[tokio::test] + async fn rearm_advances_watcher_generation() { + let temp_dir = TempDir::new().unwrap(); + let mut manager = CanaryManager::new(); + + manager.arm_canaries(temp_dir.path()).await.unwrap(); + let first_generation = manager.watch_generation(); + manager.arm_canaries(temp_dir.path()).await.unwrap(); + let second_generation = manager.watch_generation(); + + assert!(second_generation > first_generation); + } + #[tokio::test] async fn trigger_emits_evolve_event_when_receiver_exists() { let (sender, mut receiver) = mpsc::unbounded_channel(); From 76ba122cd2eb6a6eabd651a056b3dce1f5314452 Mon Sep 17 00:00:00 2001 From: Boiko Oleg Date: Sat, 5 Sep 2026 07:29:36 +0300 Subject: [PATCH 28/46] feat(evolve): add deterministic behavior profiler --- .../sandbox-kernel/src/evolve/behavior.rs | 331 ++++++++++++++++++ 1 file changed, 331 insertions(+) create mode 100644 sandbox_runtime/crates/sandbox-kernel/src/evolve/behavior.rs diff --git a/sandbox_runtime/crates/sandbox-kernel/src/evolve/behavior.rs b/sandbox_runtime/crates/sandbox-kernel/src/evolve/behavior.rs new file mode 100644 index 0000000..e4e1db1 --- /dev/null +++ b/sandbox_runtime/crates/sandbox-kernel/src/evolve/behavior.rs @@ -0,0 +1,331 @@ +use super::{RiskLevel, SecurityEvent, SecurityEventType}; +use serde::{Deserialize, Serialize}; +use std::collections::{BTreeSet, HashMap, VecDeque}; + +const DEFAULT_TRACE_EVENT_CAPACITY: usize = 256; +const DEFAULT_SESSION_ID: &str = "runtime-default"; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum BehaviorTag { + Execution, + Discovery, + CredentialInterest, + NetworkActivity, + BrowserActivity, + PolicyBoundary, + PrivilegeActivity, + PersistenceActivity, + LateralMovement, + CanaryInteraction, + EscapeActivity, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct BehaviorAssessment { + pub risk_level: RiskLevel, + pub tags: Vec, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct BehaviorTrace { + pub session_id: String, + pub started_at_ms: u64, + pub last_event_at_ms: u64, + pub risk_level: RiskLevel, + pub tags: BTreeSet, + pub events: VecDeque, + event_capacity: usize, +} + +impl BehaviorTrace { + fn new(session_id: impl Into, first_timestamp_ms: u64, event_capacity: usize) -> Self { + Self { + session_id: session_id.into(), + started_at_ms: first_timestamp_ms, + last_event_at_ms: first_timestamp_ms, + risk_level: RiskLevel::Low, + tags: BTreeSet::new(), + events: VecDeque::with_capacity(event_capacity), + event_capacity, + } + } + + fn push_event(&mut self, event: SecurityEvent) { + self.last_event_at_ms = event.timestamp_ms; + if self.events.len() >= self.event_capacity { + self.events.pop_front(); + } + self.events.push_back(event); + } +} + +pub struct BehaviorProfiler { + traces: HashMap, + event_capacity: usize, +} + +impl Default for BehaviorProfiler { + fn default() -> Self { + Self::new() + } +} + +impl BehaviorProfiler { + pub fn new() -> Self { + Self { + traces: HashMap::new(), + event_capacity: DEFAULT_TRACE_EVENT_CAPACITY, + } + } + + pub fn observe(&mut self, event: &SecurityEvent) -> BehaviorAssessment { + let session_id = event + .session_id + .as_deref() + .unwrap_or(DEFAULT_SESSION_ID) + .to_string(); + let mut tags = classify_event(event); + let base_risk = deterministic_event_risk(event); + + let trace = self.traces.entry(session_id.clone()).or_insert_with(|| { + BehaviorTrace::new(session_id, event.timestamp_ms, self.event_capacity) + }); + + for tag in &tags { + trace.tags.insert(*tag); + } + + let sequence_risk = sequence_risk(trace, event, &tags); + let effective_risk = max_risk(base_risk, sequence_risk); + if effective_risk.rank() > trace.risk_level.rank() { + trace.risk_level = effective_risk; + } + + trace.push_event(event.clone()); + + tags.sort(); + tags.dedup(); + + BehaviorAssessment { + risk_level: effective_risk, + tags, + } + } + + pub fn trace(&self, session_id: &str) -> Option<&BehaviorTrace> { + self.traces.get(session_id) + } + + pub fn traces(&self) -> Vec { + let mut traces: Vec<_> = self.traces.values().cloned().collect(); + traces.sort_by(|left, right| left.started_at_ms.cmp(&right.started_at_ms)); + traces + } +} + +fn max_risk(left: RiskLevel, right: RiskLevel) -> RiskLevel { + if left.rank() >= right.rank() { + left + } else { + right + } +} + +fn deterministic_event_risk(event: &SecurityEvent) -> RiskLevel { + let hinted = event.risk_hint.unwrap_or(RiskLevel::Low); + let structural = match event.event_type { + SecurityEventType::EscapeAttempt | SecurityEventType::ControlPlaneAccess => { + RiskLevel::Critical + } + SecurityEventType::CanaryAccess + | SecurityEventType::CredentialAccess + | SecurityEventType::PrivilegeAttempt + | SecurityEventType::PersistenceAttempt + | SecurityEventType::LateralMovementAttempt => RiskLevel::High, + SecurityEventType::PolicyViolation => RiskLevel::Medium, + _ => RiskLevel::Low, + }; + + max_risk(hinted, structural) +} + +fn classify_event(event: &SecurityEvent) -> Vec { + let mut tags = Vec::new(); + + match event.event_type { + SecurityEventType::ProcessSpawn + | SecurityEventType::ProcessExec + | SecurityEventType::ProcessExit => tags.push(BehaviorTag::Execution), + SecurityEventType::Discovery => tags.push(BehaviorTag::Discovery), + SecurityEventType::CredentialAccess => tags.push(BehaviorTag::CredentialInterest), + SecurityEventType::NetworkConnect + | SecurityEventType::NetworkListen + | SecurityEventType::DnsAttempt + | SecurityEventType::HttpRequest => tags.push(BehaviorTag::NetworkActivity), + SecurityEventType::BrowserNavigation => tags.push(BehaviorTag::BrowserActivity), + SecurityEventType::PolicyViolation => tags.push(BehaviorTag::PolicyBoundary), + SecurityEventType::PrivilegeAttempt => tags.push(BehaviorTag::PrivilegeActivity), + SecurityEventType::PersistenceAttempt => tags.push(BehaviorTag::PersistenceActivity), + SecurityEventType::LateralMovementAttempt => tags.push(BehaviorTag::LateralMovement), + SecurityEventType::CanaryAccess => { + tags.push(BehaviorTag::CanaryInteraction); + tags.push(BehaviorTag::CredentialInterest); + } + SecurityEventType::EscapeAttempt | SecurityEventType::ControlPlaneAccess => { + tags.push(BehaviorTag::EscapeActivity); + } + _ => {} + } + + if let Some(command) = event.command.as_deref() { + classify_command(command, &mut tags); + } + + tags +} + +fn classify_command(command: &str, tags: &mut Vec) { + let normalized = command.trim().to_ascii_lowercase(); + let first = normalized.split_whitespace().next().unwrap_or_default(); + + if matches!( + first, + "whoami" + | "id" + | "uname" + | "hostname" + | "ip" + | "ifconfig" + | "netstat" + | "ss" + | "ps" + | "env" + | "printenv" + | "mount" + | "df" + ) { + tags.push(BehaviorTag::Discovery); + } + + if matches!(first, "curl" | "wget" | "nc" | "ncat" | "ssh") { + tags.push(BehaviorTag::NetworkActivity); + } + + if normalized.contains(".ssh/") + || normalized.contains(".aws/credentials") + || normalized.contains(".kube/config") + || normalized.contains(".env") + { + tags.push(BehaviorTag::CredentialInterest); + } +} + +fn sequence_risk( + trace: &BehaviorTrace, + event: &SecurityEvent, + current_tags: &[BehaviorTag], +) -> RiskLevel { + if matches!( + event.event_type, + SecurityEventType::EscapeAttempt | SecurityEventType::ControlPlaneAccess + ) { + return RiskLevel::Critical; + } + + let previous_tags = &trace.tags; + let discovery_then_network = previous_tags.contains(&BehaviorTag::Discovery) + && current_tags.contains(&BehaviorTag::NetworkActivity); + let credential_then_network = previous_tags.contains(&BehaviorTag::CredentialInterest) + && current_tags.contains(&BehaviorTag::NetworkActivity); + let repeated_policy_boundary = previous_tags.contains(&BehaviorTag::PolicyBoundary) + && current_tags.contains(&BehaviorTag::PolicyBoundary); + + if credential_then_network { + return RiskLevel::High; + } + + if discovery_then_network || repeated_policy_boundary { + return RiskLevel::Medium; + } + + RiskLevel::Low +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::evolve::{EventSource, SecurityEventType}; + + #[test] + fn discovery_followed_by_network_activity_raises_medium_risk() { + let mut profiler = BehaviorProfiler::new(); + + let discovery = + SecurityEvent::new(EventSource::Process, SecurityEventType::ProcessExec) + .with_session_id("session-a") + .with_command("whoami"); + let network = + SecurityEvent::new(EventSource::Process, SecurityEventType::ProcessExec) + .with_session_id("session-a") + .with_command("curl https://example.com"); + + assert_eq!(profiler.observe(&discovery).risk_level, RiskLevel::Low); + assert_eq!(profiler.observe(&network).risk_level, RiskLevel::Medium); + + let trace = profiler.trace("session-a").expect("trace should exist"); + assert!(trace.tags.contains(&BehaviorTag::Discovery)); + assert!(trace.tags.contains(&BehaviorTag::NetworkActivity)); + assert_eq!(trace.events.len(), 2); + } + + #[test] + fn credential_interest_followed_by_network_activity_is_high_risk() { + let mut profiler = BehaviorProfiler::new(); + + let credential = + SecurityEvent::new(EventSource::Process, SecurityEventType::ProcessExec) + .with_session_id("session-a") + .with_command("cat ~/.ssh/id_rsa"); + let network = + SecurityEvent::new(EventSource::Process, SecurityEventType::ProcessExec) + .with_session_id("session-a") + .with_command("curl https://example.com"); + + profiler.observe(&credential); + assert_eq!(profiler.observe(&network).risk_level, RiskLevel::High); + } + + #[test] + fn control_plane_access_is_always_critical() { + let mut profiler = BehaviorProfiler::new(); + let event = + SecurityEvent::new(EventSource::Policy, SecurityEventType::ControlPlaneAccess) + .with_session_id("session-a"); + + assert_eq!(profiler.observe(&event).risk_level, RiskLevel::Critical); + } + + #[test] + fn trace_buffer_is_bounded() { + let mut profiler = BehaviorProfiler::new(); + profiler.event_capacity = 2; + + for index in 0..3 { + let event = + SecurityEvent::new(EventSource::Process, SecurityEventType::ProcessExec) + .with_session_id("session-a") + .with_command(format!("echo {index}")); + profiler.observe(&event); + } + + assert_eq!( + profiler + .trace("session-a") + .expect("trace should exist") + .events + .len(), + 2 + ); + } +} From 7015433f40b0a62f4d03bbf75bc1aae5eeaa2408 Mon Sep 17 00:00:00 2001 From: Boiko Oleg Date: Sat, 5 Sep 2026 07:30:08 +0300 Subject: [PATCH 29/46] fix(evolve): evaluate sequence before merging current behavior tags --- .../crates/sandbox-kernel/src/evolve/behavior.rs | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/sandbox_runtime/crates/sandbox-kernel/src/evolve/behavior.rs b/sandbox_runtime/crates/sandbox-kernel/src/evolve/behavior.rs index e4e1db1..2a3d0d0 100644 --- a/sandbox_runtime/crates/sandbox-kernel/src/evolve/behavior.rs +++ b/sandbox_runtime/crates/sandbox-kernel/src/evolve/behavior.rs @@ -92,17 +92,19 @@ impl BehaviorProfiler { BehaviorTrace::new(session_id, event.timestamp_ms, self.event_capacity) }); + let sequence_risk = sequence_risk(trace, event, &tags); + let effective_risk = max_risk(base_risk, sequence_risk); + for tag in &tags { trace.tags.insert(*tag); } - - let sequence_risk = sequence_risk(trace, event, &tags); - let effective_risk = max_risk(base_risk, sequence_risk); if effective_risk.rank() > trace.risk_level.rank() { trace.risk_level = effective_risk; } - trace.push_event(event.clone()); + let mut normalized_event = event.clone(); + normalized_event.risk_hint = Some(effective_risk); + trace.push_event(normalized_event); tags.sort(); tags.dedup(); From 5892d9e301d329e305c01b7664d1736a14d8bf43 Mon Sep 17 00:00:00 2001 From: Boiko Oleg Date: Sat, 5 Sep 2026 07:30:11 +0300 Subject: [PATCH 30/46] feat(evolve): export behavior profiling model --- sandbox_runtime/crates/sandbox-kernel/src/evolve/mod.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/sandbox_runtime/crates/sandbox-kernel/src/evolve/mod.rs b/sandbox_runtime/crates/sandbox-kernel/src/evolve/mod.rs index 60d2b8b..8fea327 100644 --- a/sandbox_runtime/crates/sandbox-kernel/src/evolve/mod.rs +++ b/sandbox_runtime/crates/sandbox-kernel/src/evolve/mod.rs @@ -1,8 +1,10 @@ +pub mod behavior; pub mod event; pub mod manager; pub mod session; pub mod state; +pub use behavior::{BehaviorAssessment, BehaviorProfiler, BehaviorTag, BehaviorTrace}; pub use event::{EventSource, RiskLevel, SecurityEvent, SecurityEventType}; pub use manager::{EvolveDecision, EvolveManager, EvolveStatus}; pub use session::EvolveSession; From 86c0879a6add98b7c61fcd6b05bb4a8bbb755458 Mon Sep 17 00:00:00 2001 From: Boiko Oleg Date: Sat, 5 Sep 2026 07:30:13 +0300 Subject: [PATCH 31/46] feat(evolve): drive decisions from behavior context --- .../sandbox-kernel/src/evolve/manager.rs | 52 +++++++++++++++++-- 1 file changed, 49 insertions(+), 3 deletions(-) diff --git a/sandbox_runtime/crates/sandbox-kernel/src/evolve/manager.rs b/sandbox_runtime/crates/sandbox-kernel/src/evolve/manager.rs index 6060f9f..1b3d628 100644 --- a/sandbox_runtime/crates/sandbox-kernel/src/evolve/manager.rs +++ b/sandbox_runtime/crates/sandbox-kernel/src/evolve/manager.rs @@ -1,5 +1,6 @@ use super::{ - EvolveSession, EvolveState, RiskLevel, SecurityEvent, StateTransitionError, + BehaviorProfiler, BehaviorTrace, EvolveSession, EvolveState, RiskLevel, SecurityEvent, + StateTransitionError, }; use serde::Serialize; use std::collections::{HashMap, VecDeque}; @@ -22,6 +23,7 @@ pub struct EvolveStatus { pub state: EvolveState, pub events_buffered: usize, pub sessions: usize, + pub behavior_traces: usize, } pub struct EvolveManager { @@ -29,6 +31,7 @@ pub struct EvolveManager { state: EvolveState, events: VecDeque, sessions: HashMap, + behavior: BehaviorProfiler, event_capacity: usize, } @@ -51,6 +54,7 @@ impl EvolveManager { state: EvolveState::Observe, events: VecDeque::with_capacity(DEFAULT_EVENT_CAPACITY), sessions, + behavior: BehaviorProfiler::new(), event_capacity: DEFAULT_EVENT_CAPACITY, } } @@ -73,9 +77,20 @@ impl EvolveManager { state: self.state, events_buffered: self.events.len(), sessions: self.sessions.len(), + behavior_traces: self.behavior.traces().len(), } } + pub fn sessions(&self) -> Vec { + let mut sessions: Vec<_> = self.sessions.values().cloned().collect(); + sessions.sort_by(|left, right| left.created_at_ms.cmp(&right.created_at_ms)); + sessions + } + + pub fn behavior_trace(&self, session_id: &str) -> Option { + self.behavior.trace(session_id).cloned() + } + pub fn recent_events(&self, limit: usize) -> Vec { let limit = limit.min(self.events.len()); self.events @@ -118,13 +133,16 @@ impl EvolveManager { .unwrap_or_else(|| DEFAULT_SESSION_ID.to_string()); event.session_id = Some(session_id.clone()); + let assessment = self.behavior.observe(&event); + event.risk_hint = Some(assessment.risk_level); + let session = self .sessions .entry(session_id.clone()) - .or_insert_with(|| EvolveSession::new(session_id)); + .or_insert_with(|| EvolveSession::new(session_id.clone())); session.record_event(&event); - let risk = event.risk_hint.unwrap_or(RiskLevel::Low); + let risk = assessment.risk_level; let event_type = event.event_type; self.push_event(event); @@ -228,6 +246,34 @@ mod tests { assert_eq!(manager.state(), EvolveState::Suspect); } + #[test] + fn behavior_sequence_can_raise_manager_risk() { + let mut manager = EvolveManager::new(); + manager.set_enabled(true); + + let discovery = + SecurityEvent::new(EventSource::Process, SecurityEventType::ProcessExec) + .with_session_id("session-a") + .with_command("whoami"); + let network = + SecurityEvent::new(EventSource::Process, SecurityEventType::ProcessExec) + .with_session_id("session-a") + .with_command("curl https://example.com"); + + assert_eq!(manager.ingest_event(discovery), EvolveDecision::Observe); + assert_eq!( + manager.ingest_event(network), + EvolveDecision::EnhancedTelemetry + ); + assert_eq!(manager.state(), EvolveState::Suspect); + + let trace = manager + .behavior_trace("session-a") + .expect("behavior trace should exist"); + assert_eq!(trace.events.len(), 2); + assert_eq!(trace.risk_level, RiskLevel::Medium); + } + #[test] fn event_buffer_is_bounded() { let mut manager = EvolveManager::new(); From df85f4b73d90142ca8dc99074c840f2c6fa98be8 Mon Sep 17 00:00:00 2001 From: Boiko Oleg Date: Sat, 5 Sep 2026 07:30:15 +0300 Subject: [PATCH 32/46] feat(evolve): expose behavioral sessions and traces --- .../sandbox-daemon/src/routes/evolve.rs | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/sandbox_runtime/crates/sandbox-daemon/src/routes/evolve.rs b/sandbox_runtime/crates/sandbox-daemon/src/routes/evolve.rs index 70da2e9..ba676de 100644 --- a/sandbox_runtime/crates/sandbox-daemon/src/routes/evolve.rs +++ b/sandbox_runtime/crates/sandbox-daemon/src/routes/evolve.rs @@ -16,6 +16,11 @@ pub struct EventsQuery { pub limit: Option, } +#[derive(Debug, Deserialize)] +pub struct TraceQuery { + pub session_id: String, +} + pub async fn handle_set_enabled( Extension(evolve_mgr): Extension>>, Json(payload): Json, @@ -41,6 +46,27 @@ pub async fn handle_status( Json(json!(manager.status())) } +pub async fn handle_sessions( + Extension(evolve_mgr): Extension>>, +) -> Json { + let manager = evolve_mgr.lock().await; + Json(json!({"sessions": manager.sessions()})) +} + +pub async fn handle_trace( + Extension(evolve_mgr): Extension>>, + Query(query): Query, +) -> Result, (StatusCode, Json)> { + let manager = evolve_mgr.lock().await; + match manager.behavior_trace(&query.session_id) { + Some(trace) => Ok(Json(json!(trace))), + None => Err(( + StatusCode::NOT_FOUND, + Json(json!({"error": "Evolve behavior trace not found"})), + )), + } +} + pub async fn handle_events( Extension(evolve_mgr): Extension>>, Query(query): Query, From 67b83d33e656dde8ee5d9b8e0efd2c5710ced648 Mon Sep 17 00:00:00 2001 From: Boiko Oleg Date: Sat, 5 Sep 2026 07:30:17 +0300 Subject: [PATCH 33/46] feat(evolve): register behavioral trace routes --- sandbox_runtime/crates/sandbox-daemon/src/main.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/sandbox_runtime/crates/sandbox-daemon/src/main.rs b/sandbox_runtime/crates/sandbox-daemon/src/main.rs index 666c807..0c992b2 100644 --- a/sandbox_runtime/crates/sandbox-daemon/src/main.rs +++ b/sandbox_runtime/crates/sandbox-daemon/src/main.rs @@ -194,6 +194,8 @@ async fn main() -> Result<(), Box> { post(routes::evolve::handle_set_enabled), ) .route("/evolve/status", get(routes::evolve::handle_status)) + .route("/evolve/sessions", get(routes::evolve::handle_sessions)) + .route("/evolve/trace", get(routes::evolve::handle_trace)) .route("/evolve/events", get(routes::evolve::handle_events)) .route("/http_probe", post(routes::probe::handle_http_probe)) .route( From 903ecb2fa9285f67a163126993413ab3153e9713 Mon Sep 17 00:00:00 2001 From: Boiko Oleg Date: Sat, 5 Sep 2026 07:30:19 +0300 Subject: [PATCH 34/46] feat(evolve): export behavior profiler types --- sandbox_runtime/crates/sandbox-kernel/src/lib.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/sandbox_runtime/crates/sandbox-kernel/src/lib.rs b/sandbox_runtime/crates/sandbox-kernel/src/lib.rs index 88b8fe6..9232faa 100644 --- a/sandbox_runtime/crates/sandbox-kernel/src/lib.rs +++ b/sandbox_runtime/crates/sandbox-kernel/src/lib.rs @@ -11,8 +11,9 @@ pub use canary::{CanaryManager, CanaryTrap}; pub use containment::{apply_runtime_containment, stop_tor_best_effort, ContainmentError}; pub use egress::{AuditMode, EgressConfig, EgressManager}; pub use evolve::{ - EventSource, EvolveDecision, EvolveManager, EvolveSession, EvolveState, EvolveStatus, RiskLevel, - SecurityEvent, SecurityEventType, StateTransitionError, + BehaviorAssessment, BehaviorProfiler, BehaviorTag, BehaviorTrace, EventSource, EvolveDecision, + EvolveManager, EvolveSession, EvolveState, EvolveStatus, RiskLevel, SecurityEvent, + SecurityEventType, StateTransitionError, }; pub use panic::KillSwitch; pub use privilege::{ From b6c446fddf9b912b7c198464add6211956f1cd92 Mon Sep 17 00:00:00 2001 From: Boiko Oleg Date: Sat, 5 Sep 2026 07:30:48 +0300 Subject: [PATCH 35/46] fix(evolve): harden behavior trace serialization and borrowing --- .../crates/sandbox-kernel/src/evolve/behavior.rs | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/sandbox_runtime/crates/sandbox-kernel/src/evolve/behavior.rs b/sandbox_runtime/crates/sandbox-kernel/src/evolve/behavior.rs index 2a3d0d0..289df2e 100644 --- a/sandbox_runtime/crates/sandbox-kernel/src/evolve/behavior.rs +++ b/sandbox_runtime/crates/sandbox-kernel/src/evolve/behavior.rs @@ -5,6 +5,10 @@ use std::collections::{BTreeSet, HashMap, VecDeque}; const DEFAULT_TRACE_EVENT_CAPACITY: usize = 256; const DEFAULT_SESSION_ID: &str = "runtime-default"; +fn default_trace_event_capacity() -> usize { + DEFAULT_TRACE_EVENT_CAPACITY +} + #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum BehaviorTag { @@ -35,6 +39,7 @@ pub struct BehaviorTrace { pub risk_level: RiskLevel, pub tags: BTreeSet, pub events: VecDeque, + #[serde(skip, default = "default_trace_event_capacity")] event_capacity: usize, } @@ -88,8 +93,9 @@ impl BehaviorProfiler { let mut tags = classify_event(event); let base_risk = deterministic_event_risk(event); + let event_capacity = self.event_capacity; let trace = self.traces.entry(session_id.clone()).or_insert_with(|| { - BehaviorTrace::new(session_id, event.timestamp_ms, self.event_capacity) + BehaviorTrace::new(session_id, event.timestamp_ms, event_capacity) }); let sequence_risk = sequence_risk(trace, event, &tags); @@ -119,6 +125,10 @@ impl BehaviorProfiler { self.traces.get(session_id) } + pub fn trace_count(&self) -> usize { + self.traces.len() + } + pub fn traces(&self) -> Vec { let mut traces: Vec<_> = self.traces.values().cloned().collect(); traces.sort_by(|left, right| left.started_at_ms.cmp(&right.started_at_ms)); From 1178df4530596c4eedea3efceadf226fb969466d Mon Sep 17 00:00:00 2001 From: Boiko Oleg Date: Sat, 5 Sep 2026 07:30:53 +0300 Subject: [PATCH 36/46] refactor(evolve): avoid cloning traces for status counts --- sandbox_runtime/crates/sandbox-kernel/src/evolve/manager.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sandbox_runtime/crates/sandbox-kernel/src/evolve/manager.rs b/sandbox_runtime/crates/sandbox-kernel/src/evolve/manager.rs index 1b3d628..e5ec9ca 100644 --- a/sandbox_runtime/crates/sandbox-kernel/src/evolve/manager.rs +++ b/sandbox_runtime/crates/sandbox-kernel/src/evolve/manager.rs @@ -77,7 +77,7 @@ impl EvolveManager { state: self.state, events_buffered: self.events.len(), sessions: self.sessions.len(), - behavior_traces: self.behavior.traces().len(), + behavior_traces: self.behavior.trace_count(), } } From 021976494b9e3e51dbbe4cf112f0145f10447aca Mon Sep 17 00:00:00 2001 From: Boiko Oleg Date: Sat, 5 Sep 2026 07:31:29 +0300 Subject: [PATCH 37/46] feat(evolve): add host bridge runtime controls --- src/mcp/bridge.ts | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/src/mcp/bridge.ts b/src/mcp/bridge.ts index 367581c..99bc1bd 100644 --- a/src/mcp/bridge.ts +++ b/src/mcp/bridge.ts @@ -311,6 +311,30 @@ export class SandboxBridge { return this.request('POST', '/rotate_tor', {}); } + public async setEvolveEnabled(enabled: boolean): Promise { + return this.request('POST', '/evolve/enable', { enabled }); + } + + public async getEvolveStatus(): Promise { + return this.request('GET', '/evolve/status'); + } + + public async getEvolveEvents(limit: number = 100): Promise { + const boundedLimit = Math.max(1, Math.min(1000, Math.trunc(limit))); + return this.request('GET', `/evolve/events?limit=${boundedLimit}`); + } + + public async getEvolveSessions(): Promise { + return this.request('GET', '/evolve/sessions'); + } + + public async getEvolveTrace(sessionId: string = this.activeEvolveSessionId): Promise { + return this.request( + 'GET', + `/evolve/trace?session_id=${encodeURIComponent(sessionId)}` + ); + } + public async exec(command: string, timeoutSecs: number = 60): Promise { const raw = await this.request('POST', '/execute', { command, From 78ffaedcbb45bc61f8cbe4376d5a8cbb090afde4 Mon Sep 17 00:00:00 2001 From: Boiko Oleg Date: Sat, 5 Sep 2026 07:31:31 +0300 Subject: [PATCH 38/46] test(evolve): cover host session correlation and observability --- tests/evolve_bridge.test.ts | 84 +++++++++++++++++++++++++++++++++++++ 1 file changed, 84 insertions(+) create mode 100644 tests/evolve_bridge.test.ts diff --git a/tests/evolve_bridge.test.ts b/tests/evolve_bridge.test.ts new file mode 100644 index 0000000..08fc4cd --- /dev/null +++ b/tests/evolve_bridge.test.ts @@ -0,0 +1,84 @@ +import { describe, expect, it, vi } from 'vitest'; +import { SandboxBridge } from '../src/mcp/bridge.js'; + +function mockedBridge() { + const bridge = new SandboxBridge({ workspaceRoot: process.cwd(), hostPort: 19997 }); + const request = vi.spyOn(bridge as any, 'request').mockResolvedValue({ status: 'success' }); + return { bridge, request }; +} + +function bodyFor( + request: ReturnType, + path: string +): Record { + const call = request.mock.calls.find((entry) => entry[1] === path); + if (!call) throw new Error(`Expected request to ${path}`); + return (call[2] || {}) as Record; +} + +describe('SandboxBridge Evolve correlation', () => { + it('propagates one behavioral session across a scoped audit surface', async () => { + const { bridge, request } = mockedBridge(); + + await bridge.setScope({ + mode: 'remote', + targets: ['203.0.113.7'], + arm_canaries: true, + }); + + const canaryBody = bodyFor(request, '/arm_canary'); + const sessionId = canaryBody.evolve_session_id; + expect(typeof sessionId).toBe('string'); + expect(canaryBody).toEqual( + expect.objectContaining({ + base_dir: '/workspace', + evolve_session_id: sessionId, + }) + ); + expect(canaryBody).not.toHaveProperty('token_label'); + + request.mockClear(); + + await bridge.exec('whoami'); + await bridge.startBackground('printf TEST', 'evolve_bg'); + await bridge.browserAudit({ url: 'https://203.0.113.7/path' }); + await bridge.httpProbe({ url: 'https://203.0.113.7/api' }); + + expect(bodyFor(request, '/execute').evolve_session_id).toBe(sessionId); + expect(bodyFor(request, '/start_background').evolve_session_id).toBe(sessionId); + expect(bodyFor(request, '/browser_audit').evolve_session_id).toBe(sessionId); + expect(bodyFor(request, '/http_probe').evolve_session_id).toBe(sessionId); + }); + + it('rotates the behavioral session when a new scope is provisioned', async () => { + const { bridge, request } = mockedBridge(); + + await bridge.setScope({ mode: 'local', arm_canaries: true }); + const firstSession = bodyFor(request, '/arm_canary').evolve_session_id; + + request.mockClear(); + await bridge.setScope({ mode: 'local', arm_canaries: true }); + const secondSession = bodyFor(request, '/arm_canary').evolve_session_id; + + expect(secondSession).not.toBe(firstSession); + }); + + it('exposes authenticated host helpers for Evolve observability', async () => { + const { bridge, request } = mockedBridge(); + + await bridge.setEvolveEnabled(true); + await bridge.getEvolveStatus(); + await bridge.getEvolveEvents(5000); + await bridge.getEvolveSessions(); + await bridge.getEvolveTrace('session/test'); + + expect(request).toHaveBeenCalledWith('POST', '/evolve/enable', { enabled: true }); + expect(request).toHaveBeenCalledWith('GET', '/evolve/status'); + expect(request).toHaveBeenCalledWith('GET', '/evolve/events?limit=1000'); + expect(request).toHaveBeenCalledWith('GET', '/evolve/sessions'); + expect(request).toHaveBeenCalledWith( + 'GET', + '/evolve/trace?session_id=session%2Ftest' + ); + }); +}); From 12d06403ecf26fcab4f7ac08becc0dc3664910e2 Mon Sep 17 00:00:00 2001 From: Boiko Oleg Date: Sat, 5 Sep 2026 07:31:59 +0300 Subject: [PATCH 39/46] fix(evolve): simplify bridge test mock typing --- tests/evolve_bridge.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/evolve_bridge.test.ts b/tests/evolve_bridge.test.ts index 08fc4cd..444153d 100644 --- a/tests/evolve_bridge.test.ts +++ b/tests/evolve_bridge.test.ts @@ -8,7 +8,7 @@ function mockedBridge() { } function bodyFor( - request: ReturnType, + request: any, path: string ): Record { const call = request.mock.calls.find((entry) => entry[1] === path); From fe4392f6abfcdc5b036e3ba9cfc4f5ec48c2adea Mon Sep 17 00:00:00 2001 From: Boiko Oleg Date: Sat, 5 Sep 2026 07:32:01 +0300 Subject: [PATCH 40/46] fix(evolve): clamp invalid event query limits --- src/mcp/bridge.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/mcp/bridge.ts b/src/mcp/bridge.ts index 99bc1bd..32afada 100644 --- a/src/mcp/bridge.ts +++ b/src/mcp/bridge.ts @@ -320,7 +320,8 @@ export class SandboxBridge { } public async getEvolveEvents(limit: number = 100): Promise { - const boundedLimit = Math.max(1, Math.min(1000, Math.trunc(limit))); + const normalizedLimit = Number.isFinite(limit) ? Math.trunc(limit) : 100; + const boundedLimit = Math.max(1, Math.min(1000, normalizedLimit)); return this.request('GET', `/evolve/events?limit=${boundedLimit}`); } From 5c6dfa77e0ab39dd215f09a266c25f6391e7d485 Mon Sep 17 00:00:00 2001 From: Boiko Oleg Date: Sat, 5 Sep 2026 07:32:34 +0300 Subject: [PATCH 41/46] feat(evolve): add behavior lineage and deterministic risk score --- .../sandbox-kernel/src/evolve/behavior.rs | 55 ++++++++++++++++++- 1 file changed, 53 insertions(+), 2 deletions(-) diff --git a/sandbox_runtime/crates/sandbox-kernel/src/evolve/behavior.rs b/sandbox_runtime/crates/sandbox-kernel/src/evolve/behavior.rs index 289df2e..e7afb59 100644 --- a/sandbox_runtime/crates/sandbox-kernel/src/evolve/behavior.rs +++ b/sandbox_runtime/crates/sandbox-kernel/src/evolve/behavior.rs @@ -1,6 +1,6 @@ use super::{RiskLevel, SecurityEvent, SecurityEventType}; use serde::{Deserialize, Serialize}; -use std::collections::{BTreeSet, HashMap, VecDeque}; +use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque}; const DEFAULT_TRACE_EVENT_CAPACITY: usize = 256; const DEFAULT_SESSION_ID: &str = "runtime-default"; @@ -28,6 +28,7 @@ pub enum BehaviorTag { #[derive(Debug, Clone, Serialize, Deserialize)] pub struct BehaviorAssessment { pub risk_level: RiskLevel, + pub risk_score: u8, pub tags: Vec, } @@ -37,7 +38,11 @@ pub struct BehaviorTrace { pub started_at_ms: u64, pub last_event_at_ms: u64, pub risk_level: RiskLevel, + pub risk_score: u8, pub tags: BTreeSet, + pub process_lineage: BTreeMap>, + pub resources: BTreeSet, + pub destinations: BTreeSet, pub events: VecDeque, #[serde(skip, default = "default_trace_event_capacity")] event_capacity: usize, @@ -50,7 +55,11 @@ impl BehaviorTrace { started_at_ms: first_timestamp_ms, last_event_at_ms: first_timestamp_ms, risk_level: RiskLevel::Low, + risk_score: risk_score(RiskLevel::Low), tags: BTreeSet::new(), + process_lineage: BTreeMap::new(), + resources: BTreeSet::new(), + destinations: BTreeSet::new(), events: VecDeque::with_capacity(event_capacity), event_capacity, } @@ -106,6 +115,19 @@ impl BehaviorProfiler { } if effective_risk.rank() > trace.risk_level.rank() { trace.risk_level = effective_risk; + trace.risk_score = risk_score(effective_risk); + } + + if let Some(process_id) = event.process_id { + trace + .process_lineage + .insert(process_id, event.parent_process_id); + } + if let Some(resource) = event.resource.as_ref() { + trace.resources.insert(resource.clone()); + } + if let Some(destination) = event.destination.as_ref() { + trace.destinations.insert(destination.clone()); } let mut normalized_event = event.clone(); @@ -117,6 +139,7 @@ impl BehaviorProfiler { BehaviorAssessment { risk_level: effective_risk, + risk_score: risk_score(effective_risk), tags, } } @@ -136,6 +159,15 @@ impl BehaviorProfiler { } } +fn risk_score(level: RiskLevel) -> u8 { + match level { + RiskLevel::Low => 10, + RiskLevel::Medium => 45, + RiskLevel::High => 80, + RiskLevel::Critical => 100, + } +} + fn max_risk(left: RiskLevel, right: RiskLevel) -> RiskLevel { if left.rank() >= right.rank() { left @@ -308,6 +340,23 @@ mod tests { assert_eq!(profiler.observe(&network).risk_level, RiskLevel::High); } + #[test] + fn trace_collects_process_resource_and_destination_lineage() { + let mut profiler = BehaviorProfiler::new(); + let event = SecurityEvent::new(EventSource::Network, SecurityEventType::NetworkConnect) + .with_session_id("session-a") + .with_process(42, Some(7)) + .with_resource("/workspace/tool.sh") + .with_destination("203.0.113.7:443"); + + profiler.observe(&event); + + let trace = profiler.trace("session-a").expect("trace should exist"); + assert_eq!(trace.process_lineage.get(&42), Some(&Some(7))); + assert!(trace.resources.contains("/workspace/tool.sh")); + assert!(trace.destinations.contains("203.0.113.7:443")); + } + #[test] fn control_plane_access_is_always_critical() { let mut profiler = BehaviorProfiler::new(); @@ -315,7 +364,9 @@ mod tests { SecurityEvent::new(EventSource::Policy, SecurityEventType::ControlPlaneAccess) .with_session_id("session-a"); - assert_eq!(profiler.observe(&event).risk_level, RiskLevel::Critical); + let assessment = profiler.observe(&event); + assert_eq!(assessment.risk_level, RiskLevel::Critical); + assert_eq!(assessment.risk_score, 100); } #[test] From 3aa060b76489ae6aa6095fbba8b5a5e48e795b0e Mon Sep 17 00:00:00 2001 From: Boiko Oleg Date: Sat, 5 Sep 2026 07:32:48 +0300 Subject: [PATCH 42/46] feat(evolve): capture exec process lineage --- .../crates/sandbox-daemon/src/routes/exec.rs | 55 +++++++++++++++++-- 1 file changed, 50 insertions(+), 5 deletions(-) diff --git a/sandbox_runtime/crates/sandbox-daemon/src/routes/exec.rs b/sandbox_runtime/crates/sandbox-daemon/src/routes/exec.rs index 0b801a0..3c46b02 100644 --- a/sandbox_runtime/crates/sandbox-daemon/src/routes/exec.rs +++ b/sandbox_runtime/crates/sandbox-daemon/src/routes/exec.rs @@ -48,6 +48,7 @@ fn emit_exec_event( command: &str, work_dir: &str, result: Option, + process_id: Option, metadata: serde_json::Value, ) { let mut event = SecurityEvent::new(EventSource::Process, event_type) @@ -62,6 +63,9 @@ fn emit_exec_event( if let Some(result) = result { event = event.with_result(result); } + if let Some(process_id) = process_id { + event = event.with_process(process_id, Some(std::process::id())); + } event_sink.emit(event); } @@ -86,10 +90,11 @@ pub async fn handle_execute( emit_exec_event( &event_sink, evolve_session_id.as_deref(), - SecurityEventType::ProcessExec, + SecurityEventType::ProcessSpawn, &command_text, &work_dir, - Some("started".to_string()), + Some("requested".to_string()), + None, json!({ "execution_mode": "sync", "timeout_secs": timeout_secs, @@ -125,10 +130,11 @@ pub async fn handle_execute( if std::path::Path::new(&work_dir).exists() { cmd.current_dir(&work_dir); } + cmd.kill_on_drop(true); - let output = match timeout(timeout_duration, cmd.output()).await { - Ok(Ok(output)) => output, - Ok(Err(e)) => { + let child = match cmd.spawn() { + Ok(child) => child, + Err(e) => { emit_exec_event( &event_sink, evolve_session_id.as_deref(), @@ -136,6 +142,7 @@ pub async fn handle_execute( &command_text, &work_dir, Some("spawn_error".to_string()), + None, json!({"command_id": cmd_id}), ); error!("Command execution failed: {}", e); @@ -144,6 +151,42 @@ pub async fn handle_execute( Json(json!({"error": format!("Command spawn failed: {}", e)})), )); } + }; + + let process_id = child.id(); + emit_exec_event( + &event_sink, + evolve_session_id.as_deref(), + SecurityEventType::ProcessExec, + &command_text, + &work_dir, + Some("started".to_string()), + process_id, + json!({ + "execution_mode": "sync", + "command_id": cmd_id + }), + ); + + let output = match timeout(timeout_duration, child.wait_with_output()).await { + Ok(Ok(output)) => output, + Ok(Err(e)) => { + emit_exec_event( + &event_sink, + evolve_session_id.as_deref(), + SecurityEventType::ProcessExit, + &command_text, + &work_dir, + Some("wait_error".to_string()), + process_id, + json!({"command_id": cmd_id}), + ); + error!("Command wait failed: {}", e); + return Err(( + StatusCode::INTERNAL_SERVER_ERROR, + Json(json!({"error": format!("Command wait failed: {}", e)})), + )); + } Err(_) => { emit_exec_event( &event_sink, @@ -152,6 +195,7 @@ pub async fn handle_execute( &command_text, &work_dir, Some("timeout".to_string()), + process_id, json!({ "command_id": cmd_id, "timeout_secs": timeout_secs @@ -191,6 +235,7 @@ pub async fn handle_execute( &command_text, &work_dir, Some(format!("exit_code={exit_code}")), + process_id, json!({ "command_id": cmd_id, "is_truncated": watchdog_res.is_truncated, From 6eb0dd73a299ddc6f46311a4137f46fbaee7f84a Mon Sep 17 00:00:00 2001 From: Boiko Oleg Date: Sat, 5 Sep 2026 07:33:13 +0300 Subject: [PATCH 43/46] test(evolve): add live Docker behavior pipeline coverage --- tests/evolve_docker.test.ts | 76 +++++++++++++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 tests/evolve_docker.test.ts diff --git a/tests/evolve_docker.test.ts b/tests/evolve_docker.test.ts new file mode 100644 index 0000000..d5efab1 --- /dev/null +++ b/tests/evolve_docker.test.ts @@ -0,0 +1,76 @@ +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import * as fs from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; +import { SandboxBridge } from '../src/mcp/bridge.js'; + +const enabled = process.env.SECURITY_AUDIT_DOCKER_E2E === '1'; +const describeDocker = enabled ? describe : describe.skip; + +describeDocker('Evolve live Docker behavior pipeline', () => { + let bridge: SandboxBridge; + let workspace: string; + const port = 19109; + + beforeAll(async () => { + workspace = fs.mkdtempSync(path.join(os.tmpdir(), 'security-audit-evolve-e2e-')); + bridge = new SandboxBridge({ workspaceRoot: workspace, hostPort: port }); + await bridge.ensureRuntime(); + await bridge.setScope({ mode: 'local', arm_canaries: false }); + await bridge.setEvolveEnabled(true); + }, 60_000); + + afterAll(() => { + try { + bridge?.getDocker().stop(); + } finally { + if (workspace) fs.rmSync(workspace, { recursive: true, force: true }); + } + }); + + it('correlates real exec telemetry into a medium-risk behavior trace', async () => { + const discovery = await bridge.exec('whoami'); + expect(discovery.exit_code).toBe(0); + + // Local mode is intentionally fail-closed for outbound networking. The command itself is still + // observable, so BehaviorProfiler can correlate discovery -> network intent without allowing + // the connection to escape the sandbox. + const network = await bridge.exec( + 'curl -fsS --connect-timeout 1 --max-time 2 https://example.com >/dev/null' + ); + expect(network.exit_code).not.toBe(0); + + const status = await bridge.getEvolveStatus(); + expect(status.enabled).toBe(true); + expect(status.state).toBe('SUSPECT'); + expect(status.behavior_traces).toBeGreaterThan(0); + + const sessions = await bridge.getEvolveSessions(); + const activeSession = sessions.sessions.find( + (session: any) => session.session_id !== 'runtime-default' && session.event_refs.length > 0 + ); + expect(activeSession).toBeTruthy(); + + const trace = await bridge.getEvolveTrace(activeSession.session_id); + expect(trace.risk_level).toBe('MEDIUM'); + expect(trace.risk_score).toBe(45); + expect(trace.tags).toEqual( + expect.arrayContaining(['execution', 'discovery', 'network_activity']) + ); + expect(trace.events.length).toBeGreaterThanOrEqual(4); + expect(Object.keys(trace.process_lineage).length).toBeGreaterThan(0); + }, 15_000); + + it('keeps the runtime network boundary intact while Evolve observes behavior', async () => { + const isolation = await bridge.request<{ is_isolated: boolean }>( + 'GET', + '/isolation_status' + ); + expect(isolation.is_isolated).toBe(false); + + const blocked = await bridge.exec( + 'curl -fsS --connect-timeout 1 --max-time 2 http://1.1.1.1 >/dev/null' + ); + expect(blocked.exit_code).not.toBe(0); + }, 10_000); +}); From b85d19424096b80efceb7b4660ecce027758094f Mon Sep 17 00:00:00 2001 From: Boiko Oleg Date: Sat, 5 Sep 2026 07:33:15 +0300 Subject: [PATCH 44/46] ci(evolve): run live behavior pipeline regression --- .github/workflows/ci.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index dcd4cea..c1f5b00 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -100,6 +100,7 @@ jobs: run: | npx vitest run tests/docker_roundtrip.test.ts npx vitest run tests/docker_security_hardening.test.ts + npx vitest run tests/evolve_docker.test.ts - name: Dump sandbox diagnostics on failure if: failure() From d1af48e2e20d91d05db53d22190f07f3bcbfbf13 Mon Sep 17 00:00:00 2001 From: Boiko Oleg Date: Sat, 5 Sep 2026 07:33:42 +0300 Subject: [PATCH 45/46] fix(evolve): separate credential interest from confirmed access --- .../sandbox-kernel/src/evolve/behavior.rs | 38 ++++++++++++++++--- 1 file changed, 33 insertions(+), 5 deletions(-) diff --git a/sandbox_runtime/crates/sandbox-kernel/src/evolve/behavior.rs b/sandbox_runtime/crates/sandbox-kernel/src/evolve/behavior.rs index e7afb59..9432732 100644 --- a/sandbox_runtime/crates/sandbox-kernel/src/evolve/behavior.rs +++ b/sandbox_runtime/crates/sandbox-kernel/src/evolve/behavior.rs @@ -15,6 +15,7 @@ pub enum BehaviorTag { Execution, Discovery, CredentialInterest, + CredentialAccess, NetworkActivity, BrowserActivity, PolicyBoundary, @@ -202,7 +203,10 @@ fn classify_event(event: &SecurityEvent) -> Vec { | SecurityEventType::ProcessExec | SecurityEventType::ProcessExit => tags.push(BehaviorTag::Execution), SecurityEventType::Discovery => tags.push(BehaviorTag::Discovery), - SecurityEventType::CredentialAccess => tags.push(BehaviorTag::CredentialInterest), + SecurityEventType::CredentialAccess => { + tags.push(BehaviorTag::CredentialInterest); + tags.push(BehaviorTag::CredentialAccess); + }, SecurityEventType::NetworkConnect | SecurityEventType::NetworkListen | SecurityEventType::DnsAttempt @@ -215,6 +219,7 @@ fn classify_event(event: &SecurityEvent) -> Vec { SecurityEventType::CanaryAccess => { tags.push(BehaviorTag::CanaryInteraction); tags.push(BehaviorTag::CredentialInterest); + tags.push(BehaviorTag::CredentialAccess); } SecurityEventType::EscapeAttempt | SecurityEventType::ControlPlaneAccess => { tags.push(BehaviorTag::EscapeActivity); @@ -280,16 +285,22 @@ fn sequence_risk( let previous_tags = &trace.tags; let discovery_then_network = previous_tags.contains(&BehaviorTag::Discovery) && current_tags.contains(&BehaviorTag::NetworkActivity); - let credential_then_network = previous_tags.contains(&BehaviorTag::CredentialInterest) + let credential_access_then_network = previous_tags.contains(&BehaviorTag::CredentialAccess) && current_tags.contains(&BehaviorTag::NetworkActivity); + let credential_interest_then_network = + previous_tags.contains(&BehaviorTag::CredentialInterest) + && current_tags.contains(&BehaviorTag::NetworkActivity); let repeated_policy_boundary = previous_tags.contains(&BehaviorTag::PolicyBoundary) && current_tags.contains(&BehaviorTag::PolicyBoundary); - if credential_then_network { + if credential_access_then_network { return RiskLevel::High; } - if discovery_then_network || repeated_policy_boundary { + if discovery_then_network + || credential_interest_then_network + || repeated_policy_boundary + { return RiskLevel::Medium; } @@ -324,7 +335,7 @@ mod tests { } #[test] - fn credential_interest_followed_by_network_activity_is_high_risk() { + fn credential_interest_followed_by_network_activity_is_medium_risk() { let mut profiler = BehaviorProfiler::new(); let credential = @@ -336,6 +347,23 @@ mod tests { .with_session_id("session-a") .with_command("curl https://example.com"); + profiler.observe(&credential); + assert_eq!(profiler.observe(&network).risk_level, RiskLevel::Medium); + } + + #[test] + fn confirmed_credential_access_followed_by_network_activity_is_high_risk() { + let mut profiler = BehaviorProfiler::new(); + + let credential = + SecurityEvent::new(EventSource::Filesystem, SecurityEventType::CredentialAccess) + .with_session_id("session-a") + .with_resource("/workspace/secret"); + let network = + SecurityEvent::new(EventSource::Process, SecurityEventType::ProcessExec) + .with_session_id("session-a") + .with_command("curl https://example.com"); + profiler.observe(&credential); assert_eq!(profiler.observe(&network).risk_level, RiskLevel::High); } From b9febd5bc2d375d4a36a4585eb0271a3b4fcd6fe Mon Sep 17 00:00:00 2001 From: Boiko Oleg Date: Sat, 5 Sep 2026 07:33:59 +0300 Subject: [PATCH 46/46] docs(evolve): record Stage 8.1-8.2 implementation status --- ...AGE_8_EVOLVE_ADAPTIVE_DECEPTION_RUNTIME.md | 65 +++++++++++++++++++ 1 file changed, 65 insertions(+) diff --git a/plan/STAGE_8_EVOLVE_ADAPTIVE_DECEPTION_RUNTIME.md b/plan/STAGE_8_EVOLVE_ADAPTIVE_DECEPTION_RUNTIME.md index b5d3191..a61d809 100644 --- a/plan/STAGE_8_EVOLVE_ADAPTIVE_DECEPTION_RUNTIME.md +++ b/plan/STAGE_8_EVOLVE_ADAPTIVE_DECEPTION_RUNTIME.md @@ -153,6 +153,71 @@ sandbox_runtime/ --- +## 6.1. Текущий implementation status + +Рабочая ветка: + +```text +stage-8-evolve-event-core +``` + +Текущее состояние: + +### Phase 8.1 - Event Core + +Реализовано: + +- `SecurityEvent`, `RiskLevel`, `EvolveState`, `EvolveSession`, `EvolveManager`; +- единый daemon event sink; +- event ingestion для canary, sync exec, background execution, browser и HTTP probe; +- route-level `PolicyViolation` events для RoE violations; +- единый `evolve_session_id` на audit scope со стороны Host MCP Bridge; +- canary trigger correlation с текущей behavioral session; +- устранён старый contract mismatch `token_label` / `base_dir`; +- stale canary watcher invalidation при повторном arm; +- manual emergency isolation синхронизирует `EvolveState::Isolate`; +- daemon observability routes для status, events, sessions и trace; +- live Docker Evolve regression scenario добавлен в CI. + +### Phase 8.2 - Behavior Layer + +Реализован baseline: + +- `BehaviorProfiler`; +- ordered `BehaviorTrace`; +- deterministic behavior tags; +- process lineage; +- resource lineage; +- destination lineage; +- deterministic risk score; +- contextual sequence correlation; +- conservative separation между credential interest и confirmed credential access; +- decision layer использует effective contextual risk. + +Текущая политика до появления Deception Fabric: + +```text +LOW -> OBSERVE +MEDIUM -> SUSPECT / enhanced telemetry +HIGH -> existing KillSwitch +CRITICAL -> existing KillSwitch +``` + +Это временный fail-closed режим. После Phase 8.3 безопасный `HIGH` path сможет переходить в `ENGAGE -> DECEIVE`. + +### Validation status + +GitHub Actions для текущего PR создаёт jobs, но runner не назначается: + +```text +runner_id: 0 +steps: [] +``` + +Поэтому CI сейчас завершается до checkout и не выполняет Rust/TypeScript/Docker код. Unit и live regression tests уже добавлены в ветку и должны быть прогнаны до merge при восстановлении runner availability. + +--- + ## 7. Implementation phases ### Phase 8.1 - Event Core