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

1"""Event system for little-loops extension architecture. 

2 

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. 

6 

7Public exports: 

8 LLEvent: Structured event dataclass with type, timestamp, and payload 

9 EventBus: Multi-observer event dispatcher with optional JSONL file sink 

10""" 

11 

12from __future__ import annotations 

13 

14import json 

15import logging 

16from collections.abc import Callable 

17from dataclasses import dataclass, field 

18from pathlib import Path 

19from typing import Any 

20 

21logger = logging.getLogger(__name__) 

22 

23# Type for event callback (matches existing EventCallback in fsm/executor.py) 

24EventCallback = Callable[[dict[str, Any]], None] 

25 

26 

27@dataclass 

28class LLEvent: 

29 """Structured event emitted by little-loops subsystems. 

30 

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 """ 

36 

37 type: str 

38 timestamp: str 

39 payload: dict[str, Any] = field(default_factory=dict) 

40 

41 def to_dict(self) -> dict[str, Any]: 

42 """Convert to dictionary for JSON serialization. 

43 

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} 

48 

49 @classmethod 

50 def from_dict(cls, data: dict[str, Any]) -> LLEvent: 

51 """Create from dictionary (JSON deserialization). 

52 

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) 

59 

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)) 

64 

65 

66class EventBus: 

67 """Multi-observer event dispatcher. 

68 

69 Dispatches event dicts to all registered observers. Exceptions in individual 

70 observers are caught and logged, not propagated. 

71 """ 

72 

73 def __init__(self) -> None: 

74 self._observers: list[EventCallback] = [] 

75 self._file_sinks: list[Path] = [] 

76 

77 def register(self, callback: EventCallback) -> None: 

78 """Register an observer to receive events.""" 

79 self._observers.append(callback) 

80 

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 

87 

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) 

92 

93 def emit(self, event: dict[str, Any]) -> None: 

94 """Dispatch event to all observers and file sinks. 

95 

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) 

104 

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) 

111 

112 @staticmethod 

113 def read_events(path: Path) -> list[LLEvent]: 

114 """Read events from a JSONL file. 

115 

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