data-analytics-agent-memory 0.1.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,87 @@
1
+ """Serialization helpers for the memory kit."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import re
8
+ from typing import Any
9
+
10
+ from .models import MemoryRecord, utc_now
11
+
12
+
13
+ def stable_memory_id(namespace: str, scope: str, key: str, source: str = "") -> str:
14
+ raw = f"{namespace}\0{scope}\0{key}\0{source}".encode("utf-8", errors="replace")
15
+ return "mem_" + hashlib.sha256(raw).hexdigest()[:24]
16
+
17
+
18
+ def json_dumps(value: Any) -> str:
19
+ return json.dumps(value, ensure_ascii=False, sort_keys=True, default=str)
20
+
21
+
22
+ def json_loads_object(value: str | bytes | None, default: Any) -> Any:
23
+ if value in (None, ""):
24
+ return default
25
+ try:
26
+ return json.loads(value)
27
+ except (TypeError, ValueError, json.JSONDecodeError):
28
+ return default
29
+
30
+
31
+ def memory_from_row(row: Any) -> MemoryRecord:
32
+ mapping = dict(row)
33
+ return MemoryRecord(
34
+ memory_id=mapping["memory_id"],
35
+ memory_type=mapping["memory_type"],
36
+ scope=mapping["scope"],
37
+ namespace=mapping["namespace"],
38
+ key=mapping["key"],
39
+ value=json_loads_object(mapping.get("value_json"), {}),
40
+ summary=mapping.get("summary") or "",
41
+ source=mapping.get("source") or "",
42
+ evidence_refs=json_loads_object(mapping.get("evidence_refs_json"), []),
43
+ confidence=float(mapping.get("confidence", 1.0)),
44
+ trust_level=mapping.get("trust_level") or "system_observed",
45
+ created_at=mapping.get("created_at") or utc_now(),
46
+ updated_at=mapping.get("updated_at") or utc_now(),
47
+ expires_at=mapping.get("expires_at"),
48
+ tags=json_loads_object(mapping.get("tags_json"), []),
49
+ related_ids=json_loads_object(mapping.get("related_ids_json"), []),
50
+ status=mapping.get("status") or "active",
51
+ tenant_id=mapping.get("tenant_id"),
52
+ project_id=mapping.get("project_id"),
53
+ user_id=mapping.get("user_id"),
54
+ privacy_level=mapping.get("privacy_level") or "internal",
55
+ )
56
+
57
+
58
+ def redact_secrets(value: Any) -> Any:
59
+ if isinstance(value, dict):
60
+ return {key: redact_secrets(item) for key, item in value.items()}
61
+ if isinstance(value, list):
62
+ return [redact_secrets(item) for item in value]
63
+ if not isinstance(value, str):
64
+ return value
65
+ return re.sub(
66
+ r"(?i)\b(api[_-]?key|access[_-]?token|password|passwd|secret|bearer)\b\s*[:=]\s*([^\s,;]+)",
67
+ r"\1=[REDACTED]",
68
+ value,
69
+ )
70
+
71
+
72
+ def compact_value(value: dict[str, Any], *, max_chars: int = 8_000) -> dict[str, Any]:
73
+ """Drop large blobs while keeping pointers and compact scalars."""
74
+
75
+ compact: dict[str, Any] = {}
76
+ for key, item in value.items():
77
+ if isinstance(item, str) and len(item) > max_chars:
78
+ compact[key] = item[: max_chars // 2] + "\n...[omitted large memory value]..."
79
+ elif isinstance(item, list) and len(json_dumps(item)) > max_chars:
80
+ compact[key] = item[:20]
81
+ compact[f"{key}_omitted_count"] = max(0, len(item) - 20)
82
+ elif isinstance(item, dict) and len(json_dumps(item)) > max_chars:
83
+ compact[key] = {k: item[k] for k in list(item)[:20]}
84
+ compact[f"{key}_omitted_count"] = max(0, len(item) - 20)
85
+ else:
86
+ compact[key] = item
87
+ return compact
@@ -0,0 +1,392 @@
1
+ """Async SQLite-backed local memory store."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import sqlite3
6
+ import re
7
+ from collections.abc import AsyncIterator
8
+ from contextlib import asynccontextmanager
9
+ from pathlib import Path
10
+ from typing import Any
11
+
12
+ import aiosqlite
13
+
14
+ from .jsonl_audit import JSONLAuditLog
15
+ from .models import MemoryRecord, utc_now
16
+ from .privacy import PrivacyGuard, PrivacyPolicy
17
+ from .serializers import json_dumps, memory_from_row, redact_secrets
18
+
19
+
20
+ class SQLiteMemoryStore:
21
+ """Async local store with soft deletion and JSONL audit logging."""
22
+
23
+ def __init__(self, root: str | Path = ".analytics-agent/memory") -> None:
24
+ self.root = Path(root)
25
+ self.db_path = self.root / "memory.sqlite"
26
+ self.audit = JSONLAuditLog(self.root / "memory_audit.jsonl")
27
+ self.fts_available = False
28
+ self.privacy = PrivacyGuard(PrivacyPolicy(block_secrets=False))
29
+ self._opened = False
30
+
31
+ async def open(self) -> None:
32
+ if self._opened:
33
+ return
34
+ self.root.mkdir(parents=True, exist_ok=True)
35
+ async with self._connect() as connection:
36
+ await connection.execute(
37
+ """
38
+ CREATE TABLE IF NOT EXISTS memories (
39
+ memory_id TEXT PRIMARY KEY, memory_type TEXT NOT NULL, scope TEXT NOT NULL,
40
+ namespace TEXT NOT NULL, key TEXT NOT NULL, value_json TEXT NOT NULL,
41
+ summary TEXT NOT NULL, source TEXT NOT NULL, evidence_refs_json TEXT NOT NULL,
42
+ confidence REAL NOT NULL, trust_level TEXT NOT NULL, created_at TEXT NOT NULL,
43
+ updated_at TEXT NOT NULL, expires_at TEXT, tags_json TEXT NOT NULL,
44
+ related_ids_json TEXT NOT NULL, status TEXT NOT NULL, tenant_id TEXT,
45
+ project_id TEXT, user_id TEXT, privacy_level TEXT NOT NULL DEFAULT 'internal'
46
+ )
47
+ """
48
+ )
49
+ await self._ensure_columns(connection, {
50
+ "tenant_id": "TEXT", "project_id": "TEXT", "user_id": "TEXT",
51
+ "privacy_level": "TEXT NOT NULL DEFAULT 'internal'",
52
+ })
53
+ for statement in (
54
+ "CREATE INDEX IF NOT EXISTS idx_mem_namespace ON memories(namespace)",
55
+ "CREATE INDEX IF NOT EXISTS idx_mem_type ON memories(memory_type)",
56
+ "CREATE INDEX IF NOT EXISTS idx_mem_scope ON memories(scope)",
57
+ "CREATE INDEX IF NOT EXISTS idx_mem_key ON memories(key)",
58
+ "CREATE INDEX IF NOT EXISTS idx_mem_status ON memories(status)",
59
+ "CREATE INDEX IF NOT EXISTS idx_mem_tenant ON memories(tenant_id)",
60
+ "CREATE INDEX IF NOT EXISTS idx_mem_project ON memories(project_id)",
61
+ "CREATE INDEX IF NOT EXISTS idx_mem_user ON memories(user_id)",
62
+ "CREATE INDEX IF NOT EXISTS idx_mem_privacy ON memories(privacy_level)",
63
+ ):
64
+ await connection.execute(statement)
65
+ try:
66
+ await connection.execute(
67
+ "CREATE VIRTUAL TABLE IF NOT EXISTS memories_fts USING fts5(memory_id UNINDEXED, searchable)"
68
+ )
69
+ except sqlite3.OperationalError:
70
+ self.fts_available = False
71
+ else:
72
+ self.fts_available = True
73
+ await self._sync_fts_index(connection)
74
+ await connection.commit()
75
+ self._opened = True
76
+
77
+ async def close(self) -> None:
78
+ self._opened = False
79
+
80
+ @asynccontextmanager
81
+ async def _connect(self):
82
+ if not self._opened and not self.root.exists():
83
+ raise RuntimeError("SQLite memory store is not open; await store.open() first.")
84
+ async with aiosqlite.connect(self.db_path, timeout=30) as connection:
85
+ connection.row_factory = aiosqlite.Row
86
+ await connection.execute("PRAGMA busy_timeout = 30000")
87
+ yield connection
88
+
89
+ @staticmethod
90
+ async def _ensure_columns(connection: aiosqlite.Connection, columns: dict[str, str]) -> None:
91
+ cursor = await connection.execute("PRAGMA table_info(memories)")
92
+ existing = {str(row["name"]) for row in await cursor.fetchall()}
93
+ for name, definition in columns.items():
94
+ if name not in existing:
95
+ await connection.execute(f"ALTER TABLE memories ADD COLUMN {name} {definition}")
96
+
97
+ async def upsert(self, record: MemoryRecord) -> MemoryRecord:
98
+ now = utc_now()
99
+ privacy_report = self.privacy.inspect({
100
+ "value": record.value, "summary": record.summary, "evidence_refs": record.evidence_refs,
101
+ })
102
+ record.value = self.privacy.scrub(redact_secrets(record.value))
103
+ record.summary = str(self.privacy.scrub(redact_secrets(record.summary)))
104
+ record.evidence_refs = self.privacy.scrub(record.evidence_refs)
105
+ record.privacy_level = _max_privacy_level(record.privacy_level, privacy_report.privacy_level)
106
+ async with self._connect() as connection:
107
+ existing = await self._get_on(connection, record.memory_id, include_inactive=True)
108
+ if existing:
109
+ record.created_at = existing.created_at
110
+ record.updated_at = now
111
+ await self._supersede_duplicate_claims(connection, record)
112
+ await connection.execute(
113
+ """
114
+ INSERT INTO memories (
115
+ memory_id, memory_type, scope, namespace, key, value_json, summary, source,
116
+ evidence_refs_json, confidence, trust_level, created_at, updated_at, expires_at,
117
+ tags_json, related_ids_json, status, tenant_id, project_id, user_id, privacy_level
118
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
119
+ ON CONFLICT(memory_id) DO UPDATE SET
120
+ memory_type=excluded.memory_type, scope=excluded.scope, namespace=excluded.namespace,
121
+ key=excluded.key, value_json=excluded.value_json, summary=excluded.summary,
122
+ source=excluded.source, evidence_refs_json=excluded.evidence_refs_json,
123
+ confidence=excluded.confidence, trust_level=excluded.trust_level,
124
+ updated_at=excluded.updated_at, expires_at=excluded.expires_at,
125
+ tags_json=excluded.tags_json, related_ids_json=excluded.related_ids_json,
126
+ status=excluded.status, tenant_id=excluded.tenant_id, project_id=excluded.project_id,
127
+ user_id=excluded.user_id, privacy_level=excluded.privacy_level
128
+ """,
129
+ self._row_values(record),
130
+ )
131
+ await self._upsert_fts(connection, record)
132
+ await connection.commit()
133
+ await self.audit.append("memory_upserted", {
134
+ "memory_id": record.memory_id, "key": record.key, "namespace": record.namespace,
135
+ })
136
+ return record
137
+
138
+ async def import_record(self, record: MemoryRecord) -> MemoryRecord:
139
+ async with self._connect() as connection:
140
+ await connection.execute(
141
+ """
142
+ INSERT INTO memories (
143
+ memory_id, memory_type, scope, namespace, key, value_json, summary, source,
144
+ evidence_refs_json, confidence, trust_level, created_at, updated_at, expires_at,
145
+ tags_json, related_ids_json, status, tenant_id, project_id, user_id, privacy_level
146
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
147
+ ON CONFLICT(memory_id) DO UPDATE SET
148
+ memory_type=excluded.memory_type, scope=excluded.scope, namespace=excluded.namespace,
149
+ key=excluded.key, value_json=excluded.value_json, summary=excluded.summary,
150
+ source=excluded.source, evidence_refs_json=excluded.evidence_refs_json,
151
+ confidence=excluded.confidence, trust_level=excluded.trust_level,
152
+ created_at=excluded.created_at, updated_at=excluded.updated_at,
153
+ expires_at=excluded.expires_at, tags_json=excluded.tags_json,
154
+ related_ids_json=excluded.related_ids_json, status=excluded.status,
155
+ tenant_id=excluded.tenant_id, project_id=excluded.project_id,
156
+ user_id=excluded.user_id, privacy_level=excluded.privacy_level
157
+ """,
158
+ self._row_values(record),
159
+ )
160
+ await self._upsert_fts(connection, record)
161
+ await connection.commit()
162
+ await self.audit.append("memory_imported", {
163
+ "memory_id": record.memory_id, "key": record.key, "namespace": record.namespace,
164
+ })
165
+ return record
166
+
167
+ async def get(self, memory_id: str, *, include_inactive: bool = False) -> MemoryRecord | None:
168
+ async with self._connect() as connection:
169
+ return await self._get_on(connection, memory_id, include_inactive=include_inactive)
170
+
171
+ @staticmethod
172
+ async def _get_on(connection: aiosqlite.Connection, memory_id: str, *, include_inactive: bool) -> MemoryRecord | None:
173
+ query = "SELECT * FROM memories WHERE memory_id = ?"
174
+ if not include_inactive:
175
+ query += " AND status = 'active'"
176
+ cursor = await connection.execute(query, (memory_id,))
177
+ row = await cursor.fetchone()
178
+ return memory_from_row(row) if row else None
179
+
180
+ async def search(
181
+ self, *, namespace: str | None = None, memory_type: str | None = None,
182
+ scope: str | None = None, tags: list[str] | None = None, key: str | None = None,
183
+ text: str | None = None, tenant_id: str | None = None, project_id: str | None = None,
184
+ user_id: str | None = None, privacy_levels: list[str] | None = None,
185
+ include_inactive: bool = False, limit: int = 50,
186
+ ) -> list[MemoryRecord]:
187
+ clauses: list[str] = []
188
+ params: list[Any] = []
189
+ if not include_inactive:
190
+ clauses.append("status = 'active'")
191
+ for column, value in (("namespace", namespace), ("memory_type", memory_type), ("scope", scope),
192
+ ("key", key), ("tenant_id", tenant_id), ("project_id", project_id),
193
+ ("user_id", user_id)):
194
+ if value:
195
+ clauses.append(f"{column} = ?")
196
+ params.append(value)
197
+ if privacy_levels:
198
+ clauses.append("privacy_level IN (" + ",".join("?" for _ in privacy_levels) + ")")
199
+ params.extend(privacy_levels)
200
+ if tags:
201
+ for tag in tags:
202
+ clauses.append("tags_json LIKE ?")
203
+ params.append(f"%{tag}%")
204
+ async with self._connect() as connection:
205
+ if text:
206
+ fts_rows = await self._search_fts(
207
+ connection, namespace=namespace, memory_type=memory_type, scope=scope, tags=tags,
208
+ key=key, text=text, tenant_id=tenant_id, project_id=project_id, user_id=user_id,
209
+ privacy_levels=privacy_levels, include_inactive=include_inactive, limit=limit,
210
+ )
211
+ if fts_rows is not None:
212
+ return fts_rows
213
+ clauses.append("(summary LIKE ? OR key LIKE ? OR value_json LIKE ?)")
214
+ like = f"%{text}%"
215
+ params.extend([like, like, like])
216
+ where = " WHERE " + " AND ".join(clauses) if clauses else ""
217
+ cursor = await connection.execute(
218
+ f"SELECT * FROM memories{where} ORDER BY updated_at DESC LIMIT ?", [*params, int(limit)],
219
+ )
220
+ return [memory_from_row(row) for row in await cursor.fetchall()]
221
+
222
+ async def recent(self, *, namespace: str | None = None, limit: int = 20) -> list[MemoryRecord]:
223
+ return await self.search(namespace=namespace, limit=limit)
224
+
225
+ async def list_active(self, *, limit: int = 100) -> list[MemoryRecord]:
226
+ return await self.search(limit=limit)
227
+
228
+ async def iter_records(self, *, include_inactive: bool = True, batch_size: int = 500) -> AsyncIterator[MemoryRecord]:
229
+ offset = 0
230
+ while True:
231
+ where = "" if include_inactive else " WHERE status = 'active'"
232
+ async with self._connect() as connection:
233
+ cursor = await connection.execute(
234
+ f"SELECT * FROM memories{where} ORDER BY updated_at ASC, memory_id ASC LIMIT ? OFFSET ?",
235
+ (int(batch_size), offset),
236
+ )
237
+ batch = [memory_from_row(row) for row in await cursor.fetchall()]
238
+ if not batch:
239
+ return
240
+ for record in batch:
241
+ yield record
242
+ offset += len(batch)
243
+
244
+ async def mark_superseded(self, memory_id: str, *, superseded_by: str | None = None) -> bool:
245
+ return await self._mark(memory_id, "superseded", {"superseded_by": superseded_by})
246
+
247
+ async def mark_deleted(self, memory_id: str, *, reason: str | None = None) -> bool:
248
+ return await self._mark(memory_id, "deleted", {"reason": reason})
249
+
250
+ async def _mark(self, memory_id: str, status: str, payload: dict[str, Any]) -> bool:
251
+ async with self._connect() as connection:
252
+ cursor = await connection.execute(
253
+ "UPDATE memories SET status = ?, updated_at = ? WHERE memory_id = ?",
254
+ (status, utc_now(), memory_id),
255
+ )
256
+ changed = bool(cursor.rowcount)
257
+ await connection.commit()
258
+ if changed:
259
+ await self.audit.append(f"memory_{status}", {"memory_id": memory_id, **payload})
260
+ return changed
261
+
262
+ async def expire_old_records(self, *, now: str | None = None) -> int:
263
+ timestamp = now or utc_now()
264
+ async with self._connect() as connection:
265
+ cursor = await connection.execute(
266
+ "UPDATE memories SET status='expired', updated_at=? WHERE expires_at IS NOT NULL AND expires_at <= ? AND status='active'",
267
+ (timestamp, timestamp),
268
+ )
269
+ count = int(cursor.rowcount or 0)
270
+ await connection.commit()
271
+ if count:
272
+ await self.audit.append("memory_expired", {"count": count})
273
+ return count
274
+
275
+ async def stats(self) -> dict[str, Any]:
276
+ async with self._connect() as connection:
277
+ cursor = await connection.execute(
278
+ "SELECT status, memory_type, COUNT(*) AS count FROM memories GROUP BY status, memory_type"
279
+ )
280
+ rows = await cursor.fetchall()
281
+ fts_count = await self._fts_row_count(connection) if self.fts_available else 0
282
+ return {
283
+ "backend": "sqlite", "db_path": str(self.db_path),
284
+ "total": sum(int(row["count"]) for row in rows),
285
+ "by_status_type": [dict(row) for row in rows], "audit_path": str(self.audit.path),
286
+ "fts_available": self.fts_available, "fts_indexed_rows": fts_count, "healthy": True,
287
+ }
288
+
289
+ async def _search_fts(self, connection: aiosqlite.Connection, **kwargs: Any) -> list[MemoryRecord] | None:
290
+ if not self.fts_available:
291
+ return None
292
+ text = kwargs["text"]
293
+ query_text = _fts_query(text)
294
+ if not query_text:
295
+ return None
296
+ clauses = ["memories_fts MATCH ?"]
297
+ params: list[Any] = [query_text]
298
+ for column, value in (("status", "active" if not kwargs["include_inactive"] else None),
299
+ ("namespace", kwargs["namespace"]), ("memory_type", kwargs["memory_type"]),
300
+ ("scope", kwargs["scope"]), ("key", kwargs["key"]),
301
+ ("tenant_id", kwargs["tenant_id"]), ("project_id", kwargs["project_id"]),
302
+ ("user_id", kwargs["user_id"])):
303
+ if value:
304
+ clauses.append(f"memories.{column} = ?")
305
+ params.append(value)
306
+ levels = kwargs["privacy_levels"]
307
+ if levels:
308
+ clauses.append("memories.privacy_level IN (" + ",".join("?" for _ in levels) + ")")
309
+ params.extend(levels)
310
+ for tag in kwargs["tags"] or []:
311
+ clauses.append("memories.tags_json LIKE ?")
312
+ params.append(f"%{tag}%")
313
+ try:
314
+ cursor = await connection.execute(
315
+ """SELECT memories.* FROM memories JOIN memories_fts ON memories_fts.memory_id=memories.memory_id
316
+ WHERE """ + " AND ".join(clauses) +
317
+ " ORDER BY bm25(memories_fts), memories.updated_at DESC LIMIT ?",
318
+ [*params, int(kwargs["limit"])],
319
+ )
320
+ return [memory_from_row(row) for row in await cursor.fetchall()]
321
+ except sqlite3.OperationalError:
322
+ return None
323
+
324
+ async def _upsert_fts(self, connection: aiosqlite.Connection, record: MemoryRecord) -> None:
325
+ if not self.fts_available:
326
+ return
327
+ searchable = " ".join([record.key, record.summary, " ".join(record.tags),
328
+ json_dumps(record.value), json_dumps(record.evidence_refs)])
329
+ await connection.execute("DELETE FROM memories_fts WHERE memory_id = ?", (record.memory_id,))
330
+ await connection.execute("INSERT INTO memories_fts(memory_id, searchable) VALUES (?, ?)",
331
+ (record.memory_id, searchable))
332
+
333
+ async def _fts_row_count(self, connection: aiosqlite.Connection) -> int:
334
+ try:
335
+ cursor = await connection.execute("SELECT COUNT(*) AS count FROM memories_fts")
336
+ row = await cursor.fetchone()
337
+ except sqlite3.OperationalError:
338
+ return 0
339
+ return int(row["count"] if row else 0)
340
+
341
+ async def _sync_fts_index(self, connection: aiosqlite.Connection) -> None:
342
+ cursor = await connection.execute("SELECT COUNT(*) AS count FROM memories")
343
+ row = await cursor.fetchone()
344
+ if await self._fts_row_count(connection) >= int(row["count"] if row else 0):
345
+ return
346
+ await connection.execute("DELETE FROM memories_fts")
347
+ cursor = await connection.execute("SELECT * FROM memories")
348
+ for row in await cursor.fetchall():
349
+ await self._upsert_fts(connection, memory_from_row(row))
350
+
351
+ async def _supersede_duplicate_claims(self, connection: aiosqlite.Connection, record: MemoryRecord) -> None:
352
+ if record.memory_type != "rag_retrieval_memory" or record.key != "claim_to_source":
353
+ return
354
+ fingerprint = record.value.get("claim_fingerprint")
355
+ if not fingerprint:
356
+ return
357
+ clauses = ["namespace=?", "memory_type='rag_retrieval_memory'", "key='claim_to_source'", "status='active'"]
358
+ params: list[Any] = [record.namespace]
359
+ for column, value in (("tenant_id", record.tenant_id), ("project_id", record.project_id), ("user_id", record.user_id)):
360
+ clauses.append(f"{column} IS ?")
361
+ params.append(value)
362
+ cursor = await connection.execute(
363
+ "SELECT * FROM memories WHERE " + " AND ".join(clauses) + " LIMIT 500", params,
364
+ )
365
+ for row in await cursor.fetchall():
366
+ candidate = memory_from_row(row)
367
+ if candidate.memory_id != record.memory_id and candidate.value.get("claim_fingerprint") == fingerprint:
368
+ await connection.execute("UPDATE memories SET status='superseded', updated_at=? WHERE memory_id=?",
369
+ (utc_now(), candidate.memory_id))
370
+ await self.audit.append("memory_superseded", {
371
+ "memory_id": candidate.memory_id, "superseded_by": record.memory_id,
372
+ })
373
+
374
+ @staticmethod
375
+ def _row_values(record: MemoryRecord) -> tuple[Any, ...]:
376
+ return (
377
+ record.memory_id, record.memory_type, record.scope, record.namespace, record.key,
378
+ json_dumps(record.value), record.summary, record.source, json_dumps(record.evidence_refs),
379
+ record.confidence, record.trust_level, record.created_at, record.updated_at, record.expires_at,
380
+ json_dumps(record.tags), json_dumps(record.related_ids), record.status, record.tenant_id,
381
+ record.project_id, record.user_id, record.privacy_level,
382
+ )
383
+
384
+
385
+ def _fts_query(value: str) -> str:
386
+ terms = [term for term in re.findall(r"[a-z0-9_]+", value.casefold()) if len(term) > 1]
387
+ return " ".join(f"{term}*" for term in terms[:12])
388
+
389
+
390
+ def _max_privacy_level(current: str, observed: str) -> str:
391
+ order = {"public": 0, "internal": 1, "sensitive": 2, "restricted": 3}
392
+ return observed if order.get(observed, 1) > order.get(current, 1) else current
agent_memory/store.py ADDED
@@ -0,0 +1,109 @@
1
+ """Store entrypoints for reusable memory."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import AsyncIterator
6
+ import os
7
+ from pathlib import Path
8
+ from typing import Any, Protocol
9
+
10
+ from .models import MemoryRecord
11
+ from .config import load_memory_settings
12
+ from .postgres_store import PostgresMemoryStore
13
+ from .sqlite_store import SQLiteMemoryStore
14
+
15
+
16
+ class MemoryStore(Protocol):
17
+ audit: Any
18
+
19
+ async def open(self) -> None: ...
20
+
21
+ async def close(self) -> None: ...
22
+
23
+ async def upsert(self, record: MemoryRecord) -> MemoryRecord: ...
24
+
25
+ async def import_record(self, record: MemoryRecord) -> MemoryRecord: ...
26
+
27
+ async def get(self, memory_id: str, *, include_inactive: bool = False) -> MemoryRecord | None: ...
28
+
29
+ async def search(
30
+ self,
31
+ *,
32
+ namespace: str | None = None,
33
+ memory_type: str | None = None,
34
+ scope: str | None = None,
35
+ tags: list[str] | None = None,
36
+ key: str | None = None,
37
+ text: str | None = None,
38
+ tenant_id: str | None = None,
39
+ project_id: str | None = None,
40
+ user_id: str | None = None,
41
+ privacy_levels: list[str] | None = None,
42
+ include_inactive: bool = False,
43
+ limit: int = 50,
44
+ ) -> list[MemoryRecord]: ...
45
+
46
+ async def recent(self, *, namespace: str | None = None, limit: int = 20) -> list[MemoryRecord]: ...
47
+
48
+ async def list_active(self, *, limit: int = 100) -> list[MemoryRecord]: ...
49
+
50
+ def iter_records(
51
+ self,
52
+ *,
53
+ include_inactive: bool = True,
54
+ batch_size: int = 500,
55
+ ) -> AsyncIterator[MemoryRecord]: ...
56
+
57
+ async def mark_superseded(self, memory_id: str, *, superseded_by: str | None = None) -> bool: ...
58
+
59
+ async def mark_deleted(self, memory_id: str, *, reason: str | None = None) -> bool: ...
60
+
61
+ async def expire_old_records(self, *, now: str | None = None) -> int: ...
62
+
63
+ async def stats(self) -> dict[str, Any]: ...
64
+
65
+
66
+ def default_memory_root(base: str | Path = ".analytics-agent") -> Path:
67
+ path = Path(base)
68
+ return path / "memory" if path.name == ".analytics-agent" else path
69
+
70
+
71
+ async def open_memory_store(
72
+ base: str | Path = ".analytics-agent",
73
+ *,
74
+ backend: str | None = None,
75
+ postgres_dsn: str | None = None,
76
+ postgres_pool_size: int | None = None,
77
+ postgres_pool_timeout: float | None = None,
78
+ memory_config_path: str | Path | None = None,
79
+ ) -> MemoryStore:
80
+ settings = load_memory_settings(memory_config_path)
81
+ selected = (backend or settings.backend).strip().casefold()
82
+ if selected in {"sqlite", "local"}:
83
+ store = SQLiteMemoryStore(default_memory_root(base))
84
+ await store.open()
85
+ return store
86
+ if selected in {"postgres", "postgresql", "pg"}:
87
+ dsn = postgres_dsn or settings.postgres_dsn or os.environ.get("AGENT_MEMORY_POSTGRES_DSN") or os.environ.get("DATABASE_URL")
88
+ if not dsn:
89
+ raise ValueError(
90
+ "Postgres memory backend requires AGENT_MEMORY_POSTGRES_DSN, DATABASE_URL, "
91
+ "or an explicit postgres_dsn."
92
+ )
93
+ pool_size = postgres_pool_size
94
+ if pool_size is None:
95
+ pool_size = settings.postgres_pool_size
96
+ pool_timeout = postgres_pool_timeout if postgres_pool_timeout is not None else settings.postgres_pool_timeout
97
+ store = PostgresMemoryStore(dsn, pool_size=pool_size, pool_timeout=pool_timeout)
98
+ await store.open()
99
+ return store
100
+ raise ValueError(f"Unsupported memory backend: {selected!r}. Use 'sqlite' or 'postgres'.")
101
+
102
+
103
+ __all__ = [
104
+ "MemoryStore",
105
+ "PostgresMemoryStore",
106
+ "SQLiteMemoryStore",
107
+ "default_memory_root",
108
+ "open_memory_store",
109
+ ]
@@ -0,0 +1,18 @@
1
+ """Small deterministic token budgeting helpers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from typing import Any
7
+
8
+
9
+ def estimate_tokens(value: Any) -> int:
10
+ text = value if isinstance(value, str) else json.dumps(value, ensure_ascii=False, default=str)
11
+ return max(1, (len(text) + 3) // 4)
12
+
13
+
14
+ def trim_text(value: str, max_tokens: int) -> str:
15
+ max_chars = max(0, int(max_tokens) * 4)
16
+ if len(value) <= max_chars:
17
+ return value
18
+ return value[: max(0, max_chars - 32)] + "\n...[trimmed]..."