Coverage for little_loops / events.py: 94%
65 statements
« prev ^ index » next coverage.py v7.12.0, created at 2026-04-02 13:00 -0500
« prev ^ index » next coverage.py v7.12.0, created at 2026-04-02 13:00 -0500
1"""Event system for little-loops extension architecture.
3Provides structured event types and a multi-observer event bus that extensions
4can subscribe to for receiving lifecycle events from FSM loops, issue management,
5and automation workflows.
7Public exports:
8 LLEvent: Structured event dataclass with type, timestamp, and payload
9 EventBus: Multi-observer event dispatcher with optional JSONL file sink
10"""
12from __future__ import annotations
14import json
15import logging
16from collections.abc import Callable
17from dataclasses import dataclass, field
18from pathlib import Path
19from typing import Any
21logger = logging.getLogger(__name__)
23# Type for event callback (matches existing EventCallback in fsm/executor.py)
24EventCallback = Callable[[dict[str, Any]], None]
27@dataclass
28class LLEvent:
29 """Structured event emitted by little-loops subsystems.
31 Attributes:
32 type: Event type identifier (e.g. "fsm.state_enter", "fsm.loop_complete")
33 timestamp: ISO 8601 timestamp string
34 payload: Type-specific event data
35 """
37 type: str
38 timestamp: str
39 payload: dict[str, Any] = field(default_factory=dict)
41 def to_dict(self) -> dict[str, Any]:
42 """Convert to dictionary for JSON serialization.
44 Produces a flat dict compatible with the existing FSM event format:
45 {"event": type, "ts": timestamp, ...payload}
46 """
47 return {"event": self.type, "ts": self.timestamp, **self.payload}
49 @classmethod
50 def from_dict(cls, data: dict[str, Any]) -> LLEvent:
51 """Create from dictionary (JSON deserialization).
53 Accepts the flat dict format: {"event": ..., "ts": ..., ...payload}
54 """
55 copy = dict(data)
56 event_type = copy.pop("event", copy.pop("type", "unknown"))
57 ts = copy.pop("ts", copy.pop("timestamp", ""))
58 return cls(type=event_type, timestamp=ts, payload=copy)
60 @classmethod
61 def from_raw_event(cls, raw: dict[str, Any]) -> LLEvent:
62 """Convert existing executor event dict to LLEvent without mutating the original."""
63 return cls.from_dict(dict(raw))
66class EventBus:
67 """Multi-observer event dispatcher.
69 Dispatches event dicts to all registered observers. Exceptions in individual
70 observers are caught and logged, not propagated.
71 """
73 def __init__(self) -> None:
74 self._observers: list[EventCallback] = []
75 self._file_sinks: list[Path] = []
77 def register(self, callback: EventCallback) -> None:
78 """Register an observer to receive events."""
79 self._observers.append(callback)
81 def unregister(self, callback: EventCallback) -> None:
82 """Remove an observer. No-op if not registered."""
83 try:
84 self._observers.remove(callback)
85 except ValueError:
86 pass
88 def add_file_sink(self, path: Path) -> None:
89 """Add a JSONL file sink. Events will be appended to this file."""
90 path.parent.mkdir(parents=True, exist_ok=True)
91 self._file_sinks.append(path)
93 def emit(self, event: dict[str, Any]) -> None:
94 """Dispatch event to all observers and file sinks.
96 Observer exceptions are caught and logged to prevent one observer
97 from blocking others.
98 """
99 for observer in self._observers:
100 try:
101 observer(event)
102 except Exception:
103 logger.warning("EventBus observer raised an exception", exc_info=True)
105 for sink_path in self._file_sinks:
106 try:
107 with open(sink_path, "a", encoding="utf-8") as f:
108 f.write(json.dumps(event) + "\n")
109 except Exception:
110 logger.warning("EventBus file sink write failed: %s", sink_path, exc_info=True)
112 @staticmethod
113 def read_events(path: Path) -> list[LLEvent]:
114 """Read events from a JSONL file.
116 Returns:
117 List of LLEvent instances, empty if file doesn't exist.
118 Malformed lines are silently skipped.
119 """
120 if not path.exists():
121 return []
122 events: list[LLEvent] = []
123 with open(path, encoding="utf-8") as f:
124 for line in f:
125 line = line.strip()
126 if line:
127 try:
128 events.append(LLEvent.from_dict(json.loads(line)))
129 except json.JSONDecodeError:
130 continue
131 return events