empathy-framework 4.1.1__py3-none-any.whl → 4.4.0__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 (45) hide show
  1. {empathy_framework-4.1.1.dist-info → empathy_framework-4.4.0.dist-info}/METADATA +77 -12
  2. {empathy_framework-4.1.1.dist-info → empathy_framework-4.4.0.dist-info}/RECORD +45 -14
  3. empathy_os/cli_unified.py +13 -0
  4. empathy_os/memory/long_term.py +5 -0
  5. empathy_os/memory/unified.py +149 -9
  6. empathy_os/meta_workflows/__init__.py +74 -0
  7. empathy_os/meta_workflows/agent_creator.py +254 -0
  8. empathy_os/meta_workflows/builtin_templates.py +567 -0
  9. empathy_os/meta_workflows/cli_meta_workflows.py +1551 -0
  10. empathy_os/meta_workflows/form_engine.py +304 -0
  11. empathy_os/meta_workflows/intent_detector.py +298 -0
  12. empathy_os/meta_workflows/models.py +567 -0
  13. empathy_os/meta_workflows/pattern_learner.py +754 -0
  14. empathy_os/meta_workflows/session_context.py +398 -0
  15. empathy_os/meta_workflows/template_registry.py +229 -0
  16. empathy_os/meta_workflows/workflow.py +980 -0
  17. empathy_os/orchestration/execution_strategies.py +888 -1
  18. empathy_os/orchestration/pattern_learner.py +699 -0
  19. empathy_os/socratic/__init__.py +273 -0
  20. empathy_os/socratic/ab_testing.py +969 -0
  21. empathy_os/socratic/blueprint.py +532 -0
  22. empathy_os/socratic/cli.py +689 -0
  23. empathy_os/socratic/collaboration.py +1112 -0
  24. empathy_os/socratic/domain_templates.py +916 -0
  25. empathy_os/socratic/embeddings.py +734 -0
  26. empathy_os/socratic/engine.py +729 -0
  27. empathy_os/socratic/explainer.py +663 -0
  28. empathy_os/socratic/feedback.py +767 -0
  29. empathy_os/socratic/forms.py +624 -0
  30. empathy_os/socratic/generator.py +716 -0
  31. empathy_os/socratic/llm_analyzer.py +635 -0
  32. empathy_os/socratic/mcp_server.py +751 -0
  33. empathy_os/socratic/session.py +306 -0
  34. empathy_os/socratic/storage.py +635 -0
  35. empathy_os/socratic/success.py +719 -0
  36. empathy_os/socratic/visual_editor.py +812 -0
  37. empathy_os/socratic/web_ui.py +925 -0
  38. empathy_os/workflows/manage_documentation.py +18 -2
  39. empathy_os/workflows/release_prep_crew.py +16 -1
  40. empathy_os/workflows/test_coverage_boost_crew.py +16 -1
  41. empathy_os/workflows/test_maintenance_crew.py +18 -1
  42. {empathy_framework-4.1.1.dist-info → empathy_framework-4.4.0.dist-info}/WHEEL +0 -0
  43. {empathy_framework-4.1.1.dist-info → empathy_framework-4.4.0.dist-info}/entry_points.txt +0 -0
  44. {empathy_framework-4.1.1.dist-info → empathy_framework-4.4.0.dist-info}/licenses/LICENSE +0 -0
  45. {empathy_framework-4.1.1.dist-info → empathy_framework-4.4.0.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,567 @@
1
+ """Core data models for meta-workflow system.
2
+
3
+ This module defines the data structures for:
4
+ - Form schemas and responses (Socratic questioning)
5
+ - Agent composition rules and specs (dynamic agent generation)
6
+ - Meta-workflow templates and results (orchestration)
7
+
8
+ Created: 2026-01-17
9
+ Purpose: Enable dynamic workflow creation via forms + agent teams
10
+ """
11
+
12
+ import json
13
+ import uuid
14
+ from dataclasses import asdict, dataclass, field
15
+ from datetime import datetime
16
+ from enum import Enum
17
+ from typing import Any
18
+
19
+ # =============================================================================
20
+ # Enums
21
+ # =============================================================================
22
+
23
+
24
+ class QuestionType(str, Enum):
25
+ """Types of form questions supported."""
26
+
27
+ TEXT_INPUT = "text_input"
28
+ SINGLE_SELECT = "single_select"
29
+ MULTI_SELECT = "multi_select"
30
+ BOOLEAN = "boolean"
31
+
32
+
33
+ class TierStrategy(str, Enum):
34
+ """Model tier escalation strategies for agents."""
35
+
36
+ CHEAP_ONLY = "cheap_only" # Use only cheap tier
37
+ PROGRESSIVE = "progressive" # Escalate cheap → capable → premium
38
+ CAPABLE_FIRST = "capable_first" # Start at capable, escalate to premium if needed
39
+ PREMIUM_ONLY = "premium_only" # Use only premium tier
40
+
41
+
42
+ # =============================================================================
43
+ # Form Components
44
+ # =============================================================================
45
+
46
+
47
+ @dataclass
48
+ class FormQuestion:
49
+ """A single question in a Socratic form.
50
+
51
+ Attributes:
52
+ id: Unique identifier for this question
53
+ text: The question text shown to user
54
+ type: Question type (text_input, single_select, etc.)
55
+ options: Available options for select questions
56
+ default: Default value if user doesn't provide one
57
+ help_text: Additional help text shown to user
58
+ required: Whether this question must be answered
59
+ """
60
+
61
+ id: str
62
+ text: str
63
+ type: QuestionType
64
+ options: list[str] = field(default_factory=list)
65
+ default: str | None = None
66
+ help_text: str | None = None
67
+ required: bool = True
68
+
69
+ def to_ask_user_format(self) -> dict[str, Any]:
70
+ """Convert to format compatible with AskUserQuestion tool.
71
+
72
+ Returns:
73
+ Dictionary with question data for AskUserQuestion
74
+ """
75
+ # Boolean questions convert to Yes/No select
76
+ if self.type == QuestionType.BOOLEAN:
77
+ return {
78
+ "question_id": self.id,
79
+ "question": self.text,
80
+ "type": "single_select",
81
+ "options": ["Yes", "No"],
82
+ "default": self.default, # Preserve default for boolean questions
83
+ "help_text": self.help_text,
84
+ }
85
+
86
+ return {
87
+ "question_id": self.id,
88
+ "question": self.text,
89
+ "type": self.type.value,
90
+ "options": self.options,
91
+ "default": self.default,
92
+ "help_text": self.help_text,
93
+ }
94
+
95
+
96
+ @dataclass
97
+ class FormSchema:
98
+ """Schema defining a collection of questions for a meta-workflow.
99
+
100
+ Attributes:
101
+ title: Form title
102
+ description: Form description
103
+ questions: List of questions to ask
104
+ """
105
+
106
+ title: str
107
+ description: str
108
+ questions: list[FormQuestion] = field(default_factory=list)
109
+
110
+ def get_question_batches(self, batch_size: int = 4) -> list[list[FormQuestion]]:
111
+ """Batch questions for asking (AskUserQuestion supports max 4 at once).
112
+
113
+ Args:
114
+ batch_size: Maximum questions per batch (default: 4)
115
+
116
+ Returns:
117
+ List of question batches
118
+ """
119
+ batches = []
120
+ for i in range(0, len(self.questions), batch_size):
121
+ batches.append(self.questions[i : i + batch_size])
122
+ return batches
123
+
124
+
125
+ @dataclass
126
+ class FormResponse:
127
+ """User's responses to a form.
128
+
129
+ Attributes:
130
+ template_id: ID of template this response is for
131
+ responses: Dictionary mapping question_id → user's answer
132
+ timestamp: When response was submitted
133
+ response_id: Unique ID for this response
134
+ """
135
+
136
+ template_id: str
137
+ responses: dict[str, Any] = field(default_factory=dict)
138
+ timestamp: str = field(default_factory=lambda: datetime.now().isoformat())
139
+ response_id: str = field(default_factory=lambda: f"resp-{datetime.now().strftime('%Y%m%d-%H%M%S')}")
140
+
141
+ def get(self, question_id: str, default: Any = None) -> Any:
142
+ """Get response for a question.
143
+
144
+ Args:
145
+ question_id: ID of question
146
+ default: Default value if not found
147
+
148
+ Returns:
149
+ User's response or default
150
+ """
151
+ return self.responses.get(question_id, default)
152
+
153
+
154
+ # =============================================================================
155
+ # Agent Components
156
+ # =============================================================================
157
+
158
+
159
+ @dataclass
160
+ class AgentCompositionRule:
161
+ """Rule defining when and how to create an agent.
162
+
163
+ Attributes:
164
+ role: Agent's role/purpose
165
+ base_template: Base agent template to use
166
+ tier_strategy: Model tier escalation strategy
167
+ tools: List of tools agent can use
168
+ required_responses: Conditions that must be met (question_id → required value)
169
+ config_mapping: Map form responses to agent config (form_key → config_key)
170
+ success_criteria: List of success criteria for this agent
171
+ """
172
+
173
+ role: str
174
+ base_template: str
175
+ tier_strategy: TierStrategy
176
+ tools: list[str] = field(default_factory=list)
177
+ required_responses: dict[str, str | list[str]] = field(default_factory=dict)
178
+ config_mapping: dict[str, str] = field(default_factory=dict)
179
+ success_criteria: list[str] = field(default_factory=list)
180
+
181
+ def should_create(self, response: FormResponse) -> bool:
182
+ """Check if agent should be created based on form responses.
183
+
184
+ Args:
185
+ response: User's form responses
186
+
187
+ Returns:
188
+ True if all required conditions are met
189
+ """
190
+ for key, required_value in self.required_responses.items():
191
+ user_response = response.get(key)
192
+
193
+ # Multi-select: check if required value in list
194
+ if isinstance(user_response, list):
195
+ # If required_value is a list, check if ANY match
196
+ if isinstance(required_value, list):
197
+ if not any(rv in user_response for rv in required_value):
198
+ return False
199
+ # Single required value must be in user's selections
200
+ else:
201
+ if required_value not in user_response:
202
+ return False
203
+
204
+ # Single value: exact match required
205
+ else:
206
+ if isinstance(required_value, list):
207
+ # User must have picked one of the allowed values
208
+ if user_response not in required_value:
209
+ return False
210
+ else:
211
+ # Exact match
212
+ if user_response != required_value:
213
+ return False
214
+
215
+ return True
216
+
217
+ def create_agent_config(self, response: FormResponse) -> dict[str, Any]:
218
+ """Create agent configuration from form responses.
219
+
220
+ Args:
221
+ response: User's form responses
222
+
223
+ Returns:
224
+ Agent configuration dictionary
225
+ """
226
+ config = {}
227
+ for form_key, config_key in self.config_mapping.items():
228
+ value = response.get(form_key)
229
+ if value is not None:
230
+ config[config_key] = value
231
+ return config
232
+
233
+
234
+ @dataclass
235
+ class AgentSpec:
236
+ """Specification for a dynamically created agent instance.
237
+
238
+ Attributes:
239
+ role: Agent's role/purpose
240
+ base_template: Base agent template used
241
+ tier_strategy: Model tier escalation strategy
242
+ tools: List of tools agent can use
243
+ config: Agent-specific configuration
244
+ success_criteria: List of success criteria
245
+ agent_id: Unique identifier for this agent instance
246
+ """
247
+
248
+ role: str
249
+ base_template: str
250
+ tier_strategy: TierStrategy
251
+ tools: list[str] = field(default_factory=list)
252
+ config: dict[str, Any] = field(default_factory=dict)
253
+ success_criteria: list[str] = field(default_factory=list)
254
+ agent_id: str = field(default_factory=lambda: f"agent-{uuid.uuid4().hex[:12]}")
255
+
256
+
257
+ # =============================================================================
258
+ # Meta-Workflow Components
259
+ # =============================================================================
260
+
261
+
262
+ @dataclass
263
+ class MetaWorkflowTemplate:
264
+ """Template defining a complete meta-workflow.
265
+
266
+ Attributes:
267
+ template_id: Unique identifier for this template
268
+ name: Human-readable name
269
+ description: Description of what this workflow does
270
+ version: Template version
271
+ tags: Tags for categorization
272
+ author: Template author
273
+ form_schema: Form questions to ask user
274
+ agent_composition_rules: Rules for creating agents
275
+ estimated_cost_range: Estimated cost range (min, max)
276
+ estimated_duration_minutes: Estimated duration in minutes
277
+ """
278
+
279
+ template_id: str
280
+ name: str
281
+ description: str
282
+ form_schema: FormSchema
283
+ agent_composition_rules: list[AgentCompositionRule] = field(default_factory=list)
284
+ version: str = "1.0.0"
285
+ tags: list[str] = field(default_factory=list)
286
+ author: str = "system"
287
+ estimated_cost_range: tuple[float, float] = (0.05, 0.50)
288
+ estimated_duration_minutes: int = 5
289
+
290
+ def to_json(self) -> str:
291
+ """Serialize template to JSON string.
292
+
293
+ Returns:
294
+ JSON string representation
295
+ """
296
+ data = {
297
+ "template_id": self.template_id,
298
+ "name": self.name,
299
+ "description": self.description,
300
+ "version": self.version,
301
+ "tags": self.tags,
302
+ "author": self.author,
303
+ "estimated_cost_range": list(self.estimated_cost_range),
304
+ "estimated_duration_minutes": self.estimated_duration_minutes,
305
+ "form_schema": {
306
+ "title": self.form_schema.title,
307
+ "description": self.form_schema.description,
308
+ "questions": [
309
+ {
310
+ "id": q.id,
311
+ "text": q.text,
312
+ "type": q.type.value,
313
+ "options": q.options,
314
+ "default": q.default,
315
+ "help_text": q.help_text,
316
+ "required": q.required,
317
+ }
318
+ for q in self.form_schema.questions
319
+ ],
320
+ },
321
+ "agent_composition_rules": [
322
+ {
323
+ "role": rule.role,
324
+ "base_template": rule.base_template,
325
+ "tier_strategy": rule.tier_strategy.value,
326
+ "tools": rule.tools,
327
+ "required_responses": rule.required_responses,
328
+ "config_mapping": rule.config_mapping,
329
+ "success_criteria": rule.success_criteria,
330
+ }
331
+ for rule in self.agent_composition_rules
332
+ ],
333
+ }
334
+ return json.dumps(data, indent=2)
335
+
336
+ @staticmethod
337
+ def from_json(json_str: str) -> "MetaWorkflowTemplate":
338
+ """Deserialize template from JSON string.
339
+
340
+ Args:
341
+ json_str: JSON string representation
342
+
343
+ Returns:
344
+ MetaWorkflowTemplate instance
345
+
346
+ Raises:
347
+ ValueError: If JSON is invalid or missing required fields
348
+ """
349
+ try:
350
+ data = json.loads(json_str)
351
+ except json.JSONDecodeError as e:
352
+ raise ValueError(f"Invalid JSON: {e}") from e
353
+
354
+ # Parse form schema
355
+ form_schema = FormSchema(
356
+ title=data["form_schema"]["title"],
357
+ description=data["form_schema"]["description"],
358
+ questions=[
359
+ FormQuestion(
360
+ id=q["id"],
361
+ text=q["text"],
362
+ type=QuestionType(q["type"]),
363
+ options=q.get("options", []),
364
+ default=q.get("default"),
365
+ help_text=q.get("help_text"),
366
+ required=q.get("required", True),
367
+ )
368
+ for q in data["form_schema"]["questions"]
369
+ ],
370
+ )
371
+
372
+ # Parse agent composition rules
373
+ rules = [
374
+ AgentCompositionRule(
375
+ role=rule["role"],
376
+ base_template=rule["base_template"],
377
+ tier_strategy=TierStrategy(rule["tier_strategy"]),
378
+ tools=rule.get("tools", []),
379
+ required_responses=rule.get("required_responses", {}),
380
+ config_mapping=rule.get("config_mapping", {}),
381
+ success_criteria=rule.get("success_criteria", []),
382
+ )
383
+ for rule in data.get("agent_composition_rules", [])
384
+ ]
385
+
386
+ return MetaWorkflowTemplate(
387
+ template_id=data["template_id"],
388
+ name=data["name"],
389
+ description=data["description"],
390
+ version=data.get("version", "1.0.0"),
391
+ tags=data.get("tags", []),
392
+ author=data.get("author", "system"),
393
+ form_schema=form_schema,
394
+ agent_composition_rules=rules,
395
+ estimated_cost_range=tuple(data.get("estimated_cost_range", [0.05, 0.50])),
396
+ estimated_duration_minutes=data.get("estimated_duration_minutes", 5),
397
+ )
398
+
399
+
400
+ @dataclass
401
+ class AgentExecutionResult:
402
+ """Result from executing a single agent.
403
+
404
+ Attributes:
405
+ agent_id: ID of agent that executed
406
+ role: Agent's role
407
+ success: Whether agent succeeded
408
+ cost: Cost of execution
409
+ duration: Duration in seconds
410
+ tier_used: Model tier used
411
+ output: Agent's output/result
412
+ error: Error message if failed
413
+ """
414
+
415
+ agent_id: str
416
+ role: str
417
+ success: bool
418
+ cost: float
419
+ duration: float
420
+ tier_used: str
421
+ output: str | dict[str, Any]
422
+ error: str | None = None
423
+
424
+
425
+ @dataclass
426
+ class MetaWorkflowResult:
427
+ """Result from executing a complete meta-workflow.
428
+
429
+ Attributes:
430
+ run_id: Unique ID for this execution
431
+ template_id: ID of template used
432
+ timestamp: When execution started
433
+ form_responses: User's form responses
434
+ agents_created: List of agents that were created
435
+ agent_results: Results from agent executions
436
+ total_cost: Total cost of execution
437
+ total_duration: Total duration in seconds
438
+ success: Whether workflow succeeded
439
+ error: Error message if failed
440
+ """
441
+
442
+ run_id: str
443
+ template_id: str
444
+ timestamp: str
445
+ form_responses: FormResponse
446
+ agents_created: list[AgentSpec] = field(default_factory=list)
447
+ agent_results: list[AgentExecutionResult] = field(default_factory=list)
448
+ total_cost: float = 0.0
449
+ total_duration: float = 0.0
450
+ success: bool = True
451
+ error: str | None = None
452
+
453
+ def to_dict(self) -> dict[str, Any]:
454
+ """Convert result to dictionary for serialization.
455
+
456
+ Returns:
457
+ Dictionary representation
458
+ """
459
+ return {
460
+ "run_id": self.run_id,
461
+ "template_id": self.template_id,
462
+ "timestamp": self.timestamp,
463
+ "form_responses": asdict(self.form_responses),
464
+ "agents_created": [asdict(agent) for agent in self.agents_created],
465
+ "agent_results": [asdict(result) for result in self.agent_results],
466
+ "total_cost": self.total_cost,
467
+ "total_duration": self.total_duration,
468
+ "success": self.success,
469
+ "error": self.error,
470
+ }
471
+
472
+ def to_json(self) -> str:
473
+ """Serialize result to JSON string.
474
+
475
+ Returns:
476
+ JSON string representation
477
+ """
478
+ return json.dumps(self.to_dict(), indent=2)
479
+
480
+ @staticmethod
481
+ def from_dict(data: dict[str, Any]) -> "MetaWorkflowResult":
482
+ """Create result from dictionary.
483
+
484
+ Args:
485
+ data: Dictionary representation
486
+
487
+ Returns:
488
+ MetaWorkflowResult instance
489
+ """
490
+ form_responses = FormResponse(
491
+ template_id=data["form_responses"]["template_id"],
492
+ responses=data["form_responses"]["responses"],
493
+ timestamp=data["form_responses"]["timestamp"],
494
+ response_id=data["form_responses"]["response_id"],
495
+ )
496
+
497
+ agents_created = [
498
+ AgentSpec(
499
+ role=agent["role"],
500
+ base_template=agent["base_template"],
501
+ tier_strategy=TierStrategy(agent["tier_strategy"]),
502
+ tools=agent["tools"],
503
+ config=agent["config"],
504
+ success_criteria=agent["success_criteria"],
505
+ agent_id=agent["agent_id"],
506
+ )
507
+ for agent in data.get("agents_created", [])
508
+ ]
509
+
510
+ agent_results = [
511
+ AgentExecutionResult(
512
+ agent_id=result["agent_id"],
513
+ role=result["role"],
514
+ success=result["success"],
515
+ cost=result["cost"],
516
+ duration=result["duration"],
517
+ tier_used=result["tier_used"],
518
+ output=result["output"],
519
+ error=result.get("error"),
520
+ )
521
+ for result in data.get("agent_results", [])
522
+ ]
523
+
524
+ return MetaWorkflowResult(
525
+ run_id=data["run_id"],
526
+ template_id=data["template_id"],
527
+ timestamp=data["timestamp"],
528
+ form_responses=form_responses,
529
+ agents_created=agents_created,
530
+ agent_results=agent_results,
531
+ total_cost=data.get("total_cost", 0.0),
532
+ total_duration=data.get("total_duration", 0.0),
533
+ success=data.get("success", True),
534
+ error=data.get("error"),
535
+ )
536
+
537
+
538
+ # =============================================================================
539
+ # Insight/Analytics Components
540
+ # =============================================================================
541
+
542
+
543
+ @dataclass
544
+ class PatternInsight:
545
+ """An insight learned from analyzing workflow patterns.
546
+
547
+ Attributes:
548
+ insight_type: Type of insight (cost, tier_performance, agent_count, etc.)
549
+ description: Human-readable description
550
+ confidence: Confidence level (0.0 to 1.0)
551
+ data: Supporting data for this insight
552
+ sample_size: Number of runs this insight is based on
553
+ """
554
+
555
+ insight_type: str
556
+ description: str
557
+ confidence: float
558
+ data: dict[str, Any] = field(default_factory=dict)
559
+ sample_size: int = 0
560
+
561
+ def to_dict(self) -> dict[str, Any]:
562
+ """Convert to dictionary.
563
+
564
+ Returns:
565
+ Dictionary representation
566
+ """
567
+ return asdict(self)