empathy-framework 4.6.2__py3-none-any.whl → 4.6.3__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 (53) hide show
  1. {empathy_framework-4.6.2.dist-info → empathy_framework-4.6.3.dist-info}/METADATA +1 -1
  2. {empathy_framework-4.6.2.dist-info → empathy_framework-4.6.3.dist-info}/RECORD +53 -20
  3. {empathy_framework-4.6.2.dist-info → empathy_framework-4.6.3.dist-info}/WHEEL +1 -1
  4. empathy_os/__init__.py +1 -1
  5. empathy_os/cli.py +361 -32
  6. empathy_os/config/xml_config.py +8 -3
  7. empathy_os/core.py +37 -4
  8. empathy_os/leverage_points.py +2 -1
  9. empathy_os/memory/short_term.py +45 -1
  10. empathy_os/meta_workflows/agent_creator 2.py +254 -0
  11. empathy_os/meta_workflows/builtin_templates 2.py +567 -0
  12. empathy_os/meta_workflows/cli_meta_workflows 2.py +1551 -0
  13. empathy_os/meta_workflows/form_engine 2.py +304 -0
  14. empathy_os/meta_workflows/intent_detector 2.py +298 -0
  15. empathy_os/meta_workflows/pattern_learner 2.py +754 -0
  16. empathy_os/meta_workflows/session_context 2.py +398 -0
  17. empathy_os/meta_workflows/template_registry 2.py +229 -0
  18. empathy_os/meta_workflows/workflow 2.py +980 -0
  19. empathy_os/models/token_estimator.py +16 -9
  20. empathy_os/models/validation.py +7 -1
  21. empathy_os/orchestration/pattern_learner 2.py +699 -0
  22. empathy_os/orchestration/real_tools 2.py +938 -0
  23. empathy_os/orchestration/real_tools.py +4 -2
  24. empathy_os/socratic/__init__ 2.py +273 -0
  25. empathy_os/socratic/ab_testing 2.py +969 -0
  26. empathy_os/socratic/blueprint 2.py +532 -0
  27. empathy_os/socratic/cli 2.py +689 -0
  28. empathy_os/socratic/collaboration 2.py +1112 -0
  29. empathy_os/socratic/domain_templates 2.py +916 -0
  30. empathy_os/socratic/embeddings 2.py +734 -0
  31. empathy_os/socratic/engine 2.py +729 -0
  32. empathy_os/socratic/explainer 2.py +663 -0
  33. empathy_os/socratic/feedback 2.py +767 -0
  34. empathy_os/socratic/forms 2.py +624 -0
  35. empathy_os/socratic/generator 2.py +716 -0
  36. empathy_os/socratic/llm_analyzer 2.py +635 -0
  37. empathy_os/socratic/mcp_server 2.py +751 -0
  38. empathy_os/socratic/session 2.py +306 -0
  39. empathy_os/socratic/storage 2.py +635 -0
  40. empathy_os/socratic/storage.py +2 -1
  41. empathy_os/socratic/success 2.py +719 -0
  42. empathy_os/socratic/visual_editor 2.py +812 -0
  43. empathy_os/socratic/web_ui 2.py +925 -0
  44. empathy_os/tier_recommender.py +5 -2
  45. empathy_os/workflow_commands.py +11 -6
  46. empathy_os/workflows/base.py +1 -1
  47. empathy_os/workflows/batch_processing 2.py +310 -0
  48. empathy_os/workflows/release_prep_crew 2.py +968 -0
  49. empathy_os/workflows/test_coverage_boost_crew 2.py +848 -0
  50. empathy_os/workflows/test_maintenance.py +3 -2
  51. {empathy_framework-4.6.2.dist-info → empathy_framework-4.6.3.dist-info}/entry_points.txt +0 -0
  52. {empathy_framework-4.6.2.dist-info → empathy_framework-4.6.3.dist-info}/licenses/LICENSE +0 -0
  53. {empathy_framework-4.6.2.dist-info → empathy_framework-4.6.3.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,635 @@
1
+ """Persistent Storage for Socratic Sessions and Blueprints
2
+
3
+ Provides multiple storage backends for persisting:
4
+ - Socratic sessions (in-progress and completed)
5
+ - Workflow blueprints (generated workflows)
6
+ - Success metrics history (for feedback loop)
7
+
8
+ Backends:
9
+ - JSONFileStorage: Simple file-based storage (default)
10
+ - SQLiteStorage: SQLite database for better querying
11
+ - RedisStorage: Redis for distributed/production use
12
+
13
+ Copyright 2026 Smart-AI-Memory
14
+ Licensed under Fair Source License 0.9
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import json
20
+ import logging
21
+ import sqlite3
22
+ from abc import ABC, abstractmethod
23
+ from dataclasses import dataclass
24
+ from datetime import datetime
25
+ from pathlib import Path
26
+ from typing import Any
27
+
28
+ from .blueprint import WorkflowBlueprint
29
+ from .session import SessionState, SocraticSession
30
+ from .success import SuccessEvaluation
31
+
32
+ logger = logging.getLogger(__name__)
33
+
34
+
35
+ # =============================================================================
36
+ # STORAGE INTERFACE
37
+ # =============================================================================
38
+
39
+
40
+ class StorageBackend(ABC):
41
+ """Abstract base for storage backends."""
42
+
43
+ @abstractmethod
44
+ def save_session(self, session: SocraticSession) -> None:
45
+ """Save a Socratic session."""
46
+
47
+ @abstractmethod
48
+ def load_session(self, session_id: str) -> SocraticSession | None:
49
+ """Load a session by ID."""
50
+
51
+ @abstractmethod
52
+ def list_sessions(
53
+ self,
54
+ state: SessionState | None = None,
55
+ limit: int = 100,
56
+ ) -> list[dict[str, Any]]:
57
+ """List sessions with optional filtering."""
58
+
59
+ @abstractmethod
60
+ def delete_session(self, session_id: str) -> bool:
61
+ """Delete a session."""
62
+
63
+ @abstractmethod
64
+ def save_blueprint(self, blueprint: WorkflowBlueprint) -> None:
65
+ """Save a workflow blueprint."""
66
+
67
+ @abstractmethod
68
+ def load_blueprint(self, blueprint_id: str) -> WorkflowBlueprint | None:
69
+ """Load a blueprint by ID."""
70
+
71
+ @abstractmethod
72
+ def list_blueprints(
73
+ self,
74
+ domain: str | None = None,
75
+ limit: int = 100,
76
+ ) -> list[dict[str, Any]]:
77
+ """List blueprints with optional filtering."""
78
+
79
+ @abstractmethod
80
+ def save_evaluation(
81
+ self,
82
+ blueprint_id: str,
83
+ evaluation: SuccessEvaluation,
84
+ ) -> None:
85
+ """Save a success evaluation for a blueprint."""
86
+
87
+ @abstractmethod
88
+ def get_evaluations(
89
+ self,
90
+ blueprint_id: str,
91
+ limit: int = 10,
92
+ ) -> list[dict[str, Any]]:
93
+ """Get evaluation history for a blueprint."""
94
+
95
+
96
+ # =============================================================================
97
+ # JSON FILE STORAGE
98
+ # =============================================================================
99
+
100
+
101
+ class JSONFileStorage(StorageBackend):
102
+ """File-based JSON storage.
103
+
104
+ Structure:
105
+ base_dir/
106
+ sessions/
107
+ {session_id}.json
108
+ blueprints/
109
+ {blueprint_id}.json
110
+ evaluations/
111
+ {blueprint_id}/
112
+ {timestamp}.json
113
+
114
+ Example:
115
+ >>> storage = JSONFileStorage(".empathy/socratic")
116
+ >>> storage.save_session(session)
117
+ >>> loaded = storage.load_session(session.session_id)
118
+ """
119
+
120
+ def __init__(self, base_dir: str = ".empathy/socratic"):
121
+ """Initialize storage.
122
+
123
+ Args:
124
+ base_dir: Base directory for storage
125
+ """
126
+ self.base_dir = Path(base_dir)
127
+ self.sessions_dir = self.base_dir / "sessions"
128
+ self.blueprints_dir = self.base_dir / "blueprints"
129
+ self.evaluations_dir = self.base_dir / "evaluations"
130
+
131
+ # Create directories
132
+ self.sessions_dir.mkdir(parents=True, exist_ok=True)
133
+ self.blueprints_dir.mkdir(parents=True, exist_ok=True)
134
+ self.evaluations_dir.mkdir(parents=True, exist_ok=True)
135
+
136
+ def save_session(self, session: SocraticSession) -> None:
137
+ """Save a session to JSON file."""
138
+ path = self.sessions_dir / f"{session.session_id}.json"
139
+ data = session.to_dict()
140
+
141
+ with path.open("w") as f:
142
+ json.dump(data, f, indent=2, default=str)
143
+
144
+ logger.debug(f"Saved session {session.session_id}")
145
+
146
+ def load_session(self, session_id: str) -> SocraticSession | None:
147
+ """Load a session from JSON file."""
148
+ path = self.sessions_dir / f"{session_id}.json"
149
+
150
+ if not path.exists():
151
+ return None
152
+
153
+ try:
154
+ with path.open() as f:
155
+ data = json.load(f)
156
+ return SocraticSession.from_dict(data)
157
+ except (json.JSONDecodeError, KeyError) as e:
158
+ logger.error(f"Failed to load session {session_id}: {e}")
159
+ return None
160
+
161
+ def list_sessions(
162
+ self,
163
+ state: SessionState | None = None,
164
+ limit: int = 100,
165
+ ) -> list[dict[str, Any]]:
166
+ """List sessions with optional state filter."""
167
+ sessions = []
168
+
169
+ for path in sorted(self.sessions_dir.glob("*.json"), reverse=True):
170
+ if len(sessions) >= limit:
171
+ break
172
+
173
+ try:
174
+ with path.open() as f:
175
+ data = json.load(f)
176
+
177
+ # Filter by state if specified
178
+ if state and data.get("state") != state.value:
179
+ continue
180
+
181
+ sessions.append({
182
+ "session_id": data.get("session_id"),
183
+ "state": data.get("state"),
184
+ "goal": data.get("goal", "")[:100],
185
+ "created_at": data.get("created_at"),
186
+ "updated_at": data.get("updated_at"),
187
+ })
188
+ except (json.JSONDecodeError, KeyError):
189
+ continue
190
+
191
+ return sessions
192
+
193
+ def delete_session(self, session_id: str) -> bool:
194
+ """Delete a session file."""
195
+ path = self.sessions_dir / f"{session_id}.json"
196
+
197
+ if path.exists():
198
+ path.unlink()
199
+ return True
200
+ return False
201
+
202
+ def save_blueprint(self, blueprint: WorkflowBlueprint) -> None:
203
+ """Save a blueprint to JSON file."""
204
+ path = self.blueprints_dir / f"{blueprint.id}.json"
205
+ data = blueprint.to_dict()
206
+
207
+ with path.open("w") as f:
208
+ json.dump(data, f, indent=2, default=str)
209
+
210
+ logger.debug(f"Saved blueprint {blueprint.id}")
211
+
212
+ def load_blueprint(self, blueprint_id: str) -> WorkflowBlueprint | None:
213
+ """Load a blueprint from JSON file."""
214
+ path = self.blueprints_dir / f"{blueprint_id}.json"
215
+
216
+ if not path.exists():
217
+ return None
218
+
219
+ try:
220
+ with path.open() as f:
221
+ data = json.load(f)
222
+ return WorkflowBlueprint.from_dict(data)
223
+ except (json.JSONDecodeError, KeyError) as e:
224
+ logger.error(f"Failed to load blueprint {blueprint_id}: {e}")
225
+ return None
226
+
227
+ def list_blueprints(
228
+ self,
229
+ domain: str | None = None,
230
+ limit: int = 100,
231
+ ) -> list[dict[str, Any]]:
232
+ """List blueprints with optional domain filter."""
233
+ blueprints = []
234
+
235
+ for path in sorted(self.blueprints_dir.glob("*.json"), reverse=True):
236
+ if len(blueprints) >= limit:
237
+ break
238
+
239
+ try:
240
+ with path.open() as f:
241
+ data = json.load(f)
242
+
243
+ # Filter by domain if specified
244
+ if domain and data.get("domain") != domain:
245
+ continue
246
+
247
+ blueprints.append({
248
+ "id": data.get("id"),
249
+ "name": data.get("name"),
250
+ "domain": data.get("domain"),
251
+ "agents_count": len(data.get("agents", [])),
252
+ "generated_at": data.get("generated_at"),
253
+ })
254
+ except (json.JSONDecodeError, KeyError):
255
+ continue
256
+
257
+ return blueprints
258
+
259
+ def save_evaluation(
260
+ self,
261
+ blueprint_id: str,
262
+ evaluation: SuccessEvaluation,
263
+ ) -> None:
264
+ """Save an evaluation to JSON file."""
265
+ eval_dir = self.evaluations_dir / blueprint_id
266
+ eval_dir.mkdir(exist_ok=True)
267
+
268
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
269
+ path = eval_dir / f"{timestamp}.json"
270
+
271
+ data = evaluation.to_dict()
272
+ with path.open("w") as f:
273
+ json.dump(data, f, indent=2, default=str)
274
+
275
+ def get_evaluations(
276
+ self,
277
+ blueprint_id: str,
278
+ limit: int = 10,
279
+ ) -> list[dict[str, Any]]:
280
+ """Get evaluation history for a blueprint."""
281
+ eval_dir = self.evaluations_dir / blueprint_id
282
+
283
+ if not eval_dir.exists():
284
+ return []
285
+
286
+ evaluations = []
287
+ for path in sorted(eval_dir.glob("*.json"), reverse=True)[:limit]:
288
+ try:
289
+ with path.open() as f:
290
+ evaluations.append(json.load(f))
291
+ except json.JSONDecodeError:
292
+ continue
293
+
294
+ return evaluations
295
+
296
+
297
+ # =============================================================================
298
+ # SQLITE STORAGE
299
+ # =============================================================================
300
+
301
+
302
+ class SQLiteStorage(StorageBackend):
303
+ """SQLite database storage for better querying.
304
+
305
+ Example:
306
+ >>> storage = SQLiteStorage(".empathy/socratic.db")
307
+ >>> storage.save_session(session)
308
+ >>> sessions = storage.list_sessions(state=SessionState.COMPLETED)
309
+ """
310
+
311
+ def __init__(self, db_path: str = ".empathy/socratic.db"):
312
+ """Initialize SQLite storage.
313
+
314
+ Args:
315
+ db_path: Path to SQLite database file
316
+ """
317
+ self.db_path = Path(db_path)
318
+ self.db_path.parent.mkdir(parents=True, exist_ok=True)
319
+
320
+ self._init_database()
321
+
322
+ def _get_connection(self) -> sqlite3.Connection:
323
+ """Get database connection."""
324
+ conn = sqlite3.connect(str(self.db_path))
325
+ conn.row_factory = sqlite3.Row
326
+ return conn
327
+
328
+ def _init_database(self) -> None:
329
+ """Initialize database schema."""
330
+ with self._get_connection() as conn:
331
+ conn.executescript("""
332
+ CREATE TABLE IF NOT EXISTS sessions (
333
+ session_id TEXT PRIMARY KEY,
334
+ state TEXT NOT NULL,
335
+ goal TEXT,
336
+ domain TEXT,
337
+ confidence REAL,
338
+ created_at TEXT,
339
+ updated_at TEXT,
340
+ data JSON NOT NULL
341
+ );
342
+
343
+ CREATE INDEX IF NOT EXISTS idx_sessions_state ON sessions(state);
344
+ CREATE INDEX IF NOT EXISTS idx_sessions_domain ON sessions(domain);
345
+ CREATE INDEX IF NOT EXISTS idx_sessions_updated ON sessions(updated_at);
346
+
347
+ CREATE TABLE IF NOT EXISTS blueprints (
348
+ blueprint_id TEXT PRIMARY KEY,
349
+ name TEXT,
350
+ domain TEXT,
351
+ agents_count INTEGER,
352
+ generated_at TEXT,
353
+ source_session_id TEXT,
354
+ data JSON NOT NULL,
355
+ FOREIGN KEY (source_session_id) REFERENCES sessions(session_id)
356
+ );
357
+
358
+ CREATE INDEX IF NOT EXISTS idx_blueprints_domain ON blueprints(domain);
359
+ CREATE INDEX IF NOT EXISTS idx_blueprints_session ON blueprints(source_session_id);
360
+
361
+ CREATE TABLE IF NOT EXISTS evaluations (
362
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
363
+ blueprint_id TEXT NOT NULL,
364
+ overall_success INTEGER,
365
+ overall_score REAL,
366
+ evaluated_at TEXT,
367
+ data JSON NOT NULL,
368
+ FOREIGN KEY (blueprint_id) REFERENCES blueprints(blueprint_id)
369
+ );
370
+
371
+ CREATE INDEX IF NOT EXISTS idx_evaluations_blueprint ON evaluations(blueprint_id);
372
+ """)
373
+
374
+ def save_session(self, session: SocraticSession) -> None:
375
+ """Save session to database."""
376
+ data = session.to_dict()
377
+ domain = session.goal_analysis.domain if session.goal_analysis else None
378
+ confidence = session.goal_analysis.confidence if session.goal_analysis else None
379
+
380
+ with self._get_connection() as conn:
381
+ conn.execute("""
382
+ INSERT OR REPLACE INTO sessions
383
+ (session_id, state, goal, domain, confidence, created_at, updated_at, data)
384
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
385
+ """, (
386
+ session.session_id,
387
+ session.state.value,
388
+ session.goal,
389
+ domain,
390
+ confidence,
391
+ session.created_at.isoformat(),
392
+ session.updated_at.isoformat(),
393
+ json.dumps(data, default=str),
394
+ ))
395
+
396
+ def load_session(self, session_id: str) -> SocraticSession | None:
397
+ """Load session from database."""
398
+ with self._get_connection() as conn:
399
+ row = conn.execute(
400
+ "SELECT data FROM sessions WHERE session_id = ?",
401
+ (session_id,)
402
+ ).fetchone()
403
+
404
+ if row:
405
+ data = json.loads(row["data"])
406
+ return SocraticSession.from_dict(data)
407
+ return None
408
+
409
+ def list_sessions(
410
+ self,
411
+ state: SessionState | None = None,
412
+ limit: int = 100,
413
+ ) -> list[dict[str, Any]]:
414
+ """List sessions from database."""
415
+ with self._get_connection() as conn:
416
+ if state:
417
+ rows = conn.execute("""
418
+ SELECT session_id, state, goal, domain, confidence, created_at, updated_at
419
+ FROM sessions
420
+ WHERE state = ?
421
+ ORDER BY updated_at DESC
422
+ LIMIT ?
423
+ """, (state.value, limit)).fetchall()
424
+ else:
425
+ rows = conn.execute("""
426
+ SELECT session_id, state, goal, domain, confidence, created_at, updated_at
427
+ FROM sessions
428
+ ORDER BY updated_at DESC
429
+ LIMIT ?
430
+ """, (limit,)).fetchall()
431
+
432
+ return [dict(row) for row in rows]
433
+
434
+ def delete_session(self, session_id: str) -> bool:
435
+ """Delete session from database."""
436
+ with self._get_connection() as conn:
437
+ cursor = conn.execute(
438
+ "DELETE FROM sessions WHERE session_id = ?",
439
+ (session_id,)
440
+ )
441
+ return cursor.rowcount > 0
442
+
443
+ def save_blueprint(self, blueprint: WorkflowBlueprint) -> None:
444
+ """Save blueprint to database."""
445
+ data = blueprint.to_dict()
446
+
447
+ with self._get_connection() as conn:
448
+ conn.execute("""
449
+ INSERT OR REPLACE INTO blueprints
450
+ (blueprint_id, name, domain, agents_count, generated_at, source_session_id, data)
451
+ VALUES (?, ?, ?, ?, ?, ?, ?)
452
+ """, (
453
+ blueprint.id,
454
+ blueprint.name,
455
+ blueprint.domain,
456
+ len(blueprint.agents),
457
+ blueprint.generated_at,
458
+ blueprint.source_session_id,
459
+ json.dumps(data, default=str),
460
+ ))
461
+
462
+ def load_blueprint(self, blueprint_id: str) -> WorkflowBlueprint | None:
463
+ """Load blueprint from database."""
464
+ with self._get_connection() as conn:
465
+ row = conn.execute(
466
+ "SELECT data FROM blueprints WHERE blueprint_id = ?",
467
+ (blueprint_id,)
468
+ ).fetchone()
469
+
470
+ if row:
471
+ data = json.loads(row["data"])
472
+ return WorkflowBlueprint.from_dict(data)
473
+ return None
474
+
475
+ def list_blueprints(
476
+ self,
477
+ domain: str | None = None,
478
+ limit: int = 100,
479
+ ) -> list[dict[str, Any]]:
480
+ """List blueprints from database."""
481
+ with self._get_connection() as conn:
482
+ if domain:
483
+ rows = conn.execute("""
484
+ SELECT blueprint_id as id, name, domain, agents_count, generated_at
485
+ FROM blueprints
486
+ WHERE domain = ?
487
+ ORDER BY generated_at DESC
488
+ LIMIT ?
489
+ """, (domain, limit)).fetchall()
490
+ else:
491
+ rows = conn.execute("""
492
+ SELECT blueprint_id as id, name, domain, agents_count, generated_at
493
+ FROM blueprints
494
+ ORDER BY generated_at DESC
495
+ LIMIT ?
496
+ """, (limit,)).fetchall()
497
+
498
+ return [dict(row) for row in rows]
499
+
500
+ def save_evaluation(
501
+ self,
502
+ blueprint_id: str,
503
+ evaluation: SuccessEvaluation,
504
+ ) -> None:
505
+ """Save evaluation to database."""
506
+ data = evaluation.to_dict()
507
+
508
+ with self._get_connection() as conn:
509
+ conn.execute("""
510
+ INSERT INTO evaluations
511
+ (blueprint_id, overall_success, overall_score, evaluated_at, data)
512
+ VALUES (?, ?, ?, ?, ?)
513
+ """, (
514
+ blueprint_id,
515
+ 1 if evaluation.overall_success else 0,
516
+ evaluation.overall_score,
517
+ evaluation.evaluated_at,
518
+ json.dumps(data, default=str),
519
+ ))
520
+
521
+ def get_evaluations(
522
+ self,
523
+ blueprint_id: str,
524
+ limit: int = 10,
525
+ ) -> list[dict[str, Any]]:
526
+ """Get evaluations from database."""
527
+ with self._get_connection() as conn:
528
+ rows = conn.execute("""
529
+ SELECT data FROM evaluations
530
+ WHERE blueprint_id = ?
531
+ ORDER BY evaluated_at DESC
532
+ LIMIT ?
533
+ """, (blueprint_id, limit)).fetchall()
534
+
535
+ return [json.loads(row["data"]) for row in rows]
536
+
537
+ def get_success_rate(self, blueprint_id: str) -> float:
538
+ """Get overall success rate for a blueprint."""
539
+ with self._get_connection() as conn:
540
+ row = conn.execute("""
541
+ SELECT
542
+ COUNT(*) as total,
543
+ SUM(overall_success) as successes
544
+ FROM evaluations
545
+ WHERE blueprint_id = ?
546
+ """, (blueprint_id,)).fetchone()
547
+
548
+ if row and row["total"] > 0:
549
+ return row["successes"] / row["total"]
550
+ return 0.0
551
+
552
+ def search_blueprints(
553
+ self,
554
+ query: str,
555
+ limit: int = 20,
556
+ ) -> list[dict[str, Any]]:
557
+ """Search blueprints by name or domain."""
558
+ with self._get_connection() as conn:
559
+ rows = conn.execute("""
560
+ SELECT blueprint_id as id, name, domain, agents_count, generated_at
561
+ FROM blueprints
562
+ WHERE name LIKE ? OR domain LIKE ?
563
+ ORDER BY generated_at DESC
564
+ LIMIT ?
565
+ """, (f"%{query}%", f"%{query}%", limit)).fetchall()
566
+
567
+ return [dict(row) for row in rows]
568
+
569
+
570
+ # =============================================================================
571
+ # STORAGE MANAGER
572
+ # =============================================================================
573
+
574
+
575
+ @dataclass
576
+ class StorageConfig:
577
+ """Storage configuration."""
578
+
579
+ backend: str = "json" # json, sqlite, redis
580
+ path: str = ".empathy/socratic"
581
+ redis_url: str | None = None
582
+
583
+
584
+ class StorageManager:
585
+ """Manages storage backend lifecycle.
586
+
587
+ Example:
588
+ >>> manager = StorageManager(StorageConfig(backend="sqlite"))
589
+ >>> storage = manager.get_storage()
590
+ >>> storage.save_session(session)
591
+ """
592
+
593
+ def __init__(self, config: StorageConfig | None = None):
594
+ """Initialize manager.
595
+
596
+ Args:
597
+ config: Storage configuration
598
+ """
599
+ self.config = config or StorageConfig()
600
+ self._storage: StorageBackend | None = None
601
+
602
+ def get_storage(self) -> StorageBackend:
603
+ """Get or create storage backend."""
604
+ if self._storage is None:
605
+ self._storage = self._create_storage()
606
+ return self._storage
607
+
608
+ def _create_storage(self) -> StorageBackend:
609
+ """Create storage backend based on config."""
610
+ if self.config.backend == "sqlite":
611
+ return SQLiteStorage(f"{self.config.path}.db")
612
+ elif self.config.backend == "redis":
613
+ # Redis would be implemented separately
614
+ logger.warning("Redis storage not implemented, using JSON")
615
+ return JSONFileStorage(self.config.path)
616
+ else:
617
+ return JSONFileStorage(self.config.path)
618
+
619
+
620
+ # Default storage instance
621
+ _default_storage: StorageBackend | None = None
622
+
623
+
624
+ def get_default_storage() -> StorageBackend:
625
+ """Get the default storage backend."""
626
+ global _default_storage
627
+ if _default_storage is None:
628
+ _default_storage = JSONFileStorage()
629
+ return _default_storage
630
+
631
+
632
+ def set_default_storage(storage: StorageBackend) -> None:
633
+ """Set the default storage backend."""
634
+ global _default_storage
635
+ _default_storage = storage
@@ -16,6 +16,7 @@ Licensed under Fair Source License 0.9
16
16
 
17
17
  from __future__ import annotations
18
18
 
19
+ import heapq
19
20
  import json
20
21
  import logging
21
22
  import sqlite3
@@ -284,7 +285,7 @@ class JSONFileStorage(StorageBackend):
284
285
  return []
285
286
 
286
287
  evaluations = []
287
- for path in sorted(eval_dir.glob("*.json"), reverse=True)[:limit]:
288
+ for path in heapq.nlargest(limit, eval_dir.glob("*.json")):
288
289
  try:
289
290
  with path.open() as f:
290
291
  evaluations.append(json.load(f))