runtimo_core/lib.rs
1//! Runtimo Core — Agent-centric capability runtime.
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 session::{Session, SessionManager};
86pub use telemetry::Telemetry;
87pub use wal::{WalEvent, WalEventType, WalReader, WalWriter};
88
89/// Error types for runtimo-core.
90///
91/// Covers all failure modes: state transitions, schema validation,
92/// capability execution, WAL/backup errors, resource limits, and telemetry.
93#[derive(Debug, thiserror::Error)]
94pub enum Error {
95 /// Invalid job state transition attempted.
96 #[error("Invalid job state transition: {from:?} -> {to:?}")]
97 InvalidTransition { from: JobState, to: JobState },
98
99 /// JSON schema validation failed for capability arguments.
100 #[error("Schema validation failed: {0}")]
101 SchemaValidationFailed(String),
102
103 /// Requested capability not found in registry.
104 #[error("Capability not found: {0}")]
105 CapabilityNotFound(String),
106
107 /// Capability execution failed.
108 #[error("Execution failed: {0}")]
109 ExecutionFailed(String),
110
111 /// Write-Ahead Log operation failed.
112 #[error("WAL error: {0}")]
113 WalError(String),
114
115 /// Backup/restore operation failed.
116 #[error("Backup error: {0}")]
117 BackupError(String),
118
119 /// System resource limit exceeded (CPU, RAM, or zombie count).
120 #[error("Resource limit exceeded: {0}")]
121 ResourceLimitExceeded(String),
122
123 /// Telemetry capture failed.
124 #[error("Telemetry error: {0}")]
125 TelemetryError(String),
126}
127
128/// Result alias for runtimo-core operations.
129pub type Result<T> = std::result::Result<T, Error>;
130
131/// Utility functions for path management.
132pub mod utils {
133 use std::path::PathBuf;
134
135 /// Returns the data directory following XDG spec.
136 pub fn data_dir() -> PathBuf {
137 std::env::var("XDG_DATA_HOME")
138 .ok()
139 .map(PathBuf::from)
140 .or_else(|| {
141 std::env::var("HOME")
142 .ok()
143 .map(|h| PathBuf::from(h).join(".local/share"))
144 })
145 .unwrap_or_else(std::env::temp_dir)
146 .join("runtimo")
147 }
148
149 /// Returns the WAL path (env override or default).
150 pub fn wal_path() -> PathBuf {
151 std::env::var("RUNTIMO_WAL_PATH")
152 .map(PathBuf::from)
153 .unwrap_or_else(|_| data_dir().join("wal.jsonl"))
154 }
155
156 /// Returns the backup directory (env override or default).
157 pub fn backup_dir() -> PathBuf {
158 std::env::var("RUNTIMO_BACKUP_DIR")
159 .map(PathBuf::from)
160 .unwrap_or_else(|_| data_dir().join("backups"))
161 }
162
163 /// Generates a unique ID from 16 random bytes (32 hex chars).
164 ///
165 /// Uses `/dev/urandom` for collision resistance — P(collision) < 10⁻¹⁵
166 /// even at 100 IDs/sec for 1 hour. Falls back to timestamp if urandom
167 /// is unavailable (e.g., non-Linux platforms).
168 pub fn generate_id() -> String {
169 let mut bytes = [0u8; 16];
170 if std::fs::File::open("/dev/urandom")
171 .ok()
172 .and_then(|mut f| std::io::Read::read_exact(&mut f, &mut bytes).ok())
173 .is_some()
174 {
175 bytes.iter().map(|b| format!("{:02x}", b)).collect()
176 } else {
177 // Fallback: timestamp-based (collision possible but rare)
178 let ts = std::time::SystemTime::now()
179 .duration_since(std::time::UNIX_EPOCH)
180 .unwrap_or_default()
181 .as_nanos();
182 format!("{:x}", ts)
183 }
184 }
185}