attune-ai 2.1.5__py3-none-any.whl → 2.2.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 (125) hide show
  1. attune/cli/__init__.py +3 -59
  2. attune/cli/commands/batch.py +4 -12
  3. attune/cli/commands/cache.py +8 -16
  4. attune/cli/commands/provider.py +17 -0
  5. attune/cli/commands/routing.py +3 -1
  6. attune/cli/commands/setup.py +122 -0
  7. attune/cli/commands/tier.py +1 -3
  8. attune/cli/commands/workflow.py +31 -0
  9. attune/cli/parsers/cache.py +1 -0
  10. attune/cli/parsers/help.py +1 -3
  11. attune/cli/parsers/provider.py +7 -0
  12. attune/cli/parsers/routing.py +1 -3
  13. attune/cli/parsers/setup.py +7 -0
  14. attune/cli/parsers/status.py +1 -3
  15. attune/cli/parsers/tier.py +1 -3
  16. attune/cli_minimal.py +9 -3
  17. attune/cli_router.py +9 -7
  18. attune/cli_unified.py +3 -0
  19. attune/dashboard/app.py +3 -1
  20. attune/dashboard/simple_server.py +3 -1
  21. attune/dashboard/standalone_server.py +7 -3
  22. attune/mcp/server.py +54 -102
  23. attune/memory/long_term.py +0 -2
  24. attune/memory/short_term/__init__.py +84 -0
  25. attune/memory/short_term/base.py +465 -0
  26. attune/memory/short_term/batch.py +219 -0
  27. attune/memory/short_term/caching.py +227 -0
  28. attune/memory/short_term/conflicts.py +265 -0
  29. attune/memory/short_term/cross_session.py +122 -0
  30. attune/memory/short_term/facade.py +653 -0
  31. attune/memory/short_term/pagination.py +207 -0
  32. attune/memory/short_term/patterns.py +271 -0
  33. attune/memory/short_term/pubsub.py +286 -0
  34. attune/memory/short_term/queues.py +244 -0
  35. attune/memory/short_term/security.py +300 -0
  36. attune/memory/short_term/sessions.py +250 -0
  37. attune/memory/short_term/streams.py +242 -0
  38. attune/memory/short_term/timelines.py +234 -0
  39. attune/memory/short_term/transactions.py +184 -0
  40. attune/memory/short_term/working.py +252 -0
  41. attune/meta_workflows/cli_commands/__init__.py +3 -0
  42. attune/meta_workflows/cli_commands/agent_commands.py +0 -4
  43. attune/meta_workflows/cli_commands/analytics_commands.py +0 -6
  44. attune/meta_workflows/cli_commands/config_commands.py +0 -5
  45. attune/meta_workflows/cli_commands/memory_commands.py +0 -5
  46. attune/meta_workflows/cli_commands/template_commands.py +0 -5
  47. attune/meta_workflows/cli_commands/workflow_commands.py +0 -6
  48. attune/meta_workflows/plan_generator.py +2 -4
  49. attune/models/adaptive_routing.py +4 -8
  50. attune/models/auth_cli.py +3 -9
  51. attune/models/auth_strategy.py +2 -4
  52. attune/models/telemetry/analytics.py +0 -2
  53. attune/models/telemetry/backend.py +0 -3
  54. attune/models/telemetry/storage.py +0 -2
  55. attune/monitoring/alerts.py +6 -10
  56. attune/orchestration/_strategies/__init__.py +156 -0
  57. attune/orchestration/_strategies/base.py +227 -0
  58. attune/orchestration/_strategies/conditional_strategies.py +365 -0
  59. attune/orchestration/_strategies/conditions.py +369 -0
  60. attune/orchestration/_strategies/core_strategies.py +479 -0
  61. attune/orchestration/_strategies/data_classes.py +64 -0
  62. attune/orchestration/_strategies/nesting.py +233 -0
  63. attune/orchestration/execution_strategies.py +58 -1567
  64. attune/orchestration/meta_orchestrator.py +1 -3
  65. attune/project_index/scanner.py +1 -3
  66. attune/project_index/scanner_parallel.py +7 -5
  67. attune/socratic/storage.py +2 -4
  68. attune/socratic_router.py +1 -3
  69. attune/telemetry/agent_coordination.py +9 -3
  70. attune/telemetry/agent_tracking.py +16 -3
  71. attune/telemetry/approval_gates.py +22 -5
  72. attune/telemetry/cli.py +1 -3
  73. attune/telemetry/commands/dashboard_commands.py +24 -8
  74. attune/telemetry/event_streaming.py +8 -2
  75. attune/telemetry/feedback_loop.py +10 -2
  76. attune/tools.py +2 -1
  77. attune/workflow_commands.py +1 -3
  78. attune/workflow_patterns/structural.py +4 -8
  79. attune/workflows/__init__.py +54 -10
  80. attune/workflows/autonomous_test_gen.py +158 -102
  81. attune/workflows/base.py +48 -672
  82. attune/workflows/batch_processing.py +1 -3
  83. attune/workflows/compat.py +156 -0
  84. attune/workflows/cost_mixin.py +141 -0
  85. attune/workflows/data_classes.py +92 -0
  86. attune/workflows/document_gen/workflow.py +11 -14
  87. attune/workflows/history.py +16 -9
  88. attune/workflows/llm_base.py +1 -3
  89. attune/workflows/migration.py +432 -0
  90. attune/workflows/output.py +2 -7
  91. attune/workflows/parsing_mixin.py +427 -0
  92. attune/workflows/perf_audit.py +3 -1
  93. attune/workflows/progress.py +9 -11
  94. attune/workflows/release_prep.py +5 -1
  95. attune/workflows/routing.py +0 -2
  96. attune/workflows/secure_release.py +4 -1
  97. attune/workflows/security_audit.py +20 -14
  98. attune/workflows/security_audit_phase3.py +28 -22
  99. attune/workflows/seo_optimization.py +27 -27
  100. attune/workflows/test_gen/test_templates.py +1 -4
  101. attune/workflows/test_gen/workflow.py +0 -2
  102. attune/workflows/test_gen_behavioral.py +6 -19
  103. attune/workflows/test_gen_parallel.py +8 -6
  104. {attune_ai-2.1.5.dist-info → attune_ai-2.2.1.dist-info}/METADATA +4 -3
  105. {attune_ai-2.1.5.dist-info → attune_ai-2.2.1.dist-info}/RECORD +121 -96
  106. {attune_ai-2.1.5.dist-info → attune_ai-2.2.1.dist-info}/entry_points.txt +0 -2
  107. attune_healthcare/monitors/monitoring/__init__.py +9 -9
  108. attune_llm/agent_factory/__init__.py +6 -6
  109. attune_llm/agent_factory/adapters/haystack_adapter.py +1 -4
  110. attune_llm/commands/__init__.py +10 -10
  111. attune_llm/commands/models.py +3 -3
  112. attune_llm/config/__init__.py +8 -8
  113. attune_llm/learning/__init__.py +3 -3
  114. attune_llm/learning/extractor.py +5 -3
  115. attune_llm/learning/storage.py +5 -3
  116. attune_llm/security/__init__.py +17 -17
  117. attune_llm/utils/tokens.py +3 -1
  118. attune/cli_legacy.py +0 -3978
  119. attune/memory/short_term.py +0 -2192
  120. attune/workflows/manage_docs.py +0 -87
  121. attune/workflows/test5.py +0 -125
  122. {attune_ai-2.1.5.dist-info → attune_ai-2.2.1.dist-info}/WHEEL +0 -0
  123. {attune_ai-2.1.5.dist-info → attune_ai-2.2.1.dist-info}/licenses/LICENSE +0 -0
  124. {attune_ai-2.1.5.dist-info → attune_ai-2.2.1.dist-info}/licenses/LICENSE_CHANGE_ANNOUNCEMENT.md +0 -0
  125. {attune_ai-2.1.5.dist-info → attune_ai-2.2.1.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,369 @@
1
+ """Condition types and evaluator for conditional execution strategies.
2
+
3
+ This module implements the conditional grammar (Pattern 7) for agent workflows:
4
+ - JSON predicates: MongoDB-style fast, deterministic conditions
5
+ - Natural language: LLM-interpreted semantic conditions
6
+ - Composite: Logical combinations (AND/OR/NOT)
7
+
8
+ Security:
9
+ - No eval() or exec() - all operators are whitelisted
10
+ - JSON predicates use safe comparison operators
11
+ - Natural language uses LLM API (no code execution)
12
+
13
+ Copyright 2025 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 operator
22
+ import re
23
+ from collections.abc import Callable
24
+ from dataclasses import dataclass
25
+ from enum import Enum
26
+ from typing import TYPE_CHECKING, Any
27
+
28
+ if TYPE_CHECKING:
29
+ from ..agent_templates import AgentTemplate
30
+
31
+ logger = logging.getLogger(__name__)
32
+
33
+
34
+ # =============================================================================
35
+ # Conditional Grammar Types (Pattern 7)
36
+ # =============================================================================
37
+
38
+
39
+ class ConditionType(Enum):
40
+ """Type of condition for gate evaluation.
41
+
42
+ Attributes:
43
+ JSON_PREDICATE: MongoDB-style JSON predicate ({"field": {"$op": value}})
44
+ NATURAL_LANGUAGE: LLM-interpreted natural language condition
45
+ COMPOSITE: Logical combination of conditions (AND/OR)
46
+ """
47
+
48
+ JSON_PREDICATE = "json"
49
+ NATURAL_LANGUAGE = "natural"
50
+ COMPOSITE = "composite"
51
+
52
+
53
+ @dataclass
54
+ class Condition:
55
+ """A conditional gate for branching in agent workflows.
56
+
57
+ Supports hybrid syntax: JSON predicates for simple conditions,
58
+ natural language for complex semantic conditions.
59
+
60
+ Attributes:
61
+ predicate: JSON predicate dict or natural language string
62
+ condition_type: How to evaluate the condition
63
+ description: Human-readable description of the condition
64
+ source_field: Which field(s) in context to evaluate
65
+
66
+ JSON Predicate Operators:
67
+ $eq: Equal to value
68
+ $ne: Not equal to value
69
+ $gt: Greater than value
70
+ $gte: Greater than or equal to value
71
+ $lt: Less than value
72
+ $lte: Less than or equal to value
73
+ $in: Value is in list
74
+ $nin: Value is not in list
75
+ $exists: Field exists (or not)
76
+ $regex: Matches regex pattern
77
+
78
+ Example (JSON):
79
+ >>> # Low confidence triggers expert review
80
+ >>> cond = Condition(
81
+ ... predicate={"confidence": {"$lt": 0.8}},
82
+ ... description="Confidence is below threshold"
83
+ ... )
84
+
85
+ Example (Natural Language):
86
+ >>> # LLM interprets complex semantic condition
87
+ >>> cond = Condition(
88
+ ... predicate="The security audit found critical vulnerabilities",
89
+ ... condition_type=ConditionType.NATURAL_LANGUAGE,
90
+ ... description="Security issues detected"
91
+ ... )
92
+ """
93
+
94
+ predicate: dict[str, Any] | str
95
+ condition_type: ConditionType = ConditionType.JSON_PREDICATE
96
+ description: str = ""
97
+ source_field: str = "" # Empty means evaluate whole context
98
+
99
+ def __post_init__(self):
100
+ """Validate condition and auto-detect type."""
101
+ if isinstance(self.predicate, str):
102
+ # Auto-detect: if it looks like prose, it's natural language
103
+ if " " in self.predicate and not self.predicate.startswith("{"):
104
+ object.__setattr__(self, "condition_type", ConditionType.NATURAL_LANGUAGE)
105
+ elif isinstance(self.predicate, dict):
106
+ # Validate JSON predicate structure
107
+ self._validate_predicate(self.predicate)
108
+ else:
109
+ raise ValueError(f"predicate must be dict or str, got {type(self.predicate)}")
110
+
111
+ def _validate_predicate(self, predicate: dict[str, Any]) -> None:
112
+ """Validate JSON predicate structure (no code execution).
113
+
114
+ Args:
115
+ predicate: The predicate dict to validate
116
+
117
+ Raises:
118
+ ValueError: If predicate contains invalid operators
119
+ """
120
+ valid_operators = {
121
+ "$eq",
122
+ "$ne",
123
+ "$gt",
124
+ "$gte",
125
+ "$lt",
126
+ "$lte",
127
+ "$in",
128
+ "$nin",
129
+ "$exists",
130
+ "$regex",
131
+ "$and",
132
+ "$or",
133
+ "$not",
134
+ }
135
+
136
+ for key, value in predicate.items():
137
+ if key.startswith("$"):
138
+ if key not in valid_operators:
139
+ raise ValueError(f"Invalid operator: {key}")
140
+ if isinstance(value, dict):
141
+ self._validate_predicate(value)
142
+
143
+
144
+ @dataclass
145
+ class Branch:
146
+ """A branch in conditional execution.
147
+
148
+ Attributes:
149
+ agents: Agents to execute in this branch
150
+ strategy: Strategy to use for executing agents (default: sequential)
151
+ label: Human-readable branch label
152
+ """
153
+
154
+ agents: list[AgentTemplate]
155
+ strategy: str = "sequential"
156
+ label: str = ""
157
+
158
+
159
+ # =============================================================================
160
+ # Condition Evaluator
161
+ # =============================================================================
162
+
163
+
164
+ class ConditionEvaluator:
165
+ """Evaluates conditions against execution context.
166
+
167
+ Supports both JSON predicates (fast, deterministic) and
168
+ natural language conditions (LLM-interpreted, semantic).
169
+
170
+ Security:
171
+ - No eval() or exec() - all operators are whitelisted
172
+ - JSON predicates use safe comparison operators
173
+ - Natural language uses LLM API (no code execution)
174
+ """
175
+
176
+ # Mapping of JSON operators to Python comparison functions
177
+ OPERATORS: dict[str, Callable[[Any, Any], bool]] = {
178
+ "$eq": operator.eq,
179
+ "$ne": operator.ne,
180
+ "$gt": operator.gt,
181
+ "$gte": operator.ge,
182
+ "$lt": operator.lt,
183
+ "$lte": operator.le,
184
+ "$in": lambda val, lst: val in lst,
185
+ "$nin": lambda val, lst: val not in lst,
186
+ "$exists": lambda val, exists: (val is not None) == exists,
187
+ "$regex": lambda val, pattern: bool(re.match(pattern, str(val))) if val else False,
188
+ }
189
+
190
+ def evaluate(self, condition: Condition, context: dict[str, Any]) -> bool:
191
+ """Evaluate a condition against the current context.
192
+
193
+ Args:
194
+ condition: The condition to evaluate
195
+ context: Execution context with agent results
196
+
197
+ Returns:
198
+ True if condition is met, False otherwise
199
+
200
+ Example:
201
+ >>> evaluator = ConditionEvaluator()
202
+ >>> context = {"confidence": 0.6, "errors": 0}
203
+ >>> cond = Condition(predicate={"confidence": {"$lt": 0.8}})
204
+ >>> evaluator.evaluate(cond, context)
205
+ True
206
+ """
207
+ if condition.condition_type == ConditionType.JSON_PREDICATE:
208
+ return self._evaluate_json(condition.predicate, context)
209
+ elif condition.condition_type == ConditionType.NATURAL_LANGUAGE:
210
+ return self._evaluate_natural_language(condition.predicate, context)
211
+ elif condition.condition_type == ConditionType.COMPOSITE:
212
+ return self._evaluate_composite(condition.predicate, context)
213
+ else:
214
+ raise ValueError(f"Unknown condition type: {condition.condition_type}")
215
+
216
+ def _evaluate_json(self, predicate: dict[str, Any], context: dict[str, Any]) -> bool:
217
+ """Evaluate JSON predicate against context.
218
+
219
+ Args:
220
+ predicate: MongoDB-style predicate dict
221
+ context: Context to evaluate against
222
+
223
+ Returns:
224
+ True if all conditions match
225
+ """
226
+ for field_name, condition_spec in predicate.items():
227
+ # Handle logical operators
228
+ if field_name == "$and":
229
+ return all(self._evaluate_json(sub, context) for sub in condition_spec)
230
+ if field_name == "$or":
231
+ return any(self._evaluate_json(sub, context) for sub in condition_spec)
232
+ if field_name == "$not":
233
+ return not self._evaluate_json(condition_spec, context)
234
+
235
+ # Get value from context (supports nested paths like "result.confidence")
236
+ value = self._get_nested_value(context, field_name)
237
+
238
+ # Evaluate condition
239
+ if isinstance(condition_spec, dict):
240
+ for op, target in condition_spec.items():
241
+ if op not in self.OPERATORS:
242
+ raise ValueError(f"Unknown operator: {op}")
243
+ if not self.OPERATORS[op](value, target):
244
+ return False
245
+ else:
246
+ # Direct equality check
247
+ if value != condition_spec:
248
+ return False
249
+
250
+ return True
251
+
252
+ def _get_nested_value(self, context: dict[str, Any], path: str) -> Any:
253
+ """Get nested value from context using dot notation.
254
+
255
+ Args:
256
+ context: Context dict
257
+ path: Dot-separated path (e.g., "result.confidence")
258
+
259
+ Returns:
260
+ Value at path or None if not found
261
+ """
262
+ parts = path.split(".")
263
+ current = context
264
+
265
+ for part in parts:
266
+ if isinstance(current, dict):
267
+ current = current.get(part)
268
+ else:
269
+ return None
270
+
271
+ return current
272
+
273
+ def _evaluate_natural_language(self, condition_text: str, context: dict[str, Any]) -> bool:
274
+ """Evaluate natural language condition using LLM.
275
+
276
+ Args:
277
+ condition_text: Natural language condition
278
+ context: Context to evaluate against
279
+
280
+ Returns:
281
+ True if LLM determines condition is met
282
+
283
+ Note:
284
+ Falls back to keyword matching if LLM unavailable.
285
+ """
286
+ logger.info(f"Evaluating natural language condition: {condition_text}")
287
+
288
+ # Try LLM evaluation first
289
+ try:
290
+ return self._evaluate_with_llm(condition_text, context)
291
+ except Exception as e: # noqa: BLE001
292
+ # INTENTIONAL: Fallback to keyword matching if any LLM error
293
+ logger.warning(f"LLM evaluation failed, using keyword fallback: {e}")
294
+ return self._keyword_fallback(condition_text, context)
295
+
296
+ def _evaluate_with_llm(self, condition_text: str, context: dict[str, Any]) -> bool:
297
+ """Use LLM to evaluate natural language condition.
298
+
299
+ Args:
300
+ condition_text: The condition in natural language
301
+ context: Execution context
302
+
303
+ Returns:
304
+ LLM's determination (True/False)
305
+ """
306
+ # Import LLM client lazily to avoid circular imports
307
+ try:
308
+ from ..llm import get_cheap_tier_client
309
+ except ImportError:
310
+ logger.warning("LLM client not available for natural language conditions")
311
+ raise
312
+
313
+ # Prepare context summary for LLM
314
+ context_summary = json.dumps(context, indent=2, default=str)[:2000]
315
+
316
+ prompt = f"""Evaluate whether the following condition is TRUE or FALSE based on the context.
317
+
318
+ Condition: {condition_text}
319
+
320
+ Context:
321
+ {context_summary}
322
+
323
+ Respond with ONLY "TRUE" or "FALSE" (no explanation)."""
324
+
325
+ client = get_cheap_tier_client()
326
+ response = client.complete(prompt, max_tokens=10)
327
+
328
+ result = response.strip().upper()
329
+ return result == "TRUE"
330
+
331
+ def _keyword_fallback(self, condition_text: str, context: dict[str, Any]) -> bool:
332
+ """Fallback keyword-based evaluation for natural language.
333
+
334
+ Args:
335
+ condition_text: The condition text
336
+ context: Execution context
337
+
338
+ Returns:
339
+ True if keywords suggest condition is likely met
340
+ """
341
+ # Simple keyword matching as fallback
342
+ condition_lower = condition_text.lower()
343
+ context_str = json.dumps(context, default=str).lower()
344
+
345
+ # Check for negation
346
+ is_negated = any(neg in condition_lower for neg in ["not ", "no ", "without "])
347
+
348
+ # Extract key terms
349
+ terms = re.findall(r"\b\w{4,}\b", condition_lower)
350
+ terms = [t for t in terms if t not in {"the", "that", "this", "with", "from"}]
351
+
352
+ # Count matching terms
353
+ matches = sum(1 for term in terms if term in context_str)
354
+ match_ratio = matches / len(terms) if terms else 0
355
+
356
+ result = match_ratio > 0.5
357
+ return not result if is_negated else result
358
+
359
+ def _evaluate_composite(self, predicate: dict[str, Any], context: dict[str, Any]) -> bool:
360
+ """Evaluate composite condition (AND/OR of other conditions).
361
+
362
+ Args:
363
+ predicate: Composite predicate with $and/$or
364
+ context: Context to evaluate against
365
+
366
+ Returns:
367
+ Result of logical combination
368
+ """
369
+ return self._evaluate_json(predicate, context)