empathy-framework 4.6.6__py3-none-any.whl → 4.7.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (273) hide show
  1. empathy_framework-4.7.1.dist-info/METADATA +690 -0
  2. empathy_framework-4.7.1.dist-info/RECORD +379 -0
  3. {empathy_framework-4.6.6.dist-info → empathy_framework-4.7.1.dist-info}/top_level.txt +1 -2
  4. empathy_healthcare_plugin/monitors/monitoring/__init__.py +9 -9
  5. empathy_llm_toolkit/agent_factory/__init__.py +6 -6
  6. empathy_llm_toolkit/agent_factory/adapters/wizard_adapter.py +7 -10
  7. empathy_llm_toolkit/agents_md/__init__.py +22 -0
  8. empathy_llm_toolkit/agents_md/loader.py +218 -0
  9. empathy_llm_toolkit/agents_md/parser.py +271 -0
  10. empathy_llm_toolkit/agents_md/registry.py +307 -0
  11. empathy_llm_toolkit/commands/__init__.py +51 -0
  12. empathy_llm_toolkit/commands/context.py +375 -0
  13. empathy_llm_toolkit/commands/loader.py +301 -0
  14. empathy_llm_toolkit/commands/models.py +231 -0
  15. empathy_llm_toolkit/commands/parser.py +371 -0
  16. empathy_llm_toolkit/commands/registry.py +429 -0
  17. empathy_llm_toolkit/config/__init__.py +8 -8
  18. empathy_llm_toolkit/config/unified.py +3 -7
  19. empathy_llm_toolkit/context/__init__.py +22 -0
  20. empathy_llm_toolkit/context/compaction.py +455 -0
  21. empathy_llm_toolkit/context/manager.py +434 -0
  22. empathy_llm_toolkit/hooks/__init__.py +24 -0
  23. empathy_llm_toolkit/hooks/config.py +306 -0
  24. empathy_llm_toolkit/hooks/executor.py +289 -0
  25. empathy_llm_toolkit/hooks/registry.py +302 -0
  26. empathy_llm_toolkit/hooks/scripts/__init__.py +39 -0
  27. empathy_llm_toolkit/hooks/scripts/evaluate_session.py +201 -0
  28. empathy_llm_toolkit/hooks/scripts/first_time_init.py +285 -0
  29. empathy_llm_toolkit/hooks/scripts/pre_compact.py +207 -0
  30. empathy_llm_toolkit/hooks/scripts/session_end.py +183 -0
  31. empathy_llm_toolkit/hooks/scripts/session_start.py +163 -0
  32. empathy_llm_toolkit/hooks/scripts/suggest_compact.py +225 -0
  33. empathy_llm_toolkit/learning/__init__.py +30 -0
  34. empathy_llm_toolkit/learning/evaluator.py +438 -0
  35. empathy_llm_toolkit/learning/extractor.py +514 -0
  36. empathy_llm_toolkit/learning/storage.py +560 -0
  37. empathy_llm_toolkit/providers.py +4 -11
  38. empathy_llm_toolkit/security/__init__.py +17 -17
  39. empathy_llm_toolkit/utils/tokens.py +2 -5
  40. empathy_os/__init__.py +202 -70
  41. empathy_os/cache_monitor.py +5 -3
  42. empathy_os/cli/__init__.py +11 -55
  43. empathy_os/cli/__main__.py +29 -15
  44. empathy_os/cli/commands/inspection.py +21 -12
  45. empathy_os/cli/commands/memory.py +4 -12
  46. empathy_os/cli/commands/profiling.py +198 -0
  47. empathy_os/cli/commands/utilities.py +27 -7
  48. empathy_os/cli.py +28 -57
  49. empathy_os/cli_unified.py +525 -1164
  50. empathy_os/cost_tracker.py +9 -3
  51. empathy_os/dashboard/server.py +200 -2
  52. empathy_os/hot_reload/__init__.py +7 -7
  53. empathy_os/hot_reload/config.py +6 -7
  54. empathy_os/hot_reload/integration.py +35 -35
  55. empathy_os/hot_reload/reloader.py +57 -57
  56. empathy_os/hot_reload/watcher.py +28 -28
  57. empathy_os/hot_reload/websocket.py +2 -2
  58. empathy_os/memory/__init__.py +11 -4
  59. empathy_os/memory/claude_memory.py +1 -1
  60. empathy_os/memory/cross_session.py +8 -12
  61. empathy_os/memory/edges.py +6 -6
  62. empathy_os/memory/file_session.py +770 -0
  63. empathy_os/memory/graph.py +30 -30
  64. empathy_os/memory/nodes.py +6 -6
  65. empathy_os/memory/short_term.py +15 -9
  66. empathy_os/memory/unified.py +606 -140
  67. empathy_os/meta_workflows/agent_creator.py +3 -9
  68. empathy_os/meta_workflows/cli_meta_workflows.py +113 -53
  69. empathy_os/meta_workflows/form_engine.py +6 -18
  70. empathy_os/meta_workflows/intent_detector.py +64 -24
  71. empathy_os/meta_workflows/models.py +3 -1
  72. empathy_os/meta_workflows/pattern_learner.py +13 -31
  73. empathy_os/meta_workflows/plan_generator.py +55 -47
  74. empathy_os/meta_workflows/session_context.py +2 -3
  75. empathy_os/meta_workflows/workflow.py +20 -51
  76. empathy_os/models/cli.py +2 -2
  77. empathy_os/models/tasks.py +1 -2
  78. empathy_os/models/telemetry.py +4 -1
  79. empathy_os/models/token_estimator.py +3 -1
  80. empathy_os/monitoring/alerts.py +938 -9
  81. empathy_os/monitoring/alerts_cli.py +346 -183
  82. empathy_os/orchestration/execution_strategies.py +12 -29
  83. empathy_os/orchestration/pattern_learner.py +20 -26
  84. empathy_os/orchestration/real_tools.py +6 -15
  85. empathy_os/platform_utils.py +2 -1
  86. empathy_os/plugins/__init__.py +2 -2
  87. empathy_os/plugins/base.py +64 -64
  88. empathy_os/plugins/registry.py +32 -32
  89. empathy_os/project_index/index.py +49 -15
  90. empathy_os/project_index/models.py +1 -2
  91. empathy_os/project_index/reports.py +1 -1
  92. empathy_os/project_index/scanner.py +1 -0
  93. empathy_os/redis_memory.py +10 -7
  94. empathy_os/resilience/__init__.py +1 -1
  95. empathy_os/resilience/health.py +10 -10
  96. empathy_os/routing/__init__.py +7 -7
  97. empathy_os/routing/chain_executor.py +37 -37
  98. empathy_os/routing/classifier.py +36 -36
  99. empathy_os/routing/smart_router.py +40 -40
  100. empathy_os/routing/{wizard_registry.py → workflow_registry.py} +47 -47
  101. empathy_os/scaffolding/__init__.py +8 -8
  102. empathy_os/scaffolding/__main__.py +1 -1
  103. empathy_os/scaffolding/cli.py +28 -28
  104. empathy_os/socratic/__init__.py +3 -19
  105. empathy_os/socratic/ab_testing.py +25 -36
  106. empathy_os/socratic/blueprint.py +38 -38
  107. empathy_os/socratic/cli.py +34 -20
  108. empathy_os/socratic/collaboration.py +30 -28
  109. empathy_os/socratic/domain_templates.py +9 -1
  110. empathy_os/socratic/embeddings.py +17 -13
  111. empathy_os/socratic/engine.py +135 -70
  112. empathy_os/socratic/explainer.py +70 -60
  113. empathy_os/socratic/feedback.py +24 -19
  114. empathy_os/socratic/forms.py +15 -10
  115. empathy_os/socratic/generator.py +51 -35
  116. empathy_os/socratic/llm_analyzer.py +25 -23
  117. empathy_os/socratic/mcp_server.py +99 -159
  118. empathy_os/socratic/session.py +19 -13
  119. empathy_os/socratic/storage.py +98 -67
  120. empathy_os/socratic/success.py +38 -27
  121. empathy_os/socratic/visual_editor.py +51 -39
  122. empathy_os/socratic/web_ui.py +99 -66
  123. empathy_os/telemetry/cli.py +3 -1
  124. empathy_os/telemetry/usage_tracker.py +1 -3
  125. empathy_os/test_generator/__init__.py +3 -3
  126. empathy_os/test_generator/cli.py +28 -28
  127. empathy_os/test_generator/generator.py +64 -66
  128. empathy_os/test_generator/risk_analyzer.py +11 -11
  129. empathy_os/vscode_bridge 2.py +173 -0
  130. empathy_os/vscode_bridge.py +173 -0
  131. empathy_os/workflows/__init__.py +212 -120
  132. empathy_os/workflows/batch_processing.py +8 -24
  133. empathy_os/workflows/bug_predict.py +1 -1
  134. empathy_os/workflows/code_review.py +20 -5
  135. empathy_os/workflows/code_review_pipeline.py +13 -8
  136. empathy_os/workflows/keyboard_shortcuts/workflow.py +6 -2
  137. empathy_os/workflows/manage_documentation.py +1 -0
  138. empathy_os/workflows/orchestrated_health_check.py +6 -11
  139. empathy_os/workflows/orchestrated_release_prep.py +3 -3
  140. empathy_os/workflows/pr_review.py +18 -10
  141. empathy_os/workflows/progressive/README 2.md +454 -0
  142. empathy_os/workflows/progressive/__init__ 2.py +92 -0
  143. empathy_os/workflows/progressive/__init__.py +2 -12
  144. empathy_os/workflows/progressive/cli 2.py +242 -0
  145. empathy_os/workflows/progressive/cli.py +14 -37
  146. empathy_os/workflows/progressive/core 2.py +488 -0
  147. empathy_os/workflows/progressive/core.py +12 -12
  148. empathy_os/workflows/progressive/orchestrator 2.py +701 -0
  149. empathy_os/workflows/progressive/orchestrator.py +166 -144
  150. empathy_os/workflows/progressive/reports 2.py +528 -0
  151. empathy_os/workflows/progressive/reports.py +22 -31
  152. empathy_os/workflows/progressive/telemetry 2.py +280 -0
  153. empathy_os/workflows/progressive/telemetry.py +8 -14
  154. empathy_os/workflows/progressive/test_gen 2.py +514 -0
  155. empathy_os/workflows/progressive/test_gen.py +29 -48
  156. empathy_os/workflows/progressive/workflow 2.py +628 -0
  157. empathy_os/workflows/progressive/workflow.py +31 -70
  158. empathy_os/workflows/release_prep.py +21 -6
  159. empathy_os/workflows/release_prep_crew.py +1 -0
  160. empathy_os/workflows/secure_release.py +13 -6
  161. empathy_os/workflows/security_audit.py +8 -3
  162. empathy_os/workflows/test_coverage_boost_crew.py +3 -2
  163. empathy_os/workflows/test_maintenance_crew.py +1 -0
  164. empathy_os/workflows/test_runner.py +16 -12
  165. empathy_software_plugin/SOFTWARE_PLUGIN_README.md +25 -703
  166. empathy_software_plugin/cli.py +0 -122
  167. patterns/README.md +119 -0
  168. patterns/__init__.py +95 -0
  169. patterns/behavior.py +298 -0
  170. patterns/code_review_memory.json +441 -0
  171. patterns/core.py +97 -0
  172. patterns/debugging.json +3763 -0
  173. patterns/empathy.py +268 -0
  174. patterns/health_check_memory.json +505 -0
  175. patterns/input.py +161 -0
  176. patterns/memory_graph.json +8 -0
  177. patterns/refactoring_memory.json +1113 -0
  178. patterns/registry.py +663 -0
  179. patterns/security_memory.json +8 -0
  180. patterns/structural.py +415 -0
  181. patterns/validation.py +194 -0
  182. coach_wizards/__init__.py +0 -45
  183. coach_wizards/accessibility_wizard.py +0 -91
  184. coach_wizards/api_wizard.py +0 -91
  185. coach_wizards/base_wizard.py +0 -209
  186. coach_wizards/cicd_wizard.py +0 -91
  187. coach_wizards/code_reviewer_README.md +0 -60
  188. coach_wizards/code_reviewer_wizard.py +0 -180
  189. coach_wizards/compliance_wizard.py +0 -91
  190. coach_wizards/database_wizard.py +0 -91
  191. coach_wizards/debugging_wizard.py +0 -91
  192. coach_wizards/documentation_wizard.py +0 -91
  193. coach_wizards/generate_wizards.py +0 -347
  194. coach_wizards/localization_wizard.py +0 -173
  195. coach_wizards/migration_wizard.py +0 -91
  196. coach_wizards/monitoring_wizard.py +0 -91
  197. coach_wizards/observability_wizard.py +0 -91
  198. coach_wizards/performance_wizard.py +0 -91
  199. coach_wizards/prompt_engineering_wizard.py +0 -661
  200. coach_wizards/refactoring_wizard.py +0 -91
  201. coach_wizards/scaling_wizard.py +0 -90
  202. coach_wizards/security_wizard.py +0 -92
  203. coach_wizards/testing_wizard.py +0 -91
  204. empathy_framework-4.6.6.dist-info/METADATA +0 -1597
  205. empathy_framework-4.6.6.dist-info/RECORD +0 -410
  206. empathy_llm_toolkit/wizards/__init__.py +0 -43
  207. empathy_llm_toolkit/wizards/base_wizard.py +0 -364
  208. empathy_llm_toolkit/wizards/customer_support_wizard.py +0 -190
  209. empathy_llm_toolkit/wizards/healthcare_wizard.py +0 -378
  210. empathy_llm_toolkit/wizards/patient_assessment_README.md +0 -64
  211. empathy_llm_toolkit/wizards/patient_assessment_wizard.py +0 -193
  212. empathy_llm_toolkit/wizards/technology_wizard.py +0 -209
  213. empathy_os/wizard_factory_cli.py +0 -170
  214. empathy_software_plugin/wizards/__init__.py +0 -42
  215. empathy_software_plugin/wizards/advanced_debugging_wizard.py +0 -395
  216. empathy_software_plugin/wizards/agent_orchestration_wizard.py +0 -511
  217. empathy_software_plugin/wizards/ai_collaboration_wizard.py +0 -503
  218. empathy_software_plugin/wizards/ai_context_wizard.py +0 -441
  219. empathy_software_plugin/wizards/ai_documentation_wizard.py +0 -503
  220. empathy_software_plugin/wizards/base_wizard.py +0 -288
  221. empathy_software_plugin/wizards/book_chapter_wizard.py +0 -519
  222. empathy_software_plugin/wizards/code_review_wizard.py +0 -604
  223. empathy_software_plugin/wizards/debugging/__init__.py +0 -50
  224. empathy_software_plugin/wizards/debugging/bug_risk_analyzer.py +0 -414
  225. empathy_software_plugin/wizards/debugging/config_loaders.py +0 -446
  226. empathy_software_plugin/wizards/debugging/fix_applier.py +0 -469
  227. empathy_software_plugin/wizards/debugging/language_patterns.py +0 -385
  228. empathy_software_plugin/wizards/debugging/linter_parsers.py +0 -470
  229. empathy_software_plugin/wizards/debugging/verification.py +0 -369
  230. empathy_software_plugin/wizards/enhanced_testing_wizard.py +0 -537
  231. empathy_software_plugin/wizards/memory_enhanced_debugging_wizard.py +0 -816
  232. empathy_software_plugin/wizards/multi_model_wizard.py +0 -501
  233. empathy_software_plugin/wizards/pattern_extraction_wizard.py +0 -422
  234. empathy_software_plugin/wizards/pattern_retriever_wizard.py +0 -400
  235. empathy_software_plugin/wizards/performance/__init__.py +0 -9
  236. empathy_software_plugin/wizards/performance/bottleneck_detector.py +0 -221
  237. empathy_software_plugin/wizards/performance/profiler_parsers.py +0 -278
  238. empathy_software_plugin/wizards/performance/trajectory_analyzer.py +0 -429
  239. empathy_software_plugin/wizards/performance_profiling_wizard.py +0 -305
  240. empathy_software_plugin/wizards/prompt_engineering_wizard.py +0 -425
  241. empathy_software_plugin/wizards/rag_pattern_wizard.py +0 -461
  242. empathy_software_plugin/wizards/security/__init__.py +0 -32
  243. empathy_software_plugin/wizards/security/exploit_analyzer.py +0 -290
  244. empathy_software_plugin/wizards/security/owasp_patterns.py +0 -241
  245. empathy_software_plugin/wizards/security/vulnerability_scanner.py +0 -604
  246. empathy_software_plugin/wizards/security_analysis_wizard.py +0 -322
  247. empathy_software_plugin/wizards/security_learning_wizard.py +0 -740
  248. empathy_software_plugin/wizards/tech_debt_wizard.py +0 -726
  249. empathy_software_plugin/wizards/testing/__init__.py +0 -27
  250. empathy_software_plugin/wizards/testing/coverage_analyzer.py +0 -459
  251. empathy_software_plugin/wizards/testing/quality_analyzer.py +0 -525
  252. empathy_software_plugin/wizards/testing/test_suggester.py +0 -533
  253. empathy_software_plugin/wizards/testing_wizard.py +0 -274
  254. wizards/__init__.py +0 -82
  255. wizards/admission_assessment_wizard.py +0 -644
  256. wizards/care_plan.py +0 -321
  257. wizards/clinical_assessment.py +0 -769
  258. wizards/discharge_planning.py +0 -77
  259. wizards/discharge_summary_wizard.py +0 -468
  260. wizards/dosage_calculation.py +0 -497
  261. wizards/incident_report_wizard.py +0 -454
  262. wizards/medication_reconciliation.py +0 -85
  263. wizards/nursing_assessment.py +0 -171
  264. wizards/patient_education.py +0 -654
  265. wizards/quality_improvement.py +0 -705
  266. wizards/sbar_report.py +0 -324
  267. wizards/sbar_wizard.py +0 -608
  268. wizards/shift_handoff_wizard.py +0 -535
  269. wizards/soap_note_wizard.py +0 -679
  270. wizards/treatment_plan.py +0 -15
  271. {empathy_framework-4.6.6.dist-info → empathy_framework-4.7.1.dist-info}/WHEEL +0 -0
  272. {empathy_framework-4.6.6.dist-info → empathy_framework-4.7.1.dist-info}/entry_points.txt +0 -0
  273. {empathy_framework-4.6.6.dist-info → empathy_framework-4.7.1.dist-info}/licenses/LICENSE +0 -0
@@ -3,21 +3,950 @@
3
3
  Provides threshold-based alerting for LLM usage metrics.
4
4
 
5
5
  **Features:**
6
- - Interactive CLI wizard (`empathy alerts init`)
6
+ - Interactive CLI workflow (`empathy alerts init`)
7
7
  - Multiple notification channels (webhook, email, stdout)
8
8
  - Threshold triggers (daily cost, error rate, etc.)
9
9
  - Cooldown mechanism (prevent spam)
10
10
  - Enterprise background daemon (`empathy alerts watch --daemon`)
11
11
 
12
- **Implementation Status:** Sprint 3 (Week 3)
12
+ **Supported Metrics:**
13
+ - daily_cost: Total USD spent in the last 24 hours
14
+ - error_rate: Percentage of failed LLM calls
15
+ - avg_latency: Average response time in milliseconds
16
+ - token_usage: Total tokens used in the last 24 hours
13
17
 
14
- Copyright 2025 Smart-AI-Memory
18
+ Copyright 2025-2026 Smart-AI-Memory
15
19
  Licensed under Fair Source License 0.9
16
20
  """
17
21
 
18
- # TODO: Implement in Sprint 3
19
- # - AlertEngine class
20
- # - CLI wizard for setup
21
- # - Background watcher (optional daemon)
22
- # - Webhook delivery
23
- # - Email notifications
22
+ from __future__ import annotations
23
+
24
+ import ipaddress
25
+ import json
26
+ import logging
27
+ import smtplib
28
+ import sqlite3
29
+ import time
30
+ import urllib.error
31
+ import urllib.parse
32
+ import urllib.request
33
+ from dataclasses import dataclass
34
+ from datetime import datetime, timedelta
35
+ from email.mime.multipart import MIMEMultipart
36
+ from email.mime.text import MIMEText
37
+ from enum import Enum
38
+ from pathlib import Path
39
+ from typing import Any
40
+
41
+ logger = logging.getLogger(__name__)
42
+
43
+
44
+ def _validate_webhook_url(url: str) -> str:
45
+ """Validate webhook URL to prevent SSRF attacks.
46
+
47
+ Args:
48
+ url: Webhook URL to validate
49
+
50
+ Returns:
51
+ Validated URL (unchanged if valid)
52
+
53
+ Raises:
54
+ ValueError: If URL is invalid or targets unsafe destinations
55
+
56
+ Security:
57
+ Prevents Server-Side Request Forgery (SSRF) by blocking:
58
+ - Non-HTTP(S) schemes (file://, gopher://, ftp://)
59
+ - Localhost and loopback addresses (127.0.0.1, ::1)
60
+ - Cloud metadata services (169.254.169.254)
61
+ - Private IP ranges (10.x, 172.16-31.x, 192.168.x)
62
+ - Common internal service ports (Redis, PostgreSQL, etc.)
63
+ """
64
+ if not url or not isinstance(url, str):
65
+ raise ValueError("webhook_url must be a non-empty string")
66
+
67
+ # Parse URL
68
+ try:
69
+ parsed = urllib.parse.urlparse(url)
70
+ except Exception as e:
71
+ raise ValueError(f"Invalid URL format: {e}")
72
+
73
+ # Only allow http and https schemes
74
+ if parsed.scheme not in ("http", "https"):
75
+ raise ValueError(
76
+ f"Invalid scheme '{parsed.scheme}'. Only http and https allowed for webhooks."
77
+ )
78
+
79
+ # Check hostname exists
80
+ hostname = parsed.hostname
81
+ if not hostname:
82
+ raise ValueError("Webhook URL must contain a valid hostname")
83
+
84
+ # Blocked hostnames (localhost, metadata services)
85
+ blocked_hosts = {
86
+ "localhost",
87
+ "127.0.0.1",
88
+ "0.0.0.0",
89
+ "::1",
90
+ "[::1]",
91
+ "169.254.169.254", # AWS metadata
92
+ "metadata.google.internal", # GCP metadata
93
+ "instance-data", # Azure metadata pattern
94
+ }
95
+
96
+ hostname_lower = hostname.lower()
97
+ if hostname_lower in blocked_hosts:
98
+ raise ValueError(f"Webhook URL cannot target local or metadata address: {hostname}")
99
+
100
+ # Check for private/internal IPs
101
+ try:
102
+ ip = ipaddress.ip_address(hostname)
103
+ if ip.is_private:
104
+ raise ValueError(f"Webhook URL cannot target private IP: {hostname}")
105
+ if ip.is_loopback:
106
+ raise ValueError(f"Webhook URL cannot target loopback address: {hostname}")
107
+ if ip.is_link_local:
108
+ raise ValueError(f"Webhook URL cannot target link-local address: {hostname}")
109
+ if ip.is_reserved:
110
+ raise ValueError(f"Webhook URL cannot target reserved IP: {hostname}")
111
+ except ValueError as e:
112
+ # Check if this is our own validation error
113
+ if "cannot target" in str(e):
114
+ raise
115
+ # Not an IP address (it's a hostname) - that's fine, continue
116
+
117
+ # Block common internal service ports
118
+ if parsed.port is not None:
119
+ blocked_ports = {
120
+ 22, # SSH
121
+ 23, # Telnet
122
+ 3306, # MySQL
123
+ 5432, # PostgreSQL
124
+ 6379, # Redis
125
+ 27017, # MongoDB
126
+ 9200, # Elasticsearch
127
+ 2379, # etcd
128
+ 8500, # Consul
129
+ }
130
+ if parsed.port in blocked_ports:
131
+ raise ValueError(
132
+ f"Webhook URL cannot target internal service port {parsed.port}. "
133
+ "Use standard HTTP (80) or HTTPS (443) ports."
134
+ )
135
+
136
+ return url
137
+
138
+
139
+ class AlertChannel(Enum):
140
+ """Notification channels for alerts."""
141
+
142
+ WEBHOOK = "webhook"
143
+ EMAIL = "email"
144
+ VSCODE_OUTPUT = "vscode_output"
145
+ STDOUT = "stdout"
146
+
147
+
148
+ class AlertMetric(Enum):
149
+ """Metrics that can be monitored."""
150
+
151
+ DAILY_COST = "daily_cost"
152
+ ERROR_RATE = "error_rate"
153
+ AVG_LATENCY = "avg_latency"
154
+ TOKEN_USAGE = "token_usage"
155
+
156
+
157
+ class AlertSeverity(Enum):
158
+ """Alert severity levels."""
159
+
160
+ INFO = "info"
161
+ WARNING = "warning"
162
+ CRITICAL = "critical"
163
+
164
+
165
+ @dataclass
166
+ class AlertConfig:
167
+ """Configuration for a single alert."""
168
+
169
+ alert_id: str
170
+ name: str
171
+ metric: AlertMetric
172
+ threshold: float
173
+ channel: AlertChannel
174
+ webhook_url: str | None = None
175
+ email: str | None = None
176
+ enabled: bool = True
177
+ cooldown_seconds: int = 3600 # 1 hour default
178
+ severity: AlertSeverity = AlertSeverity.WARNING
179
+ created_at: datetime | None = None
180
+
181
+ def to_dict(self) -> dict[str, Any]:
182
+ """Convert to dictionary."""
183
+ return {
184
+ "alert_id": self.alert_id,
185
+ "name": self.name,
186
+ "metric": self.metric.value,
187
+ "threshold": self.threshold,
188
+ "channel": self.channel.value,
189
+ "webhook_url": self.webhook_url,
190
+ "email": self.email,
191
+ "enabled": self.enabled,
192
+ "cooldown_seconds": self.cooldown_seconds,
193
+ "severity": self.severity.value,
194
+ "created_at": self.created_at.isoformat() if self.created_at else None,
195
+ }
196
+
197
+ @classmethod
198
+ def from_dict(cls, data: dict[str, Any]) -> AlertConfig:
199
+ """Create from dictionary."""
200
+ return cls(
201
+ alert_id=data["alert_id"],
202
+ name=data["name"],
203
+ metric=AlertMetric(data["metric"]),
204
+ threshold=data["threshold"],
205
+ channel=AlertChannel(data["channel"]),
206
+ webhook_url=data.get("webhook_url"),
207
+ email=data.get("email"),
208
+ enabled=data.get("enabled", True),
209
+ cooldown_seconds=data.get("cooldown_seconds", 3600),
210
+ severity=AlertSeverity(data.get("severity", "warning")),
211
+ created_at=datetime.fromisoformat(data["created_at"])
212
+ if data.get("created_at")
213
+ else None,
214
+ )
215
+
216
+
217
+ @dataclass
218
+ class AlertEvent:
219
+ """An alert event that was triggered."""
220
+
221
+ alert_id: str
222
+ alert_name: str
223
+ metric: AlertMetric
224
+ current_value: float
225
+ threshold: float
226
+ severity: AlertSeverity
227
+ triggered_at: datetime
228
+ message: str
229
+
230
+ def to_dict(self) -> dict[str, Any]:
231
+ """Convert to dictionary."""
232
+ return {
233
+ "alert_id": self.alert_id,
234
+ "alert_name": self.alert_name,
235
+ "metric": self.metric.value,
236
+ "current_value": self.current_value,
237
+ "threshold": self.threshold,
238
+ "severity": self.severity.value,
239
+ "triggered_at": self.triggered_at.isoformat(),
240
+ "message": self.message,
241
+ }
242
+
243
+
244
+ class AlertEngine:
245
+ """Alert engine with SQLite storage and notification delivery.
246
+
247
+ Monitors telemetry metrics and sends alerts when thresholds are exceeded.
248
+
249
+ Example:
250
+ >>> engine = AlertEngine()
251
+ >>> engine.add_alert(
252
+ ... alert_id="cost_alert",
253
+ ... name="Daily Cost Alert",
254
+ ... metric=AlertMetric.DAILY_COST,
255
+ ... threshold=10.0,
256
+ ... channel=AlertChannel.WEBHOOK,
257
+ ... webhook_url="https://hooks.slack.com/..."
258
+ ... )
259
+ >>> events = engine.check_and_trigger()
260
+ >>> for event in events:
261
+ ... print(f"Alert: {event.message}")
262
+ """
263
+
264
+ def __init__(
265
+ self,
266
+ db_path: str | Path = ".empathy/alerts.db",
267
+ telemetry_dir: str | Path | None = None,
268
+ ):
269
+ """Initialize AlertEngine.
270
+
271
+ Args:
272
+ db_path: Path to SQLite database for alert storage
273
+ telemetry_dir: Path to telemetry directory (default: ~/.empathy/telemetry)
274
+ """
275
+ self.db_path = Path(db_path)
276
+ self.db_path.parent.mkdir(parents=True, exist_ok=True)
277
+
278
+ self.telemetry_dir = (
279
+ Path(telemetry_dir)
280
+ if telemetry_dir
281
+ else Path.home() / ".empathy" / "telemetry"
282
+ )
283
+
284
+ self._cooldown_cache: dict[str, float] = {} # alert_id -> last_triggered_time
285
+ self._init_db()
286
+
287
+ def _init_db(self) -> None:
288
+ """Initialize SQLite database with alerts and history tables."""
289
+ conn = sqlite3.connect(self.db_path)
290
+ cursor = conn.cursor()
291
+
292
+ # Alerts configuration table
293
+ cursor.execute(
294
+ """
295
+ CREATE TABLE IF NOT EXISTS alerts (
296
+ id TEXT PRIMARY KEY,
297
+ name TEXT NOT NULL,
298
+ metric TEXT NOT NULL,
299
+ threshold REAL NOT NULL,
300
+ channel TEXT NOT NULL,
301
+ webhook_url TEXT,
302
+ email TEXT,
303
+ enabled INTEGER DEFAULT 1,
304
+ cooldown INTEGER DEFAULT 3600,
305
+ severity TEXT DEFAULT 'warning',
306
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
307
+ )
308
+ """
309
+ )
310
+
311
+ # Alert history table for audit trail
312
+ cursor.execute(
313
+ """
314
+ CREATE TABLE IF NOT EXISTS alert_history (
315
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
316
+ alert_id TEXT NOT NULL,
317
+ metric TEXT NOT NULL,
318
+ current_value REAL NOT NULL,
319
+ threshold REAL NOT NULL,
320
+ severity TEXT NOT NULL,
321
+ triggered_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
322
+ delivered INTEGER DEFAULT 0,
323
+ delivery_error TEXT,
324
+ FOREIGN KEY (alert_id) REFERENCES alerts(id)
325
+ )
326
+ """
327
+ )
328
+
329
+ conn.commit()
330
+ conn.close()
331
+
332
+ def add_alert(
333
+ self,
334
+ alert_id: str,
335
+ name: str,
336
+ metric: AlertMetric | str,
337
+ threshold: float,
338
+ channel: AlertChannel | str,
339
+ webhook_url: str | None = None,
340
+ email: str | None = None,
341
+ cooldown_seconds: int = 3600,
342
+ severity: AlertSeverity | str = AlertSeverity.WARNING,
343
+ ) -> AlertConfig:
344
+ """Add a new alert configuration.
345
+
346
+ Args:
347
+ alert_id: Unique identifier for the alert
348
+ name: Human-readable name
349
+ metric: Metric to monitor
350
+ threshold: Threshold value that triggers the alert
351
+ channel: Notification channel
352
+ webhook_url: Webhook URL (required for webhook channel)
353
+ email: Email address (required for email channel)
354
+ cooldown_seconds: Minimum seconds between alerts
355
+ severity: Alert severity level
356
+
357
+ Returns:
358
+ AlertConfig for the created alert
359
+
360
+ Raises:
361
+ ValueError: If webhook_url missing for webhook channel or email missing for email channel
362
+ """
363
+ # Normalize enum values
364
+ if isinstance(metric, str):
365
+ metric = AlertMetric(metric)
366
+ if isinstance(channel, str):
367
+ channel = AlertChannel(channel)
368
+ if isinstance(severity, str):
369
+ severity = AlertSeverity(severity)
370
+
371
+ # Validate channel requirements
372
+ if channel == AlertChannel.WEBHOOK and not webhook_url:
373
+ raise ValueError("webhook_url required for webhook channel")
374
+ if channel == AlertChannel.EMAIL and not email:
375
+ raise ValueError("email required for email channel")
376
+
377
+ conn = sqlite3.connect(self.db_path)
378
+ cursor = conn.cursor()
379
+
380
+ cursor.execute(
381
+ """
382
+ INSERT OR REPLACE INTO alerts
383
+ (id, name, metric, threshold, channel, webhook_url, email, cooldown, severity)
384
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
385
+ """,
386
+ (
387
+ alert_id,
388
+ name,
389
+ metric.value,
390
+ threshold,
391
+ channel.value,
392
+ webhook_url,
393
+ email,
394
+ cooldown_seconds,
395
+ severity.value,
396
+ ),
397
+ )
398
+
399
+ conn.commit()
400
+ conn.close()
401
+
402
+ logger.info(
403
+ "alert_created",
404
+ alert_id=alert_id,
405
+ metric=metric.value,
406
+ threshold=threshold,
407
+ channel=channel.value,
408
+ )
409
+
410
+ return AlertConfig(
411
+ alert_id=alert_id,
412
+ name=name,
413
+ metric=metric,
414
+ threshold=threshold,
415
+ channel=channel,
416
+ webhook_url=webhook_url,
417
+ email=email,
418
+ cooldown_seconds=cooldown_seconds,
419
+ severity=severity,
420
+ created_at=datetime.now(),
421
+ )
422
+
423
+ def list_alerts(self) -> list[AlertConfig]:
424
+ """List all configured alerts.
425
+
426
+ Returns:
427
+ List of AlertConfig objects
428
+ """
429
+ conn = sqlite3.connect(self.db_path)
430
+ cursor = conn.cursor()
431
+
432
+ cursor.execute(
433
+ "SELECT id, name, metric, threshold, channel, webhook_url, email, "
434
+ "enabled, cooldown, severity, created_at FROM alerts"
435
+ )
436
+ rows = cursor.fetchall()
437
+ conn.close()
438
+
439
+ alerts = []
440
+ for row in rows:
441
+ alerts.append(
442
+ AlertConfig(
443
+ alert_id=row[0],
444
+ name=row[1],
445
+ metric=AlertMetric(row[2]),
446
+ threshold=row[3],
447
+ channel=AlertChannel(row[4]),
448
+ webhook_url=row[5],
449
+ email=row[6],
450
+ enabled=bool(row[7]),
451
+ cooldown_seconds=row[8],
452
+ severity=AlertSeverity(row[9]) if row[9] else AlertSeverity.WARNING,
453
+ created_at=datetime.fromisoformat(row[10]) if row[10] else None,
454
+ )
455
+ )
456
+
457
+ return alerts
458
+
459
+ def get_alert(self, alert_id: str) -> AlertConfig | None:
460
+ """Get a specific alert by ID.
461
+
462
+ Args:
463
+ alert_id: The alert ID
464
+
465
+ Returns:
466
+ AlertConfig or None if not found
467
+ """
468
+ conn = sqlite3.connect(self.db_path)
469
+ cursor = conn.cursor()
470
+
471
+ cursor.execute(
472
+ "SELECT id, name, metric, threshold, channel, webhook_url, email, "
473
+ "enabled, cooldown, severity, created_at FROM alerts WHERE id = ?",
474
+ (alert_id,),
475
+ )
476
+ row = cursor.fetchone()
477
+ conn.close()
478
+
479
+ if not row:
480
+ return None
481
+
482
+ return AlertConfig(
483
+ alert_id=row[0],
484
+ name=row[1],
485
+ metric=AlertMetric(row[2]),
486
+ threshold=row[3],
487
+ channel=AlertChannel(row[4]),
488
+ webhook_url=row[5],
489
+ email=row[6],
490
+ enabled=bool(row[7]),
491
+ cooldown_seconds=row[8],
492
+ severity=AlertSeverity(row[9]) if row[9] else AlertSeverity.WARNING,
493
+ created_at=datetime.fromisoformat(row[10]) if row[10] else None,
494
+ )
495
+
496
+ def delete_alert(self, alert_id: str) -> bool:
497
+ """Delete an alert by ID.
498
+
499
+ Args:
500
+ alert_id: The alert ID to delete
501
+
502
+ Returns:
503
+ True if deleted, False if not found
504
+ """
505
+ conn = sqlite3.connect(self.db_path)
506
+ cursor = conn.cursor()
507
+
508
+ cursor.execute("DELETE FROM alerts WHERE id = ?", (alert_id,))
509
+ deleted = cursor.rowcount > 0
510
+
511
+ conn.commit()
512
+ conn.close()
513
+
514
+ if deleted:
515
+ logger.info("alert_deleted", alert_id=alert_id)
516
+
517
+ return deleted
518
+
519
+ def enable_alert(self, alert_id: str) -> bool:
520
+ """Enable an alert."""
521
+ return self._set_alert_enabled(alert_id, True)
522
+
523
+ def disable_alert(self, alert_id: str) -> bool:
524
+ """Disable an alert."""
525
+ return self._set_alert_enabled(alert_id, False)
526
+
527
+ def _set_alert_enabled(self, alert_id: str, enabled: bool) -> bool:
528
+ """Set alert enabled status."""
529
+ conn = sqlite3.connect(self.db_path)
530
+ cursor = conn.cursor()
531
+
532
+ cursor.execute(
533
+ "UPDATE alerts SET enabled = ? WHERE id = ?", (int(enabled), alert_id)
534
+ )
535
+ updated = cursor.rowcount > 0
536
+
537
+ conn.commit()
538
+ conn.close()
539
+
540
+ return updated
541
+
542
+ def get_metrics(self) -> dict[str, float]:
543
+ """Get current telemetry metrics.
544
+
545
+ Reads from telemetry files and calculates:
546
+ - daily_cost: Total cost in last 24 hours
547
+ - error_rate: Percentage of errors
548
+ - avg_latency: Average latency in ms
549
+ - token_usage: Total tokens in last 24 hours
550
+
551
+ Returns:
552
+ Dictionary of metric name to current value
553
+ """
554
+ usage_file = self.telemetry_dir / "usage.jsonl"
555
+
556
+ if not usage_file.exists():
557
+ logger.debug("telemetry_file_not_found", path=str(usage_file))
558
+ return {
559
+ "daily_cost": 0.0,
560
+ "error_rate": 0.0,
561
+ "avg_latency": 0.0,
562
+ "token_usage": 0,
563
+ }
564
+
565
+ # Read last 24 hours of data
566
+ cutoff = datetime.now() - timedelta(hours=24)
567
+ total_cost = 0.0
568
+ total_tokens = 0
569
+ total_latency = 0.0
570
+ total_calls = 0
571
+ error_calls = 0
572
+
573
+ try:
574
+ with open(usage_file) as f:
575
+ for line in f:
576
+ if not line.strip():
577
+ continue
578
+ try:
579
+ entry = json.loads(line)
580
+ timestamp = datetime.fromisoformat(
581
+ entry.get("timestamp", "2000-01-01")
582
+ )
583
+ if timestamp < cutoff:
584
+ continue
585
+
586
+ total_calls += 1
587
+ total_cost += entry.get("cost", 0.0)
588
+ total_tokens += entry.get("tokens", {}).get("total", 0)
589
+ total_latency += entry.get("duration_ms", 0)
590
+
591
+ if entry.get("error"):
592
+ error_calls += 1
593
+ except (json.JSONDecodeError, KeyError):
594
+ continue
595
+ except (OSError, PermissionError) as e:
596
+ logger.warning("telemetry_read_error", error=str(e))
597
+ return {
598
+ "daily_cost": 0.0,
599
+ "error_rate": 0.0,
600
+ "avg_latency": 0.0,
601
+ "token_usage": 0,
602
+ }
603
+
604
+ return {
605
+ "daily_cost": total_cost,
606
+ "error_rate": (error_calls / total_calls * 100) if total_calls > 0 else 0.0,
607
+ "avg_latency": (total_latency / total_calls) if total_calls > 0 else 0.0,
608
+ "token_usage": total_tokens,
609
+ }
610
+
611
+ def check_and_trigger(self) -> list[AlertEvent]:
612
+ """Check all alerts and trigger notifications if thresholds exceeded.
613
+
614
+ Returns:
615
+ List of AlertEvent objects for triggered alerts
616
+ """
617
+ alerts = self.list_alerts()
618
+ metrics = self.get_metrics()
619
+ triggered_events = []
620
+
621
+ for alert in alerts:
622
+ if not alert.enabled:
623
+ continue
624
+
625
+ # Check cooldown
626
+ last_triggered = self._cooldown_cache.get(alert.alert_id, 0)
627
+ if time.time() - last_triggered < alert.cooldown_seconds:
628
+ logger.debug(
629
+ "alert_in_cooldown",
630
+ alert_id=alert.alert_id,
631
+ remaining=alert.cooldown_seconds - (time.time() - last_triggered),
632
+ )
633
+ continue
634
+
635
+ # Get current metric value
636
+ current_value = metrics.get(alert.metric.value, 0.0)
637
+
638
+ # Check threshold
639
+ if current_value >= alert.threshold:
640
+ event = AlertEvent(
641
+ alert_id=alert.alert_id,
642
+ alert_name=alert.name,
643
+ metric=alert.metric,
644
+ current_value=current_value,
645
+ threshold=alert.threshold,
646
+ severity=alert.severity,
647
+ triggered_at=datetime.now(),
648
+ message=self._format_alert_message(alert, current_value),
649
+ )
650
+
651
+ # Deliver notification
652
+ success = self._deliver_notification(alert, event)
653
+
654
+ # Record in history
655
+ self._record_alert_history(event, success)
656
+
657
+ # Update cooldown
658
+ self._cooldown_cache[alert.alert_id] = time.time()
659
+
660
+ triggered_events.append(event)
661
+
662
+ logger.info(
663
+ "alert_triggered",
664
+ alert_id=alert.alert_id,
665
+ metric=alert.metric.value,
666
+ current_value=current_value,
667
+ threshold=alert.threshold,
668
+ delivered=success,
669
+ )
670
+
671
+ return triggered_events
672
+
673
+ def _format_alert_message(self, alert: AlertConfig, current_value: float) -> str:
674
+ """Format human-readable alert message."""
675
+ metric_units = {
676
+ AlertMetric.DAILY_COST: "USD",
677
+ AlertMetric.ERROR_RATE: "%",
678
+ AlertMetric.AVG_LATENCY: "ms",
679
+ AlertMetric.TOKEN_USAGE: "tokens",
680
+ }
681
+ unit = metric_units.get(alert.metric, "")
682
+
683
+ return (
684
+ f"[{alert.severity.value.upper()}] {alert.name}\n"
685
+ f"Metric: {alert.metric.value}\n"
686
+ f"Current: {current_value:.2f} {unit}\n"
687
+ f"Threshold: {alert.threshold:.2f} {unit}\n"
688
+ f"Triggered at: {datetime.now().isoformat()}"
689
+ )
690
+
691
+ def _deliver_notification(self, alert: AlertConfig, event: AlertEvent) -> bool:
692
+ """Deliver notification through configured channel.
693
+
694
+ Args:
695
+ alert: The alert configuration
696
+ event: The alert event
697
+
698
+ Returns:
699
+ True if delivered successfully
700
+ """
701
+ try:
702
+ if alert.channel == AlertChannel.WEBHOOK:
703
+ return self._deliver_webhook(alert, event)
704
+ elif alert.channel == AlertChannel.EMAIL:
705
+ return self._deliver_email(alert, event)
706
+ elif alert.channel in (AlertChannel.VSCODE_OUTPUT, AlertChannel.STDOUT):
707
+ return self._deliver_stdout(event)
708
+ else:
709
+ logger.warning("unknown_alert_channel", channel=alert.channel.value)
710
+ return False
711
+ except Exception as e:
712
+ logger.error(
713
+ "alert_delivery_failed",
714
+ alert_id=alert.alert_id,
715
+ channel=alert.channel.value,
716
+ error=str(e),
717
+ )
718
+ return False
719
+
720
+ def _deliver_webhook(self, alert: AlertConfig, event: AlertEvent) -> bool:
721
+ """Deliver alert via webhook (Slack, Discord, etc.).
722
+
723
+ Security:
724
+ Validates webhook URL to prevent SSRF attacks before making request.
725
+ See _validate_webhook_url() for details on blocked targets.
726
+ """
727
+ if not alert.webhook_url:
728
+ return False
729
+
730
+ # Validate webhook URL to prevent SSRF (CWE-918)
731
+ try:
732
+ validated_url = _validate_webhook_url(alert.webhook_url)
733
+ except ValueError as e:
734
+ logger.warning(
735
+ "invalid_webhook_url",
736
+ url=alert.webhook_url,
737
+ error=str(e),
738
+ )
739
+ return False
740
+
741
+ payload = {
742
+ "text": event.message,
743
+ "blocks": [
744
+ {
745
+ "type": "header",
746
+ "text": {
747
+ "type": "plain_text",
748
+ "text": f"🚨 {event.alert_name}",
749
+ },
750
+ },
751
+ {
752
+ "type": "section",
753
+ "fields": [
754
+ {
755
+ "type": "mrkdwn",
756
+ "text": f"*Metric:*\n{event.metric.value}",
757
+ },
758
+ {
759
+ "type": "mrkdwn",
760
+ "text": f"*Severity:*\n{event.severity.value}",
761
+ },
762
+ {
763
+ "type": "mrkdwn",
764
+ "text": f"*Current Value:*\n{event.current_value:.2f}",
765
+ },
766
+ {
767
+ "type": "mrkdwn",
768
+ "text": f"*Threshold:*\n{event.threshold:.2f}",
769
+ },
770
+ ],
771
+ },
772
+ ],
773
+ }
774
+
775
+ data = json.dumps(payload).encode("utf-8")
776
+ req = urllib.request.Request(
777
+ validated_url,
778
+ data=data,
779
+ headers={"Content-Type": "application/json"},
780
+ )
781
+
782
+ try:
783
+ with urllib.request.urlopen(req, timeout=10) as response:
784
+ if response.status == 200:
785
+ logger.info("webhook_delivered", url=validated_url)
786
+ return True
787
+ else:
788
+ logger.warning(
789
+ "webhook_unexpected_status",
790
+ url=validated_url,
791
+ status=response.status,
792
+ )
793
+ return False
794
+ except urllib.error.HTTPError as e:
795
+ logger.warning(
796
+ "webhook_http_error",
797
+ url=validated_url,
798
+ status=e.code,
799
+ error=str(e),
800
+ )
801
+ return False
802
+ except urllib.error.URLError as e:
803
+ logger.error("webhook_delivery_failed", url=validated_url, error=str(e))
804
+ return False
805
+
806
+ def _deliver_email(self, alert: AlertConfig, event: AlertEvent) -> bool:
807
+ """Deliver alert via email.
808
+
809
+ Requires SMTP_HOST, SMTP_PORT, SMTP_USER, SMTP_PASSWORD environment variables.
810
+ """
811
+ if not alert.email:
812
+ return False
813
+
814
+ import os
815
+
816
+ smtp_host = os.environ.get("SMTP_HOST", "localhost")
817
+ smtp_port = int(os.environ.get("SMTP_PORT", "587"))
818
+ smtp_user = os.environ.get("SMTP_USER", "")
819
+ smtp_password = os.environ.get("SMTP_PASSWORD", "")
820
+ from_email = os.environ.get("SMTP_FROM", "alerts@empathy-framework.local")
821
+
822
+ msg = MIMEMultipart()
823
+ msg["From"] = from_email
824
+ msg["To"] = alert.email
825
+ msg["Subject"] = f"[{event.severity.value.upper()}] {event.alert_name}"
826
+
827
+ body = f"""
828
+ Empathy Framework Alert
829
+
830
+ Alert: {event.alert_name}
831
+ Metric: {event.metric.value}
832
+ Current Value: {event.current_value:.2f}
833
+ Threshold: {event.threshold:.2f}
834
+ Severity: {event.severity.value}
835
+ Triggered: {event.triggered_at.isoformat()}
836
+
837
+ --
838
+ Empathy Framework Monitoring
839
+ """
840
+ msg.attach(MIMEText(body, "plain"))
841
+
842
+ try:
843
+ with smtplib.SMTP(smtp_host, smtp_port) as server:
844
+ if smtp_user and smtp_password:
845
+ server.starttls()
846
+ server.login(smtp_user, smtp_password)
847
+ server.sendmail(from_email, alert.email, msg.as_string())
848
+ return True
849
+ except (smtplib.SMTPException, OSError) as e:
850
+ logger.error("email_delivery_failed", email=alert.email, error=str(e))
851
+ return False
852
+
853
+ def _deliver_stdout(self, event: AlertEvent) -> bool:
854
+ """Deliver alert to stdout/console."""
855
+ print(f"\n{'='*60}")
856
+ print(event.message)
857
+ print(f"{'='*60}\n")
858
+ return True
859
+
860
+ def _record_alert_history(self, event: AlertEvent, delivered: bool) -> None:
861
+ """Record alert event in history table."""
862
+ conn = sqlite3.connect(self.db_path)
863
+ cursor = conn.cursor()
864
+
865
+ cursor.execute(
866
+ """
867
+ INSERT INTO alert_history
868
+ (alert_id, metric, current_value, threshold, severity, delivered)
869
+ VALUES (?, ?, ?, ?, ?, ?)
870
+ """,
871
+ (
872
+ event.alert_id,
873
+ event.metric.value,
874
+ event.current_value,
875
+ event.threshold,
876
+ event.severity.value,
877
+ int(delivered),
878
+ ),
879
+ )
880
+
881
+ conn.commit()
882
+ conn.close()
883
+
884
+ def get_alert_history(
885
+ self, alert_id: str | None = None, limit: int = 100
886
+ ) -> list[dict[str, Any]]:
887
+ """Get alert history.
888
+
889
+ Args:
890
+ alert_id: Filter by alert ID (optional)
891
+ limit: Maximum number of records to return
892
+
893
+ Returns:
894
+ List of alert history records
895
+ """
896
+ conn = sqlite3.connect(self.db_path)
897
+ cursor = conn.cursor()
898
+
899
+ if alert_id:
900
+ cursor.execute(
901
+ """
902
+ SELECT alert_id, metric, current_value, threshold, severity,
903
+ triggered_at, delivered, delivery_error
904
+ FROM alert_history
905
+ WHERE alert_id = ?
906
+ ORDER BY triggered_at DESC
907
+ LIMIT ?
908
+ """,
909
+ (alert_id, limit),
910
+ )
911
+ else:
912
+ cursor.execute(
913
+ """
914
+ SELECT alert_id, metric, current_value, threshold, severity,
915
+ triggered_at, delivered, delivery_error
916
+ FROM alert_history
917
+ ORDER BY triggered_at DESC
918
+ LIMIT ?
919
+ """,
920
+ (limit,),
921
+ )
922
+
923
+ rows = cursor.fetchall()
924
+ conn.close()
925
+
926
+ return [
927
+ {
928
+ "alert_id": row[0],
929
+ "metric": row[1],
930
+ "current_value": row[2],
931
+ "threshold": row[3],
932
+ "severity": row[4],
933
+ "triggered_at": row[5],
934
+ "delivered": bool(row[6]),
935
+ "delivery_error": row[7],
936
+ }
937
+ for row in rows
938
+ ]
939
+
940
+
941
+ def get_alert_engine(
942
+ db_path: str | Path = ".empathy/alerts.db",
943
+ ) -> AlertEngine:
944
+ """Get an AlertEngine instance.
945
+
946
+ Args:
947
+ db_path: Path to SQLite database
948
+
949
+ Returns:
950
+ Configured AlertEngine instance
951
+ """
952
+ return AlertEngine(db_path=db_path)