alma-memory 0.4.0__py3-none-any.whl → 0.5.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 (94) hide show
  1. alma/__init__.py +121 -45
  2. alma/confidence/__init__.py +1 -1
  3. alma/confidence/engine.py +92 -58
  4. alma/confidence/types.py +34 -14
  5. alma/config/loader.py +3 -2
  6. alma/consolidation/__init__.py +23 -0
  7. alma/consolidation/engine.py +678 -0
  8. alma/consolidation/prompts.py +84 -0
  9. alma/core.py +136 -28
  10. alma/domains/__init__.py +6 -6
  11. alma/domains/factory.py +12 -9
  12. alma/domains/schemas.py +17 -3
  13. alma/domains/types.py +8 -4
  14. alma/events/__init__.py +75 -0
  15. alma/events/emitter.py +284 -0
  16. alma/events/storage_mixin.py +246 -0
  17. alma/events/types.py +126 -0
  18. alma/events/webhook.py +425 -0
  19. alma/exceptions.py +49 -0
  20. alma/extraction/__init__.py +31 -0
  21. alma/extraction/auto_learner.py +265 -0
  22. alma/extraction/extractor.py +420 -0
  23. alma/graph/__init__.py +106 -0
  24. alma/graph/backends/__init__.py +32 -0
  25. alma/graph/backends/kuzu.py +624 -0
  26. alma/graph/backends/memgraph.py +432 -0
  27. alma/graph/backends/memory.py +236 -0
  28. alma/graph/backends/neo4j.py +417 -0
  29. alma/graph/base.py +159 -0
  30. alma/graph/extraction.py +198 -0
  31. alma/graph/store.py +860 -0
  32. alma/harness/__init__.py +4 -4
  33. alma/harness/base.py +18 -9
  34. alma/harness/domains.py +27 -11
  35. alma/initializer/__init__.py +1 -1
  36. alma/initializer/initializer.py +51 -43
  37. alma/initializer/types.py +25 -17
  38. alma/integration/__init__.py +9 -9
  39. alma/integration/claude_agents.py +32 -20
  40. alma/integration/helena.py +32 -22
  41. alma/integration/victor.py +57 -33
  42. alma/learning/__init__.py +27 -27
  43. alma/learning/forgetting.py +198 -148
  44. alma/learning/heuristic_extractor.py +40 -24
  45. alma/learning/protocols.py +65 -17
  46. alma/learning/validation.py +7 -2
  47. alma/mcp/__init__.py +4 -4
  48. alma/mcp/__main__.py +2 -1
  49. alma/mcp/resources.py +17 -16
  50. alma/mcp/server.py +102 -44
  51. alma/mcp/tools.py +180 -45
  52. alma/observability/__init__.py +84 -0
  53. alma/observability/config.py +302 -0
  54. alma/observability/logging.py +424 -0
  55. alma/observability/metrics.py +583 -0
  56. alma/observability/tracing.py +440 -0
  57. alma/progress/__init__.py +3 -3
  58. alma/progress/tracker.py +26 -20
  59. alma/progress/types.py +8 -12
  60. alma/py.typed +0 -0
  61. alma/retrieval/__init__.py +11 -11
  62. alma/retrieval/cache.py +20 -21
  63. alma/retrieval/embeddings.py +4 -4
  64. alma/retrieval/engine.py +179 -39
  65. alma/retrieval/scoring.py +73 -63
  66. alma/session/__init__.py +2 -2
  67. alma/session/manager.py +5 -5
  68. alma/session/types.py +5 -4
  69. alma/storage/__init__.py +70 -0
  70. alma/storage/azure_cosmos.py +414 -133
  71. alma/storage/base.py +215 -4
  72. alma/storage/chroma.py +1443 -0
  73. alma/storage/constants.py +103 -0
  74. alma/storage/file_based.py +59 -28
  75. alma/storage/migrations/__init__.py +21 -0
  76. alma/storage/migrations/base.py +321 -0
  77. alma/storage/migrations/runner.py +323 -0
  78. alma/storage/migrations/version_stores.py +337 -0
  79. alma/storage/migrations/versions/__init__.py +11 -0
  80. alma/storage/migrations/versions/v1_0_0.py +373 -0
  81. alma/storage/pinecone.py +1080 -0
  82. alma/storage/postgresql.py +1559 -0
  83. alma/storage/qdrant.py +1306 -0
  84. alma/storage/sqlite_local.py +504 -60
  85. alma/testing/__init__.py +46 -0
  86. alma/testing/factories.py +301 -0
  87. alma/testing/mocks.py +389 -0
  88. alma/types.py +62 -14
  89. alma_memory-0.5.1.dist-info/METADATA +939 -0
  90. alma_memory-0.5.1.dist-info/RECORD +93 -0
  91. {alma_memory-0.4.0.dist-info → alma_memory-0.5.1.dist-info}/WHEEL +1 -1
  92. alma_memory-0.4.0.dist-info/METADATA +0 -488
  93. alma_memory-0.4.0.dist-info/RECORD +0 -52
  94. {alma_memory-0.4.0.dist-info → alma_memory-0.5.1.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,939 @@
1
+ Metadata-Version: 2.4
2
+ Name: alma-memory
3
+ Version: 0.5.1
4
+ Summary: Agent Learning Memory Architecture - Persistent memory for AI agents
5
+ Author-email: RBKunnela <aiagentsprompt@gmail.com>
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/RBKunnela/ALMA-memory
8
+ Project-URL: Documentation, https://github.com/RBKunnela/ALMA-memory/tree/main/docs
9
+ Project-URL: Repository, https://github.com/RBKunnela/ALMA-memory
10
+ Project-URL: Issues, https://github.com/RBKunnela/ALMA-memory/issues
11
+ Keywords: ai,agents,memory,learning,llm,azure,claude
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
20
+ Requires-Python: >=3.10
21
+ Description-Content-Type: text/markdown
22
+ Requires-Dist: pyyaml>=6.0
23
+ Requires-Dist: python-dotenv>=1.0.0
24
+ Provides-Extra: local
25
+ Requires-Dist: sentence-transformers>=2.2.0; extra == "local"
26
+ Requires-Dist: faiss-cpu>=1.7.4; extra == "local"
27
+ Provides-Extra: azure
28
+ Requires-Dist: azure-cosmos>=4.5.0; extra == "azure"
29
+ Requires-Dist: azure-identity>=1.15.0; extra == "azure"
30
+ Requires-Dist: azure-keyvault-secrets>=4.7.0; extra == "azure"
31
+ Requires-Dist: openai>=1.0.0; extra == "azure"
32
+ Provides-Extra: postgres
33
+ Requires-Dist: psycopg[binary,pool]>=3.1.0; extra == "postgres"
34
+ Requires-Dist: numpy>=1.24.0; extra == "postgres"
35
+ Provides-Extra: qdrant
36
+ Requires-Dist: qdrant-client>=1.7.0; extra == "qdrant"
37
+ Provides-Extra: chroma
38
+ Requires-Dist: chromadb>=0.4.0; extra == "chroma"
39
+ Provides-Extra: pinecone
40
+ Requires-Dist: pinecone>=3.0.0; extra == "pinecone"
41
+ Provides-Extra: mcp
42
+ Requires-Dist: pydantic>=2.0.0; extra == "mcp"
43
+ Requires-Dist: aiohttp>=3.9.0; extra == "mcp"
44
+ Provides-Extra: observability
45
+ Requires-Dist: opentelemetry-api>=1.20.0; extra == "observability"
46
+ Requires-Dist: opentelemetry-sdk>=1.20.0; extra == "observability"
47
+ Requires-Dist: opentelemetry-exporter-otlp-proto-grpc>=1.20.0; extra == "observability"
48
+ Provides-Extra: dev
49
+ Requires-Dist: pytest>=7.0.0; extra == "dev"
50
+ Requires-Dist: pytest-asyncio>=0.21.0; extra == "dev"
51
+ Requires-Dist: pytest-cov>=4.0.0; extra == "dev"
52
+ Requires-Dist: pytest-benchmark>=4.0.0; extra == "dev"
53
+ Requires-Dist: mypy>=1.0.0; extra == "dev"
54
+ Requires-Dist: ruff>=0.1.0; extra == "dev"
55
+ Requires-Dist: black>=24.0.0; extra == "dev"
56
+ Requires-Dist: bandit[toml]>=1.7.0; extra == "dev"
57
+ Requires-Dist: numpy>=1.24.0; extra == "dev"
58
+ Provides-Extra: all
59
+ Requires-Dist: alma-memory[azure,chroma,dev,local,mcp,observability,pinecone,postgres,qdrant]; extra == "all"
60
+
61
+ # ALMA - Agent Learning Memory Architecture
62
+
63
+ [![PyPI version](https://badge.fury.io/py/alma-memory.svg)](https://pypi.org/project/alma-memory/)
64
+ [![Python 3.10+](https://img.shields.io/badge/python-3.10+-blue.svg)](https://www.python.org/downloads/)
65
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
66
+ [![CI](https://github.com/RBKunnela/ALMA-memory/actions/workflows/ci.yml/badge.svg)](https://github.com/RBKunnela/ALMA-memory/actions/workflows/ci.yml)
67
+ [![Code style: ruff](https://img.shields.io/badge/code%20style-ruff-000000.svg)](https://github.com/astral-sh/ruff)
68
+
69
+ > Persistent memory for AI agents that learn and improve over time - without model weight updates.
70
+
71
+ ---
72
+
73
+ ## Why ALMA? Key Differentiators
74
+
75
+ ALMA isn't just another memory framework. Here's what sets it apart from alternatives like Mem0:
76
+
77
+ | Feature | ALMA | Mem0 | Why It Matters |
78
+ |---------|------|------|----------------|
79
+ | **Memory Scoping** | `can_learn` / `cannot_learn` per agent | Basic user/session isolation | Prevents agents from learning outside their domain |
80
+ | **Anti-Pattern Learning** | Explicit with `why_bad` + `better_alternative` | None | Agents learn what NOT to do |
81
+ | **Multi-Agent Sharing** | `inherit_from` + `share_with` scopes | None | Agents can share knowledge hierarchically |
82
+ | **Memory Consolidation** | LLM-powered deduplication | Basic | Intelligent merge of similar memories |
83
+ | **Event System** | Webhooks + in-process callbacks | None | React to memory changes in real-time |
84
+ | **TypeScript SDK** | Full-featured client library | None | First-class JavaScript/TypeScript support |
85
+ | **Vector DB Support** | 6 backends (PostgreSQL, Qdrant, Pinecone, Chroma, SQLite, Azure) | Limited | Deploy anywhere |
86
+ | **Graph Memory** | Pluggable backends (Neo4j, Memgraph, Kuzu, In-memory) | Limited | Entity relationship tracking |
87
+ | **Harness Pattern** | Decouples agent from domain memory | None | Reusable agent architecture |
88
+ | **MCP Integration** | Native stdio/HTTP server | None | Direct Claude Code integration |
89
+ | **Domain Memory Factory** | 6 pre-built schemas | None | Instant setup for any domain |
90
+ | **Multi-Factor Scoring** | Similarity + Recency + Success + Confidence | Primarily vector + recency | More nuanced retrieval |
91
+
92
+ **Bottom line:** ALMA is purpose-built for AI agents that need to learn, remember, and improve - not just store and retrieve.
93
+
94
+ ---
95
+
96
+ ## What's New in v0.5.0
97
+
98
+ ### Phase 2: Vector Database Backends
99
+
100
+ - **Qdrant Backend** (`alma/storage/qdrant.py`)
101
+ - Full StorageBackend implementation with vector similarity search
102
+ - Metadata filtering for all queries
103
+ - Optimized `MatchAny` queries for multi-agent memory sharing
104
+
105
+ - **Pinecone Backend** (`alma/storage/pinecone.py`)
106
+ - Namespace-based organization per memory type
107
+ - Serverless spec support for automatic scaling
108
+ - Environment variable expansion in configuration
109
+
110
+ - **Chroma Backend** (`alma/storage/chroma.py`)
111
+ - Persistent, client-server, and ephemeral modes
112
+ - Native embedding storage and similarity search
113
+ - Lightweight local development option
114
+
115
+ - **Graph Database Abstraction** (`alma/graph/`)
116
+ - Pluggable `GraphBackend` interface
117
+ - Neo4j backend for production
118
+ - Memgraph backend for high-performance in-memory graphs
119
+ - Kuzu backend for embedded graph storage (no server required)
120
+ - In-memory backend for testing
121
+ - Factory function `create_graph_backend()` for easy setup
122
+
123
+ - **Testing Module** (`alma/testing/`)
124
+ - `MockStorage` - In-memory storage backend for isolated testing
125
+ - `MockEmbedder` - Deterministic fake embedding provider
126
+ - Factory functions for creating test data with sensible defaults
127
+
128
+ ### Phase 1: Core Features
129
+
130
+ - **Memory Consolidation Engine** (`alma/consolidation/`)
131
+ - LLM-powered deduplication that merges similar memories
132
+ - Cosine similarity-based grouping with configurable thresholds
133
+ - Provenance tracking (merged_from metadata)
134
+ - Dry-run mode for safety
135
+
136
+ - **Event System** (`alma/events/`)
137
+ - In-process callbacks via `EventEmitter`
138
+ - Webhook delivery with HMAC signatures
139
+ - Event types: CREATED, UPDATED, DELETED, ACCESSED, CONSOLIDATED
140
+ - Retry logic with exponential backoff
141
+
142
+ - **TypeScript/JavaScript SDK** (`packages/alma-memory-js/`)
143
+ - Full API coverage: retrieve, learn, addPreference, addKnowledge, forget
144
+ - Type-safe with comprehensive TypeScript definitions
145
+ - Error hierarchy matching Python SDK
146
+ - Automatic retry with configurable backoff
147
+
148
+ - **Multi-Agent Memory Sharing**
149
+ - `inherit_from`: Read memories from other agents
150
+ - `share_with`: Make your memories readable by others
151
+ - Origin tracking via `metadata['shared_from']`
152
+ - Optimized batch queries across agents
153
+
154
+ See [CHANGELOG.md](CHANGELOG.md) for the complete history.
155
+
156
+ ---
157
+
158
+ ## What is ALMA?
159
+
160
+ ALMA is a **memory framework** that makes AI agents appear to "learn" by:
161
+ 1. **Storing** outcomes, strategies, and knowledge from past tasks
162
+ 2. **Retrieving** relevant memories before each new task
163
+ 3. **Injecting** that knowledge into prompts
164
+ 4. **Learning** from new outcomes to improve future performance
165
+
166
+ **No fine-tuning. No model changes. Just smarter prompts.**
167
+
168
+ ```
169
+ +---------------------------------------------------------------------+
170
+ | BEFORE TASK: Retrieve relevant memories |
171
+ | +-- "Last time you tested forms, incremental validation worked" |
172
+ | +-- "User prefers verbose output" |
173
+ | +-- "Don't use sleep() - causes flaky tests" |
174
+ +---------------------------------------------------------------------+
175
+ | DURING TASK: Agent executes with injected knowledge |
176
+ +---------------------------------------------------------------------+
177
+ | AFTER TASK: Learn from outcome |
178
+ | +-- Success? -> New heuristic. Failure? -> Anti-pattern. |
179
+ +---------------------------------------------------------------------+
180
+ ```
181
+
182
+ ---
183
+
184
+ ## Installation
185
+
186
+ ```bash
187
+ pip install alma-memory
188
+ ```
189
+
190
+ **With optional backends:**
191
+ ```bash
192
+ # Local development
193
+ pip install alma-memory[local] # SQLite + FAISS + local embeddings
194
+
195
+ # Production databases
196
+ pip install alma-memory[postgres] # PostgreSQL + pgvector
197
+ pip install alma-memory[qdrant] # Qdrant vector database
198
+ pip install alma-memory[pinecone] # Pinecone vector database
199
+ pip install alma-memory[chroma] # ChromaDB
200
+
201
+ # Enterprise
202
+ pip install alma-memory[azure] # Azure Cosmos DB + Azure OpenAI
203
+
204
+ # Everything
205
+ pip install alma-memory[all]
206
+ ```
207
+
208
+ **TypeScript/JavaScript:**
209
+ ```bash
210
+ npm install alma-memory
211
+ # or
212
+ yarn add alma-memory
213
+ ```
214
+
215
+ ---
216
+
217
+ ## Quick Start
218
+
219
+ ### Python
220
+
221
+ ```python
222
+ from alma import ALMA
223
+
224
+ # Initialize
225
+ alma = ALMA.from_config(".alma/config.yaml")
226
+
227
+ # Before task: Get relevant memories
228
+ memories = alma.retrieve(
229
+ task="Test the login form validation",
230
+ agent="helena",
231
+ top_k=5
232
+ )
233
+
234
+ # Inject into your prompt
235
+ prompt = f"""
236
+ ## Your Task
237
+ Test the login form validation
238
+
239
+ ## Knowledge from Past Runs
240
+ {memories.to_prompt()}
241
+ """
242
+
243
+ # After task: Learn from outcome
244
+ alma.learn(
245
+ agent="helena",
246
+ task="Test login form",
247
+ outcome="success",
248
+ strategy_used="Tested empty fields, invalid email, valid submission",
249
+ )
250
+ ```
251
+
252
+ ### TypeScript/JavaScript
253
+
254
+ ```typescript
255
+ import { ALMA } from 'alma-memory';
256
+
257
+ // Create client
258
+ const alma = new ALMA({
259
+ baseUrl: 'http://localhost:8765',
260
+ projectId: 'my-project'
261
+ });
262
+
263
+ // Retrieve memories
264
+ const memories = await alma.retrieve({
265
+ query: 'authentication flow',
266
+ agent: 'dev-agent',
267
+ topK: 5
268
+ });
269
+
270
+ // Learn from outcomes
271
+ await alma.learn({
272
+ agent: 'dev-agent',
273
+ task: 'Implement OAuth',
274
+ outcome: 'success',
275
+ strategyUsed: 'Used passport.js middleware'
276
+ });
277
+
278
+ // Add preferences and knowledge
279
+ await alma.addPreference({
280
+ userId: 'user-123',
281
+ category: 'code_style',
282
+ preference: 'Use TypeScript strict mode'
283
+ });
284
+
285
+ await alma.addKnowledge({
286
+ agent: 'dev-agent',
287
+ domain: 'authentication',
288
+ fact: 'API uses JWT with 24h expiry'
289
+ });
290
+ ```
291
+
292
+ ---
293
+
294
+ ## Core Features
295
+
296
+ ### Five Memory Types
297
+
298
+ | Type | What It Stores | Example |
299
+ |------|----------------|---------|
300
+ | **Heuristic** | Learned strategies | "For forms with >5 fields, test validation incrementally" |
301
+ | **Outcome** | Task results | "Login test succeeded using JWT token strategy" |
302
+ | **Preference** | User constraints | "User prefers verbose test output" |
303
+ | **Domain Knowledge** | Accumulated facts | "Login uses OAuth 2.0 with 24h token expiry" |
304
+ | **Anti-pattern** | What NOT to do | "Don't use sleep() for async waits - causes flaky tests" |
305
+
306
+ ### Scoped Learning
307
+
308
+ Agents only learn within their defined domains. Helena (frontend tester) cannot learn backend logic:
309
+
310
+ ```yaml
311
+ agents:
312
+ helena:
313
+ domain: coding
314
+ can_learn:
315
+ - testing_strategies
316
+ - selector_patterns
317
+ cannot_learn:
318
+ - backend_logic
319
+ - database_queries
320
+ ```
321
+
322
+ ### Multi-Agent Memory Sharing
323
+
324
+ Enable agents to share knowledge hierarchically:
325
+
326
+ ```yaml
327
+ agents:
328
+ senior_dev:
329
+ can_learn: [architecture, best_practices]
330
+ share_with: [junior_dev, qa_agent] # Others can read my memories
331
+
332
+ junior_dev:
333
+ can_learn: [coding_patterns]
334
+ inherit_from: [senior_dev] # I can read senior's memories
335
+ ```
336
+
337
+ ```python
338
+ # Junior dev retrieves memories (includes senior's shared memories)
339
+ memories = alma.retrieve(
340
+ task="Implement user authentication",
341
+ agent="junior_dev",
342
+ include_shared=True # Include inherited memories
343
+ )
344
+
345
+ # Shared memories are marked with origin
346
+ for mem in memories.heuristics:
347
+ if mem.metadata.get('shared_from'):
348
+ print(f"Learned from {mem.metadata['shared_from']}: {mem.strategy}")
349
+ ```
350
+
351
+ ### Storage Backends
352
+
353
+ | Backend | Use Case | Vector Search | Production Ready |
354
+ |---------|----------|---------------|------------------|
355
+ | **SQLite + FAISS** | Local development | Yes | Yes |
356
+ | **PostgreSQL + pgvector** | Production, HA | Yes (HNSW) | Yes |
357
+ | **Qdrant** | Managed vector DB | Yes (HNSW) | Yes |
358
+ | **Pinecone** | Serverless vector DB | Yes | Yes |
359
+ | **Chroma** | Lightweight local | Yes | Yes |
360
+ | **Azure Cosmos DB** | Enterprise, Azure-native | Yes (DiskANN) | Yes |
361
+ | **File-based** | Testing | No | No |
362
+
363
+ ---
364
+
365
+ ## Memory Consolidation
366
+
367
+ Automatically deduplicate and merge similar memories using LLM intelligence:
368
+
369
+ ```python
370
+ from alma.consolidation import ConsolidationEngine
371
+
372
+ engine = ConsolidationEngine(
373
+ storage=alma.storage,
374
+ llm_client=my_llm_client # Optional: for intelligent merging
375
+ )
376
+
377
+ # Consolidate heuristics for an agent
378
+ result = await engine.consolidate(
379
+ agent="helena",
380
+ project_id="my-project",
381
+ memory_type="heuristics",
382
+ similarity_threshold=0.85, # Group memories above this similarity
383
+ use_llm=True, # Use LLM for intelligent merging
384
+ dry_run=False # Set True to preview without changes
385
+ )
386
+
387
+ print(f"Merged {result.merged_count} memories from {result.groups_found} groups")
388
+ ```
389
+
390
+ **Features:**
391
+ - Cosine similarity-based grouping
392
+ - LLM-powered intelligent merging (preserves important nuances)
393
+ - Provenance tracking (`merged_from` metadata)
394
+ - Support for heuristics, domain_knowledge, and anti_patterns
395
+
396
+ ---
397
+
398
+ ## Event System
399
+
400
+ React to memory changes with webhooks or in-process callbacks:
401
+
402
+ ### In-Process Callbacks
403
+
404
+ ```python
405
+ from alma.events import get_emitter, MemoryEventType
406
+
407
+ def on_memory_created(event):
408
+ print(f"Memory created: {event.memory_id} by {event.agent}")
409
+ # Trigger downstream processes, update caches, etc.
410
+
411
+ emitter = get_emitter()
412
+ emitter.subscribe(MemoryEventType.CREATED, on_memory_created)
413
+ emitter.subscribe(MemoryEventType.CONSOLIDATED, on_consolidation)
414
+ ```
415
+
416
+ ### Webhooks
417
+
418
+ ```python
419
+ from alma.events import WebhookConfig, WebhookManager, get_emitter
420
+
421
+ manager = WebhookManager()
422
+ manager.add_webhook(WebhookConfig(
423
+ url="https://your-app.com/alma-webhook",
424
+ events=[MemoryEventType.CREATED, MemoryEventType.UPDATED],
425
+ secret="your-webhook-secret", # For HMAC signature verification
426
+ retry_count=3,
427
+ retry_delay=5.0
428
+ ))
429
+ manager.start(get_emitter())
430
+ ```
431
+
432
+ **Event Types:**
433
+ - `CREATED` - New memory stored
434
+ - `UPDATED` - Memory modified
435
+ - `DELETED` - Memory removed
436
+ - `ACCESSED` - Memory retrieved
437
+ - `CONSOLIDATED` - Memories merged
438
+
439
+ ---
440
+
441
+ ## Graph Memory
442
+
443
+ Capture entity relationships for complex reasoning:
444
+
445
+ ```python
446
+ from alma.graph import create_graph_backend, BackendGraphStore, EntityExtractor
447
+
448
+ # Create graph backend - multiple options available:
449
+
450
+ # Neo4j (production, hosted)
451
+ backend = create_graph_backend(
452
+ "neo4j",
453
+ uri="neo4j+s://xxx.databases.neo4j.io",
454
+ username="neo4j",
455
+ password="your-password"
456
+ )
457
+
458
+ # Memgraph (high-performance, in-memory)
459
+ # backend = create_graph_backend("memgraph", uri="bolt://localhost:7687")
460
+
461
+ # Kuzu (embedded, no server required)
462
+ # backend = create_graph_backend("kuzu", database_path="./my_graph_db")
463
+
464
+ # In-memory (testing)
465
+ # backend = create_graph_backend("memory")
466
+
467
+ # Create store with backend
468
+ graph = BackendGraphStore(backend)
469
+
470
+ # Extract entities and relationships from text
471
+ extractor = EntityExtractor()
472
+ entities, relationships = extractor.extract(
473
+ "Alice from Acme Corp reviewed the PR that Bob submitted."
474
+ )
475
+
476
+ # Store in graph
477
+ for entity in entities:
478
+ graph.add_entity(entity)
479
+ for rel in relationships:
480
+ graph.add_relationship(rel)
481
+
482
+ # Query relationships
483
+ alice_relations = graph.get_relationships("alice", relationship_type="WORKS_FOR")
484
+ ```
485
+
486
+ ---
487
+
488
+ ## The Harness Pattern
489
+
490
+ ALMA implements a generalized harness pattern for any tool-using agent:
491
+
492
+ ```
493
+ +---------------------------------------------------------------------+
494
+ | 1. SETTING Fixed environment: tools, constraints |
495
+ +---------------------------------------------------------------------+
496
+ | 2. CONTEXT Ephemeral per-run inputs: task, user |
497
+ +---------------------------------------------------------------------+
498
+ | 3. AGENT The executor with scoped intelligence |
499
+ +---------------------------------------------------------------------+
500
+ | 4. MEMORY SCHEMA Domain-specific learning structure |
501
+ +---------------------------------------------------------------------+
502
+ ```
503
+
504
+ ```python
505
+ from alma import create_harness, Context
506
+
507
+ # Create domain-specific harness
508
+ harness = create_harness("coding", "helena", alma)
509
+
510
+ # Run with automatic memory injection
511
+ result = harness.run(Context(
512
+ task="Test the login form validation",
513
+ project_id="my-app",
514
+ ))
515
+ ```
516
+
517
+ ---
518
+
519
+ ## MCP Server Integration
520
+
521
+ Expose ALMA to Claude Code or any MCP-compatible client:
522
+
523
+ ```bash
524
+ python -m alma.mcp --config .alma/config.yaml
525
+ ```
526
+
527
+ ```json
528
+ // .mcp.json
529
+ {
530
+ "mcpServers": {
531
+ "alma-memory": {
532
+ "command": "python",
533
+ "args": ["-m", "alma.mcp", "--config", ".alma/config.yaml"]
534
+ }
535
+ }
536
+ }
537
+ ```
538
+
539
+ **Available MCP Tools:**
540
+ | Tool | Description |
541
+ |------|-------------|
542
+ | `alma_retrieve` | Get memories for a task |
543
+ | `alma_learn` | Record task outcome |
544
+ | `alma_add_preference` | Add user preference |
545
+ | `alma_add_knowledge` | Add domain knowledge |
546
+ | `alma_forget` | Prune stale memories |
547
+ | `alma_stats` | Get memory statistics |
548
+ | `alma_health` | Health check |
549
+
550
+ ---
551
+
552
+ ## Advanced Features
553
+
554
+ ### Domain Memory Factory
555
+
556
+ Create ALMA instances for any domain - not just coding:
557
+
558
+ ```python
559
+ from alma.domains import DomainMemoryFactory, get_research_schema
560
+
561
+ # Pre-built schemas
562
+ factory = DomainMemoryFactory()
563
+ alma = factory.create_alma(get_research_schema(), "my-research-project")
564
+
565
+ # Or create custom domains
566
+ schema = factory.create_schema("sales", {
567
+ "entity_types": [
568
+ {"name": "lead", "attributes": ["stage", "value"]},
569
+ {"name": "objection", "attributes": ["type", "response"]},
570
+ ],
571
+ "learning_categories": [
572
+ "objection_handling",
573
+ "closing_techniques",
574
+ "qualification_patterns",
575
+ ],
576
+ })
577
+ ```
578
+
579
+ **Pre-built schemas:** `coding`, `research`, `sales`, `general`, `customer_support`, `content_creation`
580
+
581
+ ### Progress Tracking
582
+
583
+ Track work items and get intelligent next-task suggestions:
584
+
585
+ ```python
586
+ from alma.progress import ProgressTracker
587
+
588
+ tracker = ProgressTracker("my-project")
589
+
590
+ # Create work items
591
+ item = tracker.create_work_item(
592
+ title="Fix authentication bug",
593
+ description="Login fails on mobile devices",
594
+ priority=80,
595
+ agent="Victor",
596
+ )
597
+
598
+ # Update status
599
+ tracker.update_status(item.id, "in_progress")
600
+
601
+ # Get next task (by priority, quick wins, or unblock others)
602
+ next_task = tracker.get_next_item(strategy="priority")
603
+ ```
604
+
605
+ ### Session Handoff
606
+
607
+ Maintain context across sessions - no more "starting fresh":
608
+
609
+ ```python
610
+ from alma.session import SessionManager
611
+
612
+ manager = SessionManager("my-project")
613
+
614
+ # Start session (loads previous context)
615
+ context = manager.start_session(agent="Helena", goal="Complete auth testing")
616
+
617
+ # Previous session info is available
618
+ if context.previous_handoff:
619
+ print(f"Last action: {context.previous_handoff.last_action}")
620
+ print(f"Blockers: {context.previous_handoff.blockers}")
621
+
622
+ # End session with handoff for next time
623
+ manager.create_handoff("Helena", context.session_id,
624
+ last_action="completed_oauth_tests",
625
+ last_outcome="success",
626
+ next_steps=["Test refresh tokens", "Add error cases"],
627
+ )
628
+ ```
629
+
630
+ ### LLM-Powered Fact Extraction
631
+
632
+ Automatically extract and learn from conversations:
633
+
634
+ ```python
635
+ from alma.extraction import AutoLearner
636
+
637
+ alma = ALMA.from_config(".alma/config.yaml")
638
+ auto_learner = AutoLearner(alma)
639
+
640
+ # After a conversation, automatically extract learnings
641
+ results = auto_learner.learn_from_conversation(
642
+ messages=[
643
+ {"role": "user", "content": "Test the login form"},
644
+ {"role": "assistant", "content": "I used incremental validation which worked well..."},
645
+ ],
646
+ agent="helena",
647
+ )
648
+
649
+ print(f"Extracted {results['extracted_count']} facts")
650
+ ```
651
+
652
+ ### Confidence Engine
653
+
654
+ Assess strategies before trying them:
655
+
656
+ ```python
657
+ from alma.confidence import ConfidenceEngine
658
+
659
+ engine = ConfidenceEngine(alma)
660
+
661
+ # Assess a strategy before trying it
662
+ signal = engine.assess_strategy(
663
+ strategy="Use incremental validation",
664
+ context="Testing a 5-field registration form",
665
+ agent="Helena",
666
+ )
667
+
668
+ print(f"Confidence: {signal.confidence_score:.0%}")
669
+ print(f"Recommendation: {signal.recommendation}")
670
+ # -> Confidence: 78%
671
+ # -> Recommendation: yes
672
+ ```
673
+
674
+ ---
675
+
676
+ ## Architecture
677
+
678
+ ```
679
+ +-------------------------------------------------------------------------+
680
+ | ALMA v0.5.0 |
681
+ +-------------------------------------------------------------------------+
682
+ | HARNESS LAYER |
683
+ | +-----------+ +-----------+ +-----------+ +----------------+ |
684
+ | | Setting | | Context | | Agent | | MemorySchema | |
685
+ | +-----------+ +-----------+ +-----------+ +----------------+ |
686
+ +-------------------------------------------------------------------------+
687
+ | EXTENSION MODULES |
688
+ | +-------------+ +---------------+ +------------------+ |
689
+ | | Progress | | Session | | Domain Memory | |
690
+ | | Tracking | | Handoff | | Factory | |
691
+ | +-------------+ +---------------+ +------------------+ |
692
+ | +-------------+ +---------------+ +------------------+ |
693
+ | | Auto | | Confidence | | Memory | |
694
+ | | Learner | | Engine | | Consolidation | |
695
+ | +-------------+ +---------------+ +------------------+ |
696
+ | +-------------+ +---------------+ |
697
+ | | Event | | TypeScript | |
698
+ | | System | | SDK | |
699
+ | +-------------+ +---------------+ |
700
+ +-------------------------------------------------------------------------+
701
+ | CORE LAYER |
702
+ | +-------------+ +-------------+ +-------------+ +------------+ |
703
+ | | Retrieval | | Learning | | Caching | | Forgetting | |
704
+ | | Engine | | Protocol | | Layer | | Mechanism | |
705
+ | +-------------+ +-------------+ +-------------+ +------------+ |
706
+ +-------------------------------------------------------------------------+
707
+ | STORAGE LAYER |
708
+ | +---------------+ +------------------+ +---------------+ |
709
+ | | SQLite+FAISS | | PostgreSQL+pgvec | | Azure Cosmos | |
710
+ | +---------------+ +------------------+ +---------------+ |
711
+ | +---------------+ +------------------+ +---------------+ |
712
+ | | Qdrant | | Pinecone | | Chroma | |
713
+ | +---------------+ +------------------+ +---------------+ |
714
+ +-------------------------------------------------------------------------+
715
+ | GRAPH LAYER |
716
+ | +---------------+ +------------------+ +---------------+ |
717
+ | | Neo4j | | Memgraph | | Kuzu | |
718
+ | +---------------+ +------------------+ +---------------+ |
719
+ | +---------------+ |
720
+ | | In-Memory | |
721
+ | +---------------+ |
722
+ +-------------------------------------------------------------------------+
723
+ | INTEGRATION LAYER |
724
+ | +-------------------------------------------------------------------+ |
725
+ | | MCP Server | |
726
+ | +-------------------------------------------------------------------+ |
727
+ +-------------------------------------------------------------------------+
728
+ ```
729
+
730
+ ---
731
+
732
+ ## Configuration
733
+
734
+ Create `.alma/config.yaml`:
735
+
736
+ ```yaml
737
+ alma:
738
+ project_id: "my-project"
739
+ storage: sqlite # sqlite | postgres | qdrant | pinecone | chroma | azure | file
740
+ embedding_provider: local # local | azure | mock
741
+ storage_dir: .alma
742
+ db_name: alma.db
743
+ embedding_dim: 384
744
+
745
+ agents:
746
+ helena:
747
+ domain: coding
748
+ can_learn:
749
+ - testing_strategies
750
+ - selector_patterns
751
+ cannot_learn:
752
+ - backend_logic
753
+ min_occurrences_for_heuristic: 3
754
+ share_with: [qa_lead] # Share memories with QA lead
755
+
756
+ victor:
757
+ domain: coding
758
+ can_learn:
759
+ - api_patterns
760
+ - database_queries
761
+ cannot_learn:
762
+ - frontend_selectors
763
+ inherit_from: [senior_architect] # Learn from senior architect
764
+ ```
765
+
766
+ ### Storage Backend Configuration
767
+
768
+ **PostgreSQL + pgvector:**
769
+ ```yaml
770
+ storage: postgres
771
+ postgres:
772
+ host: localhost
773
+ port: 5432
774
+ database: alma
775
+ user: alma_user
776
+ password: ${POSTGRES_PASSWORD}
777
+ vector_index_type: hnsw # hnsw | ivfflat
778
+ ```
779
+
780
+ **Qdrant:**
781
+ ```yaml
782
+ storage: qdrant
783
+ qdrant:
784
+ url: http://localhost:6333
785
+ api_key: ${QDRANT_API_KEY} # Optional for cloud
786
+ collection_prefix: alma
787
+ ```
788
+
789
+ **Pinecone:**
790
+ ```yaml
791
+ storage: pinecone
792
+ pinecone:
793
+ api_key: ${PINECONE_API_KEY}
794
+ environment: us-east-1-aws
795
+ index_name: alma-memories
796
+ ```
797
+
798
+ **Chroma:**
799
+ ```yaml
800
+ storage: chroma
801
+ chroma:
802
+ persist_directory: .alma/chroma
803
+ # Or for client-server mode:
804
+ # host: localhost
805
+ # port: 8000
806
+ ```
807
+
808
+ ### Embedding Providers
809
+
810
+ | Provider | Model | Dimensions | Cost | Best For |
811
+ |----------|-------|------------|------|----------|
812
+ | **local** | all-MiniLM-L6-v2 | 384 | Free | Development, offline |
813
+ | **azure** | text-embedding-3-small | 1536 | ~$0.02/1M | Production |
814
+ | **mock** | (hash-based) | 384 | Free | Testing only |
815
+
816
+ ---
817
+
818
+ ## Development Status
819
+
820
+ | Phase | Description | Status |
821
+ |-------|-------------|--------|
822
+ | Core Abstractions | Memory types, scopes | Done |
823
+ | Local Storage | SQLite + FAISS | Done |
824
+ | Retrieval Engine | Semantic search, scoring | Done |
825
+ | Learning Protocols | Heuristic formation | Done |
826
+ | Agent Integration | Harness pattern | Done |
827
+ | Azure Cosmos DB | Enterprise storage | Done |
828
+ | PostgreSQL | Production storage | Done |
829
+ | Cache Layer | Performance optimization | Done |
830
+ | Forgetting Mechanism | Memory pruning | Done |
831
+ | MCP Server | Claude Code integration | Done |
832
+ | Progress Tracking | Work item management | Done |
833
+ | Session Handoff | Context continuity | Done |
834
+ | Domain Factory | Any-domain support | Done |
835
+ | Confidence Engine | Strategy assessment | Done |
836
+ | Technical Debt Sprint | Security & performance fixes | Done |
837
+ | Multi-Agent Sharing | Cross-agent memory access | Done |
838
+ | Memory Consolidation | LLM-powered deduplication | Done |
839
+ | Event System | Webhooks and callbacks | Done |
840
+ | TypeScript SDK | JavaScript/TypeScript client | Done |
841
+ | Qdrant Backend | Vector database support | Done |
842
+ | Pinecone Backend | Serverless vector DB | Done |
843
+ | Chroma Backend | Lightweight vector DB | Done |
844
+ | Graph Abstraction | Pluggable graph backends | Done |
845
+ | Testing Module | Mocks and factories for testing | Done |
846
+
847
+ ---
848
+
849
+ ## Troubleshooting
850
+
851
+ ### Common Issues
852
+
853
+ **ImportError: sentence-transformers is required**
854
+ ```bash
855
+ pip install alma-memory[local]
856
+ ```
857
+
858
+ **pgvector extension not found**
859
+ ```sql
860
+ CREATE EXTENSION IF NOT EXISTS vector;
861
+ ```
862
+
863
+ **Qdrant connection refused**
864
+ ```bash
865
+ # Start Qdrant with Docker
866
+ docker run -p 6333:6333 qdrant/qdrant
867
+ ```
868
+
869
+ **Pinecone index not found**
870
+ - Ensure your index exists in the Pinecone console
871
+ - Check that `index_name` in config matches your index
872
+
873
+ **Embeddings dimension mismatch**
874
+ - Ensure `embedding_dim` in config matches your embedding provider
875
+ - Local: 384, Azure text-embedding-3-small: 1536
876
+
877
+ **Memgraph connection refused**
878
+ ```bash
879
+ # Start Memgraph with Docker
880
+ docker run -p 7687:7687 memgraph/memgraph-mage
881
+ ```
882
+
883
+ **Kuzu database locked**
884
+ - Ensure only one process accesses the database at a time
885
+ - Use `read_only=True` for concurrent read access
886
+
887
+ ### Debug Logging
888
+
889
+ ```python
890
+ import logging
891
+ logging.getLogger("alma").setLevel(logging.DEBUG)
892
+ ```
893
+
894
+ ---
895
+
896
+ ## Contributing
897
+
898
+ We welcome contributions! See [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines.
899
+
900
+ **What we need most:**
901
+ - Documentation improvements
902
+ - Test coverage for edge cases
903
+ - Additional LLM provider integrations (Ollama, Groq)
904
+ - Frontend dashboard for memory visualization
905
+
906
+ ---
907
+
908
+ ## Roadmap
909
+
910
+ **Completed:**
911
+ - Multi-agent memory sharing
912
+ - Memory consolidation engine
913
+ - Event system / webhooks
914
+ - TypeScript SDK
915
+ - Qdrant, Pinecone, Chroma backends
916
+ - Graph database abstraction
917
+
918
+ **Next:**
919
+ - Memory compression / summarization
920
+ - Temporal reasoning (time-aware retrieval)
921
+ - Proactive memory suggestions
922
+ - Visual memory explorer dashboard
923
+ - Additional graph backends (Neptune, TigerGraph)
924
+
925
+ ---
926
+
927
+ ## License
928
+
929
+ MIT
930
+
931
+ ---
932
+
933
+ ## Star History
934
+
935
+ If ALMA helps your AI agents get smarter, consider giving us a star!
936
+
937
+ ---
938
+
939
+ **Built for AI agents that get better with every task.**