use llmosafe::llmosafe_body::ResourceGuard;
use llmosafe::llmosafe_integration::{EscalationPolicy, SafetyContext};
pub struct LlmoSafeGuard {
guard: ResourceGuard,
policy: EscalationPolicy,
}
impl LlmoSafeGuard {
pub fn new() -> Self {
let guard = ResourceGuard::auto(0.8);
Self {
guard,
policy: EscalationPolicy::default(),
}
}
pub fn with_memory_ceiling_bytes(memory_ceiling_bytes: usize) -> Self {
Self {
guard: ResourceGuard::new(memory_ceiling_bytes),
policy: EscalationPolicy::default(),
}
}
pub fn check(&self) -> Result<(), String> {
let pressure = self.guard.pressure();
if pressure > 80 {
return Err(format!("Resource pressure at {}% (ceiling: 80%)", pressure));
}
self.guard
.check()
.map(|_| ())
.map_err(|e| format!("Resource guard check failed: {}", e))
}
pub fn execute<F, T>(&self, f: F) -> Result<T, String>
where
F: FnOnce() -> Result<T, String>,
{
self.check()?;
f()
}
pub fn current_rss_bytes(&self) -> usize {
ResourceGuard::current_rss_bytes()
}
pub fn system_memory_bytes(&self) -> usize {
ResourceGuard::system_memory_bytes()
}
pub fn system_cpu_load(&self) -> u8 {
ResourceGuard::system_cpu_load()
}
pub fn raw_entropy(&self) -> u16 {
self.guard.raw_entropy()
}
pub fn pressure(&self) -> u8 {
self.guard.pressure()
}
pub fn safety_context(&self) -> SafetyContext {
SafetyContext::new(self.policy.clone())
}
}
impl Default for LlmoSafeGuard {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn guard_reports_system_memory() {
let guard = LlmoSafeGuard::new();
let mem = guard.system_memory_bytes();
assert!(mem > 0, "System memory should be > 0");
}
#[test]
fn guard_reports_rss() {
let rss = LlmoSafeGuard::new().current_rss_bytes();
assert!(rss > 0, "RSS should be > 0 for running process");
}
#[test]
fn check_passes_under_normal_load() {
let guard = LlmoSafeGuard::new();
let result = guard.check();
if let Err(e) = result {
eprintln!("System under pressure: {}", e);
}
}
#[test]
fn pressure_is_bounded() {
let guard = LlmoSafeGuard::new();
let p = guard.pressure();
assert!(p <= 100, "Pressure should be 0-100, got {}", p);
}
#[test]
fn entropy_is_bounded() {
let guard = LlmoSafeGuard::new();
let e = guard.raw_entropy();
assert!(e <= 1000, "Entropy should be 0-1000, got {}", e);
}
}