Pausa: 11 crates del fractal Ente #0 con cerebro completo

PID 1 boot + bus interno autenticado + cerebro KCL/Rust:
- 6 lib crates de infra (card, bus, cas, kernel, soma, wasm, snapshot)
- ente-brain: motor de reglas O(1), observer Shannon, cristalización,
  audit hash-chain, persistencia rules.k, Prometheus /metrics
- KCL schemas card.k + rule.k como gramática autoritativa
- compat-logind D-Bus, ente-echo demo provider, ente-zero PID 1
- 22 tests OK, ~3.8k LOC Rust + ~300 LOC KCL

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Sergio
2026-05-03 22:57:44 +00:00
parent dc9c99528d
commit d6b8f18b43
53 changed files with 7753 additions and 0 deletions
+23
View File
@@ -0,0 +1,23 @@
[package]
name = "ente-brain"
version = "0.0.1"
edition.workspace = true
license.workspace = true
publish.workspace = true
[dependencies]
ente-card = { path = "../ente-card" }
ente-cas = { path = "../ente-cas" }
serde = { workspace = true }
serde_json = { workspace = true }
ulid = { workspace = true }
tokio = { workspace = true }
bincode = { workspace = true }
base64 = { workspace = true }
postcard = { workspace = true }
anyhow = { workspace = true }
tracing = { workspace = true }
[[example]]
name = "brainctl"
path = "examples/brainctl.rs"
+125
View File
@@ -0,0 +1,125 @@
//! brainctl: cliente CLI del introspect API.
//!
//! Uso:
//! cargo run --example brainctl -p ente-brain -- list-rules
//! cargo run --example brainctl -p ente-brain -- entropy
//! cargo run --example brainctl -p ente-brain -- top 10
//! cargo run --example brainctl -p ente-brain -- crystals
//! cargo run --example brainctl -p ente-brain -- crystal-kcl 0
//!
//! Path del socket: $ENTE_BRAIN_SOCK o $XDG_RUNTIME_DIR/ente-brain.sock
use ente_brain::introspect::{call, IntrospectRequest, IntrospectResponse};
use std::path::PathBuf;
fn socket_path() -> PathBuf {
if let Ok(p) = std::env::var("ENTE_BRAIN_SOCK") {
return p.into();
}
let runtime = std::env::var("XDG_RUNTIME_DIR")
.unwrap_or_else(|_| std::env::var("TMPDIR").unwrap_or_else(|_| "/tmp".into()));
format!("{runtime}/ente-brain.sock").into()
}
#[tokio::main(flavor = "current_thread")]
async fn main() -> anyhow::Result<()> {
let args: Vec<String> = std::env::args().collect();
let cmd = args.get(1).map(|s| s.as_str()).unwrap_or("entropy");
let req = match cmd {
"list-rules" | "rules" => IntrospectRequest::ListRules,
"entropy" => IntrospectRequest::EntropySnapshot,
"top" => {
let n: usize = args.get(2).and_then(|s| s.parse().ok()).unwrap_or(10);
IntrospectRequest::TopCorrelations { n }
}
"crystals" => IntrospectRequest::Crystals,
"crystal-kcl" => {
let i: usize = args.get(2).and_then(|s| s.parse().ok()).unwrap_or(0);
IntrospectRequest::CrystalKcl { index: i }
}
"promote" => {
let i: usize = args.get(2).and_then(|s| s.parse().ok()).unwrap_or(0);
IntrospectRequest::PromoteCrystal { index: i }
}
"remove" => {
let id_s = args.get(2).ok_or_else(|| anyhow::anyhow!("se requiere <ulid>"))?;
let id: ulid::Ulid = id_s.parse()?;
IntrospectRequest::RemoveRule { id }
}
"audit" => {
let limit: usize = args.get(2).and_then(|s| s.parse().ok()).unwrap_or(20);
IntrospectRequest::ListAudit { limit }
}
other => {
eprintln!("subcomando desconocido: {other}");
eprintln!("válidos: list-rules | entropy | top <n> | crystals | crystal-kcl <i> | promote <i> | remove <ulid> | audit <limit>");
std::process::exit(2);
}
};
let path = socket_path();
let resp = call(&path, req).await?;
print_response(&resp);
Ok(())
}
fn print_response(r: &IntrospectResponse) {
match r {
IntrospectResponse::Rules(rs) => {
println!("{} reglas vivas:", rs.len());
for r in rs {
println!(" {} prio={} kind={} actions={} wildcard={}",
r.id, r.priority, r.event_kind_tag, r.action_count, r.scope_wildcard);
}
}
IntrospectResponse::Rule(rule) => match rule {
Some(r) => println!("{r:#?}"),
None => println!("regla no encontrada"),
},
IntrospectResponse::Entropy { value_bits, sample_size, distinct_kinds, window_full } => {
println!("Shannon entropy : {value_bits:.4} bits");
println!("Sample size : {sample_size}");
println!("Distinct kinds : {distinct_kinds}");
println!("Window full : {window_full}");
}
IntrospectResponse::Correlations(entries) => {
println!("{} pares (top, ordenado por co-ocurrencia):", entries.len());
for e in entries {
println!(" n={:>4} P(b|a)={:.3} PMI={:>6.3}b {}{}",
e.joint_count, e.conditional_prob, e.pmi_bits, e.a, e.b);
}
}
IntrospectResponse::Crystals(cs) => {
println!("{} cristales detectados:", cs.len());
for (i, c) in cs.iter().enumerate() {
println!(" [{i}] {:?}{:?} P={:.3} PMI={:.3}b n={}",
c.antecedent, c.consequent, c.conditional_prob, c.pmi, c.support);
}
}
IntrospectResponse::Kcl(s) => println!("{s}"),
IntrospectResponse::Promoted { rule_id, kcl_snippet } => {
println!("regla creada: {rule_id}");
println!("--- KCL para auditoría / persistencia ---");
println!("{kcl_snippet}");
}
IntrospectResponse::Removed(was_present) => {
if *was_present { println!("regla eliminada"); }
else { println!("regla no encontrada"); }
}
IntrospectResponse::AuditEntries(entries) => {
println!("{} entries de audit log:", entries.len());
for e in entries {
let prev = e.prev_sha.map(hex_short).unwrap_or_else(|| "".into());
let sha = hex_short(e.sha);
println!(" seq={:>4} t={} prev={} sha={} {:?}",
e.seq, e.timestamp_ms, prev, sha, e.action);
}
}
IntrospectResponse::Error(e) => eprintln!("error: {e}"),
}
}
fn hex_short(sha: [u8; 32]) -> String {
sha[..4].iter().map(|b| format!("{:02x}", b)).collect::<String>() + ".."
}
+159
View File
@@ -0,0 +1,159 @@
# ============================================================================
# rule.k — Triplet [Sujeto + Evento + Acción(Objeto)]. La gramática del
# Cerebro del fractal. Cada regla es una sinapsis: cuando ocurre `when`,
# el motor ejecuta `then` para todos los Entes que cumplen `scope`.
#
# El motor en Rust las indexa por discriminante de EventKind para lookup
# en O(1). Las reglas son inmutables tras carga (Arc<Rule>).
# ============================================================================
schema Rule:
"""Una sinapsis del fractal. Determinista, sin estado entre disparos."""
id: str # Ulid 26 chars
priority: int = 5 # 0..255, mayor = se ejecuta primero
when: EventPattern
then: [Action]
scope: Scope = Scope {} # qué Entes son sujetos válidos
check:
len(id) == 26, "id debe ser Ulid"
priority >= 0 and priority <= 255, "priority fuera de rango"
len(then) > 0, "regla sin acciones"
# ---------- Subject: alcance del sujeto ----------
schema Scope:
"""Match del sujeto. None en todos los campos = match cualquier Ente."""
subject_id?: str # Ulid exacto
subject_label?: str # label exacto
subject_has_cap?: Capability # Ente que declara esta capacidad
check:
subject_id is None or len(subject_id) == 26, "subject_id no es Ulid"
# ---------- Event: qué dispara la regla ----------
# EventPattern es tagged union recursivo.
#
# Atómicos:
# Single — match un evento por kind
# Sequence — N eventos consecutivos dentro de within_ms
#
# Compuestos (recursivos):
# Either — OR sobre sub-patterns
# All — AND sobre sub-patterns (mismo event/history)
schema EventPattern:
type: "Single" | "Sequence" | "Either" | "All"
kind?: EventKind # Single
kinds?: [EventKind] # Sequence
within_ms?: int = 0
patterns?: [EventPattern] # Either / All (recursivo)
check:
type != "Single" or kind is not None, "Single requiere kind"
type != "Sequence" or (kinds is not None and len(kinds) > 0), \
"Sequence requiere kinds no vacío"
type != "Either" or (patterns is not None and len(patterns) > 0), \
"Either requiere patterns no vacío"
type != "All" or (patterns is not None and len(patterns) > 0), \
"All requiere patterns no vacío"
within_ms is None or within_ms >= 0, "within_ms negativo"
# EventKind con tag interno + payload opcional según tag.
schema EventKind:
tag: "EnteSpawned" | "EnteDied" | "BusAnnounce" | "BusInvoke" | "BusInvokeOf" | "DeviceAdded" | "DeviceRemoved" | "Custom"
cap?: Capability # para BusInvokeOf
custom?: str # para Custom
check:
tag != "BusInvokeOf" or cap is not None, "BusInvokeOf requiere cap"
tag != "Custom" or custom is not None, "Custom requiere custom string"
# ---------- Action: qué hacer ----------
schema Action:
"""Una acción ejecutable por el motor. Tagged union con kind."""
kind: "Log" | "Notify" | "Spawn" | "Invoke" | "Inhibit"
# Log
level?: "trace" | "debug" | "info" | "warn" | "error"
message?: str
# Notify
target_id?: str # Ulid
# Spawn
card_blob?: str # base64-encoded EntityCard JSON
# Invoke
target_cap?: Capability
blob_b64?: str
# Inhibit
reason?: str
check:
kind != "Log" or message is not None, "Log requiere message"
kind != "Notify" or (target_id is not None and message is not None), \
"Notify requiere target_id + message"
kind != "Spawn" or card_blob is not None, "Spawn requiere card_blob"
kind != "Invoke" or target_cap is not None, "Invoke requiere target_cap"
kind != "Inhibit" or reason is not None, "Inhibit requiere reason"
# ---------- Capability: re-export desde card.k para evitar inclusión circular ----------
# En uso real: `import ..ente_card.schema.card` y referencia Capability.
# Aquí declaramos una versión alineada para auto-contención del esquema.
schema Capability:
kind: "FilesystemRoot" | "KernelNetlink" | "Endpoint" | "LegacyLogind" | "Device" | "Spawn" | "Journal"
netlink_family?: "Uevent" | "Route" | "Generic" | "Audit"
endpoint_interface?: str
endpoint_version?: int
device_class?: "Block" | "Tty" | "Input" | "Drm" | "Net" | "Hidraw"
# ============================================================================
# Ejemplo de regla cristalizada (auto-generada por el observador)
# ============================================================================
example_rule = Rule {
id = "01KQQ100000000000000000000"
priority = 5
when = EventPattern {
type = "Single"
kind = EventKind {tag = "EnteSpawned"}
}
scope = Scope {
subject_label = "demo-echo"
}
then = [
Action {
kind = "Log"
level = "info"
message = "demo-echo encarnado, observando para crystallization"
}
]
}
# Ejemplo de regla compuesta: cuando un Ente se anuncia y luego es invocado
# en menos de 500ms, log estructurado para auditoría.
example_sequence = Rule {
id = "01KQQ200000000000000000000"
priority = 7
when = EventPattern {
type = "Sequence"
kinds = [
EventKind {tag = "BusAnnounce"}
EventKind {tag = "BusInvoke"}
]
within_ms = 500
}
scope = Scope {}
then = [
Action {
kind = "Log"
level = "info"
message = "patrón Announce→Invoke detectado <500ms"
}
]
}
+154
View File
@@ -0,0 +1,154 @@
//! 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,
}
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 }
}
/// 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());
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)
}
}
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 serializado, EXCLUYENDO el campo sha mismo
/// (que está en cero al momento del cálculo). Determinístico vía postcard
/// para que la verificación sea reproducible.
fn compute_sha(entry: &AuditEntry) -> [u8; 32] {
let bytes = postcard_or_json(entry);
ente_cas::sha256_of(&bytes)
}
fn postcard_or_json(entry: &AuditEntry) -> Vec<u8> {
// Preferimos postcard por estabilidad bit-a-bit. Fallback JSON si falla.
match postcard::to_stdvec(entry) {
Ok(b) => b,
Err(_) => serde_json::to_vec(entry).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);
}
}
+169
View File
@@ -0,0 +1,169 @@
//! 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 puede emitirse como snippet KCL (texto humano-readable) o
//! como `Rule` ejecutable directamente por el motor.
use crate::observer::Observer;
use crate::rules::{Action, EventKind, EventPattern, LogLevel, Rule, Scope};
use serde::{Deserialize, Serialize};
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,
}
#[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; }
out.push(Crystal {
antecedent: a.clone(),
consequent: b.clone(),
conditional_prob: cp,
pmi: mi,
support: count,
});
}
// Orden estable: por confianza descendente para fácil inspección.
out.sort_by(|x, y| y.conditional_prob.partial_cmp(&x.conditional_prob).unwrap_or(std::cmp::Ordering::Equal));
out
}
/// Genera un snippet KCL representando la regla cristalizada. El snippet usa
/// la sintaxis tagged union del schema `rule.k` (Single + EventKind nested).
pub fn crystal_to_kcl(c: &Crystal) -> String {
let id = Ulid::new();
format!(
r#"# Auto-cristalizado:
# antecedent → consequent | P(c|a) = {cp:.3}, PMI = {pmi:.3} bits, support = {sup}
Rule {{
id = "{id}"
priority = 5
when = EventPattern {{
type = "Single"
kind = EventKind {{tag = "{ant_tag}"{ant_extra}}}
}}
scope = Scope {{}}
then = [
Action {{
kind = "Log"
level = "info"
message = "crystal: {ant_tag} → {con_tag} (auto, P={cp:.2}, PMI={pmi:.2})"
}}
]
}}
"#,
id = id,
cp = c.conditional_prob,
pmi = c.pmi,
sup = c.support,
ant_tag = kind_tag(&c.antecedent),
ant_extra = kind_extra(&c.antecedent),
con_tag = kind_tag(&c.consequent),
)
}
fn kind_tag(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",
}
}
fn kind_extra(k: &EventKind) -> String {
match k {
EventKind::Custom(s) => format!(", custom = \"{}\"", s.replace('"', "\\\"")),
// Para BusInvokeOf el cap se omitiría por simplicidad; el snippet
// promovido es la versión "genérica BusInvoke" salvo que el operador
// edite manualmente.
_ => String::new(),
}
}
/// Convierte un cristal a una `Rule` ejecutable por el motor. Útil para
/// "auto-aprendizaje" donde cristales se promueven a reglas vivas tras
/// validar con el operador.
pub fn crystal_to_rule(c: &Crystal) -> Rule {
Rule {
id: Ulid::new(),
priority: 5,
when: EventPattern::Single { kind: c.antecedent.clone() },
scope: Scope::default(),
then: vec![Action::Log {
level: LogLevel::Info,
message: format!(
"crystal: {:?} → {:?} (P={:.2}, PMI={:.2}, n={})",
c.antecedent, c.consequent, c.conditional_prob, c.pmi, c.support
),
}],
}
}
#[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);
}
}
+73
View File
@@ -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),
}
}
+399
View File
@@ -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). Usado tras validación KCL.
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());
}
}
+330
View File
@@ -0,0 +1,330 @@
//! 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 como KCL. Si Some,
/// cada PromoteCrystal añade el snippet al archivo (append-only).
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 del KCL snippet a `rules_out`. Crea el archivo con
/// header si no existe; en caso contrario sólo apendea.
pub fn append_kcl_snippet(path: &Path, snippet: &str) -> std::io::Result<()> {
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)?;
}
let exists = path.exists();
let mut file = std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(path)?;
if !exists {
writeln!(file, "# Reglas promovidas automáticamente desde cristales.")?;
writeln!(file, "# Cada bloque proviene de PromoteCrystal vía brainctl.")?;
writeln!(file)?;
}
writeln!(file, "{snippet}")?;
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,
/// Genera el snippet KCL de un cristal específico (índice tras Crystals).
CrystalKcl { index: usize },
/// Promueve el cristal #index a regla viva en el motor. Devuelve el
/// rule_id asignado y el snippet KCL 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 },
}
#[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>),
Kcl(String),
/// Resultado de PromoteCrystal: id de la regla creada + snippet KCL para
/// que el operador lo persista en disco si quiere.
Promoted { rule_id: Ulid, kcl_snippet: 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>),
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");
let resp = self.dispatch(req).await;
let out = bincode::serialize(&resp)?;
stream.write_u32(out.len() as u32).await?;
stream.write_all(&out).await?;
}
}
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::CrystalKcl { index } => {
let obs = self.state.observer.read().await;
let crystals = detect_crystals(&obs, &self.state.params);
match crystals.get(index) {
Some(c) => IntrospectResponse::Kcl(crate::crystallize::crystal_to_kcl(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 snippet = crate::crystallize::crystal_to_kcl(c);
let rule_id = rule.id;
self.state.engine.write().await.insert(rule);
// Persistencia opcional al archivo KCL.
if let Some(path) = self.state.rules_out.as_ref() {
if let Err(e) = append_kcl_snippet(path, &snippet) {
warn!(?e, path = %path.display(), "rules_out append falló");
} else {
info!(path = %path.display(), %rule_id, "regla persistida a .k");
}
}
// Audit entry
self.state.audit.write().await.append(
crate::audit::AuditAction::PromoteCrystal {
rule_id, crystal: c.clone(),
}
);
IntrospectResponse::Promoted { rule_id, kcl_snippet: snippet }
}
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())
}
}
}
}
// 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
}
+135
View File
@@ -0,0 +1,135 @@
//! Loader de reglas desde archivos `.k` vía subprocess al CLI de KCL.
//!
//! No usamos el SDK Rust de KCL para no arrastrar la dependencia de Go runtime
//! ni cgo. El CLI `kcl` produce JSON validado contra el schema declarado
//! en el propio `.k` — equivalente funcional al SDK con coste cero de compile.
//!
//! Si `kcl` no está en PATH, el caller decide: cargar JSON crudo (skip KCL),
//! o fallar el boot.
//!
//! ## Formato esperado del .k file
//!
//! ```kcl
//! import .rule # schema/rule.k
//!
//! rules: [Rule] = [
//! Rule { id = "...", priority = 5, when = ..., then = [...] },
//! ...
//! ]
//! ```
//!
//! Salida tras `kcl run --format json`: `{"rules": [...]}`. El loader busca
//! la primera array en el JSON (top-level o anidada un nivel) y la deserializa.
use crate::rules::Rule;
use ente_card::EntityCard;
use std::path::Path;
use std::process::Command;
use tracing::{debug, info};
/// Detecta si `kcl` está disponible en PATH. Útil para degradar a JSON-only
/// en entornos sin la toolchain.
pub fn kcl_available() -> bool {
Command::new("kcl")
.arg("version")
.output()
.map(|o| o.status.success())
.unwrap_or(false)
}
/// Ejecuta `kcl run <path> --format=json` y devuelve el JSON crudo.
pub fn run_kcl(path: &Path) -> anyhow::Result<String> {
let output = Command::new("kcl")
.arg("run")
.arg(path)
.arg("--format=json")
.output()
.map_err(|e| anyhow::anyhow!("invocando `kcl`: {e}. ¿Instalado en PATH?"))?;
if !output.status.success() {
anyhow::bail!(
"kcl run {} falló: {}",
path.display(),
String::from_utf8_lossy(&output.stderr)
);
}
debug!(path = %path.display(), out_bytes = output.stdout.len(), "kcl run ok");
Ok(String::from_utf8(output.stdout)?)
}
/// Carga reglas desde un archivo `.k` o JSON. Discrimina por extensión:
/// `.k` → invoca KCL, `.json` → directo.
pub fn load_rules_file(path: &Path) -> anyhow::Result<Vec<Rule>> {
let raw = match path.extension().and_then(|e| e.to_str()) {
Some("k") => {
info!(path = %path.display(), "cargando reglas vía kcl");
run_kcl(path)?
}
_ => {
info!(path = %path.display(), "cargando reglas como JSON crudo");
std::fs::read_to_string(path)?
}
};
extract_rules_from_json(&raw)
}
/// Extrae un `Vec<Rule>` de JSON que puede ser:
/// 1. Array directo: `[{...}, {...}]`
/// 2. Object con un campo array: `{"rules": [...]}`
pub fn extract_rules_from_json(raw: &str) -> anyhow::Result<Vec<Rule>> {
let v: serde_json::Value = serde_json::from_str(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"),
};
let rules: Vec<Rule> = serde_json::from_value(arr)?;
Ok(rules)
}
// ============================================================================
// Carga de Cards desde KCL/JSON. Cierra la "puerta genética": ninguna Card
// se acepta sin pasar `validate()` extendido en ente-card.
// ============================================================================
/// Carga una `EntityCard` desde un archivo `.k` (vía kcl run) o `.json`.
/// Pasa por `EntityCard::validate()` antes de devolver — falla rápida.
pub fn load_card_file(path: &Path) -> anyhow::Result<EntityCard> {
let raw = match path.extension().and_then(|e| e.to_str()) {
Some("k") => {
info!(path = %path.display(), "cargando Card vía kcl");
run_kcl(path)?
}
_ => {
info!(path = %path.display(), "cargando Card como JSON crudo");
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 (KCL output típico)
pub fn extract_card_from_json(raw: &str) -> anyhow::Result<EntityCard> {
let v: serde_json::Value = serde_json::from_str(raw)?;
// Intento 1: deserializar el value directamente.
if let Ok(c) = serde_json::from_value::<EntityCard>(v.clone()) {
return Ok(c);
}
// Intento 2: si es dict, buscar el primer value que parsee como Card.
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);
}
}
}
anyhow::bail!("JSON no contiene una EntityCard válida")
}
+36
View File
@@ -0,0 +1,36 @@
//! 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 generación de snippets KCL
//! 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 crystallize;
pub mod dispatch;
pub mod engine;
pub mod introspect;
pub mod kcl_loader;
pub mod metrics;
pub mod observer;
pub mod rules;
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 kcl_loader::{kcl_available, 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};
+119
View File
@@ -0,0 +1,119 @@
//! 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 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()));
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",
}
}
+167
View File
@@ -0,0 +1,167 @@
//! 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,
}
pub struct Observer {
window: VecDeque<TimedEvent>,
window_size: usize,
marginal: HashMap<EventKind, u64>,
cooccur: HashMap<(EventKind, EventKind), u64>,
total: u64,
}
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,
}
}
/// 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.
for w in &self.window {
*self.cooccur
.entry((w.kind.clone(), kind.clone()))
.or_insert(0) += 1;
}
self.window.push_back(timed);
if self.window.len() > self.window_size {
self.window.pop_front();
}
*self.marginal.entry(kind).or_insert(0) += 1;
self.total += 1;
}
/// 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(a, b) / Σ_x cooccur(a, x). Esto da una
/// probabilidad condicional propia [0, 1].
pub fn conditional_prob(&self, a: &EventKind, b: &EventKind) -> f64 {
let joint = self.cooccur
.get(&(a.clone(), b.clone()))
.copied()
.unwrap_or(0) as f64;
let row_total: u64 = self.cooccur.iter()
.filter_map(|((x, _), c)| if x == a { Some(*c) } else { None })
.sum();
if row_total == 0 { 0.0 } else { joint / row_total as f64 }
}
/// Información mutua puntual entre `a` y `b`:
/// 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 {
if self.total == 0 { return 0.0; }
let total = self.total as f64;
let joint = self.cooccur
.get(&(a.clone(), b.clone()))
.copied()
.unwrap_or(0) as f64 / total;
let pa = self.marginal.get(a).copied().unwrap_or(0) as f64 / total;
let pb = self.marginal.get(b).copied().unwrap_or(0) as f64 / total;
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 }
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..)
}
}
#[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}");
}
}
+204
View File
@@ -0,0 +1,204 @@
//! Tipos de regla. Equivalente Rust de `schema/rule.k`.
//!
//! Cargables desde JSON (que KCL produce tras validación). 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 (base64 si viene de KCL, bytes ya en Rust).
#[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)
}
}