alma-memory 0.3.0__py3-none-any.whl → 0.5.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 (77) hide show
  1. alma/__init__.py +99 -29
  2. alma/confidence/__init__.py +47 -0
  3. alma/confidence/engine.py +540 -0
  4. alma/confidence/types.py +351 -0
  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 +15 -15
  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 +264 -0
  22. alma/extraction/extractor.py +420 -0
  23. alma/graph/__init__.py +81 -0
  24. alma/graph/backends/__init__.py +18 -0
  25. alma/graph/backends/memory.py +236 -0
  26. alma/graph/backends/neo4j.py +417 -0
  27. alma/graph/base.py +159 -0
  28. alma/graph/extraction.py +198 -0
  29. alma/graph/store.py +860 -0
  30. alma/harness/__init__.py +4 -4
  31. alma/harness/base.py +18 -9
  32. alma/harness/domains.py +27 -11
  33. alma/initializer/__init__.py +37 -0
  34. alma/initializer/initializer.py +418 -0
  35. alma/initializer/types.py +250 -0
  36. alma/integration/__init__.py +9 -9
  37. alma/integration/claude_agents.py +10 -10
  38. alma/integration/helena.py +32 -22
  39. alma/integration/victor.py +57 -33
  40. alma/learning/__init__.py +27 -27
  41. alma/learning/forgetting.py +198 -148
  42. alma/learning/heuristic_extractor.py +40 -24
  43. alma/learning/protocols.py +62 -14
  44. alma/learning/validation.py +7 -2
  45. alma/mcp/__init__.py +4 -4
  46. alma/mcp/__main__.py +2 -1
  47. alma/mcp/resources.py +17 -16
  48. alma/mcp/server.py +102 -44
  49. alma/mcp/tools.py +174 -37
  50. alma/progress/__init__.py +3 -3
  51. alma/progress/tracker.py +26 -20
  52. alma/progress/types.py +8 -12
  53. alma/py.typed +0 -0
  54. alma/retrieval/__init__.py +11 -11
  55. alma/retrieval/cache.py +20 -21
  56. alma/retrieval/embeddings.py +4 -4
  57. alma/retrieval/engine.py +114 -35
  58. alma/retrieval/scoring.py +73 -63
  59. alma/session/__init__.py +2 -2
  60. alma/session/manager.py +5 -5
  61. alma/session/types.py +5 -4
  62. alma/storage/__init__.py +41 -0
  63. alma/storage/azure_cosmos.py +107 -31
  64. alma/storage/base.py +157 -4
  65. alma/storage/chroma.py +1443 -0
  66. alma/storage/file_based.py +56 -20
  67. alma/storage/pinecone.py +1080 -0
  68. alma/storage/postgresql.py +1452 -0
  69. alma/storage/qdrant.py +1306 -0
  70. alma/storage/sqlite_local.py +376 -31
  71. alma/types.py +62 -14
  72. alma_memory-0.5.0.dist-info/METADATA +905 -0
  73. alma_memory-0.5.0.dist-info/RECORD +76 -0
  74. {alma_memory-0.3.0.dist-info → alma_memory-0.5.0.dist-info}/WHEEL +1 -1
  75. alma_memory-0.3.0.dist-info/METADATA +0 -438
  76. alma_memory-0.3.0.dist-info/RECORD +0 -46
  77. {alma_memory-0.3.0.dist-info → alma_memory-0.5.0.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,417 @@
1
+ """
2
+ ALMA Graph Memory - Neo4j Backend.
3
+
4
+ Neo4j implementation of the GraphBackend interface.
5
+ """
6
+
7
+ import json
8
+ import logging
9
+ from datetime import datetime, timezone
10
+ from typing import Any, Dict, List, Optional
11
+
12
+ from alma.graph.base import GraphBackend
13
+ from alma.graph.store import Entity, Relationship
14
+
15
+ logger = logging.getLogger(__name__)
16
+
17
+
18
+ class Neo4jBackend(GraphBackend):
19
+ """
20
+ Neo4j graph database backend.
21
+
22
+ Requires neo4j Python driver: pip install neo4j
23
+
24
+ Example usage:
25
+ backend = Neo4jBackend(
26
+ uri="bolt://localhost:7687",
27
+ username="neo4j",
28
+ password="password"
29
+ )
30
+ backend.add_entity(entity)
31
+ backend.close()
32
+ """
33
+
34
+ def __init__(
35
+ self,
36
+ uri: str,
37
+ username: str,
38
+ password: str,
39
+ database: str = "neo4j",
40
+ ):
41
+ """
42
+ Initialize Neo4j connection.
43
+
44
+ Args:
45
+ uri: Neo4j connection URI (bolt:// or neo4j+s://)
46
+ username: Database username
47
+ password: Database password
48
+ database: Database name (default: "neo4j")
49
+ """
50
+ self.uri = uri
51
+ self.username = username
52
+ self.password = password
53
+ self.database = database
54
+ self._driver = None
55
+
56
+ def _get_driver(self):
57
+ """Lazy initialization of Neo4j driver."""
58
+ if self._driver is None:
59
+ try:
60
+ from neo4j import GraphDatabase
61
+
62
+ self._driver = GraphDatabase.driver(
63
+ self.uri,
64
+ auth=(self.username, self.password),
65
+ )
66
+ except ImportError as err:
67
+ raise ImportError(
68
+ "neo4j package required for Neo4j graph backend. "
69
+ "Install with: pip install neo4j"
70
+ ) from err
71
+ return self._driver
72
+
73
+ def _run_query(self, query: str, parameters: Optional[Dict] = None) -> List[Dict]:
74
+ """Execute a Cypher query."""
75
+ driver = self._get_driver()
76
+ with driver.session(database=self.database) as session:
77
+ result = session.run(query, parameters or {})
78
+ return [dict(record) for record in result]
79
+
80
+ def add_entity(self, entity: Entity) -> str:
81
+ """Add or update an entity in Neo4j."""
82
+ # Extract project_id and agent from properties if present
83
+ properties = entity.properties.copy()
84
+ project_id = properties.pop("project_id", None)
85
+ agent = properties.pop("agent", None)
86
+
87
+ query = """
88
+ MERGE (e:Entity {id: $id})
89
+ SET e.name = $name,
90
+ e.entity_type = $entity_type,
91
+ e.properties = $properties,
92
+ e.created_at = $created_at
93
+ """
94
+ params = {
95
+ "id": entity.id,
96
+ "name": entity.name,
97
+ "entity_type": entity.entity_type,
98
+ "properties": json.dumps(properties),
99
+ "created_at": entity.created_at.isoformat(),
100
+ }
101
+
102
+ # Add optional fields if present
103
+ if project_id:
104
+ query += ", e.project_id = $project_id"
105
+ params["project_id"] = project_id
106
+ if agent:
107
+ query += ", e.agent = $agent"
108
+ params["agent"] = agent
109
+
110
+ query += " RETURN e.id as id"
111
+
112
+ result = self._run_query(query, params)
113
+ return result[0]["id"] if result else entity.id
114
+
115
+ def add_relationship(self, relationship: Relationship) -> str:
116
+ """Add or update a relationship in Neo4j."""
117
+ # Sanitize relationship type for Cypher (remove special characters)
118
+ rel_type = (
119
+ relationship.relation_type.replace("-", "_").replace(" ", "_").upper()
120
+ )
121
+
122
+ query = f"""
123
+ MATCH (source:Entity {{id: $source_id}})
124
+ MATCH (target:Entity {{id: $target_id}})
125
+ MERGE (source)-[r:{rel_type}]->(target)
126
+ SET r.id = $id,
127
+ r.properties = $properties,
128
+ r.confidence = $confidence,
129
+ r.created_at = $created_at
130
+ RETURN r.id as id
131
+ """
132
+ result = self._run_query(
133
+ query,
134
+ {
135
+ "id": relationship.id,
136
+ "source_id": relationship.source_id,
137
+ "target_id": relationship.target_id,
138
+ "properties": json.dumps(relationship.properties),
139
+ "confidence": relationship.confidence,
140
+ "created_at": relationship.created_at.isoformat(),
141
+ },
142
+ )
143
+ return result[0]["id"] if result else relationship.id
144
+
145
+ def get_entity(self, entity_id: str) -> Optional[Entity]:
146
+ """Get an entity by ID."""
147
+ query = """
148
+ MATCH (e:Entity {id: $id})
149
+ RETURN e.id as id, e.name as name, e.entity_type as entity_type,
150
+ e.properties as properties, e.created_at as created_at,
151
+ e.project_id as project_id, e.agent as agent
152
+ """
153
+ result = self._run_query(query, {"id": entity_id})
154
+ if not result:
155
+ return None
156
+
157
+ r = result[0]
158
+ properties = json.loads(r["properties"]) if r["properties"] else {}
159
+
160
+ # Add project_id and agent back to properties if present
161
+ if r.get("project_id"):
162
+ properties["project_id"] = r["project_id"]
163
+ if r.get("agent"):
164
+ properties["agent"] = r["agent"]
165
+
166
+ return Entity(
167
+ id=r["id"],
168
+ name=r["name"],
169
+ entity_type=r["entity_type"],
170
+ properties=properties,
171
+ created_at=(
172
+ datetime.fromisoformat(r["created_at"])
173
+ if r["created_at"]
174
+ else datetime.now(timezone.utc)
175
+ ),
176
+ )
177
+
178
+ def get_entities(
179
+ self,
180
+ entity_type: Optional[str] = None,
181
+ project_id: Optional[str] = None,
182
+ agent: Optional[str] = None,
183
+ limit: int = 100,
184
+ ) -> List[Entity]:
185
+ """Get entities with optional filtering."""
186
+ conditions = []
187
+ params: Dict[str, Any] = {"limit": limit}
188
+
189
+ if entity_type:
190
+ conditions.append("e.entity_type = $entity_type")
191
+ params["entity_type"] = entity_type
192
+ if project_id:
193
+ conditions.append("e.project_id = $project_id")
194
+ params["project_id"] = project_id
195
+ if agent:
196
+ conditions.append("e.agent = $agent")
197
+ params["agent"] = agent
198
+
199
+ where_clause = f"WHERE {' AND '.join(conditions)}" if conditions else ""
200
+
201
+ query = f"""
202
+ MATCH (e:Entity)
203
+ {where_clause}
204
+ RETURN e.id as id, e.name as name, e.entity_type as entity_type,
205
+ e.properties as properties, e.created_at as created_at,
206
+ e.project_id as project_id, e.agent as agent
207
+ LIMIT $limit
208
+ """
209
+
210
+ results = self._run_query(query, params)
211
+ entities = []
212
+ for r in results:
213
+ properties = json.loads(r["properties"]) if r["properties"] else {}
214
+ if r.get("project_id"):
215
+ properties["project_id"] = r["project_id"]
216
+ if r.get("agent"):
217
+ properties["agent"] = r["agent"]
218
+
219
+ entities.append(
220
+ Entity(
221
+ id=r["id"],
222
+ name=r["name"],
223
+ entity_type=r["entity_type"],
224
+ properties=properties,
225
+ created_at=(
226
+ datetime.fromisoformat(r["created_at"])
227
+ if r["created_at"]
228
+ else datetime.now(timezone.utc)
229
+ ),
230
+ )
231
+ )
232
+ return entities
233
+
234
+ def get_relationships(self, entity_id: str) -> List[Relationship]:
235
+ """Get all relationships for an entity (both directions)."""
236
+ query = """
237
+ MATCH (e:Entity {id: $entity_id})-[r]-(other:Entity)
238
+ RETURN r.id as id,
239
+ CASE WHEN startNode(r).id = $entity_id THEN e.id ELSE other.id END as source_id,
240
+ CASE WHEN endNode(r).id = $entity_id THEN e.id ELSE other.id END as target_id,
241
+ type(r) as relation_type, r.properties as properties,
242
+ r.confidence as confidence, r.created_at as created_at
243
+ """
244
+
245
+ results = self._run_query(query, {"entity_id": entity_id})
246
+ relationships = []
247
+ for r in results:
248
+ rel_id = (
249
+ r["id"] or f"{r['source_id']}-{r['relation_type']}-{r['target_id']}"
250
+ )
251
+ relationships.append(
252
+ Relationship(
253
+ id=rel_id,
254
+ source_id=r["source_id"],
255
+ target_id=r["target_id"],
256
+ relation_type=r["relation_type"],
257
+ properties=json.loads(r["properties"]) if r["properties"] else {},
258
+ confidence=r["confidence"] or 1.0,
259
+ created_at=(
260
+ datetime.fromisoformat(r["created_at"])
261
+ if r["created_at"]
262
+ else datetime.now(timezone.utc)
263
+ ),
264
+ )
265
+ )
266
+ return relationships
267
+
268
+ def search_entities(
269
+ self,
270
+ query: str,
271
+ embedding: Optional[List[float]] = None,
272
+ top_k: int = 10,
273
+ ) -> List[Entity]:
274
+ """
275
+ Search for entities by name.
276
+
277
+ Note: Vector similarity search requires Neo4j 5.x with vector index.
278
+ Falls back to text search if embedding is provided but vector index
279
+ is not available.
280
+ """
281
+ # For now, we do text-based search
282
+ # Vector search can be added when Neo4j vector indexes are set up
283
+ cypher = """
284
+ MATCH (e:Entity)
285
+ WHERE toLower(e.name) CONTAINS toLower($query)
286
+ RETURN e.id as id, e.name as name, e.entity_type as entity_type,
287
+ e.properties as properties, e.created_at as created_at,
288
+ e.project_id as project_id, e.agent as agent
289
+ LIMIT $limit
290
+ """
291
+
292
+ results = self._run_query(cypher, {"query": query, "limit": top_k})
293
+ entities = []
294
+ for r in results:
295
+ properties = json.loads(r["properties"]) if r["properties"] else {}
296
+ if r.get("project_id"):
297
+ properties["project_id"] = r["project_id"]
298
+ if r.get("agent"):
299
+ properties["agent"] = r["agent"]
300
+
301
+ entities.append(
302
+ Entity(
303
+ id=r["id"],
304
+ name=r["name"],
305
+ entity_type=r["entity_type"],
306
+ properties=properties,
307
+ created_at=(
308
+ datetime.fromisoformat(r["created_at"])
309
+ if r["created_at"]
310
+ else datetime.now(timezone.utc)
311
+ ),
312
+ )
313
+ )
314
+ return entities
315
+
316
+ def delete_entity(self, entity_id: str) -> bool:
317
+ """Delete an entity and its relationships."""
318
+ query = """
319
+ MATCH (e:Entity {id: $id})
320
+ DETACH DELETE e
321
+ RETURN count(e) as deleted
322
+ """
323
+ result = self._run_query(query, {"id": entity_id})
324
+ return result[0]["deleted"] > 0 if result else False
325
+
326
+ def delete_relationship(self, relationship_id: str) -> bool:
327
+ """Delete a specific relationship by ID."""
328
+ query = """
329
+ MATCH ()-[r]-()
330
+ WHERE r.id = $id
331
+ DELETE r
332
+ RETURN count(r) as deleted
333
+ """
334
+ result = self._run_query(query, {"id": relationship_id})
335
+ return result[0]["deleted"] > 0 if result else False
336
+
337
+ def close(self) -> None:
338
+ """Close the Neo4j driver connection."""
339
+ if self._driver:
340
+ self._driver.close()
341
+ self._driver = None
342
+
343
+ # Additional methods for compatibility with existing GraphStore API
344
+
345
+ def find_entities(
346
+ self,
347
+ name: Optional[str] = None,
348
+ entity_type: Optional[str] = None,
349
+ limit: int = 10,
350
+ ) -> List[Entity]:
351
+ """
352
+ Find entities by name or type.
353
+
354
+ This method provides compatibility with the existing GraphStore API.
355
+ """
356
+ if name:
357
+ return self.search_entities(query=name, top_k=limit)
358
+
359
+ return self.get_entities(entity_type=entity_type, limit=limit)
360
+
361
+ def get_relationships_directional(
362
+ self,
363
+ entity_id: str,
364
+ direction: str = "both",
365
+ relation_type: Optional[str] = None,
366
+ ) -> List[Relationship]:
367
+ """
368
+ Get relationships for an entity with direction control.
369
+
370
+ This method provides compatibility with the existing GraphStore API.
371
+
372
+ Args:
373
+ entity_id: The entity ID.
374
+ direction: "outgoing", "incoming", or "both".
375
+ relation_type: Optional filter by relationship type.
376
+
377
+ Returns:
378
+ List of matching relationships.
379
+ """
380
+ if direction == "outgoing":
381
+ pattern = "(e)-[r]->(other)"
382
+ elif direction == "incoming":
383
+ pattern = "(e)<-[r]-(other)"
384
+ else:
385
+ pattern = "(e)-[r]-(other)"
386
+
387
+ type_filter = f":{relation_type}" if relation_type else ""
388
+
389
+ query = f"""
390
+ MATCH (e:Entity {{id: $entity_id}}){pattern.replace("[r]", f"[r{type_filter}]")}
391
+ RETURN r.id as id, e.id as source_id, other.id as target_id,
392
+ type(r) as relation_type, r.properties as properties,
393
+ r.confidence as confidence, r.created_at as created_at
394
+ """
395
+
396
+ results = self._run_query(query, {"entity_id": entity_id})
397
+ relationships = []
398
+ for r in results:
399
+ rel_id = (
400
+ r["id"] or f"{r['source_id']}-{r['relation_type']}-{r['target_id']}"
401
+ )
402
+ relationships.append(
403
+ Relationship(
404
+ id=rel_id,
405
+ source_id=r["source_id"],
406
+ target_id=r["target_id"],
407
+ relation_type=r["relation_type"],
408
+ properties=json.loads(r["properties"]) if r["properties"] else {},
409
+ confidence=r["confidence"] or 1.0,
410
+ created_at=(
411
+ datetime.fromisoformat(r["created_at"])
412
+ if r["created_at"]
413
+ else datetime.now(timezone.utc)
414
+ ),
415
+ )
416
+ )
417
+ return relationships
alma/graph/base.py ADDED
@@ -0,0 +1,159 @@
1
+ """
2
+ ALMA Graph Memory - Abstract Backend Interface.
3
+
4
+ Defines the abstract base class for graph database backends,
5
+ enabling pluggable graph storage implementations.
6
+ """
7
+
8
+ from abc import ABC, abstractmethod
9
+ from typing import List, Optional
10
+
11
+ from alma.graph.store import Entity, Relationship
12
+
13
+
14
+ class GraphBackend(ABC):
15
+ """
16
+ Abstract base class for graph database backends.
17
+
18
+ This interface defines the contract that all graph storage implementations
19
+ must follow, enabling ALMA to work with different graph databases like
20
+ Neo4j, Amazon Neptune, or in-memory stores.
21
+ """
22
+
23
+ @abstractmethod
24
+ def add_entity(self, entity: Entity) -> str:
25
+ """
26
+ Add or update an entity in the graph.
27
+
28
+ Args:
29
+ entity: The entity to add or update.
30
+
31
+ Returns:
32
+ The entity ID.
33
+ """
34
+ pass
35
+
36
+ @abstractmethod
37
+ def add_relationship(self, relationship: Relationship) -> str:
38
+ """
39
+ Add or update a relationship between entities.
40
+
41
+ Args:
42
+ relationship: The relationship to add or update.
43
+
44
+ Returns:
45
+ The relationship ID.
46
+ """
47
+ pass
48
+
49
+ @abstractmethod
50
+ def get_entity(self, entity_id: str) -> Optional[Entity]:
51
+ """
52
+ Get an entity by its ID.
53
+
54
+ Args:
55
+ entity_id: The unique identifier of the entity.
56
+
57
+ Returns:
58
+ The entity if found, None otherwise.
59
+ """
60
+ pass
61
+
62
+ @abstractmethod
63
+ def get_entities(
64
+ self,
65
+ entity_type: Optional[str] = None,
66
+ project_id: Optional[str] = None,
67
+ agent: Optional[str] = None,
68
+ limit: int = 100,
69
+ ) -> List[Entity]:
70
+ """
71
+ Get entities with optional filtering.
72
+
73
+ Args:
74
+ entity_type: Filter by entity type (person, organization, etc.).
75
+ project_id: Filter by project ID.
76
+ agent: Filter by agent name.
77
+ limit: Maximum number of entities to return.
78
+
79
+ Returns:
80
+ List of matching entities.
81
+ """
82
+ pass
83
+
84
+ @abstractmethod
85
+ def get_relationships(self, entity_id: str) -> List[Relationship]:
86
+ """
87
+ Get all relationships for an entity.
88
+
89
+ Args:
90
+ entity_id: The entity ID to get relationships for.
91
+
92
+ Returns:
93
+ List of relationships where the entity is source or target.
94
+ """
95
+ pass
96
+
97
+ @abstractmethod
98
+ def search_entities(
99
+ self,
100
+ query: str,
101
+ embedding: Optional[List[float]] = None,
102
+ top_k: int = 10,
103
+ ) -> List[Entity]:
104
+ """
105
+ Search for entities by name or using vector similarity.
106
+
107
+ Args:
108
+ query: Text query to search for in entity names.
109
+ embedding: Optional embedding vector for semantic search.
110
+ top_k: Maximum number of results to return.
111
+
112
+ Returns:
113
+ List of matching entities, ordered by relevance.
114
+ """
115
+ pass
116
+
117
+ @abstractmethod
118
+ def delete_entity(self, entity_id: str) -> bool:
119
+ """
120
+ Delete an entity and all its relationships.
121
+
122
+ Args:
123
+ entity_id: The entity ID to delete.
124
+
125
+ Returns:
126
+ True if the entity was deleted, False if not found.
127
+ """
128
+ pass
129
+
130
+ @abstractmethod
131
+ def delete_relationship(self, relationship_id: str) -> bool:
132
+ """
133
+ Delete a specific relationship.
134
+
135
+ Args:
136
+ relationship_id: The relationship ID to delete.
137
+
138
+ Returns:
139
+ True if the relationship was deleted, False if not found.
140
+ """
141
+ pass
142
+
143
+ @abstractmethod
144
+ def close(self) -> None:
145
+ """
146
+ Close the backend connection and release resources.
147
+
148
+ Should be called when the backend is no longer needed.
149
+ """
150
+ pass
151
+
152
+ def __enter__(self):
153
+ """Context manager entry."""
154
+ return self
155
+
156
+ def __exit__(self, exc_type, exc_val, exc_tb):
157
+ """Context manager exit - ensures close is called."""
158
+ self.close()
159
+ return False