runtimo_core/lib.rs
1//! Runtimo Core — Agent-centric capability runtime for persistent machines.
2//!
3//! Runtimo provides structured execution, resource limits, crash recovery,
4//! and two-layer telemetry (hardware + process tracking) for machines that
5//! cannot be factory-reset. Every capability execution captures before/after
6//! snapshots, enabling full audit trails and undo support.
7//!
8//! # Architecture
9//!
10//! - **Capabilities** — Pluggable operations implementing the [`Capability`] trait
11//! - **Jobs** — Lifecycle-tracked execution units ([`Job`], [`JobState`])
12//! - **Telemetry** — Hardware awareness ([`Telemetry`])
13//! - **Process Snapshot** — Running process awareness ([`ProcessSnapshot`])
14//! - **WAL** — Append-only crash recovery log ([`WalWriter`]/[`WalReader`])
15//! - **Backup** — Undo support via pre-mutation file backups ([`BackupManager`])
16//! - **Resource Guards** — Circuit breaker via [`LlmoSafeGuard`]
17//!
18//! # Quick Start
19//!
20//! ```rust
21//! use runtimo_core::{FileRead, Capability, Context};
22//! use serde_json::json;
23//!
24//! let cap = FileRead;
25//! assert_eq!(cap.name(), "FileRead");
26//! ```
27//!
28//! # Execution with Full Telemetry
29//!
30//! ```rust,ignore
31//! use runtimo_core::{FileRead, execute_with_telemetry};
32//! use serde_json::json;
33//! use std::path::Path;
34//!
35//! let cap = FileRead;
36//! let result = execute_with_telemetry(
37//! &cap,
38//! &json!({"path": "/tmp/test.txt"}),
39//! false,
40//! Path::new("/tmp/runtimo.wal"),
41//! ).unwrap();
42//! assert!(result.success);
43//! ```
44//!
45//! # Performance (Measured on AMD EPYC 7B13)
46//!
47//! | Operation | Latency | Notes |
48//! |-----------|---------|-------|
49//! | Cold start | <1s | Binary load + init |
50//! | FileRead | <10ms | Small files (<1KB) |
51//! | FileWrite | <50ms | Includes backup copy |
52//! | Telemetry capture | <100ms | 15+ shell subprocesses |
53//! | Process snapshot | <50ms | ps aux parse |
54//! | Memory baseline | <50MB | RSS at idle |
55//!
56//! # Feature Flags
57//!
58//! No optional features currently. All functionality is included by default.
59
60pub mod backup;
61pub mod capabilities;
62pub mod capability;
63pub mod cmd;
64pub mod config;
65pub mod executor;
66pub mod job;
67pub mod llmosafe;
68pub mod monitor;
69pub mod processes;
70pub mod schema;
71pub mod session;
72pub mod telemetry;
73pub mod validation;
74pub mod wal;
75
76pub use backup::BackupManager;
77pub use capabilities::{FileRead, FileWrite, GitExec, Kill, ShellExec, Undo};
78pub use capability::{Capability, CapabilityRegistry, Context, Output};
79pub use config::RuntimoConfig;
80pub use executor::{execute_with_telemetry, execute_with_telemetry_and_session, ExecutionResult};
81pub use job::{Job, JobId, JobState};
82pub use llmosafe::LlmoSafeGuard;
83pub use monitor::{HealthAlert, HealthMonitor, HealthState};
84pub use processes::ProcessSnapshot;
85pub use schema::SchemaValidator;
86pub use session::{Session, SessionManager};
87pub use telemetry::Telemetry;
88pub use wal::{WalEvent, WalEventType, WalReader, WalWriter};
89
90/// Error types for runtimo-core.
91///
92/// Covers all failure modes: state transitions, schema validation,
93/// capability execution, WAL/backup errors, resource limits, and telemetry.
94#[derive(Debug, thiserror::Error)]
95pub enum Error {
96 /// Invalid job state transition attempted.
97 #[error("Invalid job state transition: {from:?} -> {to:?}")]
98 InvalidTransition { from: JobState, to: JobState },
99
100 /// JSON schema validation failed for capability arguments.
101 #[error("Schema validation failed: {0}")]
102 SchemaValidationFailed(String),
103
104 /// Requested capability not found in registry.
105 #[error("Capability not found: {0}")]
106 CapabilityNotFound(String),
107
108 /// Capability execution failed.
109 #[error("Execution failed: {0}")]
110 ExecutionFailed(String),
111
112 /// Write-Ahead Log operation failed.
113 #[error("WAL error: {0}")]
114 WalError(String),
115
116 /// Backup/restore operation failed.
117 #[error("Backup error: {0}")]
118 BackupError(String),
119
120 /// System resource limit exceeded (CPU, RAM, or zombie count).
121 #[error("Resource limit exceeded: {0}")]
122 ResourceLimitExceeded(String),
123
124 /// Telemetry capture failed.
125 #[error("Telemetry error: {0}")]
126 TelemetryError(String),
127}
128
129/// Result alias for runtimo-core operations.
130pub type Result<T> = std::result::Result<T, Error>;
131
132/// Utility functions for path management.
133pub mod utils {
134 use std::path::PathBuf;
135
136 /// Returns the data directory following XDG spec.
137 pub fn data_dir() -> PathBuf {
138 std::env::var("XDG_DATA_HOME")
139 .ok()
140 .map(PathBuf::from)
141 .or_else(|| {
142 std::env::var("HOME")
143 .ok()
144 .map(|h| PathBuf::from(h).join(".local/share"))
145 })
146 .unwrap_or_else(std::env::temp_dir)
147 .join("runtimo")
148 }
149
150 /// Returns the WAL path (env override or default).
151 pub fn wal_path() -> PathBuf {
152 std::env::var("RUNTIMO_WAL_PATH")
153 .map(PathBuf::from)
154 .unwrap_or_else(|_| data_dir().join("wal.jsonl"))
155 }
156
157 /// Returns the backup directory (env override or default).
158 pub fn backup_dir() -> PathBuf {
159 std::env::var("RUNTIMO_BACKUP_DIR")
160 .map(PathBuf::from)
161 .unwrap_or_else(|_| data_dir().join("backups"))
162 }
163
164 /// Generates a unique ID from 16 random bytes (32 hex chars).
165 ///
166 /// Uses `/dev/urandom` for collision resistance — P(collision) < 10⁻¹⁵
167 /// even at 100 IDs/sec for 1 hour. Falls back to timestamp if urandom
168 /// is unavailable (e.g., non-Linux platforms).
169 pub fn generate_id() -> String {
170 let mut bytes = [0u8; 16];
171 if std::fs::File::open("/dev/urandom")
172 .ok()
173 .and_then(|mut f| std::io::Read::read_exact(&mut f, &mut bytes).ok())
174 .is_some()
175 {
176 bytes.iter().map(|b| format!("{:02x}", b)).collect()
177 } else {
178 // Fallback: timestamp-based (collision possible but rare)
179 let ts = std::time::SystemTime::now()
180 .duration_since(std::time::UNIX_EPOCH)
181 .unwrap_or_default()
182 .as_nanos();
183 format!("{:x}", ts)
184 }
185 }
186}