refactor(monorepo): reorganización lógica + renames + SDDs + split CHANGELOG
Reorganización física de crates/: - core/ (mezclaba 6 propósitos) se divide en protocol/, init/, runtime/, compat/ - shared/ (3 crates) se redistribuye en protocol/ e init/ - lapaloma (sub-módulo de ui_engine) se promueve a modules/pineal/ Renames de proyectos: - shipote → shuma (runtime de sandboxes) - nouser → akasha (explorador de Mónadas) - yahweh → nahual (motor GPUI, antes ui_engine/) - lapaloma → pineal (data-viz agnóstica) Fraccionamiento UI → core agnóstico: - vista-core (DeckState + snap, 175 LOC, 5 tests verdes) - barra-core (Task + render_html + sanitize, 90 LOC, 5 tests verdes) - vista-web y barra-web ahora son thin DOM bindings Documentación nueva: - 16 SDDs por subdirectorio (≤80 LOC c/u): protocol/init/runtime/compat + 10 módulos + apps/ - docs/STATUS.md con cifras reales por proyecto - docs/ROADMAP.md con plan a finalización (6 hitos, ~6-8 semanas) - CHANGELOG.md particionado en docs/changelog/<proyecto>.md (7 buckets) Automatización: - scripts/reorg.py — script idempotente que: git mv directorios, renombra package names, recomputa path = refs, reescribe imports rust, actualiza workspace Cargo.toml. Soporta --dry-run. - scripts/split-changelog.py — particiona CHANGELOG por componente. Validación: - cargo check --workspace pasa (124 crates + 2 nuevos cores). - 10 tests adicionales (5 en vista-core + 5 en barra-core) verdes. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,550 @@
|
||||
//! Audit log: cada acción mutadora del cerebro deja una entry inmutable
|
||||
//! con su predecesor encadenado por SHA256 (estilo Merkle). Verificable a
|
||||
//! posteriori sin confianza en quien escribe.
|
||||
//!
|
||||
//! Los entries viven en memoria. Para persistencia, `flush_to_cas()` los
|
||||
//! escribe al content-addressable store y devuelve el SHA del head, que
|
||||
//! puede guardarse en un archivo de "head pointer" (fuera de scope aquí).
|
||||
|
||||
use crate::crystallize::Crystal;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::VecDeque;
|
||||
use ulid::Ulid;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct AuditEntry {
|
||||
/// Sequence number monotónico desde el inicio del log.
|
||||
pub seq: u64,
|
||||
/// Wall-clock al insertar.
|
||||
pub timestamp_ms: u64,
|
||||
/// SHA256 del entry anterior. None para el primer entry.
|
||||
pub prev_sha: Option<[u8; 32]>,
|
||||
/// SHA256 de este entry (auto-calculado al construir).
|
||||
pub sha: [u8; 32],
|
||||
/// Acción registrada.
|
||||
pub action: AuditAction,
|
||||
}
|
||||
|
||||
/// Sin `#[serde(tag)]`: bincode requiere external tagging (default serde
|
||||
/// para enums) para no usar `deserialize_any`. JSON sigue legible.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub enum AuditAction {
|
||||
PromoteCrystal { rule_id: Ulid, crystal: Crystal },
|
||||
RemoveRule { rule_id: Ulid },
|
||||
LoadRulesFile { path: String, count: usize },
|
||||
}
|
||||
|
||||
pub struct AuditLog {
|
||||
entries: VecDeque<AuditEntry>,
|
||||
next_seq: u64,
|
||||
/// Cap del log en memoria. Entries más viejos se descartan tras flush.
|
||||
cap: usize,
|
||||
/// Total acumulado de entries flusheadas a CAS.
|
||||
flushed_count: u64,
|
||||
/// SHA del último entry persistido a CAS — el "head pointer" del log.
|
||||
last_flushed_sha: Option<[u8; 32]>,
|
||||
/// Path opcional donde escribir el head pointer tras cada flush.
|
||||
head_pointer_path: Option<std::path::PathBuf>,
|
||||
/// Subscribers a entries en tiempo real. Cada `append` empuja a todos.
|
||||
/// Subscribers cuyo receiver se dropeó se purgan en el siguiente push.
|
||||
subscribers: Vec<tokio::sync::mpsc::UnboundedSender<AuditEntry>>,
|
||||
/// Wall-clock del último flush exitoso a CAS. None si aún no se flush.
|
||||
last_flush_at_ms: Option<u64>,
|
||||
}
|
||||
|
||||
impl AuditLog {
|
||||
pub fn new() -> Self {
|
||||
Self::with_cap(512)
|
||||
}
|
||||
|
||||
pub fn with_cap(cap: usize) -> Self {
|
||||
Self {
|
||||
entries: VecDeque::new(),
|
||||
next_seq: 0,
|
||||
cap,
|
||||
flushed_count: 0,
|
||||
last_flushed_sha: None,
|
||||
head_pointer_path: None,
|
||||
subscribers: Vec::new(),
|
||||
last_flush_at_ms: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Registra un nuevo subscriber. El receiver recibe cada `AuditEntry`
|
||||
/// futuro hasta que el receiver se dropee (subscriber se purga al
|
||||
/// siguiente `append`).
|
||||
pub fn subscribe(&mut self) -> tokio::sync::mpsc::UnboundedReceiver<AuditEntry> {
|
||||
let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
|
||||
self.subscribers.push(tx);
|
||||
rx
|
||||
}
|
||||
|
||||
pub fn subscriber_count(&self) -> usize { self.subscribers.len() }
|
||||
|
||||
pub fn with_head_pointer(mut self, path: std::path::PathBuf) -> Self {
|
||||
self.head_pointer_path = Some(path);
|
||||
self
|
||||
}
|
||||
|
||||
/// Apendea una acción. Calcula el SHA encadenado contra el último entry.
|
||||
pub fn append(&mut self, action: AuditAction) -> AuditEntry {
|
||||
let prev_sha = self.entries.back().map(|e| e.sha);
|
||||
let timestamp_ms = now_ms();
|
||||
let seq = self.next_seq;
|
||||
self.next_seq += 1;
|
||||
|
||||
// Pre-construct con sha en cero, luego calcular sha sobre el
|
||||
// serializado canónico, luego sobreescribir el campo.
|
||||
let mut entry = AuditEntry {
|
||||
seq, timestamp_ms, prev_sha, sha: [0u8; 32], action,
|
||||
};
|
||||
entry.sha = compute_sha(&entry);
|
||||
|
||||
if self.entries.len() >= self.cap {
|
||||
self.entries.pop_front();
|
||||
}
|
||||
self.entries.push_back(entry.clone());
|
||||
// Empujar a subscribers, purgando los muertos in-place.
|
||||
self.subscribers.retain(|tx| tx.send(entry.clone()).is_ok());
|
||||
entry
|
||||
}
|
||||
|
||||
pub fn recent(&self, limit: usize) -> impl Iterator<Item = &AuditEntry> {
|
||||
let n = if limit == 0 { self.entries.len() } else { limit.min(self.entries.len()) };
|
||||
self.entries.iter().skip(self.entries.len() - n)
|
||||
}
|
||||
|
||||
pub fn len(&self) -> usize { self.entries.len() }
|
||||
pub fn is_empty(&self) -> bool { self.entries.is_empty() }
|
||||
|
||||
pub fn head_sha(&self) -> Option<[u8; 32]> {
|
||||
self.entries.back().map(|e| e.sha)
|
||||
}
|
||||
|
||||
/// Persiste el entry pasado al CAS y devuelve su SHA. Pensado para
|
||||
/// snapshots externos — el log en memoria sigue intacto.
|
||||
pub fn persist_to_cas(entry: &AuditEntry) -> anyhow::Result<[u8; 32]> {
|
||||
let bytes = serde_json::to_vec(entry)?;
|
||||
let sha = ente_cas::store(&bytes)?;
|
||||
Ok(sha)
|
||||
}
|
||||
|
||||
/// Persiste TODOS los entries actuales al CAS y actualiza el head pointer.
|
||||
/// Idempotente: re-flushar dos veces da los mismos SHAs (CAS dedup).
|
||||
/// Devuelve cuántas entries se flushearon en esta pasada.
|
||||
///
|
||||
/// Forma canónica: serializamos `entry` con `sha = [0; 32]` (formato
|
||||
/// pre-hash). El CAS computa sha256 sobre esos bytes y devuelve un SHA
|
||||
/// que por construcción coincide con `entry.sha` calculado al append.
|
||||
pub fn flush_to_cas(&mut self) -> anyhow::Result<usize> {
|
||||
let mut written = 0;
|
||||
let mut last_sha = self.last_flushed_sha;
|
||||
for entry in &self.entries {
|
||||
if entry.seq < self.flushed_count { continue; }
|
||||
let bytes = canonical_bytes(entry);
|
||||
let sha = ente_cas::store(&bytes)?;
|
||||
debug_assert_eq!(sha, entry.sha,
|
||||
"CAS sha != entry.sha — fórmula canónica rota");
|
||||
last_sha = Some(sha);
|
||||
written += 1;
|
||||
}
|
||||
self.flushed_count += written as u64;
|
||||
self.last_flushed_sha = last_sha;
|
||||
if written > 0 {
|
||||
self.last_flush_at_ms = Some(now_ms());
|
||||
}
|
||||
// Persistir head pointer si está configurado.
|
||||
if let (Some(path), Some(sha)) = (&self.head_pointer_path, last_sha) {
|
||||
let pointer = AuditHeadPointer {
|
||||
last_seq: self.next_seq.saturating_sub(1),
|
||||
last_sha: sha,
|
||||
flushed_count: self.flushed_count,
|
||||
timestamp_ms: now_ms(),
|
||||
};
|
||||
let json = serde_json::to_vec_pretty(&pointer)?;
|
||||
// Escritura atómica: tmp + rename
|
||||
let tmp = path.with_extension("tmp");
|
||||
if let Some(parent) = path.parent() { let _ = std::fs::create_dir_all(parent); }
|
||||
std::fs::write(&tmp, json)?;
|
||||
std::fs::rename(&tmp, path)?;
|
||||
}
|
||||
Ok(written)
|
||||
}
|
||||
|
||||
pub fn flushed_count(&self) -> u64 { self.flushed_count }
|
||||
pub fn last_flushed_sha(&self) -> Option<[u8; 32]> { self.last_flushed_sha }
|
||||
pub fn last_flush_at_ms(&self) -> Option<u64> { self.last_flush_at_ms }
|
||||
|
||||
/// Segundos transcurridos desde el último flush. None si nunca se flush.
|
||||
pub fn last_flush_age_secs(&self) -> Option<f64> {
|
||||
let then = self.last_flush_at_ms?;
|
||||
let now = now_ms();
|
||||
Some((now.saturating_sub(then)) as f64 / 1000.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// Pointer al head del audit log — escrito atómicamente en disco tras cada
|
||||
/// flush. Permite verificar la integridad del log sin escanearlo entero:
|
||||
/// el cliente lee el head, recupera el blob desde CAS, valida `prev_sha`
|
||||
/// recursivamente hasta el genesis.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct AuditHeadPointer {
|
||||
pub last_seq: u64,
|
||||
pub last_sha: [u8; 32],
|
||||
pub flushed_count: u64,
|
||||
pub timestamp_ms: u64,
|
||||
}
|
||||
|
||||
/// Reporte de un replay: número de actions aplicadas + reglas finales.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct ReplayReport {
|
||||
pub applied: u64,
|
||||
pub final_rule_count: usize,
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
/// Reporte de verificación de la cadena audit.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct VerificationReport {
|
||||
/// Cuántas entries se recorrieron y verificaron exitosamente.
|
||||
pub verified: u64,
|
||||
/// Si hubo error, el seq donde se detectó.
|
||||
pub broken_at_seq: Option<u64>,
|
||||
/// Detalles del error si hubo.
|
||||
pub error: Option<String>,
|
||||
/// SHA del genesis (primer entry; prev_sha = None).
|
||||
pub genesis_sha: Option<[u8; 32]>,
|
||||
}
|
||||
|
||||
/// Recorre la cadena del audit log desde `start_sha` hacia atrás vía `prev_sha`
|
||||
/// hasta el genesis. Para cada entry valida:
|
||||
/// 1. CAS contiene un blob bajo ese SHA
|
||||
/// 2. sha256(blob) == SHA esperado (defensa contra tampering del CAS)
|
||||
/// 3. El blob deserializa a AuditEntry con sha=[0;32] (forma canónica)
|
||||
///
|
||||
/// Devuelve un VerificationReport con el conteo, posibles errores y
|
||||
/// el SHA del genesis (útil para clientes que quieren cachearlo).
|
||||
pub fn verify_chain_from_cas(start_sha: [u8; 32]) -> VerificationReport {
|
||||
let mut current = Some(start_sha);
|
||||
let mut verified = 0u64;
|
||||
let mut last_seen: Option<AuditEntry> = None;
|
||||
|
||||
while let Some(sha) = current {
|
||||
let path = ente_cas::cas_root().join(ente_cas::hex(&sha));
|
||||
let bytes = match std::fs::read(&path) {
|
||||
Ok(b) => b,
|
||||
Err(e) => return VerificationReport {
|
||||
verified,
|
||||
broken_at_seq: last_seen.as_ref().map(|e| e.seq),
|
||||
error: Some(format!("CAS read {}: {e}", path.display())),
|
||||
genesis_sha: None,
|
||||
},
|
||||
};
|
||||
// Verificación 1: el blob hashea a la SHA esperada (CAS contract).
|
||||
let actual = ente_cas::sha256_of(&bytes);
|
||||
if actual != sha {
|
||||
return VerificationReport {
|
||||
verified,
|
||||
broken_at_seq: last_seen.as_ref().map(|e| e.seq),
|
||||
error: Some(format!(
|
||||
"CAS tamper en {}: expected {} got {}",
|
||||
path.display(), ente_cas::hex(&sha), ente_cas::hex(&actual)
|
||||
)),
|
||||
genesis_sha: None,
|
||||
};
|
||||
}
|
||||
// Verificación 2: deserialize. El blob canónico tiene sha=[0;32].
|
||||
let mut entry: AuditEntry = match serde_json::from_slice(&bytes) {
|
||||
Ok(e) => e,
|
||||
Err(e) => return VerificationReport {
|
||||
verified,
|
||||
broken_at_seq: last_seen.as_ref().map(|e| e.seq),
|
||||
error: Some(format!("deserialize: {e}")),
|
||||
genesis_sha: None,
|
||||
},
|
||||
};
|
||||
// Re-poblar el sha en el entry para reportar coherentemente.
|
||||
entry.sha = sha;
|
||||
verified += 1;
|
||||
|
||||
let prev = entry.prev_sha;
|
||||
last_seen = Some(entry);
|
||||
current = prev;
|
||||
}
|
||||
|
||||
VerificationReport {
|
||||
verified,
|
||||
broken_at_seq: None,
|
||||
error: None,
|
||||
genesis_sha: last_seen.as_ref().map(|e| e.sha),
|
||||
}
|
||||
}
|
||||
|
||||
/// Devuelve el set de SHAs alcanzables desde `start_sha` siguiendo
|
||||
/// `prev_sha` hasta el genesis. Usado por el GC del CAS para construir
|
||||
/// las "raíces vivas" del audit log.
|
||||
pub fn reachable_from_head(start_sha: [u8; 32]) -> std::collections::HashSet<[u8; 32]> {
|
||||
let mut set = std::collections::HashSet::new();
|
||||
let mut current = Some(start_sha);
|
||||
while let Some(sha) = current {
|
||||
if !set.insert(sha) { break; } // ciclo (no debería pasar) — corta
|
||||
let path = ente_cas::cas_root().join(ente_cas::hex(&sha));
|
||||
let bytes = match std::fs::read(&path) { Ok(b) => b, Err(_) => break };
|
||||
let entry: AuditEntry = match serde_json::from_slice(&bytes) {
|
||||
Ok(e) => e, Err(_) => break,
|
||||
};
|
||||
current = entry.prev_sha;
|
||||
}
|
||||
set
|
||||
}
|
||||
|
||||
/// Recorre la cadena entera (head→genesis) y reconstruye la lista de
|
||||
/// actions en orden cronológico (oldest first). Útil tanto para replay
|
||||
/// como para auditoría retrospectiva.
|
||||
pub fn collect_chain_from_cas(start_sha: [u8; 32]) -> anyhow::Result<Vec<AuditEntry>> {
|
||||
let mut entries = Vec::new();
|
||||
let mut current = Some(start_sha);
|
||||
while let Some(sha) = current {
|
||||
let path = ente_cas::cas_root().join(ente_cas::hex(&sha));
|
||||
let bytes = std::fs::read(&path)?;
|
||||
let mut entry: AuditEntry = serde_json::from_slice(&bytes)?;
|
||||
entry.sha = sha;
|
||||
let prev = entry.prev_sha;
|
||||
entries.push(entry);
|
||||
current = prev;
|
||||
}
|
||||
// entries está en orden head→genesis. Reverse para chronological.
|
||||
entries.reverse();
|
||||
Ok(entries)
|
||||
}
|
||||
|
||||
/// Aplica las actions de la cadena en orden cronológico contra un engine
|
||||
/// fresco. PromoteCrystal → insert. RemoveRule → remove. LoadRulesFile →
|
||||
/// log informativo (los archivos pueden no existir en el ambiente actual).
|
||||
pub fn replay_chain(
|
||||
start_sha: [u8; 32],
|
||||
engine: &mut crate::engine::RuleEngine,
|
||||
) -> ReplayReport {
|
||||
let entries = match collect_chain_from_cas(start_sha) {
|
||||
Ok(es) => es,
|
||||
Err(e) => return ReplayReport {
|
||||
applied: 0, final_rule_count: engine.len(),
|
||||
error: Some(format!("collect chain: {e}")),
|
||||
},
|
||||
};
|
||||
let mut applied = 0u64;
|
||||
for entry in &entries {
|
||||
match &entry.action {
|
||||
AuditAction::PromoteCrystal { rule_id, crystal } => {
|
||||
let mut rule = crate::crystallize::crystal_to_rule(crystal);
|
||||
rule.id = *rule_id; // preservar identidad histórica
|
||||
engine.insert(rule);
|
||||
}
|
||||
AuditAction::RemoveRule { rule_id } => {
|
||||
engine.remove(*rule_id);
|
||||
}
|
||||
AuditAction::LoadRulesFile { path: _, count: _ } => {
|
||||
// Los archivos referenciados por path pueden haber cambiado
|
||||
// o no existir. Log y skip — el replay sólo reconstruye
|
||||
// promotes/removes que tienen estado en CAS.
|
||||
}
|
||||
}
|
||||
applied += 1;
|
||||
}
|
||||
ReplayReport {
|
||||
applied,
|
||||
final_rule_count: engine.len(),
|
||||
error: None,
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for AuditLog {
|
||||
fn default() -> Self { Self::new() }
|
||||
}
|
||||
|
||||
fn now_ms() -> u64 {
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|d| d.as_millis() as u64)
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
/// SHA256 sobre el entry en forma canónica (sha=[0;32]). Hash y CAS storage
|
||||
/// ven los mismos bytes, así que `ente_cas::store(canonical)` devuelve el
|
||||
/// mismo SHA que `compute_sha(entry)`.
|
||||
fn compute_sha(entry: &AuditEntry) -> [u8; 32] {
|
||||
let bytes = canonical_bytes(entry);
|
||||
ente_cas::sha256_of(&bytes)
|
||||
}
|
||||
|
||||
/// Forma canónica: el entry serializado JSON con `sha = [0; 32]`.
|
||||
/// JSON sin pretty-print es determinístico para nuestros tipos.
|
||||
fn canonical_bytes(entry: &AuditEntry) -> Vec<u8> {
|
||||
let canonical = AuditEntry {
|
||||
sha: [0u8; 32],
|
||||
..entry.clone()
|
||||
};
|
||||
serde_json::to_vec(&canonical).unwrap_or_default()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn chain_links_consecutive_entries() {
|
||||
let mut log = AuditLog::new();
|
||||
let e1 = log.append(AuditAction::RemoveRule { rule_id: Ulid::new() });
|
||||
let e2 = log.append(AuditAction::RemoveRule { rule_id: Ulid::new() });
|
||||
assert!(e1.prev_sha.is_none());
|
||||
assert_eq!(e2.prev_sha, Some(e1.sha));
|
||||
assert_ne!(e1.sha, e2.sha);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn seq_monotonic() {
|
||||
let mut log = AuditLog::new();
|
||||
let e1 = log.append(AuditAction::RemoveRule { rule_id: Ulid::new() });
|
||||
let e2 = log.append(AuditAction::RemoveRule { rule_id: Ulid::new() });
|
||||
assert_eq!(e2.seq, e1.seq + 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cap_evicts_oldest() {
|
||||
let mut log = AuditLog::with_cap(3);
|
||||
for _ in 0..5 {
|
||||
log.append(AuditAction::RemoveRule { rule_id: Ulid::new() });
|
||||
}
|
||||
assert_eq!(log.len(), 3);
|
||||
// El primer seq superviviente debe ser 2.
|
||||
assert_eq!(log.recent(0).next().unwrap().seq, 2);
|
||||
}
|
||||
|
||||
// ---------- Tests de integración con CAS real (en directorio temporal) ----------
|
||||
|
||||
use crate::engine::RuleEngine;
|
||||
use std::sync::Mutex;
|
||||
|
||||
/// Lock para serializar tests que mutan ENTE_CAS_ROOT (test threads
|
||||
/// comparten env vars). Sin esto, dos tests en paralelo pisan el path.
|
||||
static CAS_TEST_LOCK: Mutex<()> = Mutex::new(());
|
||||
|
||||
fn with_temp_cas<F: FnOnce()>(f: F) {
|
||||
let _guard = CAS_TEST_LOCK.lock().unwrap();
|
||||
let dir = std::env::temp_dir().join(format!("ente-cas-test-{}", Ulid::new()));
|
||||
std::env::set_var("ENTE_CAS_ROOT", &dir);
|
||||
let _cleanup = scopeguard(&dir);
|
||||
f();
|
||||
}
|
||||
|
||||
fn scopeguard(dir: &std::path::Path) -> impl Drop + '_ {
|
||||
struct G<'a>(&'a std::path::Path);
|
||||
impl<'a> Drop for G<'a> {
|
||||
fn drop(&mut self) {
|
||||
std::env::remove_var("ENTE_CAS_ROOT");
|
||||
let _ = std::fs::remove_dir_all(self.0);
|
||||
}
|
||||
}
|
||||
G(dir)
|
||||
}
|
||||
|
||||
fn dummy_crystal(ant: EventKind, con: EventKind) -> Crystal {
|
||||
Crystal {
|
||||
antecedent: ant,
|
||||
consequent: con,
|
||||
conditional_prob: 0.9,
|
||||
pmi: 1.5,
|
||||
support: 7,
|
||||
gap_stats: None,
|
||||
}
|
||||
}
|
||||
|
||||
use crate::rules::EventKind;
|
||||
|
||||
#[test]
|
||||
fn flush_round_trip_preserves_chain() {
|
||||
with_temp_cas(|| {
|
||||
let mut log = AuditLog::new();
|
||||
let id1 = Ulid::new();
|
||||
let id2 = Ulid::new();
|
||||
log.append(AuditAction::PromoteCrystal {
|
||||
rule_id: id1,
|
||||
crystal: dummy_crystal(EventKind::EnteSpawned, EventKind::EnteDied),
|
||||
});
|
||||
log.append(AuditAction::PromoteCrystal {
|
||||
rule_id: id2,
|
||||
crystal: dummy_crystal(EventKind::BusAnnounce, EventKind::BusInvoke),
|
||||
});
|
||||
log.append(AuditAction::RemoveRule { rule_id: id1 });
|
||||
|
||||
assert_eq!(log.flush_to_cas().unwrap(), 3);
|
||||
let head = log.last_flushed_sha().expect("head set");
|
||||
let report = verify_chain_from_cas(head);
|
||||
assert!(report.error.is_none(), "verification failed: {:?}", report.error);
|
||||
assert_eq!(report.verified, 3);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replay_reconstructs_engine_state() {
|
||||
with_temp_cas(|| {
|
||||
let mut log = AuditLog::new();
|
||||
let id1: Ulid = "01KQR3000000000000000000A1".parse().unwrap();
|
||||
let id2: Ulid = "01KQR3000000000000000000A2".parse().unwrap();
|
||||
let id3: Ulid = "01KQR3000000000000000000A3".parse().unwrap();
|
||||
log.append(AuditAction::PromoteCrystal {
|
||||
rule_id: id1,
|
||||
crystal: dummy_crystal(EventKind::EnteSpawned, EventKind::EnteDied),
|
||||
});
|
||||
log.append(AuditAction::PromoteCrystal {
|
||||
rule_id: id2,
|
||||
crystal: dummy_crystal(EventKind::BusAnnounce, EventKind::BusInvoke),
|
||||
});
|
||||
log.append(AuditAction::PromoteCrystal {
|
||||
rule_id: id3,
|
||||
crystal: dummy_crystal(EventKind::DeviceAdded, EventKind::DeviceRemoved),
|
||||
});
|
||||
log.append(AuditAction::RemoveRule { rule_id: id2 });
|
||||
log.flush_to_cas().unwrap();
|
||||
let head = log.last_flushed_sha().unwrap();
|
||||
|
||||
let mut engine = RuleEngine::empty();
|
||||
let rep = replay_chain(head, &mut engine);
|
||||
assert!(rep.error.is_none(), "replay error: {:?}", rep.error);
|
||||
assert_eq!(rep.applied, 4);
|
||||
assert_eq!(engine.len(), 2, "id2 should be removed, id1 + id3 remain");
|
||||
// Ulids preservados
|
||||
let ids: Vec<Ulid> = engine.rules().map(|r| r.id).collect();
|
||||
assert!(ids.contains(&id1));
|
||||
assert!(!ids.contains(&id2));
|
||||
assert!(ids.contains(&id3));
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replay_after_eviction_still_works() {
|
||||
with_temp_cas(|| {
|
||||
// Cap pequeño: la mayoría de entries se evictan de memoria pero
|
||||
// siguen en CAS. Replay debe poder reconstruir desde CAS solo.
|
||||
let mut log = AuditLog::with_cap(2);
|
||||
let mut ids = Vec::new();
|
||||
for _ in 0..6 {
|
||||
let id = Ulid::new();
|
||||
ids.push(id);
|
||||
log.append(AuditAction::PromoteCrystal {
|
||||
rule_id: id,
|
||||
crystal: dummy_crystal(EventKind::EnteSpawned, EventKind::EnteDied),
|
||||
});
|
||||
log.flush_to_cas().unwrap();
|
||||
}
|
||||
assert_eq!(log.len(), 2, "cap eviction limita memoria");
|
||||
let head = log.last_flushed_sha().unwrap();
|
||||
|
||||
let mut engine = RuleEngine::empty();
|
||||
let rep = replay_chain(head, &mut engine);
|
||||
assert!(rep.error.is_none());
|
||||
assert_eq!(rep.applied, 6);
|
||||
assert_eq!(engine.len(), 6);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
//! Autopromote loop. Background task que cada N segundos detecta cristales
|
||||
//! con thresholds altos y los promueve sin intervención humana.
|
||||
//!
|
||||
//! Anti-doble-promote: tras promover, registramos en un set la pareja
|
||||
//! (antecedent_kind, consequent_kind). Antes de promover, verificamos que
|
||||
//! no exista ya una regla con el mismo trigger_kind (heurística simple —
|
||||
//! evita ráfagas de duplicados de la misma estadística).
|
||||
|
||||
use crate::audit::AuditAction;
|
||||
use crate::crystallize::{crystal_to_rule, detect_crystals, Crystal, CrystallizationParams};
|
||||
use crate::introspect::{append_rule_jsonl, BrainState};
|
||||
use crate::rules::EventKind;
|
||||
use std::collections::HashSet;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use tokio::sync::Mutex;
|
||||
use tracing::{info, warn};
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct AutopromoteParams {
|
||||
pub interval_secs: u64,
|
||||
pub threshold: CrystallizationParams,
|
||||
}
|
||||
|
||||
impl Default for AutopromoteParams {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
interval_secs: 60,
|
||||
// Más estrictos que el threshold default — evitar ruido.
|
||||
threshold: CrystallizationParams {
|
||||
min_support: 10,
|
||||
min_conditional_prob: 0.85,
|
||||
min_pmi: 2.0,
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Spawn del bucle. El handle Mutex evita que dos pasadas concurrentes
|
||||
/// promuevan el mismo cristal (el lock garantiza serialización por brain).
|
||||
pub fn spawn_autopromote_loop(state: BrainState, params: AutopromoteParams) {
|
||||
let promoted_keys: Arc<Mutex<HashSet<(EventKind, EventKind)>>> =
|
||||
Arc::new(Mutex::new(HashSet::new()));
|
||||
|
||||
tokio::spawn(async move {
|
||||
let mut tick = tokio::time::interval(Duration::from_secs(params.interval_secs));
|
||||
tick.tick().await; // descartar primer tick inmediato
|
||||
info!(?params, "autopromote loop activo");
|
||||
loop {
|
||||
tick.tick().await;
|
||||
run_one_pass(&state, ¶ms, &promoted_keys).await;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async fn run_one_pass(
|
||||
state: &BrainState,
|
||||
params: &AutopromoteParams,
|
||||
promoted_keys: &Arc<Mutex<HashSet<(EventKind, EventKind)>>>,
|
||||
) {
|
||||
let crystals: Vec<Crystal> = {
|
||||
let obs = state.observer.read().await;
|
||||
detect_crystals(&obs, ¶ms.threshold)
|
||||
};
|
||||
if crystals.is_empty() { return; }
|
||||
|
||||
let mut pk = promoted_keys.lock().await;
|
||||
for c in crystals {
|
||||
let key = (c.antecedent.clone(), c.consequent.clone());
|
||||
if pk.contains(&key) {
|
||||
// Ya promovido — el observer puede seguir reportando este
|
||||
// cristal pero no necesitamos otra regla.
|
||||
continue;
|
||||
}
|
||||
promote_one(state, &c).await;
|
||||
pk.insert(key);
|
||||
}
|
||||
}
|
||||
|
||||
async fn promote_one(state: &BrainState, c: &Crystal) {
|
||||
let rule = crystal_to_rule(c);
|
||||
let rule_id = rule.id;
|
||||
if let Some(path) = state.rules_out.as_ref() {
|
||||
if let Err(e) = append_rule_jsonl(path, &rule) {
|
||||
warn!(?e, "autopromote: rules_out append falló");
|
||||
}
|
||||
}
|
||||
state.engine.write().await.insert(rule);
|
||||
|
||||
state.audit.write().await.append(AuditAction::PromoteCrystal {
|
||||
rule_id,
|
||||
crystal: c.clone(),
|
||||
});
|
||||
info!(
|
||||
%rule_id,
|
||||
antecedent = ?c.antecedent,
|
||||
consequent = ?c.consequent,
|
||||
cp = c.conditional_prob,
|
||||
pmi = c.pmi,
|
||||
"autopromote: cristal → regla"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,244 @@
|
||||
//! Cristalización: del flujo observado a reglas explícitas.
|
||||
//!
|
||||
//! Detecta pares (a, b) donde:
|
||||
//! - support(a, b) ≥ min_support (suficientes muestras para no ser ruido)
|
||||
//! - P(b|a) ≥ min_conditional_prob (a predice b con confianza)
|
||||
//! - PMI(a; b) ≥ min_pmi (más correlacionados que random)
|
||||
//!
|
||||
//! Cada cristal se materializa como `Rule` ejecutable (`crystal_to_rule`).
|
||||
//! Para persistencia/transporte, `crystal_to_json_pretty` serializa la Rule
|
||||
//! resultante con serde — sin formatos intermedios.
|
||||
|
||||
use crate::observer::{GapStats, Observer};
|
||||
use crate::rules::{Action, EventKind, EventPattern, LogLevel, Rule, Scope};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::time::Instant;
|
||||
use ulid::Ulid;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct Crystal {
|
||||
pub antecedent: EventKind,
|
||||
pub consequent: EventKind,
|
||||
pub conditional_prob: f64,
|
||||
pub pmi: f64,
|
||||
pub support: u64,
|
||||
/// Estadísticas del gap temporal entre antecedent → consequent.
|
||||
/// None si no hay histograma. Habilita generación de reglas Sequence
|
||||
/// con `within_ms = (mean + 2σ) * 1000`.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub gap_stats: Option<GapStats>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct CrystallizationParams {
|
||||
pub min_support: u64,
|
||||
pub min_conditional_prob: f64,
|
||||
pub min_pmi: f64,
|
||||
}
|
||||
|
||||
impl Default for CrystallizationParams {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
min_support: 5,
|
||||
min_conditional_prob: 0.7,
|
||||
min_pmi: 0.5,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn detect_crystals(obs: &Observer, params: &CrystallizationParams) -> Vec<Crystal> {
|
||||
let mut out = Vec::new();
|
||||
for ((a, b), &count) in obs.cooccurrences() {
|
||||
if count < params.min_support { continue; }
|
||||
let cp = obs.conditional_prob(a, b);
|
||||
if cp < params.min_conditional_prob { continue; }
|
||||
let mi = obs.pmi(a, b);
|
||||
if mi < params.min_pmi { continue; }
|
||||
// Stats del histograma si existen para este par.
|
||||
let gap_stats = obs.gap_histograms()
|
||||
.get(&(a.clone(), b.clone()))
|
||||
.map(|h| h.stats());
|
||||
out.push(Crystal {
|
||||
antecedent: a.clone(),
|
||||
consequent: b.clone(),
|
||||
conditional_prob: cp,
|
||||
pmi: mi,
|
||||
support: count,
|
||||
gap_stats,
|
||||
});
|
||||
}
|
||||
out.sort_by(|x, y| y.conditional_prob.partial_cmp(&x.conditional_prob).unwrap_or(std::cmp::Ordering::Equal));
|
||||
out
|
||||
}
|
||||
|
||||
/// Serializa la `Rule` derivada del cristal como JSON pretty-printed. Ese
|
||||
/// JSON es el formato canónico de persistencia: el loader lo lee como una
|
||||
/// línea de JSONL o como elemento de un array. Los stats del cristal (P, PMI,
|
||||
/// support) viven en el audit log vía `AuditAction::PromoteCrystal`, no se
|
||||
/// duplican aquí.
|
||||
pub fn crystal_to_json_pretty(c: &Crystal) -> String {
|
||||
serde_json::to_string_pretty(&crystal_to_rule(c))
|
||||
.expect("Rule serialize should never fail")
|
||||
}
|
||||
|
||||
/// Convierte un cristal a una `Rule` ejecutable. Si hay gap_stats con
|
||||
/// muestras suficientes (≥ 4), genera una regla `Sequence` con
|
||||
/// `within_ms = (mean + 2σ) * 1000`. 2σ cubre ~95% de la distribución
|
||||
/// asumiendo normalidad — captura el "tiempo típico de respuesta" del
|
||||
/// patrón observado. Si no hay stats, fallback a `Single { antecedent }`.
|
||||
pub fn crystal_to_rule(c: &Crystal) -> Rule {
|
||||
let when = match &c.gap_stats {
|
||||
Some(s) if s.count >= 4 => {
|
||||
// Mínimo 1ms para evitar within_ms=0 cuando varianza colapsa.
|
||||
let bound_secs = (s.mean_secs + 2.0 * s.stddev_secs).max(0.001);
|
||||
EventPattern::Sequence {
|
||||
kinds: vec![c.antecedent.clone(), c.consequent.clone()],
|
||||
within_ms: (bound_secs * 1000.0).ceil() as u64,
|
||||
}
|
||||
}
|
||||
_ => EventPattern::Single { kind: c.antecedent.clone() },
|
||||
};
|
||||
let message = match &c.gap_stats {
|
||||
Some(s) if s.count >= 4 => format!(
|
||||
"crystal seq: {:?} → {:?} (P={:.2}, PMI={:.2}, gap={:.3}±{:.3}s)",
|
||||
c.antecedent, c.consequent, c.conditional_prob, c.pmi,
|
||||
s.mean_secs, s.stddev_secs,
|
||||
),
|
||||
_ => format!(
|
||||
"crystal: {:?} → {:?} (P={:.2}, PMI={:.2}, n={})",
|
||||
c.antecedent, c.consequent, c.conditional_prob, c.pmi, c.support
|
||||
),
|
||||
};
|
||||
Rule {
|
||||
id: Ulid::new(),
|
||||
priority: 5,
|
||||
when,
|
||||
scope: Scope::default(),
|
||||
then: vec![Action::Log { level: LogLevel::Info, message }],
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// ============================================================================
|
||||
// Patrones extendidos: Burst (alta frecuencia) y Silence (ausencia prolongada).
|
||||
// Estos cristales son sobre un único kind, no pares — capturan dinámicas
|
||||
// temporales de eventos individuales.
|
||||
// ============================================================================
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub enum PatternCrystal {
|
||||
/// Mismo evento aparece con frecuencia alta. `frequency_per_sec` se
|
||||
/// estima sobre el window de observación.
|
||||
Burst {
|
||||
kind: EventKind,
|
||||
count: u64,
|
||||
frequency_per_sec: f64,
|
||||
},
|
||||
/// Evento que dejó de aparecer. `since_secs` es el tiempo desde la
|
||||
/// última observación.
|
||||
Silence {
|
||||
kind: EventKind,
|
||||
last_count: u64,
|
||||
since_secs: f64,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct PatternParams {
|
||||
/// Mínimo de ocurrencias para considerar Burst.
|
||||
pub burst_min_count: u64,
|
||||
/// Frecuencia mínima (eventos por segundo) para considerar Burst.
|
||||
pub burst_min_freq_hz: f64,
|
||||
/// Tiempo desde última ocurrencia para considerar Silence.
|
||||
pub silence_min_secs: f64,
|
||||
/// Mínimo total previo para considerar Silence (eventos < N son ruido).
|
||||
pub silence_min_prior_count: u64,
|
||||
}
|
||||
|
||||
impl Default for PatternParams {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
burst_min_count: 10,
|
||||
burst_min_freq_hz: 5.0,
|
||||
silence_min_secs: 30.0,
|
||||
silence_min_prior_count: 3,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Detecta Bursts y Silences sobre la distribución marginal del observer.
|
||||
/// La frecuencia de un Burst se aproxima asumiendo que la observación cubre
|
||||
/// el rango entre `last_seen` y `Instant::now()` para ese kind.
|
||||
pub fn detect_pattern_crystals(obs: &Observer, params: &PatternParams) -> Vec<PatternCrystal> {
|
||||
let mut out = Vec::new();
|
||||
let now = Instant::now();
|
||||
for (kind, &count) in obs.marginals() {
|
||||
let last_seen = obs.last_seen_marginal(kind);
|
||||
// ---- Burst ----
|
||||
if count >= params.burst_min_count {
|
||||
// Aproximación: si vimos `count` eventos hasta `last_seen`, y el
|
||||
// primer evento sucedió en algún momento del window, la freq es
|
||||
// count / window_age. Sin tiempo del primer evento, usamos
|
||||
// last_seen → now como denominador (subestima freq) o asumimos
|
||||
// ventana fija de 60s. Usamos la última como aproximación.
|
||||
let elapsed = last_seen
|
||||
.map(|t| now.saturating_duration_since(t).as_secs_f64().max(0.001))
|
||||
.unwrap_or(60.0);
|
||||
// Estimación conservadora: count / max(window_age, 1s).
|
||||
// Si tenemos histograma, podríamos refinar — TODO.
|
||||
let freq = count as f64 / elapsed.max(1.0);
|
||||
if freq >= params.burst_min_freq_hz {
|
||||
out.push(PatternCrystal::Burst {
|
||||
kind: kind.clone(),
|
||||
count,
|
||||
frequency_per_sec: freq,
|
||||
});
|
||||
}
|
||||
}
|
||||
// ---- Silence ----
|
||||
if count >= params.silence_min_prior_count {
|
||||
if let Some(t) = last_seen {
|
||||
let since = now.saturating_duration_since(t).as_secs_f64();
|
||||
if since >= params.silence_min_secs {
|
||||
out.push(PatternCrystal::Silence {
|
||||
kind: kind.clone(),
|
||||
last_count: count,
|
||||
since_secs: since,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::rules::EventKind::*;
|
||||
|
||||
#[test]
|
||||
fn detects_perfect_correlation() {
|
||||
let mut obs = Observer::new(100);
|
||||
for _ in 0..10 {
|
||||
obs.record(EnteSpawned);
|
||||
obs.record(EnteDied);
|
||||
}
|
||||
let crystals = detect_crystals(&obs, &CrystallizationParams {
|
||||
min_support: 3,
|
||||
min_conditional_prob: 0.5,
|
||||
min_pmi: 0.0,
|
||||
});
|
||||
assert!(crystals.iter().any(|c| matches!(c.antecedent, EnteSpawned)
|
||||
&& matches!(c.consequent, EnteDied)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_below_threshold() {
|
||||
let mut obs = Observer::new(100);
|
||||
// Sin co-ocurrencia significativa.
|
||||
for _ in 0..3 { obs.record(EnteSpawned); }
|
||||
let crystals = detect_crystals(&obs, &CrystallizationParams::default());
|
||||
assert!(crystals.is_empty(), "no debería haber cristales: {:?}", crystals);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
//! Despacho asíncrono de Actions. El motor entrega `Vec<Arc<Rule>>` matched;
|
||||
//! este módulo las traduce a efectos del fractal vía un `ActionSink` trait.
|
||||
//!
|
||||
//! Esto invierte la dependencia: ente-brain no conoce a ente-zero. El init
|
||||
//! implementa `ActionSink` y wirea spawn/invoke/log a sus propias estructuras.
|
||||
|
||||
use crate::rules::{Action, LogLevel, Rule};
|
||||
use std::sync::Arc;
|
||||
use tracing::{debug, error, info, trace, warn};
|
||||
|
||||
/// Backend de ejecución de Actions. ente-zero implementa esto delegando a
|
||||
/// graph_tx (Spawn → SpawnRequest, Invoke → bus call, etc.).
|
||||
pub trait ActionSink: Send + Sync {
|
||||
/// Spawn una Card decodificada. Implementación: GraphEvent::SpawnRequest.
|
||||
fn spawn(&self, card_blob: &str);
|
||||
/// Invoke por bus. blob crudo; el sink lo enruta vía bus_mediator.
|
||||
fn invoke(&self, target_cap: ente_card::Capability, blob: Vec<u8>);
|
||||
/// Notifica a un Ente específico (target_id). Implementación: forward por bus.
|
||||
fn notify(&self, target_id: ulid::Ulid, message: &str);
|
||||
/// Inhibe un comportamiento (placeholder; semántica depende del sink).
|
||||
fn inhibit(&self, reason: &str);
|
||||
}
|
||||
|
||||
/// Sink por defecto que sólo logea. Útil para tests y dev sin runtime.
|
||||
pub struct NullSink;
|
||||
|
||||
impl ActionSink for NullSink {
|
||||
fn spawn(&self, card_blob: &str) {
|
||||
info!(blob_len = card_blob.len(), "NullSink::spawn (no-op)");
|
||||
}
|
||||
fn invoke(&self, target_cap: ente_card::Capability, blob: Vec<u8>) {
|
||||
info!(?target_cap, blob_len = blob.len(), "NullSink::invoke (no-op)");
|
||||
}
|
||||
fn notify(&self, target_id: ulid::Ulid, message: &str) {
|
||||
info!(%target_id, %message, "NullSink::notify (no-op)");
|
||||
}
|
||||
fn inhibit(&self, reason: &str) {
|
||||
info!(%reason, "NullSink::inhibit (no-op)");
|
||||
}
|
||||
}
|
||||
|
||||
/// Ejecuta las reglas matched. Cada Rule puede tener N Actions; ejecutamos
|
||||
/// todas. Las acciones de Log se evalúan inline (tracing es async-safe).
|
||||
/// Las acciones de Spawn/Invoke/Notify se delegan al sink — el sink decide
|
||||
/// si procesarlas sincrónica o asincrónicamente.
|
||||
pub async fn dispatch_actions(rules: &[Arc<Rule>], sink: &dyn ActionSink) {
|
||||
for rule in rules {
|
||||
trace!(id = %rule.id, priority = rule.priority, n = rule.then.len(), "dispatching rule");
|
||||
for action in &rule.then {
|
||||
execute_action(action, sink, rule.id).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn execute_action(action: &Action, sink: &dyn ActionSink, rule_id: ulid::Ulid) {
|
||||
match action {
|
||||
Action::Log { level, message } => emit_log(level, message, rule_id),
|
||||
Action::Notify { target_id, message } => sink.notify(*target_id, message),
|
||||
Action::Spawn { card_blob } => sink.spawn(card_blob),
|
||||
Action::Invoke { target_cap, blob } => sink.invoke(target_cap.clone(), blob.clone()),
|
||||
Action::Inhibit { reason } => sink.inhibit(reason),
|
||||
}
|
||||
}
|
||||
|
||||
fn emit_log(level: &LogLevel, message: &str, rule_id: ulid::Ulid) {
|
||||
match level {
|
||||
LogLevel::Trace => trace!(rule = %rule_id, "{}", message),
|
||||
LogLevel::Debug => debug!(rule = %rule_id, "{}", message),
|
||||
LogLevel::Info => info! (rule = %rule_id, "{}", message),
|
||||
LogLevel::Warn => warn! (rule = %rule_id, "{}", message),
|
||||
LogLevel::Error => error!(rule = %rule_id, "{}", message),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,399 @@
|
||||
//! Motor de inferencia. HashMap<EventKindDiscriminant, Vec<Arc<Rule>>> para
|
||||
//! lookup O(1) por tipo de evento, luego filter lineal por scope + filtros
|
||||
//! del payload (BusInvokeOf, Custom).
|
||||
//!
|
||||
//! Inmutabilidad fractal: `Arc<Rule>` es el unit de compartición. Clonar una
|
||||
//! regla del motor para entregarla al dispatcher es un refcount bump, no copia.
|
||||
|
||||
use crate::observer::TimedEvent;
|
||||
use crate::rules::{EventKind, EventPattern, Rule, Scope};
|
||||
use ente_card::Capability;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use ulid::Ulid;
|
||||
|
||||
/// Discriminante barato de `EventKind` para indexar el HashMap. Sin payload —
|
||||
/// el match de payload se hace en una segunda pasada lineal en O(k) donde k
|
||||
/// es el número de reglas para ese tag.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub enum EventKindDiscriminant {
|
||||
EnteSpawned,
|
||||
EnteDied,
|
||||
BusAnnounce,
|
||||
BusInvoke,
|
||||
BusInvokeOf,
|
||||
DeviceAdded,
|
||||
DeviceRemoved,
|
||||
Custom,
|
||||
}
|
||||
|
||||
impl From<&EventKind> for EventKindDiscriminant {
|
||||
fn from(k: &EventKind) -> Self {
|
||||
match k {
|
||||
EventKind::EnteSpawned => Self::EnteSpawned,
|
||||
EventKind::EnteDied => Self::EnteDied,
|
||||
EventKind::BusAnnounce => Self::BusAnnounce,
|
||||
EventKind::BusInvoke => Self::BusInvoke,
|
||||
EventKind::BusInvokeOf(_) => Self::BusInvokeOf,
|
||||
EventKind::DeviceAdded => Self::DeviceAdded,
|
||||
EventKind::DeviceRemoved => Self::DeviceRemoved,
|
||||
EventKind::Custom(_) => Self::Custom,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Snapshot del Ente que disparó el evento. Necesario para evaluar `Scope`.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct SubjectInfo {
|
||||
pub id: Option<Ulid>,
|
||||
pub label: Option<String>,
|
||||
pub capabilities: Vec<Capability>,
|
||||
}
|
||||
|
||||
pub struct RuleEngine {
|
||||
rules: Vec<Arc<Rule>>,
|
||||
/// Reglas atómicas (Single, Sequence) indexadas por discriminante del
|
||||
/// kind que las dispara. Lookup O(1).
|
||||
by_kind: HashMap<EventKindDiscriminant, Vec<Arc<Rule>>>,
|
||||
/// Reglas compuestas (Either, All): se evalúan contra cada evento.
|
||||
/// Para fractales con N pequeño no afecta perf; con N grande, optimizar
|
||||
/// emitiendo a múltiples buckets en insert (fan-out).
|
||||
compound: Vec<Arc<Rule>>,
|
||||
}
|
||||
|
||||
impl Default for RuleEngine {
|
||||
fn default() -> Self { Self::empty() }
|
||||
}
|
||||
|
||||
impl RuleEngine {
|
||||
pub fn empty() -> Self {
|
||||
Self { rules: Vec::new(), by_kind: HashMap::new(), compound: Vec::new() }
|
||||
}
|
||||
|
||||
/// Carga reglas desde JSON (lista de Rule).
|
||||
pub fn load_json(json: &str) -> anyhow::Result<Self> {
|
||||
let rules: Vec<Rule> = serde_json::from_str(json)?;
|
||||
let mut engine = Self::empty();
|
||||
for r in rules {
|
||||
r.validate().map_err(|e| anyhow::anyhow!("regla inválida: {e}"))?;
|
||||
engine.insert(r);
|
||||
}
|
||||
Ok(engine)
|
||||
}
|
||||
|
||||
pub fn insert(&mut self, rule: Rule) {
|
||||
let arc = Arc::new(rule);
|
||||
// Atómicas → bucket por discriminante. Compuestas → bucket fallback.
|
||||
if let Some(trigger) = arc.when.trigger_kind() {
|
||||
let disc = EventKindDiscriminant::from(trigger);
|
||||
self.by_kind.entry(disc).or_default().push(arc.clone());
|
||||
} else {
|
||||
self.compound.push(arc.clone());
|
||||
}
|
||||
self.rules.push(arc);
|
||||
}
|
||||
|
||||
pub fn remove(&mut self, id: Ulid) -> bool {
|
||||
let before = self.rules.len();
|
||||
self.rules.retain(|r| r.id != id);
|
||||
for v in self.by_kind.values_mut() {
|
||||
v.retain(|r| r.id != id);
|
||||
}
|
||||
self.compound.retain(|r| r.id != id);
|
||||
before != self.rules.len()
|
||||
}
|
||||
|
||||
pub fn rules(&self) -> impl Iterator<Item = &Arc<Rule>> { self.rules.iter() }
|
||||
|
||||
pub fn len(&self) -> usize { self.rules.len() }
|
||||
pub fn is_empty(&self) -> bool { self.rules.is_empty() }
|
||||
|
||||
/// Despacho determinista. Devuelve reglas que matchean, ordenadas por
|
||||
/// prioridad descendente. Cada Arc<Rule> se clona (refcount) — sin copiar
|
||||
/// los datos.
|
||||
///
|
||||
/// `history` es el slice de eventos recientes (en orden cronológico,
|
||||
/// más reciente al final) usado para evaluar Sequence patterns.
|
||||
/// Para reglas Single, history se ignora.
|
||||
///
|
||||
/// Si el evento es `BusInvokeOf(_)`, también consultamos el bucket
|
||||
/// `BusInvoke` (regla genérica que ignora la cap).
|
||||
pub fn dispatch(
|
||||
&self,
|
||||
event: &EventKind,
|
||||
subject: &SubjectInfo,
|
||||
history: &[TimedEvent],
|
||||
) -> Vec<Arc<Rule>> {
|
||||
let primary = EventKindDiscriminant::from(event);
|
||||
let mut buckets: Vec<&Vec<Arc<Rule>>> = Vec::with_capacity(2);
|
||||
if let Some(v) = self.by_kind.get(&primary) {
|
||||
buckets.push(v);
|
||||
}
|
||||
if matches!(event, EventKind::BusInvokeOf(_)) {
|
||||
if let Some(v) = self.by_kind.get(&EventKindDiscriminant::BusInvoke) {
|
||||
buckets.push(v);
|
||||
}
|
||||
}
|
||||
let mut hits: Vec<Arc<Rule>> = buckets.into_iter()
|
||||
.flat_map(|v| v.iter())
|
||||
.filter(|r| matches_pattern(&r.when, event, history))
|
||||
.filter(|r| matches_scope(&r.scope, subject))
|
||||
.cloned()
|
||||
.collect();
|
||||
// Fallback: reglas compuestas (Either/All) se evalúan siempre.
|
||||
for r in &self.compound {
|
||||
if matches_pattern(&r.when, event, history) && matches_scope(&r.scope, subject) {
|
||||
hits.push(r.clone());
|
||||
}
|
||||
}
|
||||
hits.sort_by(|a, b| b.priority.cmp(&a.priority));
|
||||
hits
|
||||
}
|
||||
}
|
||||
|
||||
/// Match recursivo del pattern. Atomic patterns evalúan contra el evento
|
||||
/// actual + history. Compuestos (Either/All) recursan sobre sus children.
|
||||
fn matches_pattern(pattern: &EventPattern, event: &EventKind, history: &[TimedEvent]) -> bool {
|
||||
match pattern {
|
||||
EventPattern::Single { kind } => matches_event_payload(kind, event),
|
||||
EventPattern::Sequence { kinds, within_ms } => {
|
||||
if kinds.is_empty() { return false; }
|
||||
let last_kind = kinds.last().unwrap();
|
||||
if !matches_event_payload(last_kind, event) { return false; }
|
||||
if history.len() < kinds.len() { return false; }
|
||||
let tail = &history[history.len() - kinds.len()..];
|
||||
for (t, k) in tail.iter().zip(kinds) {
|
||||
if !matches_event_payload(k, &t.kind) { return false; }
|
||||
}
|
||||
if *within_ms > 0 {
|
||||
let span = tail.last().unwrap().at.duration_since(tail.first().unwrap().at);
|
||||
if span > Duration::from_millis(*within_ms) { return false; }
|
||||
}
|
||||
true
|
||||
}
|
||||
EventPattern::Either { patterns } => {
|
||||
patterns.iter().any(|p| matches_pattern(p, event, history))
|
||||
}
|
||||
EventPattern::All { patterns } => {
|
||||
patterns.iter().all(|p| matches_pattern(p, event, history))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn matches_event_payload(rule_kind: &EventKind, evt: &EventKind) -> bool {
|
||||
use EventKind::*;
|
||||
match (rule_kind, evt) {
|
||||
(EnteSpawned, EnteSpawned) => true,
|
||||
(EnteDied, EnteDied) => true,
|
||||
(BusAnnounce, BusAnnounce) => true,
|
||||
(BusInvoke, BusInvoke) | (BusInvoke, BusInvokeOf(_)) => true,
|
||||
(BusInvokeOf(want), BusInvokeOf(got)) => want == got,
|
||||
(DeviceAdded, DeviceAdded) => true,
|
||||
(DeviceRemoved, DeviceRemoved) => true,
|
||||
(Custom(want), Custom(got)) => want == got,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn matches_scope(scope: &Scope, subj: &SubjectInfo) -> bool {
|
||||
if scope.is_wildcard() { return true; }
|
||||
if let Some(id) = scope.subject_id {
|
||||
if subj.id != Some(id) { return false; }
|
||||
}
|
||||
if let Some(lbl) = &scope.subject_label {
|
||||
if subj.label.as_ref() != Some(lbl) { return false; }
|
||||
}
|
||||
if let Some(cap) = &scope.subject_has_cap {
|
||||
if !subj.capabilities.contains(cap) { return false; }
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::rules::{Action, EventPattern, LogLevel};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
fn rule_single(id_str: &str, kind: EventKind, prio: u8) -> Rule {
|
||||
Rule {
|
||||
id: id_str.parse().unwrap(),
|
||||
priority: prio,
|
||||
when: EventPattern::Single { kind },
|
||||
then: vec![Action::Log {
|
||||
level: LogLevel::Info,
|
||||
message: id_str.into(),
|
||||
}],
|
||||
scope: Scope::default(),
|
||||
}
|
||||
}
|
||||
|
||||
fn empty_history() -> Vec<TimedEvent> { Vec::new() }
|
||||
|
||||
#[test]
|
||||
fn dispatch_picks_only_matching_kind() {
|
||||
let mut e = RuleEngine::empty();
|
||||
e.insert(rule_single("01KQQ100000000000000000001", EventKind::EnteSpawned, 5));
|
||||
e.insert(rule_single("01KQQ100000000000000000002", EventKind::EnteDied, 5));
|
||||
let hits = e.dispatch(&EventKind::EnteSpawned, &SubjectInfo::default(), &empty_history());
|
||||
assert_eq!(hits.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn priority_orders_descending() {
|
||||
let mut e = RuleEngine::empty();
|
||||
e.insert(rule_single("01KQQ100000000000000000003", EventKind::EnteSpawned, 1));
|
||||
e.insert(rule_single("01KQQ100000000000000000004", EventKind::EnteSpawned, 9));
|
||||
let hits = e.dispatch(&EventKind::EnteSpawned, &SubjectInfo::default(), &empty_history());
|
||||
assert_eq!(hits[0].priority, 9);
|
||||
assert_eq!(hits[1].priority, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scope_filters_by_label() {
|
||||
let mut e = RuleEngine::empty();
|
||||
let mut r = rule_single("01KQQ100000000000000000005", EventKind::EnteSpawned, 5);
|
||||
r.scope = Scope { subject_label: Some("foo".into()), ..Default::default() };
|
||||
e.insert(r);
|
||||
let foo = SubjectInfo { label: Some("foo".into()), ..Default::default() };
|
||||
let bar = SubjectInfo { label: Some("bar".into()), ..Default::default() };
|
||||
assert_eq!(e.dispatch(&EventKind::EnteSpawned, &foo, &empty_history()).len(), 1);
|
||||
assert_eq!(e.dispatch(&EventKind::EnteSpawned, &bar, &empty_history()).len(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bus_invoke_generic_matches_specific() {
|
||||
let mut e = RuleEngine::empty();
|
||||
e.insert(rule_single("01KQQ100000000000000000006", EventKind::BusInvoke, 5));
|
||||
let hits = e.dispatch(
|
||||
&EventKind::BusInvokeOf(Capability::LegacyLogind),
|
||||
&SubjectInfo::default(),
|
||||
&empty_history(),
|
||||
);
|
||||
assert_eq!(hits.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sequence_pattern_matches_with_history() {
|
||||
let mut e = RuleEngine::empty();
|
||||
let r = Rule {
|
||||
id: "01KQQ100000000000000000007".parse().unwrap(),
|
||||
priority: 5,
|
||||
when: EventPattern::Sequence {
|
||||
kinds: vec![EventKind::EnteSpawned, EventKind::BusAnnounce],
|
||||
within_ms: 1000,
|
||||
},
|
||||
then: vec![Action::Log { level: LogLevel::Info, message: "seq".into() }],
|
||||
scope: Scope::default(),
|
||||
};
|
||||
e.insert(r);
|
||||
|
||||
let now = Instant::now();
|
||||
let history = vec![
|
||||
TimedEvent { kind: EventKind::EnteSpawned, at: now },
|
||||
TimedEvent { kind: EventKind::BusAnnounce, at: now + Duration::from_millis(50) },
|
||||
];
|
||||
let hits = e.dispatch(&EventKind::BusAnnounce, &SubjectInfo::default(), &history);
|
||||
assert_eq!(hits.len(), 1, "esperaba match secuencia, got {}", hits.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sequence_rejects_outside_time_window() {
|
||||
let mut e = RuleEngine::empty();
|
||||
let r = Rule {
|
||||
id: "01KQQ100000000000000000008".parse().unwrap(),
|
||||
priority: 5,
|
||||
when: EventPattern::Sequence {
|
||||
kinds: vec![EventKind::EnteSpawned, EventKind::BusAnnounce],
|
||||
within_ms: 100,
|
||||
},
|
||||
then: vec![Action::Log { level: LogLevel::Info, message: "seq".into() }],
|
||||
scope: Scope::default(),
|
||||
};
|
||||
e.insert(r);
|
||||
let now = Instant::now();
|
||||
let history = vec![
|
||||
TimedEvent { kind: EventKind::EnteSpawned, at: now },
|
||||
TimedEvent { kind: EventKind::BusAnnounce, at: now + Duration::from_millis(500) },
|
||||
];
|
||||
let hits = e.dispatch(&EventKind::BusAnnounce, &SubjectInfo::default(), &history);
|
||||
assert!(hits.is_empty(), "no debería matchear fuera de la ventana");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn either_matches_any_branch() {
|
||||
let mut e = RuleEngine::empty();
|
||||
let r = Rule {
|
||||
id: "01KQQ100000000000000000010".parse().unwrap(),
|
||||
priority: 5,
|
||||
when: EventPattern::Either { patterns: vec![
|
||||
EventPattern::Single { kind: EventKind::EnteSpawned },
|
||||
EventPattern::Single { kind: EventKind::EnteDied },
|
||||
]},
|
||||
then: vec![Action::Log { level: LogLevel::Info, message: "either".into() }],
|
||||
scope: Scope::default(),
|
||||
};
|
||||
e.insert(r);
|
||||
assert_eq!(e.dispatch(&EventKind::EnteSpawned, &SubjectInfo::default(), &[]).len(), 1);
|
||||
assert_eq!(e.dispatch(&EventKind::EnteDied, &SubjectInfo::default(), &[]).len(), 1);
|
||||
assert_eq!(e.dispatch(&EventKind::BusAnnounce, &SubjectInfo::default(), &[]).len(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn all_requires_every_branch() {
|
||||
let mut e = RuleEngine::empty();
|
||||
// All: matchear sólo si el evento actual es BusAnnounce Y la
|
||||
// secuencia EnteSpawned→BusAnnounce ocurrió en history.
|
||||
let r = Rule {
|
||||
id: "01KQQ100000000000000000011".parse().unwrap(),
|
||||
priority: 5,
|
||||
when: EventPattern::All { patterns: vec![
|
||||
EventPattern::Single { kind: EventKind::BusAnnounce },
|
||||
EventPattern::Sequence {
|
||||
kinds: vec![EventKind::EnteSpawned, EventKind::BusAnnounce],
|
||||
within_ms: 0,
|
||||
},
|
||||
]},
|
||||
then: vec![Action::Log { level: LogLevel::Info, message: "all".into() }],
|
||||
scope: Scope::default(),
|
||||
};
|
||||
e.insert(r);
|
||||
|
||||
let now = Instant::now();
|
||||
let history = vec![
|
||||
TimedEvent { kind: EventKind::EnteSpawned, at: now },
|
||||
TimedEvent { kind: EventKind::BusAnnounce, at: now + Duration::from_millis(10) },
|
||||
];
|
||||
// Single y Sequence ambos matchean → All matches.
|
||||
assert_eq!(e.dispatch(&EventKind::BusAnnounce, &SubjectInfo::default(), &history).len(), 1);
|
||||
// Sólo Single matchea (history vacío) → All no matches.
|
||||
assert!(e.dispatch(&EventKind::BusAnnounce, &SubjectInfo::default(), &[]).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sequence_requires_correct_order() {
|
||||
let mut e = RuleEngine::empty();
|
||||
let r = Rule {
|
||||
id: "01KQQ100000000000000000009".parse().unwrap(),
|
||||
priority: 5,
|
||||
when: EventPattern::Sequence {
|
||||
kinds: vec![EventKind::EnteSpawned, EventKind::BusAnnounce],
|
||||
within_ms: 0,
|
||||
},
|
||||
then: vec![Action::Log { level: LogLevel::Info, message: "seq".into() }],
|
||||
scope: Scope::default(),
|
||||
};
|
||||
e.insert(r);
|
||||
let now = Instant::now();
|
||||
// Orden invertido en el history.
|
||||
let history = vec![
|
||||
TimedEvent { kind: EventKind::BusAnnounce, at: now },
|
||||
TimedEvent { kind: EventKind::EnteSpawned, at: now + Duration::from_millis(10) },
|
||||
];
|
||||
// El evento actual es EnteSpawned, pero el último de la secuencia
|
||||
// requerida es BusAnnounce — no debería matchear.
|
||||
let hits = e.dispatch(&EventKind::EnteSpawned, &SubjectInfo::default(), &history);
|
||||
assert!(hits.is_empty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,476 @@
|
||||
//! Introspect API. Unix Domain Socket + framing length-prefijo + bincode.
|
||||
//!
|
||||
//! Una herramienta externa (ej. `brainctl`) puede consultar el estado del
|
||||
//! cerebro sin tocar el bus interno del fractal. Esto separa observación de
|
||||
//! ejecución — la introspección es read-only por diseño.
|
||||
|
||||
use crate::crystallize::{detect_crystals, Crystal, CrystallizationParams};
|
||||
use crate::engine::RuleEngine;
|
||||
use crate::observer::Observer;
|
||||
use crate::rules::Rule;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::io::Write;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::net::{UnixListener, UnixStream};
|
||||
use tokio::sync::RwLock;
|
||||
use tracing::{debug, info, trace, warn};
|
||||
use ulid::Ulid;
|
||||
|
||||
const MAX_FRAME: usize = 4 * 1024 * 1024; // 4 MiB — correlation matrices crecen
|
||||
|
||||
/// Estado compartido entre el bucle del Init y el servidor de introspección.
|
||||
/// `Arc<RwLock<...>>` permite muchos lectores concurrentes (introspect) y
|
||||
/// un escritor (el dispatcher de eventos en el bucle primordial).
|
||||
#[derive(Clone)]
|
||||
pub struct BrainState {
|
||||
pub engine: Arc<RwLock<RuleEngine>>,
|
||||
pub observer: Arc<RwLock<Observer>>,
|
||||
pub params: CrystallizationParams,
|
||||
/// Path opcional donde apendear reglas promovidas en JSONL. Si Some,
|
||||
/// cada PromoteCrystal añade una línea (append-only) con la Rule serializada.
|
||||
pub rules_out: Option<Arc<PathBuf>>,
|
||||
/// Audit log en memoria. Cada promote/remove deja huella aquí.
|
||||
pub audit: Arc<RwLock<crate::audit::AuditLog>>,
|
||||
}
|
||||
|
||||
impl BrainState {
|
||||
pub fn new(window_size: usize) -> Self {
|
||||
Self::with_params(window_size, CrystallizationParams::default())
|
||||
}
|
||||
|
||||
pub fn with_params(window_size: usize, params: CrystallizationParams) -> Self {
|
||||
Self {
|
||||
engine: Arc::new(RwLock::new(RuleEngine::empty())),
|
||||
observer: Arc::new(RwLock::new(Observer::new(window_size))),
|
||||
params,
|
||||
rules_out: None,
|
||||
audit: Arc::new(RwLock::new(crate::audit::AuditLog::new())),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_rules_out(mut self, path: PathBuf) -> Self {
|
||||
self.rules_out = Some(Arc::new(path));
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// Append-only writer de una `Rule` serializada a `rules_out` en formato
|
||||
/// JSONL: una línea = un Rule JSON. Idempotente respecto a re-flushes
|
||||
/// porque el caller se encarga de no apendar la misma rule dos veces.
|
||||
/// El loader (`loader::extract_rules_from_json`) acepta tanto JSONL como
|
||||
/// arrays — el archivo es legible en ambos modos.
|
||||
pub fn append_rule_jsonl(path: &Path, rule: &Rule) -> std::io::Result<()> {
|
||||
if let Some(parent) = path.parent() {
|
||||
std::fs::create_dir_all(parent)?;
|
||||
}
|
||||
let mut file = std::fs::OpenOptions::new()
|
||||
.create(true)
|
||||
.append(true)
|
||||
.open(path)?;
|
||||
let line = serde_json::to_string(rule)
|
||||
.map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
|
||||
writeln!(file, "{line}")?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub enum IntrospectRequest {
|
||||
/// Lista resumida de reglas vivas.
|
||||
ListRules,
|
||||
/// Detalle de una regla concreta.
|
||||
GetRule(Ulid),
|
||||
/// Snapshot de la entropía y conteos básicos.
|
||||
EntropySnapshot,
|
||||
/// Top N pares (a, b) por co-ocurrencia.
|
||||
TopCorrelations { n: usize },
|
||||
/// Cristales detectados con los parámetros del BrainState.
|
||||
Crystals,
|
||||
/// Serializa la Rule derivada de un cristal específico como JSON
|
||||
/// (índice tras Crystals).
|
||||
CrystalJson { index: usize },
|
||||
/// Promueve el cristal #index a regla viva en el motor. Devuelve el
|
||||
/// rule_id asignado y el JSON de la Rule para auditoría/persistencia.
|
||||
PromoteCrystal { index: usize },
|
||||
/// Elimina una regla viva por id. Útil para revertir un promote.
|
||||
RemoveRule { id: Ulid },
|
||||
/// Lista las últimas N entradas del audit log. limit=0 = todas.
|
||||
ListAudit { limit: usize },
|
||||
/// Persiste todas las entries pendientes al CAS y actualiza el head
|
||||
/// pointer si el log lo tiene configurado.
|
||||
FlushAudit,
|
||||
/// Recarga reglas desde el archivo configurado por --rules-out (o el
|
||||
/// path provisto). Vacía el engine antes de cargar.
|
||||
ReloadRules { path: Option<String> },
|
||||
/// Verifica la cadena audit recorriendo prev_sha hasta el genesis,
|
||||
/// validando integridad de cada entry contra el CAS.
|
||||
VerifyAudit,
|
||||
/// Reconstruye el engine desde la cadena audit. Vacía engine y aplica
|
||||
/// PromoteCrystal/RemoveRule en orden cronológico.
|
||||
ReplayAudit,
|
||||
/// Mantiene la conexión abierta y empuja cada `AuditEntry` nuevo en
|
||||
/// frames `IntrospectResponse::AuditStreamFrame` hasta que el cliente
|
||||
/// cierra. Tras esta request no se aceptan más requests en la misma conn.
|
||||
StreamAudit,
|
||||
/// Garbage-collect el CAS. Considera reachable: todo lo alcanzable desde
|
||||
/// el head del audit log. Cualquier blob extra (Wasm modules referenciados
|
||||
/// por Cards) debe haberse pasado en `extra_roots` por el caller.
|
||||
GcCas { extra_roots: Vec<[u8; 32]> },
|
||||
/// Detecta cristales de patrones temporales (Burst, Silence).
|
||||
PatternCrystals,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub enum IntrospectResponse {
|
||||
Rules(Vec<RuleSummary>),
|
||||
Rule(Option<Rule>),
|
||||
Entropy { value_bits: f64, sample_size: u64, distinct_kinds: usize, window_full: bool },
|
||||
Correlations(Vec<CorrelationEntry>),
|
||||
Crystals(Vec<Crystal>),
|
||||
Json(String),
|
||||
/// Resultado de PromoteCrystal: id de la regla creada + JSON de la Rule
|
||||
/// para que el operador lo persista en disco si quiere.
|
||||
Promoted { rule_id: Ulid, rule_json: String },
|
||||
/// Resultado de RemoveRule: true si existía, false si ya no.
|
||||
Removed(bool),
|
||||
/// Entradas del audit log (más recientes al final).
|
||||
AuditEntries(Vec<crate::audit::AuditEntry>),
|
||||
/// Resultado de FlushAudit: cuántas entries se escribieron y SHA del head.
|
||||
Flushed { written: usize, head_sha: Option<[u8; 32]>, total_flushed: u64 },
|
||||
/// Resultado de ReloadRules: número total de reglas tras el reload.
|
||||
Reloaded { count: usize },
|
||||
/// Resultado de VerifyAudit.
|
||||
AuditVerified(crate::audit::VerificationReport),
|
||||
/// Resultado de ReplayAudit.
|
||||
Replayed(crate::audit::ReplayReport),
|
||||
/// Frame de streaming. El cliente lee estos en bucle hasta EOF.
|
||||
AuditStreamFrame(crate::audit::AuditEntry),
|
||||
/// Resultado de GcCas: cuántos blobs eliminados y bytes liberados.
|
||||
GcResult { deleted: usize, freed_bytes: u64 },
|
||||
/// Cristales de Burst/Silence detectados.
|
||||
Patterns(Vec<crate::crystallize::PatternCrystal>),
|
||||
Error(String),
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct RuleSummary {
|
||||
pub id: Ulid,
|
||||
pub priority: u8,
|
||||
pub event_kind_tag: String,
|
||||
pub action_count: usize,
|
||||
pub scope_wildcard: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct CorrelationEntry {
|
||||
pub a: String,
|
||||
pub b: String,
|
||||
pub joint_count: u64,
|
||||
pub conditional_prob: f64,
|
||||
pub pmi_bits: f64,
|
||||
}
|
||||
|
||||
pub struct IntrospectServer {
|
||||
state: BrainState,
|
||||
}
|
||||
|
||||
impl IntrospectServer {
|
||||
pub fn new(state: BrainState) -> Self { Self { state } }
|
||||
|
||||
/// Spawn del listener. Devuelve cuando bind() falla; en caso contrario
|
||||
/// corre indefinidamente.
|
||||
pub async fn serve(self, path: &Path) -> anyhow::Result<()> {
|
||||
let _ = std::fs::remove_file(path);
|
||||
if let Some(parent) = path.parent() {
|
||||
let _ = std::fs::create_dir_all(parent);
|
||||
}
|
||||
let listener = UnixListener::bind(path)?;
|
||||
info!(path = %path.display(), "brain introspect escuchando");
|
||||
let arc_self = Arc::new(self);
|
||||
loop {
|
||||
match listener.accept().await {
|
||||
Ok((stream, _)) => {
|
||||
trace!("introspect conn aceptada");
|
||||
let me = arc_self.clone();
|
||||
tokio::spawn(async move {
|
||||
if let Err(e) = me.handle(stream).await {
|
||||
warn!(?e, "introspect conn ended");
|
||||
}
|
||||
});
|
||||
}
|
||||
Err(e) => {
|
||||
warn!(?e, "introspect accept failed");
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn handle(self: Arc<Self>, mut stream: UnixStream) -> anyhow::Result<()> {
|
||||
loop {
|
||||
let mut len_buf = [0u8; 4];
|
||||
if stream.read_exact(&mut len_buf).await.is_err() {
|
||||
return Ok(()); // EOF
|
||||
}
|
||||
let len = u32::from_be_bytes(len_buf) as usize;
|
||||
if len > MAX_FRAME {
|
||||
anyhow::bail!("frame oversize: {len}");
|
||||
}
|
||||
let mut buf = vec![0u8; len];
|
||||
stream.read_exact(&mut buf).await?;
|
||||
let req: IntrospectRequest = bincode::deserialize(&buf)?;
|
||||
debug!(?req, "introspect request");
|
||||
|
||||
// StreamAudit toma posesión de la conn — no más requests aquí.
|
||||
if matches!(req, IntrospectRequest::StreamAudit) {
|
||||
return self.stream_audit(stream).await;
|
||||
}
|
||||
|
||||
let resp = self.dispatch(req).await;
|
||||
|
||||
let out = bincode::serialize(&resp)?;
|
||||
stream.write_u32(out.len() as u32).await?;
|
||||
stream.write_all(&out).await?;
|
||||
}
|
||||
}
|
||||
|
||||
/// Modo streaming: subscribe al audit log y empuja cada entry como
|
||||
/// frame `AuditStreamFrame`. La función retorna cuando el cliente
|
||||
/// cierra (write falla) o el subscriber se desconecta.
|
||||
async fn stream_audit(self: Arc<Self>, mut stream: UnixStream) -> anyhow::Result<()> {
|
||||
let mut rx = self.state.audit.write().await.subscribe();
|
||||
info!("audit stream client conectado");
|
||||
while let Some(entry) = rx.recv().await {
|
||||
let frame = IntrospectResponse::AuditStreamFrame(entry);
|
||||
let bytes = bincode::serialize(&frame)?;
|
||||
if stream.write_u32(bytes.len() as u32).await.is_err() { break; }
|
||||
if stream.write_all(&bytes).await.is_err() { break; }
|
||||
}
|
||||
info!("audit stream client desconectado");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn dispatch(&self, req: IntrospectRequest) -> IntrospectResponse {
|
||||
match req {
|
||||
IntrospectRequest::ListRules => {
|
||||
let engine = self.state.engine.read().await;
|
||||
let rules = engine.rules()
|
||||
.map(|r| RuleSummary {
|
||||
id: r.id,
|
||||
priority: r.priority,
|
||||
event_kind_tag: format!("{:?}", r.when),
|
||||
action_count: r.then.len(),
|
||||
scope_wildcard: r.scope.is_wildcard(),
|
||||
})
|
||||
.collect();
|
||||
IntrospectResponse::Rules(rules)
|
||||
}
|
||||
IntrospectRequest::GetRule(id) => {
|
||||
let engine = self.state.engine.read().await;
|
||||
let found = engine.rules()
|
||||
.find(|r| r.id == id)
|
||||
.map(|r| Rule::clone(r));
|
||||
IntrospectResponse::Rule(found)
|
||||
}
|
||||
IntrospectRequest::EntropySnapshot => {
|
||||
let obs = self.state.observer.read().await;
|
||||
IntrospectResponse::Entropy {
|
||||
value_bits: obs.shannon_entropy(),
|
||||
sample_size: obs.total(),
|
||||
distinct_kinds: obs.marginals().len(),
|
||||
window_full: obs.current_window() >= obs.window_size(),
|
||||
}
|
||||
}
|
||||
IntrospectRequest::TopCorrelations { n } => {
|
||||
let obs = self.state.observer.read().await;
|
||||
let mut entries: Vec<CorrelationEntry> = obs.cooccurrences().iter()
|
||||
.map(|((a, b), &joint)| CorrelationEntry {
|
||||
a: format!("{:?}", a),
|
||||
b: format!("{:?}", b),
|
||||
joint_count: joint,
|
||||
conditional_prob: obs.conditional_prob(a, b),
|
||||
pmi_bits: obs.pmi(a, b),
|
||||
})
|
||||
.collect();
|
||||
entries.sort_by(|x, y| y.joint_count.cmp(&x.joint_count));
|
||||
entries.truncate(n);
|
||||
IntrospectResponse::Correlations(entries)
|
||||
}
|
||||
IntrospectRequest::Crystals => {
|
||||
let obs = self.state.observer.read().await;
|
||||
let crystals = detect_crystals(&obs, &self.state.params);
|
||||
IntrospectResponse::Crystals(crystals)
|
||||
}
|
||||
IntrospectRequest::CrystalJson { index } => {
|
||||
let obs = self.state.observer.read().await;
|
||||
let crystals = detect_crystals(&obs, &self.state.params);
|
||||
match crystals.get(index) {
|
||||
Some(c) => IntrospectResponse::Json(crate::crystallize::crystal_to_json_pretty(c)),
|
||||
None => IntrospectResponse::Error(format!("no crystal at index {index}")),
|
||||
}
|
||||
}
|
||||
IntrospectRequest::PromoteCrystal { index } => {
|
||||
let crystals = {
|
||||
let obs = self.state.observer.read().await;
|
||||
detect_crystals(&obs, &self.state.params)
|
||||
};
|
||||
match crystals.get(index) {
|
||||
Some(c) => {
|
||||
let rule = crate::crystallize::crystal_to_rule(c);
|
||||
let rule_id = rule.id;
|
||||
let rule_json = serde_json::to_string_pretty(&rule)
|
||||
.unwrap_or_else(|_| "<serialize failed>".into());
|
||||
self.state.engine.write().await.insert(rule.clone());
|
||||
// Persistencia opcional al archivo JSONL.
|
||||
if let Some(path) = self.state.rules_out.as_ref() {
|
||||
if let Err(e) = append_rule_jsonl(path, &rule) {
|
||||
warn!(?e, path = %path.display(), "rules_out append falló");
|
||||
} else {
|
||||
info!(path = %path.display(), %rule_id, "regla persistida a JSONL");
|
||||
}
|
||||
}
|
||||
// Audit entry
|
||||
self.state.audit.write().await.append(
|
||||
crate::audit::AuditAction::PromoteCrystal {
|
||||
rule_id, crystal: c.clone(),
|
||||
}
|
||||
);
|
||||
IntrospectResponse::Promoted { rule_id, rule_json }
|
||||
}
|
||||
None => IntrospectResponse::Error(format!("no crystal at index {index}")),
|
||||
}
|
||||
}
|
||||
IntrospectRequest::RemoveRule { id } => {
|
||||
let removed = self.state.engine.write().await.remove(id);
|
||||
if removed {
|
||||
self.state.audit.write().await.append(
|
||||
crate::audit::AuditAction::RemoveRule { rule_id: id }
|
||||
);
|
||||
}
|
||||
IntrospectResponse::Removed(removed)
|
||||
}
|
||||
IntrospectRequest::ListAudit { limit } => {
|
||||
let audit = self.state.audit.read().await;
|
||||
IntrospectResponse::AuditEntries(audit.recent(limit).cloned().collect())
|
||||
}
|
||||
IntrospectRequest::FlushAudit => {
|
||||
let mut audit = self.state.audit.write().await;
|
||||
match audit.flush_to_cas() {
|
||||
Ok(written) => IntrospectResponse::Flushed {
|
||||
written,
|
||||
head_sha: audit.last_flushed_sha(),
|
||||
total_flushed: audit.flushed_count(),
|
||||
},
|
||||
Err(e) => IntrospectResponse::Error(format!("flush_to_cas: {e}")),
|
||||
}
|
||||
}
|
||||
IntrospectRequest::VerifyAudit => {
|
||||
let head = self.state.audit.read().await.last_flushed_sha();
|
||||
let head = match head {
|
||||
Some(h) => h,
|
||||
None => return IntrospectResponse::Error(
|
||||
"audit log sin entries flushadas — nada que verificar".into()
|
||||
),
|
||||
};
|
||||
let report = crate::audit::verify_chain_from_cas(head);
|
||||
IntrospectResponse::AuditVerified(report)
|
||||
}
|
||||
IntrospectRequest::StreamAudit => {
|
||||
// Inalcanzable por construcción: handle() detecta StreamAudit
|
||||
// antes de llamar a dispatch(). Pero el match exige cubrir.
|
||||
IntrospectResponse::Error(
|
||||
"StreamAudit no debe llegar a dispatch — bug del handler".into()
|
||||
)
|
||||
}
|
||||
IntrospectRequest::PatternCrystals => {
|
||||
let obs = self.state.observer.read().await;
|
||||
let params = crate::crystallize::PatternParams::default();
|
||||
let patterns = crate::crystallize::detect_pattern_crystals(&obs, ¶ms);
|
||||
IntrospectResponse::Patterns(patterns)
|
||||
}
|
||||
IntrospectRequest::GcCas { extra_roots } => {
|
||||
// Reachable = audit chain desde head + extra_roots provistos.
|
||||
let mut reachable = std::collections::HashSet::new();
|
||||
if let Some(head) = self.state.audit.read().await.last_flushed_sha() {
|
||||
reachable.extend(crate::audit::reachable_from_head(head));
|
||||
}
|
||||
reachable.extend(extra_roots);
|
||||
match ente_cas::gc(&reachable) {
|
||||
Ok((deleted, freed_bytes)) => IntrospectResponse::GcResult { deleted, freed_bytes },
|
||||
Err(e) => IntrospectResponse::Error(format!("gc: {e}")),
|
||||
}
|
||||
}
|
||||
IntrospectRequest::ReplayAudit => {
|
||||
let head = self.state.audit.read().await.last_flushed_sha();
|
||||
let head = match head {
|
||||
Some(h) => h,
|
||||
None => return IntrospectResponse::Error(
|
||||
"audit log sin entries flushadas — nada que replayar".into()
|
||||
),
|
||||
};
|
||||
let mut engine = self.state.engine.write().await;
|
||||
*engine = crate::engine::RuleEngine::empty();
|
||||
let report = crate::audit::replay_chain(head, &mut engine);
|
||||
IntrospectResponse::Replayed(report)
|
||||
}
|
||||
IntrospectRequest::ReloadRules { path } => {
|
||||
// Path explícito gana sobre el rules_out configurado.
|
||||
let resolved = path.map(std::path::PathBuf::from)
|
||||
.or_else(|| self.state.rules_out.as_ref().map(|p| p.as_path().to_path_buf()));
|
||||
let path = match resolved {
|
||||
Some(p) => p,
|
||||
None => return IntrospectResponse::Error(
|
||||
"ReloadRules sin path y sin rules_out configurado".into()
|
||||
),
|
||||
};
|
||||
let rules = match crate::loader::load_rules_file(&path) {
|
||||
Ok(r) => r,
|
||||
Err(e) => return IntrospectResponse::Error(format!("load: {e}")),
|
||||
};
|
||||
// Vaciamos el engine antes de re-cargar — semántica clean-slate.
|
||||
let mut engine = self.state.engine.write().await;
|
||||
*engine = crate::engine::RuleEngine::empty();
|
||||
let count = rules.len();
|
||||
for r in rules { engine.insert(r); }
|
||||
drop(engine);
|
||||
self.state.audit.write().await.append(
|
||||
crate::audit::AuditAction::LoadRulesFile {
|
||||
path: path.to_string_lossy().into_owned(),
|
||||
count,
|
||||
}
|
||||
);
|
||||
IntrospectResponse::Reloaded { count }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Cliente helper para tools externos (brainctl).
|
||||
pub async fn call(path: &Path, req: IntrospectRequest) -> anyhow::Result<IntrospectResponse> {
|
||||
let mut stream = UnixStream::connect(path).await?;
|
||||
let buf = bincode::serialize(&req)?;
|
||||
stream.write_u32(buf.len() as u32).await?;
|
||||
stream.write_all(&buf).await?;
|
||||
|
||||
let mut len_buf = [0u8; 4];
|
||||
stream.read_exact(&mut len_buf).await?;
|
||||
let len = u32::from_be_bytes(len_buf) as usize;
|
||||
if len > MAX_FRAME {
|
||||
anyhow::bail!("response oversize: {len}");
|
||||
}
|
||||
let mut buf = vec![0u8; len];
|
||||
stream.read_exact(&mut buf).await?;
|
||||
Ok(bincode::deserialize(&buf)?)
|
||||
}
|
||||
|
||||
/// Consume la lista marginal del observer para humanos. Suprime el detalle
|
||||
/// crudo de `EventKind` (ej. payloads largos en BusInvokeOf).
|
||||
pub fn marginal_summary(obs: &Observer) -> Vec<(String, u64)> {
|
||||
let mut entries: Vec<(String, u64)> = obs.marginals().iter()
|
||||
.map(|(k, &c)| (format!("{:?}", k), c))
|
||||
.collect();
|
||||
entries.sort_by(|x, y| y.1.cmp(&x.1));
|
||||
entries
|
||||
}
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
//! ente-brain: motor de reglas determinista + observador estadístico.
|
||||
//!
|
||||
//! Tres capas:
|
||||
//! 1. `rules` — tipos de regla (Triplet: Subject + Event + Action)
|
||||
//! 2. `engine` — RuleEngine con HashMap<EventKindDiscriminant, Vec<Arc<Rule>>>
|
||||
//! para dispatch O(1)
|
||||
//! 3. `dispatch` — ejecutor async de Actions (vía tokio)
|
||||
//! 4. `observer` — sliding window + marginales + co-ocurrencias
|
||||
//! + Shannon entropy + información mutua
|
||||
//! 5. `crystallize` — detección de patrones estadísticamente significativos
|
||||
//! y materialización en `Rule` ejecutables
|
||||
//! 6. `introspect` — Unix socket bincode API para tools externos
|
||||
//!
|
||||
//! Diseño de inmutabilidad:
|
||||
//! - Rules son `Arc<Rule>` — clonar es zero-copy (refcount bump).
|
||||
//! - El motor expone sólo lecturas; mutaciones pasan por `insert/remove`.
|
||||
//! - Observer mantiene contadores incrementales — sin recomputación.
|
||||
|
||||
pub mod audit;
|
||||
pub mod autopromote;
|
||||
pub mod crystallize;
|
||||
pub mod dispatch;
|
||||
pub mod engine;
|
||||
pub mod introspect;
|
||||
pub mod loader;
|
||||
pub mod metrics;
|
||||
pub mod observer;
|
||||
pub mod rules;
|
||||
|
||||
pub use autopromote::{spawn_autopromote_loop, AutopromoteParams};
|
||||
pub use crystallize::{detect_crystals, Crystal, CrystallizationParams};
|
||||
pub use dispatch::{dispatch_actions, ActionSink, NullSink};
|
||||
pub use engine::{EventKindDiscriminant, RuleEngine, SubjectInfo};
|
||||
pub use introspect::{IntrospectRequest, IntrospectResponse, IntrospectServer, BrainState};
|
||||
pub use loader::{load_card_file, load_rules_file};
|
||||
pub use metrics::serve_metrics;
|
||||
pub use observer::{Observer, TimedEvent};
|
||||
pub use rules::{Action, EventKind, EventPattern, LogLevel, Rule, Scope};
|
||||
@@ -0,0 +1,172 @@
|
||||
//! Loader de Cards y Reglas desde archivos JSON.
|
||||
//!
|
||||
//! Sustituye al antiguo `kcl_loader.rs` (eliminado): la rama KCL invocaba
|
||||
//! un subprocess al CLI Go `kcl` que ningún target real tenía instalado y
|
||||
//! cuya validación duplicaba `EntityCard::validate()`. La fuente de verdad
|
||||
//! del shape de la Card es Rust + serde; en disco se guarda JSON crudo.
|
||||
//!
|
||||
//! Ergonomía de autoría futura (RON, Dhall, etc.) se añade como ramas
|
||||
//! adicionales aquí cuando duela escribir JSON a mano. Hoy: una sola rama.
|
||||
|
||||
use crate::rules::Rule;
|
||||
use ente_card::EntityCard;
|
||||
use std::path::Path;
|
||||
use tracing::info;
|
||||
|
||||
/// Carga una `EntityCard` desde un archivo JSON. Pasa por
|
||||
/// `EntityCard::validate()` antes de devolver — falla rápida.
|
||||
pub fn load_card_file(path: &Path) -> anyhow::Result<EntityCard> {
|
||||
info!(path = %path.display(), "cargando Card desde JSON");
|
||||
let raw = std::fs::read_to_string(path)?;
|
||||
let card = extract_card_from_json(&raw)?;
|
||||
card.validate()
|
||||
.map_err(|e| anyhow::anyhow!("Card inválida ({}): {e}", path.display()))?;
|
||||
Ok(card)
|
||||
}
|
||||
|
||||
/// Extrae una `EntityCard` de JSON. Acepta:
|
||||
/// 1. Object directamente serializable como EntityCard.
|
||||
/// 2. Object dict con un único valor que sea EntityCard (compat con
|
||||
/// salidas de generadores que envuelven en `{"seed": {...}}`).
|
||||
pub fn extract_card_from_json(raw: &str) -> anyhow::Result<EntityCard> {
|
||||
let v: serde_json::Value = serde_json::from_str(raw)?;
|
||||
let direct_err = match serde_json::from_value::<EntityCard>(v.clone()) {
|
||||
Ok(c) => return Ok(c),
|
||||
Err(e) => e,
|
||||
};
|
||||
if let serde_json::Value::Object(map) = v {
|
||||
for (_, vv) in map {
|
||||
if let Ok(c) = serde_json::from_value::<EntityCard>(vv) {
|
||||
return Ok(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Propagamos el error del intento directo: es el caso típico (JSON top-level
|
||||
// = EntityCard) y su mensaje apunta al campo concreto que rompió.
|
||||
anyhow::bail!("JSON no contiene una EntityCard válida: {direct_err}")
|
||||
}
|
||||
|
||||
/// Carga reglas desde un archivo JSON.
|
||||
pub fn load_rules_file(path: &Path) -> anyhow::Result<Vec<Rule>> {
|
||||
info!(path = %path.display(), "cargando reglas desde JSON");
|
||||
let raw = std::fs::read_to_string(path)?;
|
||||
extract_rules_from_json(&raw)
|
||||
}
|
||||
|
||||
/// Extrae un `Vec<Rule>` de un blob de texto. Acepta tres formas:
|
||||
/// 1. JSONL: una `Rule` por línea (el formato que escribe `append_rule_jsonl`).
|
||||
/// 2. Array directo: `[{...}, {...}]`.
|
||||
/// 3. Object con un campo array: `{"rules": [...]}`.
|
||||
///
|
||||
/// Heurística: si el primer carácter no-blanco es `[` o `{` con formato
|
||||
/// "objeto-con-array", parseamos como JSON único; en otro caso intentamos
|
||||
/// línea-por-línea. Líneas vacías o que empiecen con `#` se ignoran (compat
|
||||
/// con archivos editados a mano que dejen comentarios estilo shell).
|
||||
pub fn extract_rules_from_json(raw: &str) -> anyhow::Result<Vec<Rule>> {
|
||||
let trimmed_start = raw.trim_start();
|
||||
let looks_jsonl = trimmed_start.starts_with('{')
|
||||
&& raw.lines().filter(|l| {
|
||||
let t = l.trim();
|
||||
!t.is_empty() && !t.starts_with('#')
|
||||
}).count() > 1;
|
||||
|
||||
if !looks_jsonl {
|
||||
// Camino clásico: un único documento JSON (array o objeto).
|
||||
if let Ok(v) = serde_json::from_str::<serde_json::Value>(raw) {
|
||||
let arr = match v {
|
||||
serde_json::Value::Array(_) => v,
|
||||
serde_json::Value::Object(map) => map
|
||||
.into_values()
|
||||
.find(|x| x.is_array())
|
||||
.ok_or_else(|| anyhow::anyhow!("JSON no contiene ningún array"))?,
|
||||
_ => anyhow::bail!("JSON debe ser array o object con campo array"),
|
||||
};
|
||||
return Ok(serde_json::from_value(arr)?);
|
||||
}
|
||||
// Caer a JSONL si el documento único no parsea — útil para archivos
|
||||
// que mezclan comentarios `#` (no JSON válido como documento único).
|
||||
}
|
||||
|
||||
let mut rules = Vec::new();
|
||||
for (idx, line) in raw.lines().enumerate() {
|
||||
let t = line.trim();
|
||||
if t.is_empty() || t.starts_with('#') { continue; }
|
||||
let rule: Rule = serde_json::from_str(t)
|
||||
.map_err(|e| anyhow::anyhow!("JSONL línea {}: {e}", idx + 1))?;
|
||||
rules.push(rule);
|
||||
}
|
||||
Ok(rules)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::introspect::append_rule_jsonl;
|
||||
use crate::rules::{Action, EventKind, EventPattern, LogLevel, Rule, Scope};
|
||||
use ulid::Ulid;
|
||||
|
||||
fn sample_rule() -> Rule {
|
||||
Rule {
|
||||
id: Ulid::new(),
|
||||
priority: 5,
|
||||
when: EventPattern::Single { kind: EventKind::EnteSpawned },
|
||||
then: vec![Action::Log {
|
||||
level: LogLevel::Info,
|
||||
message: "test".into(),
|
||||
}],
|
||||
scope: Scope::default(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rules_from_array() {
|
||||
let r = sample_rule();
|
||||
let raw = format!("[{}]", serde_json::to_string(&r).unwrap());
|
||||
let parsed = extract_rules_from_json(&raw).expect("array parse");
|
||||
assert_eq!(parsed.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rules_from_object_with_array() {
|
||||
let r = sample_rule();
|
||||
let raw = format!(r#"{{"rules":[{}]}}"#, serde_json::to_string(&r).unwrap());
|
||||
let parsed = extract_rules_from_json(&raw).expect("object parse");
|
||||
assert_eq!(parsed.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rules_from_jsonl_with_comments_and_blanks() {
|
||||
let r1 = sample_rule();
|
||||
let r2 = sample_rule();
|
||||
let raw = format!(
|
||||
"# header comment\n\n{}\n# inline comment\n{}\n\n",
|
||||
serde_json::to_string(&r1).unwrap(),
|
||||
serde_json::to_string(&r2).unwrap()
|
||||
);
|
||||
let parsed = extract_rules_from_json(&raw).expect("jsonl parse");
|
||||
assert_eq!(parsed.len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn append_rule_jsonl_roundtrip() {
|
||||
let dir = tempdir_unique();
|
||||
let path = dir.join("rules.jsonl");
|
||||
let r1 = sample_rule();
|
||||
let r2 = sample_rule();
|
||||
append_rule_jsonl(&path, &r1).expect("append 1");
|
||||
append_rule_jsonl(&path, &r2).expect("append 2");
|
||||
let raw = std::fs::read_to_string(&path).expect("read back");
|
||||
let parsed = extract_rules_from_json(&raw).expect("roundtrip parse");
|
||||
assert_eq!(parsed.len(), 2);
|
||||
assert_eq!(parsed[0].id, r1.id);
|
||||
assert_eq!(parsed[1].id, r2.id);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
fn tempdir_unique() -> std::path::PathBuf {
|
||||
let base = std::env::temp_dir();
|
||||
let p = base.join(format!("ente-brain-loader-{}", Ulid::new()));
|
||||
std::fs::create_dir_all(&p).unwrap();
|
||||
p
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
//! Endpoint Prometheus en TCP. Formato text/plain (exposition format 0.0.4).
|
||||
//!
|
||||
//! Sin dependencias adicionales — la cardinalidad de nuestras métricas es
|
||||
//! pequeña y el formato es trivial. Si crece, sustituir por la crate
|
||||
//! `prometheus` con su Registry + encoders.
|
||||
|
||||
use crate::introspect::BrainState;
|
||||
use crate::rules::EventKind;
|
||||
use std::net::SocketAddr;
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::net::{TcpListener, TcpStream};
|
||||
use tracing::{info, trace, warn};
|
||||
|
||||
/// Lanza el listener Prometheus. Devuelve cuando bind() falla; en caso
|
||||
/// contrario corre indefinidamente. Pensado para `tokio::spawn`.
|
||||
pub async fn serve_metrics(state: BrainState, addr: SocketAddr) -> anyhow::Result<()> {
|
||||
let listener = TcpListener::bind(addr).await?;
|
||||
info!(?addr, "prometheus /metrics escuchando");
|
||||
loop {
|
||||
match listener.accept().await {
|
||||
Ok((stream, peer)) => {
|
||||
trace!(?peer, "metrics scrape");
|
||||
let s = state.clone();
|
||||
tokio::spawn(async move {
|
||||
if let Err(e) = handle_scrape(stream, s).await {
|
||||
warn!(?e, "metrics conn ended");
|
||||
}
|
||||
});
|
||||
}
|
||||
Err(e) => {
|
||||
warn!(?e, "metrics accept failed");
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn handle_scrape(mut stream: TcpStream, state: BrainState) -> anyhow::Result<()> {
|
||||
// Drenamos el request line + headers sin parsear (cualquier path
|
||||
// responde igual — Prometheus envía GET /metrics típicamente).
|
||||
let mut buf = [0u8; 1024];
|
||||
let _ = stream.read(&mut buf).await;
|
||||
let body = format_metrics(&state).await;
|
||||
let resp = format!(
|
||||
"HTTP/1.1 200 OK\r\n\
|
||||
Content-Type: text/plain; version=0.0.4\r\n\
|
||||
Content-Length: {}\r\n\
|
||||
Connection: close\r\n\
|
||||
\r\n\
|
||||
{}",
|
||||
body.len(), body
|
||||
);
|
||||
stream.write_all(resp.as_bytes()).await?;
|
||||
stream.shutdown().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn format_metrics(state: &BrainState) -> String {
|
||||
let obs = state.observer.read().await;
|
||||
let engine = state.engine.read().await;
|
||||
let audit = state.audit.read().await;
|
||||
|
||||
let mut out = String::with_capacity(2048);
|
||||
|
||||
// ---- Entropía ----
|
||||
out.push_str("# HELP ente_brain_entropy_bits Shannon entropy of marginal event distribution.\n");
|
||||
out.push_str("# TYPE ente_brain_entropy_bits gauge\n");
|
||||
out.push_str(&format!("ente_brain_entropy_bits {:.6}\n", obs.shannon_entropy()));
|
||||
|
||||
// ---- Tamaño de muestra ----
|
||||
out.push_str("# HELP ente_brain_events_total Total events recorded by the observer.\n");
|
||||
out.push_str("# TYPE ente_brain_events_total counter\n");
|
||||
out.push_str(&format!("ente_brain_events_total {}\n", obs.total()));
|
||||
|
||||
// ---- Distinct kinds ----
|
||||
out.push_str("# HELP ente_brain_distinct_kinds Number of distinct EventKind tags seen.\n");
|
||||
out.push_str("# TYPE ente_brain_distinct_kinds gauge\n");
|
||||
out.push_str(&format!("ente_brain_distinct_kinds {}\n", obs.marginals().len()));
|
||||
|
||||
// ---- Window ocupación ----
|
||||
out.push_str("# HELP ente_brain_window_size Current sliding window length.\n");
|
||||
out.push_str("# TYPE ente_brain_window_size gauge\n");
|
||||
out.push_str(&format!("ente_brain_window_size {}\n", obs.current_window()));
|
||||
|
||||
// ---- Reglas vivas ----
|
||||
out.push_str("# HELP ente_brain_rules_active Number of rules currently in the engine.\n");
|
||||
out.push_str("# TYPE ente_brain_rules_active gauge\n");
|
||||
out.push_str(&format!("ente_brain_rules_active {}\n", engine.len()));
|
||||
|
||||
// ---- Eventos por kind ----
|
||||
out.push_str("# HELP ente_brain_events_by_kind Events by EventKind tag.\n");
|
||||
out.push_str("# TYPE ente_brain_events_by_kind counter\n");
|
||||
for (k, c) in obs.marginals() {
|
||||
out.push_str(&format!(
|
||||
"ente_brain_events_by_kind{{kind=\"{}\"}} {}\n",
|
||||
kind_label(k), c
|
||||
));
|
||||
}
|
||||
|
||||
// ---- Cristales detectados (con params actuales) ----
|
||||
let crystals = crate::detect_crystals(&obs, &state.params);
|
||||
out.push_str("# HELP ente_brain_crystals_total Number of crystals detected with current params.\n");
|
||||
out.push_str("# TYPE ente_brain_crystals_total gauge\n");
|
||||
out.push_str(&format!("ente_brain_crystals_total {}\n", crystals.len()));
|
||||
|
||||
// ---- Audit log ----
|
||||
out.push_str("# HELP ente_brain_audit_chain_length Total entries persisted to CAS.\n");
|
||||
out.push_str("# TYPE ente_brain_audit_chain_length counter\n");
|
||||
out.push_str(&format!("ente_brain_audit_chain_length {}\n", audit.flushed_count()));
|
||||
|
||||
out.push_str("# HELP ente_brain_audit_in_memory Entries currently in the in-memory ring.\n");
|
||||
out.push_str("# TYPE ente_brain_audit_in_memory gauge\n");
|
||||
out.push_str(&format!("ente_brain_audit_in_memory {}\n", audit.len()));
|
||||
|
||||
out.push_str("# HELP ente_brain_audit_subscribers Active stream-audit subscribers.\n");
|
||||
out.push_str("# TYPE ente_brain_audit_subscribers gauge\n");
|
||||
out.push_str(&format!("ente_brain_audit_subscribers {}\n", audit.subscriber_count()));
|
||||
|
||||
if let Some(age) = audit.last_flush_age_secs() {
|
||||
out.push_str("# HELP ente_brain_audit_last_flush_age_seconds Time since last flush to CAS.\n");
|
||||
out.push_str("# TYPE ente_brain_audit_last_flush_age_seconds gauge\n");
|
||||
out.push_str(&format!("ente_brain_audit_last_flush_age_seconds {:.3}\n", age));
|
||||
}
|
||||
if let Some(sha) = audit.last_flushed_sha() {
|
||||
// Info-style metric con head sha como label. Útil para dashboards
|
||||
// que quieran mostrar "current head".
|
||||
out.push_str("# HELP ente_brain_audit_head_info Current head SHA of the audit chain.\n");
|
||||
out.push_str("# TYPE ente_brain_audit_head_info gauge\n");
|
||||
out.push_str(&format!(
|
||||
"ente_brain_audit_head_info{{sha=\"{}\"}} 1\n",
|
||||
ente_cas::hex(&sha)
|
||||
));
|
||||
}
|
||||
|
||||
// ---- Histogramas de gaps temporales (top-32 pares más frecuentes) ----
|
||||
out.push_str("# HELP ente_brain_pair_gap_seconds Time gap between correlated events.\n");
|
||||
out.push_str("# TYPE ente_brain_pair_gap_seconds histogram\n");
|
||||
let limits = crate::observer::GapHistogram::bucket_limits();
|
||||
for ((a, b), hist) in obs.top_gap_pairs(32) {
|
||||
let labels = format!(r#"a="{}",b="{}""#, kind_label(a), kind_label(b));
|
||||
for (i, &limit) in limits.iter().enumerate() {
|
||||
out.push_str(&format!(
|
||||
"ente_brain_pair_gap_seconds_bucket{{{},le=\"{}\"}} {}\n",
|
||||
labels, limit, hist.buckets[i]
|
||||
));
|
||||
}
|
||||
out.push_str(&format!(
|
||||
"ente_brain_pair_gap_seconds_bucket{{{},le=\"+Inf\"}} {}\n",
|
||||
labels, hist.count
|
||||
));
|
||||
out.push_str(&format!(
|
||||
"ente_brain_pair_gap_seconds_sum{{{}}} {:.6}\n",
|
||||
labels, hist.sum_secs
|
||||
));
|
||||
out.push_str(&format!(
|
||||
"ente_brain_pair_gap_seconds_count{{{}}} {}\n",
|
||||
labels, hist.count
|
||||
));
|
||||
}
|
||||
|
||||
out
|
||||
}
|
||||
|
||||
fn kind_label(k: &EventKind) -> &'static str {
|
||||
match k {
|
||||
EventKind::EnteSpawned => "EnteSpawned",
|
||||
EventKind::EnteDied => "EnteDied",
|
||||
EventKind::BusAnnounce => "BusAnnounce",
|
||||
EventKind::BusInvoke => "BusInvoke",
|
||||
EventKind::BusInvokeOf(_) => "BusInvokeOf",
|
||||
EventKind::DeviceAdded => "DeviceAdded",
|
||||
EventKind::DeviceRemoved => "DeviceRemoved",
|
||||
EventKind::Custom(_) => "Custom",
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,453 @@
|
||||
//! Observador estadístico. Mantiene marginales y co-ocurrencias dentro de una
|
||||
//! ventana deslizante. Calcula entropía de Shannon e información mutua para
|
||||
//! identificar correlaciones significativas.
|
||||
//!
|
||||
//! Diseño:
|
||||
//! - Counters incrementales: cada `record()` es O(window_size) en el peor
|
||||
//! caso (actualiza co-ocurrencias con cada evento del window).
|
||||
//! - Sin recomputaciones globales: marginales y joint counts son state.
|
||||
//! - El cálculo de H(X), P(B|A), I(A;B) es O(|distinct events|).
|
||||
|
||||
use crate::rules::EventKind;
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
use std::time::Instant;
|
||||
|
||||
/// Evento timestamped. El timestamp se conserva para futuras políticas de
|
||||
/// expiración por tiempo (no sólo por count).
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct TimedEvent {
|
||||
pub kind: EventKind,
|
||||
pub at: Instant,
|
||||
}
|
||||
|
||||
/// Histograma de gaps temporales con buckets exponenciales en segundos.
|
||||
/// Cubre 6 órdenes de magnitud: 1ms hasta 1000s.
|
||||
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
|
||||
pub struct GapHistogram {
|
||||
/// Buckets cumulativos (Prometheus-style): cada índice cuenta eventos
|
||||
/// con gap ≤ ese límite. Limites: 1ms, 10ms, 100ms, 1s, 10s, 100s, 1000s.
|
||||
pub buckets: [u64; 7],
|
||||
pub count: u64,
|
||||
pub sum_secs: f64,
|
||||
/// Suma de cuadrados — permite calcular varianza/stddev en O(1).
|
||||
pub sum_squares_secs: f64,
|
||||
pub max_secs: f64,
|
||||
}
|
||||
|
||||
/// Estadísticas resumidas de un GapHistogram, usables en cristales temporales.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct GapStats {
|
||||
pub count: u64,
|
||||
pub mean_secs: f64,
|
||||
pub stddev_secs: f64,
|
||||
pub max_secs: f64,
|
||||
}
|
||||
|
||||
const GAP_BUCKET_LIMITS_SECS: [f64; 7] = [
|
||||
0.001, 0.01, 0.1, 1.0, 10.0, 100.0, 1000.0,
|
||||
];
|
||||
|
||||
impl GapHistogram {
|
||||
pub fn observe(&mut self, gap_secs: f64) {
|
||||
for (i, &limit) in GAP_BUCKET_LIMITS_SECS.iter().enumerate() {
|
||||
if gap_secs <= limit {
|
||||
self.buckets[i] += 1;
|
||||
}
|
||||
}
|
||||
self.count += 1;
|
||||
self.sum_secs += gap_secs;
|
||||
self.sum_squares_secs += gap_secs * gap_secs;
|
||||
if gap_secs > self.max_secs { self.max_secs = gap_secs; }
|
||||
}
|
||||
|
||||
pub fn mean_secs(&self) -> f64 {
|
||||
if self.count == 0 { 0.0 } else { self.sum_secs / self.count as f64 }
|
||||
}
|
||||
|
||||
/// Desviación estándar muestral. Computada vía `sum_squares - n*mean²`
|
||||
/// para precisión razonable sin almacenar las muestras.
|
||||
pub fn stddev_secs(&self) -> f64 {
|
||||
if self.count < 2 { return 0.0; }
|
||||
let n = self.count as f64;
|
||||
let mean = self.mean_secs();
|
||||
let var = (self.sum_squares_secs - n * mean * mean) / (n - 1.0);
|
||||
// Numerical floor: var puede ser ligeramente negativo por float ε.
|
||||
if var <= 0.0 { 0.0 } else { var.sqrt() }
|
||||
}
|
||||
|
||||
pub fn stats(&self) -> GapStats {
|
||||
GapStats {
|
||||
count: self.count,
|
||||
mean_secs: self.mean_secs(),
|
||||
stddev_secs: self.stddev_secs(),
|
||||
max_secs: self.max_secs,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn bucket_limits() -> &'static [f64; 7] { &GAP_BUCKET_LIMITS_SECS }
|
||||
}
|
||||
|
||||
pub struct Observer {
|
||||
window: VecDeque<TimedEvent>,
|
||||
window_size: usize,
|
||||
marginal: HashMap<EventKind, u64>,
|
||||
cooccur: HashMap<(EventKind, EventKind), u64>,
|
||||
total: u64,
|
||||
/// Last-seen timestamps para aplicar decay en query time. None = sin
|
||||
/// time-decay (modo tradicional).
|
||||
last_seen_marginal: HashMap<EventKind, Instant>,
|
||||
last_seen_cooccur: HashMap<(EventKind, EventKind), Instant>,
|
||||
/// Half-life del decay exponencial en segundos. None = sin decay
|
||||
/// (las consultas devuelven los counts crudos).
|
||||
half_life_secs: Option<f64>,
|
||||
/// Histograma de gaps temporales por par (a, b). Capturado al `record()`.
|
||||
gap_histograms: HashMap<(EventKind, EventKind), GapHistogram>,
|
||||
/// Sets de "qué cambió desde el último snapshot". Se vacían en
|
||||
/// `snapshot()` y `snapshot_delta()`. Usado para escritura incremental.
|
||||
dirty_marginal: std::collections::HashSet<EventKind>,
|
||||
dirty_cooccur: std::collections::HashSet<(EventKind, EventKind)>,
|
||||
}
|
||||
|
||||
impl Observer {
|
||||
pub fn new(window_size: usize) -> Self {
|
||||
Self {
|
||||
window: VecDeque::with_capacity(window_size),
|
||||
window_size,
|
||||
marginal: HashMap::new(),
|
||||
cooccur: HashMap::new(),
|
||||
total: 0,
|
||||
last_seen_marginal: HashMap::new(),
|
||||
last_seen_cooccur: HashMap::new(),
|
||||
half_life_secs: None,
|
||||
gap_histograms: HashMap::new(),
|
||||
dirty_marginal: std::collections::HashSet::new(),
|
||||
dirty_cooccur: std::collections::HashSet::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Activa decay exponencial con half-life en segundos. λ = ln(2)/half_life.
|
||||
/// Aplicado en query time sobre los counts crudos usando last_seen.
|
||||
pub fn with_half_life(mut self, half_life_secs: f64) -> Self {
|
||||
if half_life_secs > 0.0 {
|
||||
self.half_life_secs = Some(half_life_secs);
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
pub fn half_life(&self) -> Option<f64> { self.half_life_secs }
|
||||
|
||||
/// Registra un evento. Actualiza marginales y co-ocurrencias contra todo
|
||||
/// evento aún en la ventana.
|
||||
pub fn record(&mut self, kind: EventKind) {
|
||||
let now = Instant::now();
|
||||
let timed = TimedEvent { kind: kind.clone(), at: now };
|
||||
|
||||
// Co-ocurrencias: este evento con cada uno previo en ventana.
|
||||
// Capturamos también el gap temporal (now - w.at) para histograma.
|
||||
for w in &self.window {
|
||||
let key = (w.kind.clone(), kind.clone());
|
||||
*self.cooccur.entry(key.clone()).or_insert(0) += 1;
|
||||
self.last_seen_cooccur.insert(key.clone(), now);
|
||||
let gap_secs = now.duration_since(w.at).as_secs_f64();
|
||||
self.gap_histograms.entry(key.clone()).or_default().observe(gap_secs);
|
||||
self.dirty_cooccur.insert(key);
|
||||
}
|
||||
|
||||
self.window.push_back(timed);
|
||||
if self.window.len() > self.window_size {
|
||||
self.window.pop_front();
|
||||
}
|
||||
|
||||
*self.marginal.entry(kind.clone()).or_insert(0) += 1;
|
||||
self.last_seen_marginal.insert(kind.clone(), now);
|
||||
self.dirty_marginal.insert(kind);
|
||||
self.total += 1;
|
||||
}
|
||||
|
||||
/// Aplica el decay sobre un count crudo dado el `last_seen` correspondiente.
|
||||
/// Si half_life es None, devuelve el count tal cual (sin decay).
|
||||
fn decay(&self, count: u64, last_seen: Option<Instant>) -> f64 {
|
||||
let raw = count as f64;
|
||||
let (hl, last) = match (self.half_life_secs, last_seen) {
|
||||
(Some(hl), Some(t)) => (hl, t),
|
||||
_ => return raw,
|
||||
};
|
||||
let age_secs = Instant::now().duration_since(last).as_secs_f64();
|
||||
raw * 0.5_f64.powf(age_secs / hl)
|
||||
}
|
||||
|
||||
/// Marginal con decay aplicado.
|
||||
pub fn marginal_decayed(&self, k: &EventKind) -> f64 {
|
||||
let raw = self.marginal.get(k).copied().unwrap_or(0);
|
||||
let last = self.last_seen_marginal.get(k).copied();
|
||||
self.decay(raw, last)
|
||||
}
|
||||
|
||||
/// Cooccurrence con decay aplicado.
|
||||
pub fn cooccur_decayed(&self, a: &EventKind, b: &EventKind) -> f64 {
|
||||
let raw = self.cooccur.get(&(a.clone(), b.clone())).copied().unwrap_or(0);
|
||||
let last = self.last_seen_cooccur.get(&(a.clone(), b.clone())).copied();
|
||||
self.decay(raw, last)
|
||||
}
|
||||
|
||||
/// Entropía de Shannon de la distribución marginal de eventos.
|
||||
/// H(X) = −Σ p(x) log₂ p(x). Unidad: bits.
|
||||
pub fn shannon_entropy(&self) -> f64 {
|
||||
if self.total == 0 { return 0.0; }
|
||||
let total = self.total as f64;
|
||||
self.marginal.values()
|
||||
.map(|&c| {
|
||||
let p = c as f64 / total;
|
||||
if p > 0.0 { -p * p.log2() } else { 0.0 }
|
||||
})
|
||||
.sum()
|
||||
}
|
||||
|
||||
/// P(b | a) = "dado que algo siguió a `a` dentro del window, qué fracción
|
||||
/// fue `b`". Suma 1 sobre todos los b posibles para un a fijo.
|
||||
///
|
||||
/// Implementación: cooccur_decayed(a, b) / Σ_x cooccur_decayed(a, x).
|
||||
/// Si half_life is None, los decayed values son los counts crudos.
|
||||
pub fn conditional_prob(&self, a: &EventKind, b: &EventKind) -> f64 {
|
||||
let joint = self.cooccur_decayed(a, b);
|
||||
let row_total: f64 = self.cooccur.keys()
|
||||
.filter(|(x, _)| x == a)
|
||||
.map(|(x, y)| self.cooccur_decayed(x, y))
|
||||
.sum();
|
||||
if row_total <= 0.0 { 0.0 } else { joint / row_total }
|
||||
}
|
||||
|
||||
/// Información mutua puntual entre `a` y `b` con decay aplicado:
|
||||
/// PMI(a, b) = log₂( P(a, b) / (P(a) · P(b)) ).
|
||||
/// Positivo → más correlacionados de lo que sugiere independencia.
|
||||
pub fn pmi(&self, a: &EventKind, b: &EventKind) -> f64 {
|
||||
// Total decayed: suma de marginales con decay (no usamos self.total
|
||||
// directo porque debería ser consistente con los decayed values).
|
||||
let total_decayed: f64 = self.marginal.keys()
|
||||
.map(|k| self.marginal_decayed(k))
|
||||
.sum();
|
||||
if total_decayed <= 0.0 { return 0.0; }
|
||||
let joint = self.cooccur_decayed(a, b) / total_decayed;
|
||||
let pa = self.marginal_decayed(a) / total_decayed;
|
||||
let pb = self.marginal_decayed(b) / total_decayed;
|
||||
if joint <= 0.0 || pa <= 0.0 || pb <= 0.0 { return 0.0; }
|
||||
(joint / (pa * pb)).log2()
|
||||
}
|
||||
|
||||
/// Información mutua acumulada de la pareja (a, b) ponderada por su
|
||||
/// probabilidad conjunta. Útil como medida de "interés" del par.
|
||||
pub fn weighted_pmi(&self, a: &EventKind, b: &EventKind) -> f64 {
|
||||
if self.total == 0 { return 0.0; }
|
||||
let joint = self.cooccur
|
||||
.get(&(a.clone(), b.clone()))
|
||||
.copied()
|
||||
.unwrap_or(0) as f64 / self.total as f64;
|
||||
joint * self.pmi(a, b)
|
||||
}
|
||||
|
||||
pub fn marginals(&self) -> &HashMap<EventKind, u64> { &self.marginal }
|
||||
|
||||
/// Última vez que se vio un kind. None si nunca o si fue restaurado
|
||||
/// desde snapshot (los Instants no portables se descartan).
|
||||
pub fn last_seen_marginal(&self, kind: &EventKind) -> Option<Instant> {
|
||||
self.last_seen_marginal.get(kind).copied()
|
||||
}
|
||||
pub fn cooccurrences(&self) -> &HashMap<(EventKind, EventKind), u64> { &self.cooccur }
|
||||
pub fn total(&self) -> u64 { self.total }
|
||||
pub fn window_size(&self) -> usize { self.window_size }
|
||||
pub fn current_window(&self) -> usize { self.window.len() }
|
||||
|
||||
/// Últimos N eventos del window, en orden cronológico (más viejo primero).
|
||||
/// Si N > window.len(), devuelve todo el window.
|
||||
pub fn recent(&self, n: usize) -> impl Iterator<Item = &TimedEvent> {
|
||||
let start = self.window.len().saturating_sub(n);
|
||||
self.window.range(start..)
|
||||
}
|
||||
|
||||
pub fn gap_histograms(&self) -> &HashMap<(EventKind, EventKind), GapHistogram> {
|
||||
&self.gap_histograms
|
||||
}
|
||||
|
||||
/// Top-K pares por count del histograma (más frecuentes primero).
|
||||
/// Útil para limitar cardinalidad de métricas exportadas.
|
||||
pub fn top_gap_pairs(&self, k: usize) -> Vec<(&(EventKind, EventKind), &GapHistogram)> {
|
||||
let mut pairs: Vec<_> = self.gap_histograms.iter().collect();
|
||||
pairs.sort_by(|a, b| b.1.count.cmp(&a.1.count));
|
||||
pairs.truncate(k);
|
||||
pairs
|
||||
}
|
||||
|
||||
/// Snapshot full: estado estadístico completo. Limpia los sets dirty
|
||||
/// como side-effect — los próximos `snapshot_delta()` cubren sólo los
|
||||
/// cambios posteriores.
|
||||
pub fn snapshot(&mut self) -> ObserverSnapshot {
|
||||
self.dirty_marginal.clear();
|
||||
self.dirty_cooccur.clear();
|
||||
ObserverSnapshot {
|
||||
schema_version: OBSERVER_SCHEMA_VERSION,
|
||||
is_delta: false,
|
||||
window_size: self.window_size,
|
||||
half_life_secs: self.half_life_secs,
|
||||
total: self.total,
|
||||
marginal: self.marginal.iter()
|
||||
.map(|(k, v)| (k.clone(), *v))
|
||||
.collect(),
|
||||
cooccur: self.cooccur.iter()
|
||||
.map(|((a, b), c)| (a.clone(), b.clone(), *c))
|
||||
.collect(),
|
||||
gap_histograms: self.gap_histograms.iter()
|
||||
.map(|((a, b), h)| (a.clone(), b.clone(), h.clone()))
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Snapshot incremental: sólo incluye los kinds y pares que cambiaron
|
||||
/// desde el último `snapshot()` o `snapshot_delta()`. Útil para
|
||||
/// checkpoints frecuentes con poco overhead. Limpia los sets dirty.
|
||||
pub fn snapshot_delta(&mut self) -> ObserverSnapshot {
|
||||
let marginal: Vec<_> = self.dirty_marginal.iter()
|
||||
.filter_map(|k| self.marginal.get(k).map(|v| (k.clone(), *v)))
|
||||
.collect();
|
||||
let cooccur: Vec<_> = self.dirty_cooccur.iter()
|
||||
.filter_map(|(a, b)| {
|
||||
self.cooccur.get(&(a.clone(), b.clone()))
|
||||
.map(|c| (a.clone(), b.clone(), *c))
|
||||
})
|
||||
.collect();
|
||||
// Para histogramas: incluimos los pares cuyo cooccur cambió.
|
||||
let gap_histograms: Vec<_> = self.dirty_cooccur.iter()
|
||||
.filter_map(|(a, b)| {
|
||||
self.gap_histograms.get(&(a.clone(), b.clone()))
|
||||
.map(|h| (a.clone(), b.clone(), h.clone()))
|
||||
})
|
||||
.collect();
|
||||
self.dirty_marginal.clear();
|
||||
self.dirty_cooccur.clear();
|
||||
ObserverSnapshot {
|
||||
schema_version: OBSERVER_SCHEMA_VERSION,
|
||||
is_delta: true,
|
||||
window_size: self.window_size,
|
||||
half_life_secs: self.half_life_secs,
|
||||
total: self.total,
|
||||
marginal, cooccur, gap_histograms,
|
||||
}
|
||||
}
|
||||
|
||||
/// Aplica un delta sobre el estado actual. Para `is_delta=true`, los
|
||||
/// valores en marginal/cooccur sobrescriben las entradas existentes.
|
||||
/// Si `is_delta=false`, equivale a `from_snapshot` pero in-place.
|
||||
pub fn apply_delta(&mut self, delta: ObserverSnapshot) {
|
||||
let now = Instant::now();
|
||||
if !delta.is_delta {
|
||||
// Full: reset state.
|
||||
*self = Self::from_snapshot(delta);
|
||||
return;
|
||||
}
|
||||
// Incremental merge.
|
||||
for (k, v) in delta.marginal {
|
||||
self.last_seen_marginal.insert(k.clone(), now);
|
||||
self.marginal.insert(k, v);
|
||||
}
|
||||
for (a, b, c) in delta.cooccur {
|
||||
self.last_seen_cooccur.insert((a.clone(), b.clone()), now);
|
||||
self.cooccur.insert((a, b), c);
|
||||
}
|
||||
for (a, b, h) in delta.gap_histograms {
|
||||
self.gap_histograms.insert((a, b), h);
|
||||
}
|
||||
// total: sólo subimos (el delta podría estar atrasado).
|
||||
if delta.total > self.total { self.total = delta.total; }
|
||||
}
|
||||
|
||||
/// Reconstruye Observer desde un snapshot. El window queda vacío;
|
||||
/// last_seen_* se inicializa en `now()` para que el decay arranque
|
||||
/// "ahora" para todos los counts (aproximación razonable post-reboot).
|
||||
pub fn from_snapshot(snap: ObserverSnapshot) -> Self {
|
||||
let now = Instant::now();
|
||||
let mut marginal = HashMap::new();
|
||||
let mut last_seen_marginal = HashMap::new();
|
||||
for (k, v) in snap.marginal {
|
||||
last_seen_marginal.insert(k.clone(), now);
|
||||
marginal.insert(k, v);
|
||||
}
|
||||
let mut cooccur = HashMap::new();
|
||||
let mut last_seen_cooccur = HashMap::new();
|
||||
for (a, b, c) in snap.cooccur {
|
||||
last_seen_cooccur.insert((a.clone(), b.clone()), now);
|
||||
cooccur.insert((a, b), c);
|
||||
}
|
||||
let gap_histograms = snap.gap_histograms.into_iter()
|
||||
.map(|(a, b, h)| ((a, b), h))
|
||||
.collect();
|
||||
Self {
|
||||
window: VecDeque::with_capacity(snap.window_size),
|
||||
window_size: snap.window_size,
|
||||
marginal,
|
||||
cooccur,
|
||||
total: snap.total,
|
||||
last_seen_marginal,
|
||||
last_seen_cooccur,
|
||||
half_life_secs: snap.half_life_secs,
|
||||
gap_histograms,
|
||||
dirty_marginal: std::collections::HashSet::new(),
|
||||
dirty_cooccur: std::collections::HashSet::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const OBSERVER_SCHEMA_VERSION: u16 = 1;
|
||||
|
||||
/// Snapshot serializable. Se persiste a JSON en disco y se restaura al
|
||||
/// reboot para preservar contadores, co-ocurrencias e histogramas.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct ObserverSnapshot {
|
||||
pub schema_version: u16,
|
||||
/// `true` si sólo contiene los cambios desde el último snapshot.
|
||||
/// `false` = full state, sobreescribe el observer al aplicar.
|
||||
#[serde(default)]
|
||||
pub is_delta: bool,
|
||||
pub window_size: usize,
|
||||
pub half_life_secs: Option<f64>,
|
||||
pub total: u64,
|
||||
/// Marginales serializados como Vec porque HashMap<EventKind, _> usa
|
||||
/// EventKind como key — y EventKind tiene variantes con payloads que
|
||||
/// no son JSON-key-serializable (BusInvokeOf, Custom).
|
||||
pub marginal: Vec<(EventKind, u64)>,
|
||||
pub cooccur: Vec<(EventKind, EventKind, u64)>,
|
||||
pub gap_histograms: Vec<(EventKind, EventKind, GapHistogram)>,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::rules::EventKind::*;
|
||||
|
||||
#[test]
|
||||
fn entropy_zero_for_single_event() {
|
||||
let mut obs = Observer::new(10);
|
||||
for _ in 0..5 { obs.record(EnteSpawned); }
|
||||
// Distribución degenerada: una sola observación posible → H = 0.
|
||||
assert!(obs.shannon_entropy() < 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn entropy_one_for_balanced_binary() {
|
||||
let mut obs = Observer::new(100);
|
||||
for _ in 0..10 { obs.record(EnteSpawned); }
|
||||
for _ in 0..10 { obs.record(EnteDied); }
|
||||
// Bernoulli(0.5) → H = 1 bit.
|
||||
assert!((obs.shannon_entropy() - 1.0).abs() < 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn conditional_prob_perfect_dependency() {
|
||||
let mut obs = Observer::new(100);
|
||||
// Spawned siempre seguido por Died.
|
||||
for _ in 0..5 {
|
||||
obs.record(EnteSpawned);
|
||||
obs.record(EnteDied);
|
||||
}
|
||||
let p = obs.conditional_prob(&EnteSpawned, &EnteDied);
|
||||
assert!(p > 0.0, "esperamos correlación positiva, got {p}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
//! Tipos de regla. La fuente de verdad del shape es esta definición Rust;
|
||||
//! `schema/rule.k` queda como referencia de diseño no cargada.
|
||||
//!
|
||||
//! Cargables desde JSON (array, objeto-con-array, o JSONL). El motor no
|
||||
//! acepta Rules construidas a mano sin pasar por validate() — ver
|
||||
//! `engine::insert`.
|
||||
|
||||
use ente_card::Capability;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use ulid::Ulid;
|
||||
|
||||
/// Triplet [Sujeto + Evento + Acción]. Inmutable tras carga.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct Rule {
|
||||
pub id: Ulid,
|
||||
#[serde(default = "default_priority")]
|
||||
pub priority: u8,
|
||||
pub when: EventPattern,
|
||||
pub then: Vec<Action>,
|
||||
#[serde(default)]
|
||||
pub scope: Scope,
|
||||
}
|
||||
|
||||
fn default_priority() -> u8 { 5 }
|
||||
|
||||
impl Rule {
|
||||
pub fn validate(&self) -> Result<(), RuleError> {
|
||||
if self.then.is_empty() {
|
||||
return Err(RuleError::EmptyActions);
|
||||
}
|
||||
self.when.validate_recursive()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum RuleError {
|
||||
EmptyActions,
|
||||
EmptySequence,
|
||||
EmptyCompound,
|
||||
InvalidPriority,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for RuleError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Self::EmptyActions => write!(f, "regla sin acciones"),
|
||||
Self::EmptySequence => write!(f, "Sequence pattern con kinds vacío"),
|
||||
Self::EmptyCompound => write!(f, "Either/All con patterns vacío"),
|
||||
Self::InvalidPriority => write!(f, "prioridad fuera de rango"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for RuleError {}
|
||||
|
||||
/// Match del sujeto. Vacío en todos los campos = match cualquier Ente.
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
||||
pub struct Scope {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub subject_id: Option<Ulid>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub subject_label: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub subject_has_cap: Option<Capability>,
|
||||
}
|
||||
|
||||
impl Scope {
|
||||
pub fn is_wildcard(&self) -> bool {
|
||||
self.subject_id.is_none()
|
||||
&& self.subject_label.is_none()
|
||||
&& self.subject_has_cap.is_none()
|
||||
}
|
||||
}
|
||||
|
||||
/// Patrón de evento que dispara una regla. Tagged union — JSON con campo
|
||||
/// `type`. Soporta composición recursiva (Either/All) sobre Single y
|
||||
/// Sequence atómicos.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
|
||||
#[serde(tag = "type")]
|
||||
pub enum EventPattern {
|
||||
/// Match un único evento por kind.
|
||||
Single { kind: EventKind },
|
||||
/// Match si los últimos N eventos del history coinciden en orden con
|
||||
/// `kinds`, todos dentro de `within_ms` (0 = sin límite temporal).
|
||||
Sequence {
|
||||
kinds: Vec<EventKind>,
|
||||
#[serde(default)]
|
||||
within_ms: u64,
|
||||
},
|
||||
/// OR: match si cualquier sub-pattern matchea.
|
||||
Either { patterns: Vec<EventPattern> },
|
||||
/// AND: match si todos los sub-patterns matchean simultáneamente
|
||||
/// contra el mismo (event, history).
|
||||
All { patterns: Vec<EventPattern> },
|
||||
}
|
||||
|
||||
impl EventPattern {
|
||||
/// `true` si el pattern es atómico (no recursivo) y puede ser indexado
|
||||
/// por discriminante de `EventKind` para dispatch O(1). Compuestos
|
||||
/// (Either/All) se evalúan en un bucket de fallback.
|
||||
pub fn is_simple(&self) -> bool {
|
||||
matches!(self, Self::Single { .. } | Self::Sequence { .. })
|
||||
}
|
||||
|
||||
/// Última `EventKind` que dispara la evaluación de un pattern atómico.
|
||||
/// Devuelve None para compuestos.
|
||||
pub fn trigger_kind(&self) -> Option<&EventKind> {
|
||||
match self {
|
||||
Self::Single { kind } => Some(kind),
|
||||
Self::Sequence { kinds, .. } => kinds.last(),
|
||||
Self::Either { .. } | Self::All { .. } => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Validación recursiva. Compuestos vacíos se rechazan al cargar.
|
||||
pub fn validate_recursive(&self) -> Result<(), RuleError> {
|
||||
match self {
|
||||
Self::Single { .. } => Ok(()),
|
||||
Self::Sequence { kinds, .. } => {
|
||||
if kinds.is_empty() { Err(RuleError::EmptySequence) } else { Ok(()) }
|
||||
}
|
||||
Self::Either { patterns } | Self::All { patterns } => {
|
||||
if patterns.is_empty() {
|
||||
return Err(RuleError::EmptyCompound);
|
||||
}
|
||||
for p in patterns { p.validate_recursive()?; }
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Tipo de evento que dispara reglas. Indexado por discriminante en el motor.
|
||||
/// Diseñado para que `EventKindDiscriminant::from(&kind)` sea barato (no hash
|
||||
/// del payload, sólo del tag).
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
|
||||
pub enum EventKind {
|
||||
EnteSpawned,
|
||||
EnteDied,
|
||||
BusAnnounce,
|
||||
BusInvoke,
|
||||
BusInvokeOf(Capability),
|
||||
DeviceAdded,
|
||||
DeviceRemoved,
|
||||
Custom(String),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum LogLevel { Trace, Debug, Info, Warn, Error }
|
||||
|
||||
impl LogLevel {
|
||||
pub fn as_str(&self) -> &'static str {
|
||||
match self {
|
||||
Self::Trace => "trace",
|
||||
Self::Debug => "debug",
|
||||
Self::Info => "info",
|
||||
Self::Warn => "warn",
|
||||
Self::Error => "error",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(tag = "kind", rename_all = "PascalCase")]
|
||||
pub enum Action {
|
||||
Log {
|
||||
#[serde(default = "default_log_level")]
|
||||
level: LogLevel,
|
||||
message: String,
|
||||
},
|
||||
Notify {
|
||||
target_id: Ulid,
|
||||
message: String,
|
||||
},
|
||||
/// `card_blob` es JSON del EntityCard codificado en base64. El motor lo
|
||||
/// decodifica y forwarda como SpawnRequest al graph.
|
||||
Spawn {
|
||||
card_blob: String,
|
||||
},
|
||||
Invoke {
|
||||
target_cap: Capability,
|
||||
/// blob crudo (en JSON viaja como base64 vía `blob_b64`).
|
||||
#[serde(with = "blob_b64")]
|
||||
blob: Vec<u8>,
|
||||
},
|
||||
Inhibit {
|
||||
reason: String,
|
||||
},
|
||||
}
|
||||
|
||||
fn default_log_level() -> LogLevel { LogLevel::Info }
|
||||
|
||||
mod blob_b64 {
|
||||
use base64::{engine::general_purpose::STANDARD, Engine};
|
||||
use serde::{Deserialize, Deserializer, Serializer};
|
||||
|
||||
pub fn serialize<S: Serializer>(bytes: &[u8], s: S) -> Result<S::Ok, S::Error> {
|
||||
s.serialize_str(&STANDARD.encode(bytes))
|
||||
}
|
||||
|
||||
pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Vec<u8>, D::Error> {
|
||||
let s = String::deserialize(d)?;
|
||||
STANDARD.decode(&s).map_err(serde::de::Error::custom)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user