refactor(brain): A2 — split arje-brain en 3 sub-crates

DAG de dependencias limpio (modularidad horizontal):
- arje-brain-rules     — rules + engine + dispatch (motor determinista)
- arje-brain-cognitive — observer + crystallize (estadística)
- arje-brain-audit     — audit chain → CAS (accountability)
- arje-brain           — umbrella de integración (introspect +
                         autopromote + metrics + loader)

Habilitador clave: TimedEvent movido de observer.rs a rules.rs
(engine lo necesitaba, era el único acoplo que rompía el DAG).

arje-brain re-exporta la API de los 3 sub-crates: arje-zero y chasqui
(consumidores) no requieren cambios. cargo check --workspace verde.
24 tests del brain pasan (4 rules + 6 cognitive + 5 audit + 9 umbrella).

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
sergio
2026-05-20 00:24:48 +00:00
parent b83d40a833
commit 848fc7a072
21 changed files with 221 additions and 89 deletions
@@ -0,0 +1,16 @@
[package]
name = "arje-brain-rules"
version = "0.0.1"
edition.workspace = true
license.workspace = true
publish.workspace = true
description = "Motor de reglas determinista: triplets Subject+Event+Action, RuleEngine O(1), dispatch async."
[dependencies]
arje-card = { path = "../../protocol/arje-card" }
serde = { workspace = true }
serde_json = { workspace = true }
ulid = { workspace = true }
tracing = { workspace = true }
anyhow = { workspace = true }
base64 = { workspace = true }
@@ -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: arje_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: arje_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::rules::TimedEvent;
use crate::rules::{EventKind, EventPattern, Rule, Scope};
use arje_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,13 @@
//! arje-brain-rules — motor de reglas determinista.
//!
//! Capa base del brain: tipos de regla (triplet Subject+Event+Action),
//! `RuleEngine` con dispatch O(1) por discriminante de evento, y el
//! ejecutor async de acciones. Sin dependencias estadísticas ni de UI.
pub mod rules;
pub mod engine;
pub mod dispatch;
pub use rules::{Action, EventKind, EventPattern, LogLevel, Rule, Scope, TimedEvent};
pub use engine::{EventKindDiscriminant, RuleEngine, SubjectInfo};
pub use dispatch::{dispatch_actions, ActionSink, NullSink};
@@ -0,0 +1,216 @@
//! 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 arje_card::Capability;
use serde::{Deserialize, Serialize};
use std::time::Instant;
use ulid::Ulid;
/// Evento timestamped. El timestamp se conserva para futuras políticas de
/// expiración por tiempo (no sólo por count). Tipo base compartido entre
/// el motor de reglas (`engine`) y el observador estadístico (`cognitive`).
#[derive(Debug, Clone)]
pub struct TimedEvent {
pub kind: EventKind,
pub at: Instant,
}
/// 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)
}
}