alma-memory 0.2.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.
@@ -0,0 +1,447 @@
1
+ """
2
+ ALMA Victor Integration.
3
+
4
+ Victor-specific integration for backend/API QA testing with ALMA memory.
5
+
6
+ Victor specializes in:
7
+ - API endpoint testing
8
+ - Database validation
9
+ - Performance testing
10
+ - Health check verification
11
+ - Authentication/authorization testing
12
+
13
+ This module provides Victor-specific memory categories, prompts, and utilities.
14
+ """
15
+
16
+ import logging
17
+ from typing import Optional, Dict, Any, List
18
+ from dataclasses import dataclass, field
19
+
20
+ from alma.core import ALMA
21
+ from alma.types import MemorySlice
22
+ from alma.harness.domains import CodingDomain
23
+ from alma.integration.claude_agents import (
24
+ ClaudeAgentHooks,
25
+ TaskContext,
26
+ TaskOutcome,
27
+ AgentType,
28
+ )
29
+
30
+ logger = logging.getLogger(__name__)
31
+
32
+
33
+ # Victor's learning categories
34
+ VICTOR_CATEGORIES = [
35
+ "api_design_patterns",
36
+ "authentication_patterns",
37
+ "error_handling",
38
+ "performance_optimization",
39
+ "database_query_patterns",
40
+ "caching_strategies",
41
+ ]
42
+
43
+ # Categories Victor should NOT learn
44
+ VICTOR_FORBIDDEN = [
45
+ "frontend_styling",
46
+ "ui_testing",
47
+ "marketing_content",
48
+ ]
49
+
50
+
51
+ @dataclass
52
+ class APITestContext(TaskContext):
53
+ """
54
+ Victor-specific test context.
55
+
56
+ Extends TaskContext with API/backend testing-specific fields.
57
+ """
58
+ endpoint: Optional[str] = None
59
+ method: str = "GET"
60
+ expected_status: Optional[int] = None
61
+ request_body: Optional[Dict[str, Any]] = None
62
+ headers: Dict[str, str] = field(default_factory=dict)
63
+ is_auth_test: bool = False
64
+ is_performance_test: bool = False
65
+ is_database_test: bool = False
66
+
67
+ def __post_init__(self):
68
+ # Ensure agent name is victor
69
+ self.agent_name = "victor"
70
+ # Set default task type if not specified
71
+ if not self.task_type:
72
+ self.task_type = self._infer_task_type()
73
+
74
+ def _infer_task_type(self) -> str:
75
+ """Infer task type from context."""
76
+ if self.is_auth_test:
77
+ return "authentication_patterns"
78
+ if self.is_performance_test:
79
+ return "performance_optimization"
80
+ if self.is_database_test:
81
+ return "database_query_patterns"
82
+ if self.endpoint:
83
+ return "api_design_patterns"
84
+ return "api_testing"
85
+
86
+
87
+ @dataclass
88
+ class APITestOutcome(TaskOutcome):
89
+ """
90
+ Victor-specific test outcome.
91
+
92
+ Extends TaskOutcome with API/backend testing-specific results.
93
+ """
94
+ response_status: Optional[int] = None
95
+ response_time_ms: Optional[int] = None
96
+ response_body: Optional[Dict[str, Any]] = None
97
+ database_queries_count: int = 0
98
+ cache_hits: int = 0
99
+ cache_misses: int = 0
100
+ validation_errors: List[str] = field(default_factory=list)
101
+ performance_metrics: Dict[str, float] = field(default_factory=dict)
102
+
103
+ def __post_init__(self):
104
+ # Use response_time_ms as duration if not set
105
+ if self.duration_ms is None and self.response_time_ms is not None:
106
+ self.duration_ms = self.response_time_ms
107
+
108
+
109
+ class VictorHooks(ClaudeAgentHooks):
110
+ """
111
+ Victor-specific integration hooks.
112
+
113
+ Extends ClaudeAgentHooks with backend/API testing-specific functionality.
114
+ """
115
+
116
+ def __init__(self, alma: ALMA, auto_learn: bool = True):
117
+ """
118
+ Initialize Victor hooks.
119
+
120
+ Args:
121
+ alma: ALMA instance
122
+ auto_learn: Whether to automatically learn from outcomes
123
+ """
124
+ harness = CodingDomain.create_victor(alma)
125
+ super().__init__(
126
+ alma=alma,
127
+ agent_type=AgentType.VICTOR,
128
+ harness=harness,
129
+ auto_learn=auto_learn,
130
+ )
131
+
132
+ def get_api_patterns(
133
+ self,
134
+ endpoint_type: str,
135
+ top_k: int = 5,
136
+ ) -> List[Dict[str, Any]]:
137
+ """
138
+ Get proven API patterns for an endpoint type.
139
+
140
+ Args:
141
+ endpoint_type: Type of endpoint (CRUD, auth, search, etc.)
142
+ top_k: Maximum patterns to return
143
+
144
+ Returns:
145
+ List of API patterns with success rates
146
+ """
147
+ memories = self.alma.retrieve(
148
+ task=f"API patterns for {endpoint_type} endpoints",
149
+ agent=self.agent_name,
150
+ top_k=top_k,
151
+ )
152
+
153
+ patterns = []
154
+ for h in memories.heuristics:
155
+ if "api" in h.condition.lower() or "endpoint" in h.condition.lower():
156
+ patterns.append({
157
+ "pattern": h.strategy,
158
+ "condition": h.condition,
159
+ "confidence": h.confidence,
160
+ "occurrences": h.occurrence_count,
161
+ })
162
+
163
+ return patterns
164
+
165
+ def get_error_handling_patterns(self, top_k: int = 5) -> List[Dict[str, Any]]:
166
+ """
167
+ Get proven error handling patterns.
168
+
169
+ Returns strategies for handling API errors, validation, and responses.
170
+ """
171
+ memories = self.alma.retrieve(
172
+ task="error handling patterns validation responses",
173
+ agent=self.agent_name,
174
+ top_k=top_k,
175
+ )
176
+
177
+ patterns = []
178
+ for h in memories.heuristics:
179
+ if any(kw in h.condition.lower() for kw in ["error", "exception", "validation"]):
180
+ patterns.append({
181
+ "condition": h.condition,
182
+ "strategy": h.strategy,
183
+ "confidence": h.confidence,
184
+ })
185
+
186
+ return patterns
187
+
188
+ def get_performance_strategies(self, top_k: int = 5) -> List[Dict[str, Any]]:
189
+ """
190
+ Get performance optimization strategies.
191
+
192
+ Returns strategies for caching, query optimization, etc.
193
+ """
194
+ memories = self.alma.retrieve(
195
+ task="performance optimization caching query database",
196
+ agent=self.agent_name,
197
+ top_k=top_k,
198
+ )
199
+
200
+ strategies = []
201
+ for h in memories.heuristics:
202
+ if any(kw in h.condition.lower() for kw in ["performance", "cache", "query", "slow"]):
203
+ strategies.append({
204
+ "condition": h.condition,
205
+ "strategy": h.strategy,
206
+ "confidence": h.confidence,
207
+ })
208
+
209
+ for dk in memories.domain_knowledge:
210
+ if dk.domain in ["performance_optimization", "caching_strategies"]:
211
+ strategies.append({
212
+ "fact": dk.fact,
213
+ "source": dk.source,
214
+ })
215
+
216
+ return strategies
217
+
218
+ def get_auth_patterns(self, top_k: int = 5) -> List[Dict[str, Any]]:
219
+ """
220
+ Get authentication/authorization testing patterns.
221
+
222
+ Returns patterns for testing auth flows, tokens, permissions.
223
+ """
224
+ memories = self.alma.retrieve(
225
+ task="authentication authorization JWT token permission testing",
226
+ agent=self.agent_name,
227
+ top_k=top_k,
228
+ )
229
+
230
+ patterns = []
231
+ for h in memories.heuristics:
232
+ if any(kw in h.condition.lower() for kw in ["auth", "token", "permission", "jwt"]):
233
+ patterns.append({
234
+ "condition": h.condition,
235
+ "strategy": h.strategy,
236
+ "confidence": h.confidence,
237
+ })
238
+
239
+ return patterns
240
+
241
+ def record_api_pattern(
242
+ self,
243
+ endpoint: str,
244
+ method: str,
245
+ pattern_type: str,
246
+ description: str,
247
+ success: bool,
248
+ ) -> bool:
249
+ """
250
+ Record an API pattern for learning.
251
+
252
+ Args:
253
+ endpoint: API endpoint tested
254
+ method: HTTP method
255
+ pattern_type: Type of pattern (error_handling, validation, etc.)
256
+ description: Pattern description
257
+ success: Whether the pattern worked
258
+
259
+ Returns:
260
+ True if recorded successfully
261
+ """
262
+ fact = f"[{method}] {endpoint}: {description}"
263
+ return self.add_knowledge(
264
+ domain=pattern_type,
265
+ fact=fact,
266
+ source=f"api_test:success={success}",
267
+ )
268
+
269
+ def record_performance_metric(
270
+ self,
271
+ endpoint: str,
272
+ response_time_ms: int,
273
+ query_count: int,
274
+ threshold_ms: int = 500,
275
+ ) -> bool:
276
+ """
277
+ Record a performance metric for learning.
278
+
279
+ Args:
280
+ endpoint: API endpoint tested
281
+ response_time_ms: Response time in milliseconds
282
+ query_count: Number of database queries
283
+ threshold_ms: Performance threshold
284
+
285
+ Returns:
286
+ True if recorded successfully
287
+ """
288
+ is_slow = response_time_ms > threshold_ms
289
+ status = "SLOW" if is_slow else "OK"
290
+ fact = f"{endpoint}: {response_time_ms}ms, {query_count} queries [{status}]"
291
+
292
+ return self.add_knowledge(
293
+ domain="performance_optimization",
294
+ fact=fact,
295
+ source=f"performance_test:threshold={threshold_ms}ms",
296
+ )
297
+
298
+ def format_api_test_prompt(
299
+ self,
300
+ memories: MemorySlice,
301
+ test_context: APITestContext,
302
+ ) -> str:
303
+ """
304
+ Format memories for Victor's API testing prompt.
305
+
306
+ Provides Victor-specific formatting with test context.
307
+ """
308
+ sections = []
309
+
310
+ # Base memory formatting
311
+ base_format = self.format_memories_for_prompt(memories)
312
+ if base_format:
313
+ sections.append(base_format)
314
+
315
+ # Add test context
316
+ sections.append("\n## Current Test Context")
317
+ sections.append(f"- **Task**: {test_context.task_description}")
318
+ sections.append(f"- **Task Type**: {test_context.task_type}")
319
+
320
+ if test_context.endpoint:
321
+ sections.append(f"- **Endpoint**: {test_context.method} {test_context.endpoint}")
322
+ if test_context.expected_status:
323
+ sections.append(f"- **Expected Status**: {test_context.expected_status}")
324
+ if test_context.request_body:
325
+ sections.append(f"- **Request Body**: {len(test_context.request_body)} fields")
326
+
327
+ if test_context.is_auth_test:
328
+ sections.append("- **Focus**: Authentication/Authorization")
329
+ if test_context.is_performance_test:
330
+ sections.append("- **Focus**: Performance testing")
331
+ if test_context.is_database_test:
332
+ sections.append("- **Focus**: Database validation")
333
+
334
+ return "\n".join(sections)
335
+
336
+
337
+ def create_victor_hooks(alma: ALMA, auto_learn: bool = True) -> VictorHooks:
338
+ """
339
+ Convenience function to create Victor hooks.
340
+
341
+ Args:
342
+ alma: ALMA instance
343
+ auto_learn: Whether to automatically learn
344
+
345
+ Returns:
346
+ Configured VictorHooks
347
+ """
348
+ return VictorHooks(alma=alma, auto_learn=auto_learn)
349
+
350
+
351
+ def victor_pre_task(
352
+ alma: ALMA,
353
+ task: str,
354
+ endpoint: Optional[str] = None,
355
+ method: str = "GET",
356
+ project_id: str = "default",
357
+ top_k: int = 5,
358
+ ) -> Dict[str, Any]:
359
+ """
360
+ Convenience function for Victor pre-task hook.
361
+
362
+ Quick integration without creating full hooks object.
363
+
364
+ Args:
365
+ alma: ALMA instance
366
+ task: Task description
367
+ endpoint: Optional API endpoint
368
+ method: HTTP method
369
+ project_id: Project ID
370
+ top_k: Max memories per type
371
+
372
+ Returns:
373
+ Dict with memories and formatted prompt
374
+ """
375
+ hooks = VictorHooks(alma=alma, auto_learn=False)
376
+
377
+ context = APITestContext(
378
+ task_description=task,
379
+ task_type="", # Will be inferred
380
+ agent_name="victor",
381
+ project_id=project_id,
382
+ endpoint=endpoint,
383
+ method=method,
384
+ )
385
+
386
+ memories = hooks.pre_task(context, top_k=top_k)
387
+ prompt = hooks.format_api_test_prompt(memories, context)
388
+
389
+ return {
390
+ "memories": memories,
391
+ "prompt": prompt,
392
+ "context": context,
393
+ }
394
+
395
+
396
+ def victor_post_task(
397
+ alma: ALMA,
398
+ task: str,
399
+ success: bool,
400
+ strategy_used: str,
401
+ endpoint: Optional[str] = None,
402
+ method: str = "GET",
403
+ response_status: Optional[int] = None,
404
+ response_time_ms: Optional[int] = None,
405
+ project_id: str = "default",
406
+ error_message: Optional[str] = None,
407
+ ) -> bool:
408
+ """
409
+ Convenience function for Victor post-task hook.
410
+
411
+ Quick integration without creating full hooks object.
412
+
413
+ Args:
414
+ alma: ALMA instance
415
+ task: Task description
416
+ success: Whether task succeeded
417
+ strategy_used: Strategy used
418
+ endpoint: API endpoint tested
419
+ method: HTTP method
420
+ response_status: HTTP response status
421
+ response_time_ms: Response time
422
+ project_id: Project ID
423
+ error_message: Error if failed
424
+
425
+ Returns:
426
+ True if learning was recorded
427
+ """
428
+ hooks = VictorHooks(alma=alma, auto_learn=True)
429
+
430
+ context = APITestContext(
431
+ task_description=task,
432
+ task_type="", # Will be inferred
433
+ agent_name="victor",
434
+ project_id=project_id,
435
+ endpoint=endpoint,
436
+ method=method,
437
+ )
438
+
439
+ outcome = APITestOutcome(
440
+ success=success,
441
+ strategy_used=strategy_used,
442
+ response_status=response_status,
443
+ response_time_ms=response_time_ms,
444
+ error_message=error_message,
445
+ )
446
+
447
+ return hooks.post_task(context, outcome)
@@ -0,0 +1,86 @@
1
+ """
2
+ ALMA Learning Protocols.
3
+
4
+ Provides learning, validation, forgetting, and heuristic extraction.
5
+ """
6
+
7
+ from alma.learning.protocols import LearningProtocol
8
+ from alma.learning.validation import (
9
+ ScopeValidator,
10
+ ValidationResult,
11
+ ValidationReport,
12
+ TaskTypeValidator,
13
+ validate_learning_request,
14
+ )
15
+ from alma.learning.forgetting import (
16
+ # Forgetting Engine
17
+ ForgettingEngine,
18
+ PrunePolicy,
19
+ PruneResult,
20
+ PruneSummary,
21
+ PruneReason,
22
+ # Decay Functions
23
+ DecayFunction,
24
+ ExponentialDecay,
25
+ LinearDecay,
26
+ StepDecay,
27
+ NoDecay,
28
+ # Confidence Decay
29
+ ConfidenceDecayer,
30
+ DecayResult,
31
+ # Memory Health Monitoring
32
+ MemoryHealthMonitor,
33
+ MemoryHealthMetrics,
34
+ HealthAlert,
35
+ HealthThresholds,
36
+ # Cleanup Scheduling
37
+ CleanupScheduler,
38
+ CleanupJob,
39
+ CleanupResult,
40
+ )
41
+ from alma.learning.heuristic_extractor import (
42
+ HeuristicExtractor,
43
+ PatternCandidate,
44
+ ExtractionResult,
45
+ extract_heuristics_from_outcome,
46
+ )
47
+
48
+ __all__ = [
49
+ # Core Protocol
50
+ "LearningProtocol",
51
+ # Validation
52
+ "ScopeValidator",
53
+ "ValidationResult",
54
+ "ValidationReport",
55
+ "TaskTypeValidator",
56
+ "validate_learning_request",
57
+ # Forgetting Engine
58
+ "ForgettingEngine",
59
+ "PrunePolicy",
60
+ "PruneResult",
61
+ "PruneSummary",
62
+ "PruneReason",
63
+ # Decay Functions
64
+ "DecayFunction",
65
+ "ExponentialDecay",
66
+ "LinearDecay",
67
+ "StepDecay",
68
+ "NoDecay",
69
+ # Confidence Decay
70
+ "ConfidenceDecayer",
71
+ "DecayResult",
72
+ # Memory Health Monitoring
73
+ "MemoryHealthMonitor",
74
+ "MemoryHealthMetrics",
75
+ "HealthAlert",
76
+ "HealthThresholds",
77
+ # Cleanup Scheduling
78
+ "CleanupScheduler",
79
+ "CleanupJob",
80
+ "CleanupResult",
81
+ # Heuristic Extraction
82
+ "HeuristicExtractor",
83
+ "PatternCandidate",
84
+ "ExtractionResult",
85
+ "extract_heuristics_from_outcome",
86
+ ]