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
@@ -1,28 +1,43 @@
1
1
  """Execution strategies for agent composition patterns.
2
2
 
3
- This module implements the 6 grammar rules for composing agents:
3
+ This module implements the 7 grammar rules for composing agents:
4
4
  1. Sequential (A → B → C)
5
5
  2. Parallel (A || B || C)
6
6
  3. Debate (A ⇄ B ⇄ C → Synthesis)
7
7
  4. Teaching (Junior → Expert validation)
8
8
  5. Refinement (Draft → Review → Polish)
9
9
  6. Adaptive (Classifier → Specialist)
10
+ 7. Conditional (if X then A else B) - branching based on gates
10
11
 
11
12
  Security:
12
13
  - All agent outputs validated before passing to next agent
13
14
  - No eval() or exec() usage
14
15
  - Timeout enforcement at strategy level
16
+ - Condition predicates validated (no code execution)
15
17
 
16
18
  Example:
17
19
  >>> strategy = SequentialStrategy()
18
20
  >>> agents = [agent1, agent2, agent3]
19
21
  >>> result = await strategy.execute(agents, context)
22
+
23
+ >>> # Conditional branching example
24
+ >>> cond_strategy = ConditionalStrategy(
25
+ ... condition=Condition(predicate={"confidence": {"$lt": 0.8}}),
26
+ ... then_branch=expert_agents,
27
+ ... else_branch=fast_agents
28
+ ... )
29
+ >>> result = await cond_strategy.execute([], context)
20
30
  """
21
31
 
22
32
  import asyncio
33
+ import json
23
34
  import logging
35
+ import operator
36
+ import re
24
37
  from abc import ABC, abstractmethod
38
+ from collections.abc import Callable
25
39
  from dataclasses import dataclass, field
40
+ from enum import Enum
26
41
  from typing import Any
27
42
 
28
43
  from .agent_templates import AgentTemplate
@@ -75,6 +90,548 @@ class StrategyResult:
75
90
  self.errors = []
76
91
 
77
92
 
93
+ # =============================================================================
94
+ # Conditional Grammar Types (Pattern 7)
95
+ # =============================================================================
96
+
97
+
98
+ class ConditionType(Enum):
99
+ """Type of condition for gate evaluation.
100
+
101
+ Attributes:
102
+ JSON_PREDICATE: MongoDB-style JSON predicate ({"field": {"$op": value}})
103
+ NATURAL_LANGUAGE: LLM-interpreted natural language condition
104
+ COMPOSITE: Logical combination of conditions (AND/OR)
105
+ """
106
+
107
+ JSON_PREDICATE = "json"
108
+ NATURAL_LANGUAGE = "natural"
109
+ COMPOSITE = "composite"
110
+
111
+
112
+ @dataclass
113
+ class Condition:
114
+ """A conditional gate for branching in agent workflows.
115
+
116
+ Supports hybrid syntax: JSON predicates for simple conditions,
117
+ natural language for complex semantic conditions.
118
+
119
+ Attributes:
120
+ predicate: JSON predicate dict or natural language string
121
+ condition_type: How to evaluate the condition
122
+ description: Human-readable description of the condition
123
+ source_field: Which field(s) in context to evaluate
124
+
125
+ JSON Predicate Operators:
126
+ $eq: Equal to value
127
+ $ne: Not equal to value
128
+ $gt: Greater than value
129
+ $gte: Greater than or equal to value
130
+ $lt: Less than value
131
+ $lte: Less than or equal to value
132
+ $in: Value is in list
133
+ $nin: Value is not in list
134
+ $exists: Field exists (or not)
135
+ $regex: Matches regex pattern
136
+
137
+ Example (JSON):
138
+ >>> # Low confidence triggers expert review
139
+ >>> cond = Condition(
140
+ ... predicate={"confidence": {"$lt": 0.8}},
141
+ ... description="Confidence is below threshold"
142
+ ... )
143
+
144
+ Example (Natural Language):
145
+ >>> # LLM interprets complex semantic condition
146
+ >>> cond = Condition(
147
+ ... predicate="The security audit found critical vulnerabilities",
148
+ ... condition_type=ConditionType.NATURAL_LANGUAGE,
149
+ ... description="Security issues detected"
150
+ ... )
151
+ """
152
+
153
+ predicate: dict[str, Any] | str
154
+ condition_type: ConditionType = ConditionType.JSON_PREDICATE
155
+ description: str = ""
156
+ source_field: str = "" # Empty means evaluate whole context
157
+
158
+ def __post_init__(self):
159
+ """Validate condition and auto-detect type."""
160
+ if isinstance(self.predicate, str):
161
+ # Auto-detect: if it looks like prose, it's natural language
162
+ if " " in self.predicate and not self.predicate.startswith("{"):
163
+ object.__setattr__(self, "condition_type", ConditionType.NATURAL_LANGUAGE)
164
+ elif isinstance(self.predicate, dict):
165
+ # Validate JSON predicate structure
166
+ self._validate_predicate(self.predicate)
167
+ else:
168
+ raise ValueError(f"predicate must be dict or str, got {type(self.predicate)}")
169
+
170
+ def _validate_predicate(self, predicate: dict[str, Any]) -> None:
171
+ """Validate JSON predicate structure (no code execution).
172
+
173
+ Args:
174
+ predicate: The predicate dict to validate
175
+
176
+ Raises:
177
+ ValueError: If predicate contains invalid operators
178
+ """
179
+ valid_operators = {
180
+ "$eq",
181
+ "$ne",
182
+ "$gt",
183
+ "$gte",
184
+ "$lt",
185
+ "$lte",
186
+ "$in",
187
+ "$nin",
188
+ "$exists",
189
+ "$regex",
190
+ "$and",
191
+ "$or",
192
+ "$not",
193
+ }
194
+
195
+ for key, value in predicate.items():
196
+ if key.startswith("$"):
197
+ if key not in valid_operators:
198
+ raise ValueError(f"Invalid operator: {key}")
199
+ if isinstance(value, dict):
200
+ self._validate_predicate(value)
201
+
202
+
203
+ @dataclass
204
+ class Branch:
205
+ """A branch in conditional execution.
206
+
207
+ Attributes:
208
+ agents: Agents to execute in this branch
209
+ strategy: Strategy to use for executing agents (default: sequential)
210
+ label: Human-readable branch label
211
+ """
212
+
213
+ agents: list[AgentTemplate]
214
+ strategy: str = "sequential"
215
+ label: str = ""
216
+
217
+
218
+ # =============================================================================
219
+ # Nested Sentence Types (Phase 2 - Recursive Composition)
220
+ # =============================================================================
221
+
222
+
223
+ @dataclass
224
+ class WorkflowReference:
225
+ """Reference to a workflow for nested composition.
226
+
227
+ Enables "sentences within sentences" - workflows that invoke other workflows.
228
+ Supports both registered workflow IDs and inline definitions.
229
+
230
+ Attributes:
231
+ workflow_id: ID of registered workflow (mutually exclusive with inline)
232
+ inline: Inline workflow definition (mutually exclusive with workflow_id)
233
+ context_mapping: Optional mapping of parent context fields to child
234
+ result_key: Key to store nested workflow result in parent context
235
+
236
+ Example (by ID):
237
+ >>> ref = WorkflowReference(
238
+ ... workflow_id="security-audit-team",
239
+ ... result_key="security_result"
240
+ ... )
241
+
242
+ Example (inline):
243
+ >>> ref = WorkflowReference(
244
+ ... inline=InlineWorkflow(
245
+ ... agents=[agent1, agent2],
246
+ ... strategy="parallel"
247
+ ... ),
248
+ ... result_key="analysis_result"
249
+ ... )
250
+ """
251
+
252
+ workflow_id: str = ""
253
+ inline: "InlineWorkflow | None" = None
254
+ context_mapping: dict[str, str] = field(default_factory=dict)
255
+ result_key: str = "nested_result"
256
+
257
+ def __post_init__(self):
258
+ """Validate that exactly one reference type is provided."""
259
+ if bool(self.workflow_id) == bool(self.inline):
260
+ raise ValueError(
261
+ "WorkflowReference must have exactly one of: workflow_id or inline"
262
+ )
263
+
264
+
265
+ @dataclass
266
+ class InlineWorkflow:
267
+ """Inline workflow definition for nested composition.
268
+
269
+ Allows defining a sub-workflow directly within a parent workflow,
270
+ without requiring registration.
271
+
272
+ Attributes:
273
+ agents: Agents to execute
274
+ strategy: Strategy name (from STRATEGY_REGISTRY)
275
+ description: Human-readable description
276
+
277
+ Example:
278
+ >>> inline = InlineWorkflow(
279
+ ... agents=[analyzer, reviewer],
280
+ ... strategy="sequential",
281
+ ... description="Code review sub-workflow"
282
+ ... )
283
+ """
284
+
285
+ agents: list[AgentTemplate]
286
+ strategy: str = "sequential"
287
+ description: str = ""
288
+
289
+
290
+ class NestingContext:
291
+ """Tracks nesting depth and prevents infinite recursion.
292
+
293
+ Attributes:
294
+ current_depth: Current nesting level (0 = root)
295
+ max_depth: Maximum allowed nesting depth
296
+ workflow_stack: Stack of workflow IDs for cycle detection
297
+ """
298
+
299
+ CONTEXT_KEY = "_nesting"
300
+ DEFAULT_MAX_DEPTH = 3
301
+
302
+ def __init__(self, max_depth: int = DEFAULT_MAX_DEPTH):
303
+ """Initialize nesting context.
304
+
305
+ Args:
306
+ max_depth: Maximum allowed nesting depth
307
+ """
308
+ self.current_depth = 0
309
+ self.max_depth = max_depth
310
+ self.workflow_stack: list[str] = []
311
+
312
+ @classmethod
313
+ def from_context(cls, context: dict[str, Any]) -> "NestingContext":
314
+ """Extract or create NestingContext from execution context.
315
+
316
+ Args:
317
+ context: Execution context dict
318
+
319
+ Returns:
320
+ NestingContext instance
321
+ """
322
+ if cls.CONTEXT_KEY in context:
323
+ return context[cls.CONTEXT_KEY]
324
+ return cls()
325
+
326
+ def can_nest(self, workflow_id: str = "") -> bool:
327
+ """Check if another nesting level is allowed.
328
+
329
+ Args:
330
+ workflow_id: ID of workflow to nest (for cycle detection)
331
+
332
+ Returns:
333
+ True if nesting is allowed
334
+ """
335
+ if self.current_depth >= self.max_depth:
336
+ return False
337
+ if workflow_id and workflow_id in self.workflow_stack:
338
+ return False # Cycle detected
339
+ return True
340
+
341
+ def enter(self, workflow_id: str = "") -> "NestingContext":
342
+ """Create a child context for nested execution.
343
+
344
+ Args:
345
+ workflow_id: ID of workflow being entered
346
+
347
+ Returns:
348
+ New NestingContext with incremented depth
349
+ """
350
+ child = NestingContext(self.max_depth)
351
+ child.current_depth = self.current_depth + 1
352
+ child.workflow_stack = self.workflow_stack.copy()
353
+ if workflow_id:
354
+ child.workflow_stack.append(workflow_id)
355
+ return child
356
+
357
+ def to_context(self, context: dict[str, Any]) -> dict[str, Any]:
358
+ """Add nesting context to execution context.
359
+
360
+ Args:
361
+ context: Execution context dict
362
+
363
+ Returns:
364
+ Updated context with nesting info
365
+ """
366
+ context = context.copy()
367
+ context[self.CONTEXT_KEY] = self
368
+ return context
369
+
370
+
371
+ # Registry for named workflows (populated at runtime)
372
+ WORKFLOW_REGISTRY: dict[str, "WorkflowDefinition"] = {}
373
+
374
+
375
+ @dataclass
376
+ class WorkflowDefinition:
377
+ """A registered workflow definition.
378
+
379
+ Workflows can be registered and referenced by ID in nested compositions.
380
+
381
+ Attributes:
382
+ id: Unique workflow identifier
383
+ agents: Agents in the workflow
384
+ strategy: Composition strategy name
385
+ description: Human-readable description
386
+ """
387
+
388
+ id: str
389
+ agents: list[AgentTemplate]
390
+ strategy: str = "sequential"
391
+ description: str = ""
392
+
393
+
394
+ def register_workflow(workflow: WorkflowDefinition) -> None:
395
+ """Register a workflow for nested references.
396
+
397
+ Args:
398
+ workflow: Workflow definition to register
399
+ """
400
+ WORKFLOW_REGISTRY[workflow.id] = workflow
401
+ logger.info(f"Registered workflow: {workflow.id}")
402
+
403
+
404
+ def get_workflow(workflow_id: str) -> WorkflowDefinition:
405
+ """Get a registered workflow by ID.
406
+
407
+ Args:
408
+ workflow_id: Workflow identifier
409
+
410
+ Returns:
411
+ WorkflowDefinition
412
+
413
+ Raises:
414
+ ValueError: If workflow is not registered
415
+ """
416
+ if workflow_id not in WORKFLOW_REGISTRY:
417
+ raise ValueError(
418
+ f"Unknown workflow: {workflow_id}. "
419
+ f"Available: {list(WORKFLOW_REGISTRY.keys())}"
420
+ )
421
+ return WORKFLOW_REGISTRY[workflow_id]
422
+
423
+
424
+ class ConditionEvaluator:
425
+ """Evaluates conditions against execution context.
426
+
427
+ Supports both JSON predicates (fast, deterministic) and
428
+ natural language conditions (LLM-interpreted, semantic).
429
+
430
+ Security:
431
+ - No eval() or exec() - all operators are whitelisted
432
+ - JSON predicates use safe comparison operators
433
+ - Natural language uses LLM API (no code execution)
434
+ """
435
+
436
+ # Mapping of JSON operators to Python comparison functions
437
+ OPERATORS: dict[str, Callable[[Any, Any], bool]] = {
438
+ "$eq": operator.eq,
439
+ "$ne": operator.ne,
440
+ "$gt": operator.gt,
441
+ "$gte": operator.ge,
442
+ "$lt": operator.lt,
443
+ "$lte": operator.le,
444
+ "$in": lambda val, lst: val in lst,
445
+ "$nin": lambda val, lst: val not in lst,
446
+ "$exists": lambda val, exists: (val is not None) == exists,
447
+ "$regex": lambda val, pattern: bool(re.match(pattern, str(val))) if val else False,
448
+ }
449
+
450
+ def evaluate(self, condition: Condition, context: dict[str, Any]) -> bool:
451
+ """Evaluate a condition against the current context.
452
+
453
+ Args:
454
+ condition: The condition to evaluate
455
+ context: Execution context with agent results
456
+
457
+ Returns:
458
+ True if condition is met, False otherwise
459
+
460
+ Example:
461
+ >>> evaluator = ConditionEvaluator()
462
+ >>> context = {"confidence": 0.6, "errors": 0}
463
+ >>> cond = Condition(predicate={"confidence": {"$lt": 0.8}})
464
+ >>> evaluator.evaluate(cond, context)
465
+ True
466
+ """
467
+ if condition.condition_type == ConditionType.JSON_PREDICATE:
468
+ return self._evaluate_json(condition.predicate, context)
469
+ elif condition.condition_type == ConditionType.NATURAL_LANGUAGE:
470
+ return self._evaluate_natural_language(condition.predicate, context)
471
+ elif condition.condition_type == ConditionType.COMPOSITE:
472
+ return self._evaluate_composite(condition.predicate, context)
473
+ else:
474
+ raise ValueError(f"Unknown condition type: {condition.condition_type}")
475
+
476
+ def _evaluate_json(self, predicate: dict[str, Any], context: dict[str, Any]) -> bool:
477
+ """Evaluate JSON predicate against context.
478
+
479
+ Args:
480
+ predicate: MongoDB-style predicate dict
481
+ context: Context to evaluate against
482
+
483
+ Returns:
484
+ True if all conditions match
485
+ """
486
+ for field, condition_spec in predicate.items():
487
+ # Handle logical operators
488
+ if field == "$and":
489
+ return all(self._evaluate_json(sub, context) for sub in condition_spec)
490
+ if field == "$or":
491
+ return any(self._evaluate_json(sub, context) for sub in condition_spec)
492
+ if field == "$not":
493
+ return not self._evaluate_json(condition_spec, context)
494
+
495
+ # Get value from context (supports nested paths like "result.confidence")
496
+ value = self._get_nested_value(context, field)
497
+
498
+ # Evaluate condition
499
+ if isinstance(condition_spec, dict):
500
+ for op, target in condition_spec.items():
501
+ if op not in self.OPERATORS:
502
+ raise ValueError(f"Unknown operator: {op}")
503
+ if not self.OPERATORS[op](value, target):
504
+ return False
505
+ else:
506
+ # Direct equality check
507
+ if value != condition_spec:
508
+ return False
509
+
510
+ return True
511
+
512
+ def _get_nested_value(self, context: dict[str, Any], path: str) -> Any:
513
+ """Get nested value from context using dot notation.
514
+
515
+ Args:
516
+ context: Context dict
517
+ path: Dot-separated path (e.g., "result.confidence")
518
+
519
+ Returns:
520
+ Value at path or None if not found
521
+ """
522
+ parts = path.split(".")
523
+ current = context
524
+
525
+ for part in parts:
526
+ if isinstance(current, dict):
527
+ current = current.get(part)
528
+ else:
529
+ return None
530
+
531
+ return current
532
+
533
+ def _evaluate_natural_language(
534
+ self, condition_text: str, context: dict[str, Any]
535
+ ) -> bool:
536
+ """Evaluate natural language condition using LLM.
537
+
538
+ Args:
539
+ condition_text: Natural language condition
540
+ context: Context to evaluate against
541
+
542
+ Returns:
543
+ True if LLM determines condition is met
544
+
545
+ Note:
546
+ Falls back to keyword matching if LLM unavailable.
547
+ """
548
+ logger.info(f"Evaluating natural language condition: {condition_text}")
549
+
550
+ # Try LLM evaluation first
551
+ try:
552
+ return self._evaluate_with_llm(condition_text, context)
553
+ except Exception as e:
554
+ logger.warning(f"LLM evaluation failed, using keyword fallback: {e}")
555
+ return self._keyword_fallback(condition_text, context)
556
+
557
+ def _evaluate_with_llm(self, condition_text: str, context: dict[str, Any]) -> bool:
558
+ """Use LLM to evaluate natural language condition.
559
+
560
+ Args:
561
+ condition_text: The condition in natural language
562
+ context: Execution context
563
+
564
+ Returns:
565
+ LLM's determination (True/False)
566
+ """
567
+ # Import LLM client lazily to avoid circular imports
568
+ try:
569
+ from ..llm import get_cheap_tier_client
570
+ except ImportError:
571
+ logger.warning("LLM client not available for natural language conditions")
572
+ raise
573
+
574
+ # Prepare context summary for LLM
575
+ context_summary = json.dumps(context, indent=2, default=str)[:2000]
576
+
577
+ prompt = f"""Evaluate whether the following condition is TRUE or FALSE based on the context.
578
+
579
+ Condition: {condition_text}
580
+
581
+ Context:
582
+ {context_summary}
583
+
584
+ Respond with ONLY "TRUE" or "FALSE" (no explanation)."""
585
+
586
+ client = get_cheap_tier_client()
587
+ response = client.complete(prompt, max_tokens=10)
588
+
589
+ result = response.strip().upper()
590
+ return result == "TRUE"
591
+
592
+ def _keyword_fallback(self, condition_text: str, context: dict[str, Any]) -> bool:
593
+ """Fallback keyword-based evaluation for natural language.
594
+
595
+ Args:
596
+ condition_text: The condition text
597
+ context: Execution context
598
+
599
+ Returns:
600
+ True if keywords suggest condition is likely met
601
+ """
602
+ # Simple keyword matching as fallback
603
+ condition_lower = condition_text.lower()
604
+ context_str = json.dumps(context, default=str).lower()
605
+
606
+ # Check for negation
607
+ is_negated = any(neg in condition_lower for neg in ["not ", "no ", "without "])
608
+
609
+ # Extract key terms
610
+ terms = re.findall(r"\b\w{4,}\b", condition_lower)
611
+ terms = [t for t in terms if t not in {"the", "that", "this", "with", "from"}]
612
+
613
+ # Count matching terms
614
+ matches = sum(1 for term in terms if term in context_str)
615
+ match_ratio = matches / len(terms) if terms else 0
616
+
617
+ result = match_ratio > 0.5
618
+ return not result if is_negated else result
619
+
620
+ def _evaluate_composite(
621
+ self, predicate: dict[str, Any], context: dict[str, Any]
622
+ ) -> bool:
623
+ """Evaluate composite condition (AND/OR of other conditions).
624
+
625
+ Args:
626
+ predicate: Composite predicate with $and/$or
627
+ context: Context to evaluate against
628
+
629
+ Returns:
630
+ Result of logical combination
631
+ """
632
+ return self._evaluate_json(predicate, context)
633
+
634
+
78
635
  class ExecutionStrategy(ABC):
79
636
  """Base class for agent composition strategies.
80
637
 
@@ -723,6 +1280,332 @@ class AdaptiveStrategy(ExecutionStrategy):
723
1280
  )
724
1281
 
725
1282
 
1283
+ class ConditionalStrategy(ExecutionStrategy):
1284
+ """Conditional branching (if X then A else B).
1285
+
1286
+ The 7th grammar rule enabling dynamic workflow decisions based on gates.
1287
+
1288
+ Use when:
1289
+ - Quality gates determine next steps
1290
+ - Error handling requires different paths
1291
+ - Agent consensus affects workflow
1292
+ """
1293
+
1294
+ def __init__(
1295
+ self,
1296
+ condition: Condition,
1297
+ then_branch: Branch,
1298
+ else_branch: Branch | None = None,
1299
+ ):
1300
+ """Initialize conditional strategy."""
1301
+ self.condition = condition
1302
+ self.then_branch = then_branch
1303
+ self.else_branch = else_branch
1304
+ self.evaluator = ConditionEvaluator()
1305
+
1306
+ async def execute(
1307
+ self, agents: list[AgentTemplate], context: dict[str, Any]
1308
+ ) -> StrategyResult:
1309
+ """Execute conditional branching."""
1310
+ logger.info(f"Conditional: Evaluating '{self.condition.description or 'condition'}'")
1311
+
1312
+ condition_met = self.evaluator.evaluate(self.condition, context)
1313
+ logger.info(f"Conditional: Condition evaluated to {condition_met}")
1314
+
1315
+ if condition_met:
1316
+ selected_branch = self.then_branch
1317
+ branch_label = "then"
1318
+ else:
1319
+ if self.else_branch is None:
1320
+ return StrategyResult(
1321
+ success=True,
1322
+ outputs=[],
1323
+ aggregated_output={"branch_taken": None},
1324
+ total_duration=0.0,
1325
+ )
1326
+ selected_branch = self.else_branch
1327
+ branch_label = "else"
1328
+
1329
+ logger.info(f"Conditional: Taking '{branch_label}' branch")
1330
+
1331
+ branch_strategy = get_strategy(selected_branch.strategy)
1332
+ branch_context = context.copy()
1333
+ branch_context["_conditional"] = {"condition_met": condition_met, "branch": branch_label}
1334
+
1335
+ result = await branch_strategy.execute(selected_branch.agents, branch_context)
1336
+ result.aggregated_output["_conditional"] = {
1337
+ "condition_met": condition_met,
1338
+ "branch_taken": branch_label,
1339
+ }
1340
+ return result
1341
+
1342
+
1343
+ class MultiConditionalStrategy(ExecutionStrategy):
1344
+ """Multiple conditional branches (switch/case pattern)."""
1345
+
1346
+ def __init__(
1347
+ self,
1348
+ conditions: list[tuple[Condition, Branch]],
1349
+ default_branch: Branch | None = None,
1350
+ ):
1351
+ """Initialize multi-conditional strategy."""
1352
+ self.conditions = conditions
1353
+ self.default_branch = default_branch
1354
+ self.evaluator = ConditionEvaluator()
1355
+
1356
+ async def execute(
1357
+ self, agents: list[AgentTemplate], context: dict[str, Any]
1358
+ ) -> StrategyResult:
1359
+ """Execute multi-conditional branching."""
1360
+ for i, (condition, branch) in enumerate(self.conditions):
1361
+ if self.evaluator.evaluate(condition, context):
1362
+ logger.info(f"MultiConditional: Condition {i + 1} matched")
1363
+ branch_strategy = get_strategy(branch.strategy)
1364
+ result = await branch_strategy.execute(branch.agents, context)
1365
+ result.aggregated_output["_matched_index"] = i
1366
+ return result
1367
+
1368
+ if self.default_branch:
1369
+ branch_strategy = get_strategy(self.default_branch.strategy)
1370
+ return await branch_strategy.execute(self.default_branch.agents, context)
1371
+
1372
+ return StrategyResult(
1373
+ success=True,
1374
+ outputs=[],
1375
+ aggregated_output={"reason": "No conditions matched"},
1376
+ total_duration=0.0,
1377
+ )
1378
+
1379
+
1380
+ class NestedStrategy(ExecutionStrategy):
1381
+ """Nested workflow execution (sentences within sentences).
1382
+
1383
+ Enables recursive composition where workflows invoke other workflows.
1384
+ Implements the "subordinate clause" pattern in the grammar metaphor.
1385
+
1386
+ Features:
1387
+ - Reference workflows by ID or define inline
1388
+ - Configurable max depth (default: 3)
1389
+ - Cycle detection prevents infinite recursion
1390
+ - Full context inheritance from parent to child
1391
+
1392
+ Use when:
1393
+ - Complex multi-stage pipelines need modular sub-workflows
1394
+ - Reusable workflow components should be shared
1395
+ - Hierarchical team structures (teams containing sub-teams)
1396
+
1397
+ Example:
1398
+ >>> # Parent workflow with nested sub-workflow
1399
+ >>> strategy = NestedStrategy(
1400
+ ... workflow_ref=WorkflowReference(workflow_id="security-audit"),
1401
+ ... max_depth=3
1402
+ ... )
1403
+ >>> result = await strategy.execute([], context)
1404
+
1405
+ Example (inline):
1406
+ >>> strategy = NestedStrategy(
1407
+ ... workflow_ref=WorkflowReference(
1408
+ ... inline=InlineWorkflow(
1409
+ ... agents=[analyzer, reviewer],
1410
+ ... strategy="parallel"
1411
+ ... )
1412
+ ... )
1413
+ ... )
1414
+ """
1415
+
1416
+ def __init__(
1417
+ self,
1418
+ workflow_ref: WorkflowReference,
1419
+ max_depth: int = NestingContext.DEFAULT_MAX_DEPTH,
1420
+ ):
1421
+ """Initialize nested strategy.
1422
+
1423
+ Args:
1424
+ workflow_ref: Reference to workflow (by ID or inline)
1425
+ max_depth: Maximum nesting depth allowed
1426
+ """
1427
+ self.workflow_ref = workflow_ref
1428
+ self.max_depth = max_depth
1429
+
1430
+ async def execute(
1431
+ self, agents: list[AgentTemplate], context: dict[str, Any]
1432
+ ) -> StrategyResult:
1433
+ """Execute nested workflow.
1434
+
1435
+ Args:
1436
+ agents: Ignored (workflow_ref defines agents)
1437
+ context: Parent execution context (inherited by child)
1438
+
1439
+ Returns:
1440
+ StrategyResult from nested workflow execution
1441
+
1442
+ Raises:
1443
+ RecursionError: If max depth exceeded or cycle detected
1444
+ """
1445
+ # Get or create nesting context
1446
+ nesting = NestingContext.from_context(context)
1447
+
1448
+ # Resolve workflow
1449
+ if self.workflow_ref.workflow_id:
1450
+ workflow_id = self.workflow_ref.workflow_id
1451
+ workflow = get_workflow(workflow_id)
1452
+ workflow_agents = workflow.agents
1453
+ strategy_name = workflow.strategy
1454
+ else:
1455
+ workflow_id = f"inline_{id(self.workflow_ref.inline)}"
1456
+ workflow_agents = self.workflow_ref.inline.agents
1457
+ strategy_name = self.workflow_ref.inline.strategy
1458
+
1459
+ # Check nesting limits
1460
+ if not nesting.can_nest(workflow_id):
1461
+ if nesting.current_depth >= nesting.max_depth:
1462
+ error_msg = (
1463
+ f"Maximum nesting depth ({nesting.max_depth}) exceeded. "
1464
+ f"Current stack: {' → '.join(nesting.workflow_stack)}"
1465
+ )
1466
+ else:
1467
+ error_msg = (
1468
+ f"Cycle detected: workflow '{workflow_id}' already in stack. "
1469
+ f"Stack: {' → '.join(nesting.workflow_stack)}"
1470
+ )
1471
+ logger.error(error_msg)
1472
+ raise RecursionError(error_msg)
1473
+
1474
+ logger.info(
1475
+ f"Nested: Entering '{workflow_id}' at depth {nesting.current_depth + 1}"
1476
+ )
1477
+
1478
+ # Create child context with updated nesting
1479
+ child_nesting = nesting.enter(workflow_id)
1480
+ child_context = child_nesting.to_context(context.copy())
1481
+
1482
+ # Execute nested workflow
1483
+ strategy = get_strategy(strategy_name)
1484
+ result = await strategy.execute(workflow_agents, child_context)
1485
+
1486
+ # Augment result with nesting metadata
1487
+ result.aggregated_output["_nested"] = {
1488
+ "workflow_id": workflow_id,
1489
+ "depth": child_nesting.current_depth,
1490
+ "parent_stack": nesting.workflow_stack,
1491
+ }
1492
+
1493
+ # Store result under specified key if provided
1494
+ if self.workflow_ref.result_key:
1495
+ result.aggregated_output[self.workflow_ref.result_key] = result.aggregated_output.copy()
1496
+
1497
+ logger.info(f"Nested: Exiting '{workflow_id}'")
1498
+
1499
+ return result
1500
+
1501
+
1502
+ class NestedSequentialStrategy(ExecutionStrategy):
1503
+ """Sequential execution with nested workflow support.
1504
+
1505
+ Like SequentialStrategy but steps can be either agents OR workflow references.
1506
+ Enables mixing direct agent execution with nested sub-workflows.
1507
+
1508
+ Example:
1509
+ >>> strategy = NestedSequentialStrategy(
1510
+ ... steps=[
1511
+ ... StepDefinition(agent=analyzer),
1512
+ ... StepDefinition(workflow_ref=WorkflowReference(workflow_id="review-team")),
1513
+ ... StepDefinition(agent=reporter),
1514
+ ... ]
1515
+ ... )
1516
+ """
1517
+
1518
+ def __init__(
1519
+ self,
1520
+ steps: list["StepDefinition"],
1521
+ max_depth: int = NestingContext.DEFAULT_MAX_DEPTH,
1522
+ ):
1523
+ """Initialize nested sequential strategy.
1524
+
1525
+ Args:
1526
+ steps: List of step definitions (agents or workflow refs)
1527
+ max_depth: Maximum nesting depth
1528
+ """
1529
+ self.steps = steps
1530
+ self.max_depth = max_depth
1531
+
1532
+ async def execute(
1533
+ self, agents: list[AgentTemplate], context: dict[str, Any]
1534
+ ) -> StrategyResult:
1535
+ """Execute steps sequentially, handling both agents and nested workflows."""
1536
+ if not self.steps:
1537
+ raise ValueError("steps list cannot be empty")
1538
+
1539
+ logger.info(f"NestedSequential: Executing {len(self.steps)} steps")
1540
+
1541
+ results: list[AgentResult] = []
1542
+ current_context = context.copy()
1543
+ total_duration = 0.0
1544
+
1545
+ for i, step in enumerate(self.steps):
1546
+ logger.info(f"NestedSequential: Step {i + 1}/{len(self.steps)}")
1547
+
1548
+ if step.agent:
1549
+ # Direct agent execution
1550
+ result = await self._execute_agent(step.agent, current_context)
1551
+ results.append(result)
1552
+ total_duration += result.duration_seconds
1553
+
1554
+ if result.success:
1555
+ current_context[f"{step.agent.id}_output"] = result.output
1556
+ else:
1557
+ # Nested workflow execution
1558
+ nested_strategy = NestedStrategy(
1559
+ workflow_ref=step.workflow_ref,
1560
+ max_depth=self.max_depth,
1561
+ )
1562
+ nested_result = await nested_strategy.execute([], current_context)
1563
+ total_duration += nested_result.total_duration
1564
+
1565
+ # Convert to AgentResult for consistency
1566
+ results.append(
1567
+ AgentResult(
1568
+ agent_id=f"nested_{step.workflow_ref.workflow_id or 'inline'}",
1569
+ success=nested_result.success,
1570
+ output=nested_result.aggregated_output,
1571
+ confidence=nested_result.aggregated_output.get("avg_confidence", 0.0),
1572
+ duration_seconds=nested_result.total_duration,
1573
+ )
1574
+ )
1575
+
1576
+ if nested_result.success:
1577
+ key = step.workflow_ref.result_key or f"step_{i}_output"
1578
+ current_context[key] = nested_result.aggregated_output
1579
+
1580
+ return StrategyResult(
1581
+ success=all(r.success for r in results),
1582
+ outputs=results,
1583
+ aggregated_output=self._aggregate_results(results),
1584
+ total_duration=total_duration,
1585
+ errors=[r.error for r in results if not r.success],
1586
+ )
1587
+
1588
+
1589
+ @dataclass
1590
+ class StepDefinition:
1591
+ """Definition of a step in NestedSequentialStrategy.
1592
+
1593
+ Either agent OR workflow_ref must be provided (mutually exclusive).
1594
+
1595
+ Attributes:
1596
+ agent: Agent to execute directly
1597
+ workflow_ref: Nested workflow to execute
1598
+ """
1599
+
1600
+ agent: AgentTemplate | None = None
1601
+ workflow_ref: WorkflowReference | None = None
1602
+
1603
+ def __post_init__(self):
1604
+ """Validate that exactly one step type is provided."""
1605
+ if bool(self.agent) == bool(self.workflow_ref):
1606
+ raise ValueError("StepDefinition must have exactly one of: agent or workflow_ref")
1607
+
1608
+
726
1609
  # Strategy registry for lookup by name
727
1610
  STRATEGY_REGISTRY: dict[str, type[ExecutionStrategy]] = {
728
1611
  "sequential": SequentialStrategy,
@@ -731,6 +1614,10 @@ STRATEGY_REGISTRY: dict[str, type[ExecutionStrategy]] = {
731
1614
  "teaching": TeachingStrategy,
732
1615
  "refinement": RefinementStrategy,
733
1616
  "adaptive": AdaptiveStrategy,
1617
+ "conditional": ConditionalStrategy,
1618
+ "multi_conditional": MultiConditionalStrategy,
1619
+ "nested": NestedStrategy,
1620
+ "nested_sequential": NestedSequentialStrategy,
734
1621
  }
735
1622
 
736
1623