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.
agent_memory/models.py ADDED
@@ -0,0 +1,183 @@
1
+ """Typed contracts for reusable external agent memory."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import asdict, dataclass, field
6
+ from datetime import UTC, datetime
7
+ from typing import Any
8
+
9
+
10
+ MEMORY_TYPES = {
11
+ "session_memory",
12
+ "project_memory",
13
+ "user_preference",
14
+ "task_state",
15
+ "artifact_memory",
16
+ "decision_memory",
17
+ "clarification_memory",
18
+ "rag_retrieval_memory",
19
+ "entity_memory",
20
+ "run_summary",
21
+ }
22
+ SCOPES = {"global", "project", "session", "run", "dataset", "task", "user"}
23
+ TRUST_LEVELS = {
24
+ "user_provided",
25
+ "source_grounded",
26
+ "system_observed",
27
+ "inferred",
28
+ "stale",
29
+ "conflicting",
30
+ }
31
+ STATUSES = {"active", "superseded", "expired", "deleted", "rejected"}
32
+ PRIVACY_LEVELS = {"public", "internal", "sensitive", "restricted"}
33
+
34
+
35
+ def utc_now() -> str:
36
+ return datetime.now(UTC).isoformat(timespec="seconds").replace("+00:00", "Z")
37
+
38
+
39
+ @dataclass
40
+ class MemoryRecord:
41
+ """Structured, scoped, auditable memory record.
42
+
43
+ Values are intentionally dictionaries so products can store compact,
44
+ product-specific state without storing raw files or full chat histories.
45
+ """
46
+
47
+ memory_id: str
48
+ memory_type: str
49
+ scope: str
50
+ namespace: str
51
+ key: str
52
+ value: dict[str, Any]
53
+ summary: str
54
+ source: str
55
+ evidence_refs: list[dict[str, Any]] = field(default_factory=list)
56
+ confidence: float = 1.0
57
+ trust_level: str = "system_observed"
58
+ created_at: str = field(default_factory=utc_now)
59
+ updated_at: str = field(default_factory=utc_now)
60
+ expires_at: str | None = None
61
+ tags: list[str] = field(default_factory=list)
62
+ related_ids: list[str] = field(default_factory=list)
63
+ status: str = "active"
64
+ tenant_id: str | None = None
65
+ project_id: str | None = None
66
+ user_id: str | None = None
67
+ privacy_level: str = "internal"
68
+
69
+ def __post_init__(self) -> None:
70
+ if self.memory_type not in MEMORY_TYPES:
71
+ raise ValueError(f"Unsupported memory_type: {self.memory_type}")
72
+ if self.scope not in SCOPES:
73
+ raise ValueError(f"Unsupported scope: {self.scope}")
74
+ if self.trust_level not in TRUST_LEVELS:
75
+ raise ValueError(f"Unsupported trust_level: {self.trust_level}")
76
+ if self.status not in STATUSES:
77
+ raise ValueError(f"Unsupported status: {self.status}")
78
+ if self.privacy_level not in PRIVACY_LEVELS:
79
+ raise ValueError(f"Unsupported privacy_level: {self.privacy_level}")
80
+ self.confidence = max(0.0, min(1.0, float(self.confidence)))
81
+ self.tags = [str(tag) for tag in self.tags if str(tag).strip()]
82
+ self.related_ids = [str(item) for item in self.related_ids if str(item).strip()]
83
+ self.tenant_id = _clean_optional_id(self.tenant_id)
84
+ self.project_id = _clean_optional_id(self.project_id)
85
+ self.user_id = _clean_optional_id(self.user_id)
86
+
87
+ def to_dict(self) -> dict[str, Any]:
88
+ return asdict(self)
89
+
90
+ @classmethod
91
+ def from_dict(cls, value: dict[str, Any]) -> "MemoryRecord":
92
+ return cls(
93
+ memory_id=str(value["memory_id"]),
94
+ memory_type=str(value["memory_type"]),
95
+ scope=str(value["scope"]),
96
+ namespace=str(value["namespace"]),
97
+ key=str(value["key"]),
98
+ value=dict(value.get("value") or {}),
99
+ summary=str(value.get("summary") or ""),
100
+ source=str(value.get("source") or ""),
101
+ evidence_refs=list(value.get("evidence_refs") or []),
102
+ confidence=float(value.get("confidence", 1.0)),
103
+ trust_level=str(value.get("trust_level") or "system_observed"),
104
+ created_at=str(value.get("created_at") or utc_now()),
105
+ updated_at=str(value.get("updated_at") or utc_now()),
106
+ expires_at=value.get("expires_at"),
107
+ tags=list(value.get("tags") or []),
108
+ related_ids=list(value.get("related_ids") or []),
109
+ status=str(value.get("status") or "active"),
110
+ tenant_id=value.get("tenant_id"),
111
+ project_id=value.get("project_id"),
112
+ user_id=value.get("user_id"),
113
+ privacy_level=str(value.get("privacy_level") or "internal"),
114
+ )
115
+
116
+
117
+ @dataclass(frozen=True)
118
+ class RetrievalQuery:
119
+ request: str
120
+ namespace: str = "default"
121
+ scope: str | None = None
122
+ project_id: str | None = None
123
+ session_id: str | None = None
124
+ dataset_id: str | None = None
125
+ run_id: str | None = None
126
+ task_id: str | None = None
127
+ tenant_id: str | None = None
128
+ user_id: str | None = None
129
+ keys: list[str] = field(default_factory=list)
130
+ tags: list[str] = field(default_factory=list)
131
+ entities: list[str] = field(default_factory=list)
132
+ artifact_refs: list[str] = field(default_factory=list)
133
+ document_ids: list[str] = field(default_factory=list)
134
+ source_hashes: list[str] = field(default_factory=list)
135
+ memory_types: list[str] = field(default_factory=list)
136
+ require_source_grounded: bool = False
137
+ min_confidence: float | None = None
138
+ strict_isolation: bool = True
139
+ limit: int = 20
140
+
141
+
142
+ @dataclass
143
+ class RankedMemory:
144
+ record: MemoryRecord
145
+ score: float
146
+ reasons: list[str] = field(default_factory=list)
147
+
148
+ def to_dict(self) -> dict[str, Any]:
149
+ return {
150
+ "memory_id": self.record.memory_id,
151
+ "score": round(self.score, 4),
152
+ "reasons": list(self.reasons),
153
+ "record": self.record.to_dict(),
154
+ }
155
+
156
+
157
+ @dataclass
158
+ class MemoryConflict:
159
+ memory_id: str
160
+ field: str
161
+ severity: str
162
+ reason: str
163
+ current_value: Any = None
164
+ memory_value: Any = None
165
+
166
+ def to_dict(self) -> dict[str, Any]:
167
+ return asdict(self)
168
+
169
+
170
+ @dataclass
171
+ class MemoryContextPacket:
172
+ context_packet: dict[str, Any]
173
+ token_budget: dict[str, Any]
174
+
175
+ def to_dict(self) -> dict[str, Any]:
176
+ return asdict(self)
177
+
178
+
179
+ def _clean_optional_id(value: Any) -> str | None:
180
+ if value in (None, ""):
181
+ return None
182
+ text = str(value).strip()
183
+ return text or None
agent_memory/policy.py ADDED
@@ -0,0 +1,81 @@
1
+ """Memory policy engine."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from dataclasses import dataclass, field
7
+ from typing import Any
8
+
9
+ from .models import MemoryRecord
10
+ from .privacy import PrivacyGuard
11
+ from .rag import RAGEvidenceValidator
12
+ from .serializers import compact_value
13
+
14
+
15
+ @dataclass
16
+ class MemoryPolicyDecision:
17
+ allowed: bool
18
+ requires_approval: bool = False
19
+ reasons: list[str] = field(default_factory=list)
20
+ record: MemoryRecord | None = None
21
+
22
+
23
+ class MemoryPolicyEngine:
24
+ """Default local policy for safe memory writes and auto-application."""
25
+
26
+ AUTO_STORE_TYPES = {
27
+ "project_memory",
28
+ "task_state",
29
+ "artifact_memory",
30
+ "decision_memory",
31
+ "clarification_memory",
32
+ "rag_retrieval_memory",
33
+ "entity_memory",
34
+ "run_summary",
35
+ "session_memory",
36
+ }
37
+
38
+ def __init__(self, privacy: PrivacyGuard | None = None) -> None:
39
+ self.privacy = privacy or PrivacyGuard()
40
+
41
+ def evaluate_store(self, record: MemoryRecord, *, explicit_user_preference: bool = False) -> MemoryPolicyDecision:
42
+ reasons: list[str] = []
43
+ requires_approval = False
44
+ if record.memory_type == "user_preference" and record.trust_level != "user_provided" and not explicit_user_preference:
45
+ requires_approval = True
46
+ reasons.append("User preferences require explicit or strongly implied user intent.")
47
+ if record.memory_type not in self.AUTO_STORE_TYPES and record.memory_type != "user_preference":
48
+ reasons.append(f"Unsupported automatic memory type: {record.memory_type}")
49
+ return MemoryPolicyDecision(False, False, reasons)
50
+ if record.memory_type == "rag_retrieval_memory" and record.key == "claim_to_source":
51
+ evidence = RAGEvidenceValidator().validate(record)
52
+ if not evidence["passed"]:
53
+ reasons.extend(f"Invalid RAG evidence: {error}" for error in evidence["errors"])
54
+ return MemoryPolicyDecision(False, requires_approval, reasons)
55
+ scrubbed = MemoryRecord.from_dict(record.to_dict())
56
+ privacy_report = self.privacy.inspect({"value": scrubbed.value, "summary": scrubbed.summary, "evidence_refs": scrubbed.evidence_refs})
57
+ if privacy_report.blocked:
58
+ return MemoryPolicyDecision(False, requires_approval, privacy_report.reasons)
59
+ scrubbed.value = compact_value(self.privacy.scrub(scrubbed.value))
60
+ scrubbed.summary = str(self.privacy.scrub(scrubbed.summary))
61
+ scrubbed.evidence_refs = self.privacy.scrub(scrubbed.evidence_refs)
62
+ scrubbed.privacy_level = _max_privacy_level(scrubbed.privacy_level, privacy_report.privacy_level)
63
+ if privacy_report.findings:
64
+ scrubbed.tags = list(dict.fromkeys([*scrubbed.tags, "privacy_reviewed", f"privacy:{privacy_report.privacy_level}"]))
65
+ if len(json.dumps(scrubbed.value, ensure_ascii=False, default=str)) > 50_000:
66
+ reasons.append("Memory value remains too large after compaction.")
67
+ return MemoryPolicyDecision(False, requires_approval, reasons)
68
+ return MemoryPolicyDecision(True, requires_approval, reasons, scrubbed)
69
+
70
+ @staticmethod
71
+ def can_auto_apply(record: MemoryRecord) -> bool:
72
+ return (
73
+ record.status == "active"
74
+ and record.trust_level in {"user_provided", "source_grounded", "system_observed"}
75
+ and record.memory_type in {"decision_memory", "task_state", "artifact_memory", "session_memory"}
76
+ )
77
+
78
+
79
+ def _max_privacy_level(current: str, observed: str) -> str:
80
+ order = {"public": 0, "internal": 1, "sensitive": 2, "restricted": 3}
81
+ return observed if order.get(observed, 1) > order.get(current, 1) else current
@@ -0,0 +1,424 @@
1
+ """Native asyncio PostgreSQL memory store."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import re
7
+ from collections.abc import AsyncIterator
8
+ from typing import Any
9
+
10
+ from .models import MemoryRecord, utc_now
11
+ from .privacy import PrivacyGuard, PrivacyPolicy
12
+ from .serializers import json_dumps, memory_from_row, redact_secrets
13
+ from .sqlite_store import _max_privacy_level
14
+
15
+ try:
16
+ from psycopg.rows import dict_row
17
+ from psycopg_pool import AsyncConnectionPool
18
+ except ImportError: # pragma: no cover - optional PostgreSQL extra
19
+ dict_row = None
20
+ AsyncConnectionPool = None # type: ignore[assignment,misc]
21
+
22
+
23
+ class PostgresAuditLog:
24
+ """Append-only audit events stored in PostgreSQL."""
25
+
26
+ path = "postgres://memory_audit_events"
27
+
28
+ def __init__(self, store: "PostgresMemoryStore") -> None:
29
+ self._store = store
30
+
31
+ async def initialize(self) -> None:
32
+ async with self._store._pool.connection() as connection:
33
+ await connection.execute(
34
+ """
35
+ CREATE TABLE IF NOT EXISTS memory_audit_events (
36
+ event_id BIGSERIAL PRIMARY KEY,
37
+ event_type TEXT NOT NULL,
38
+ payload_json TEXT NOT NULL,
39
+ created_at TEXT NOT NULL
40
+ )
41
+ """
42
+ )
43
+
44
+ async def append(self, event_type: str, payload: dict[str, Any], *, connection: Any = None) -> None:
45
+ record = {"timestamp": utc_now(), "event_type": event_type, **payload}
46
+ if connection is not None:
47
+ await self._append_on(connection, event_type, record)
48
+ return
49
+ async with self._store._pool.connection() as conn:
50
+ await self._append_on(conn, event_type, record)
51
+
52
+ @staticmethod
53
+ async def _append_on(connection: Any, event_type: str, record: dict[str, Any]) -> None:
54
+ await connection.execute(
55
+ "INSERT INTO memory_audit_events(event_type, payload_json, created_at) VALUES (%s, %s, %s)",
56
+ (event_type, json_dumps(record), record["timestamp"]),
57
+ )
58
+
59
+ async def read_recent(self, limit: int = 100) -> list[dict[str, Any]]:
60
+ async with self._store._pool.connection() as connection:
61
+ cursor = await connection.execute(
62
+ "SELECT payload_json FROM memory_audit_events ORDER BY event_id DESC LIMIT %s",
63
+ (int(limit),),
64
+ )
65
+ rows = await cursor.fetchall()
66
+ records: list[dict[str, Any]] = []
67
+ for row in reversed(rows):
68
+ try:
69
+ payload = json.loads(row["payload_json"])
70
+ except (TypeError, json.JSONDecodeError):
71
+ continue
72
+ if isinstance(payload, dict):
73
+ records.append(payload)
74
+ return records
75
+
76
+
77
+ class PostgresMemoryStore:
78
+ """Async durable memory store for shared, multi-user deployments."""
79
+
80
+ def __init__(
81
+ self,
82
+ dsn: str,
83
+ *,
84
+ connect_timeout: int = 10,
85
+ pool_size: int = 20,
86
+ pool_timeout: float = 10.0,
87
+ ) -> None:
88
+ if AsyncConnectionPool is None or dict_row is None:
89
+ raise RuntimeError(
90
+ "Postgres memory backend requires psycopg with pool support. "
91
+ "Install it with: pip install 'coding-agent[postgres]'"
92
+ )
93
+ if pool_size < 1 or pool_timeout <= 0:
94
+ raise ValueError("pool_size and pool_timeout must be positive.")
95
+ self.dsn = dsn
96
+ self.pool_size = int(pool_size)
97
+ self.pool_timeout = float(pool_timeout)
98
+ self._pool = AsyncConnectionPool(
99
+ conninfo=dsn,
100
+ min_size=1,
101
+ max_size=self.pool_size,
102
+ timeout=self.pool_timeout,
103
+ kwargs={"row_factory": dict_row, "connect_timeout": connect_timeout},
104
+ open=False,
105
+ )
106
+ self.privacy = PrivacyGuard(PrivacyPolicy(block_secrets=False))
107
+ self.fts_available = True
108
+ self.audit = PostgresAuditLog(self)
109
+ self._opened = False
110
+
111
+ async def open(self) -> None:
112
+ if self._opened:
113
+ return
114
+ await self._pool.open()
115
+ try:
116
+ async with self._pool.connection() as connection:
117
+ await connection.execute(
118
+ """
119
+ CREATE TABLE IF NOT EXISTS memories (
120
+ memory_id TEXT PRIMARY KEY,
121
+ memory_type TEXT NOT NULL,
122
+ scope TEXT NOT NULL,
123
+ namespace TEXT NOT NULL,
124
+ key TEXT NOT NULL,
125
+ value_json TEXT NOT NULL,
126
+ summary TEXT NOT NULL,
127
+ source TEXT NOT NULL,
128
+ evidence_refs_json TEXT NOT NULL,
129
+ confidence DOUBLE PRECISION NOT NULL,
130
+ trust_level TEXT NOT NULL,
131
+ created_at TEXT NOT NULL,
132
+ updated_at TEXT NOT NULL,
133
+ expires_at TEXT,
134
+ tags_json TEXT NOT NULL,
135
+ related_ids_json TEXT NOT NULL,
136
+ status TEXT NOT NULL,
137
+ tenant_id TEXT,
138
+ project_id TEXT,
139
+ user_id TEXT,
140
+ privacy_level TEXT NOT NULL DEFAULT 'internal'
141
+ )
142
+ """
143
+ )
144
+ statements = (
145
+ "CREATE INDEX IF NOT EXISTS idx_mem_namespace ON memories(namespace)",
146
+ "CREATE INDEX IF NOT EXISTS idx_mem_type ON memories(memory_type)",
147
+ "CREATE INDEX IF NOT EXISTS idx_mem_scope ON memories(scope)",
148
+ "CREATE INDEX IF NOT EXISTS idx_mem_key ON memories(key)",
149
+ "CREATE INDEX IF NOT EXISTS idx_mem_status ON memories(status)",
150
+ "CREATE INDEX IF NOT EXISTS idx_mem_tenant ON memories(tenant_id)",
151
+ "CREATE INDEX IF NOT EXISTS idx_mem_project ON memories(project_id)",
152
+ "CREATE INDEX IF NOT EXISTS idx_mem_user ON memories(user_id)",
153
+ "CREATE INDEX IF NOT EXISTS idx_mem_privacy ON memories(privacy_level)",
154
+ """
155
+ CREATE INDEX IF NOT EXISTS idx_mem_search ON memories USING GIN (
156
+ to_tsvector('simple', COALESCE(key, '') || ' ' || COALESCE(summary, '') || ' ' ||
157
+ COALESCE(value_json, '') || ' ' || COALESCE(evidence_refs_json, '') || ' ' ||
158
+ COALESCE(tags_json, '')))
159
+ """,
160
+ )
161
+ for statement in statements:
162
+ await connection.execute(statement)
163
+ await self.audit.initialize()
164
+ self._opened = True
165
+ except BaseException:
166
+ await self._pool.close()
167
+ raise
168
+
169
+ async def close(self) -> None:
170
+ if self._opened:
171
+ await self._pool.close()
172
+ self._opened = False
173
+
174
+ async def upsert(self, record: MemoryRecord) -> MemoryRecord:
175
+ now = utc_now()
176
+ privacy_report = self.privacy.inspect({
177
+ "value": record.value, "summary": record.summary, "evidence_refs": record.evidence_refs,
178
+ })
179
+ record.value = self.privacy.scrub(redact_secrets(record.value))
180
+ record.summary = str(self.privacy.scrub(redact_secrets(record.summary)))
181
+ record.evidence_refs = self.privacy.scrub(record.evidence_refs)
182
+ record.privacy_level = _max_privacy_level(record.privacy_level, privacy_report.privacy_level)
183
+ async with self._pool.connection() as connection:
184
+ existing = await self._get_on(connection, record.memory_id, include_inactive=True)
185
+ if existing:
186
+ record.created_at = existing.created_at
187
+ record.updated_at = now
188
+ await self._supersede_duplicate_claims(connection, record)
189
+ await connection.execute(
190
+ """
191
+ INSERT INTO memories (
192
+ memory_id, memory_type, scope, namespace, key, value_json, summary, source,
193
+ evidence_refs_json, confidence, trust_level, created_at, updated_at, expires_at,
194
+ tags_json, related_ids_json, status, tenant_id, project_id, user_id, privacy_level
195
+ ) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
196
+ ON CONFLICT(memory_id) DO UPDATE SET
197
+ memory_type=EXCLUDED.memory_type, scope=EXCLUDED.scope, namespace=EXCLUDED.namespace,
198
+ key=EXCLUDED.key, value_json=EXCLUDED.value_json, summary=EXCLUDED.summary,
199
+ source=EXCLUDED.source, evidence_refs_json=EXCLUDED.evidence_refs_json,
200
+ confidence=EXCLUDED.confidence, trust_level=EXCLUDED.trust_level,
201
+ updated_at=EXCLUDED.updated_at, expires_at=EXCLUDED.expires_at,
202
+ tags_json=EXCLUDED.tags_json, related_ids_json=EXCLUDED.related_ids_json,
203
+ status=EXCLUDED.status, tenant_id=EXCLUDED.tenant_id, project_id=EXCLUDED.project_id,
204
+ user_id=EXCLUDED.user_id, privacy_level=EXCLUDED.privacy_level
205
+ """,
206
+ self._row_values(record),
207
+ )
208
+ await self.audit.append("memory_upserted", {
209
+ "memory_id": record.memory_id, "key": record.key, "namespace": record.namespace,
210
+ }, connection=connection)
211
+ return record
212
+
213
+ async def import_record(self, record: MemoryRecord) -> MemoryRecord:
214
+ async with self._pool.connection() as connection:
215
+ await connection.execute(
216
+ """
217
+ INSERT INTO memories (
218
+ memory_id, memory_type, scope, namespace, key, value_json, summary, source,
219
+ evidence_refs_json, confidence, trust_level, created_at, updated_at, expires_at,
220
+ tags_json, related_ids_json, status, tenant_id, project_id, user_id, privacy_level
221
+ ) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
222
+ ON CONFLICT(memory_id) DO UPDATE SET
223
+ memory_type=EXCLUDED.memory_type, scope=EXCLUDED.scope, namespace=EXCLUDED.namespace,
224
+ key=EXCLUDED.key, value_json=EXCLUDED.value_json, summary=EXCLUDED.summary,
225
+ source=EXCLUDED.source, evidence_refs_json=EXCLUDED.evidence_refs_json,
226
+ confidence=EXCLUDED.confidence, trust_level=EXCLUDED.trust_level,
227
+ created_at=EXCLUDED.created_at, updated_at=EXCLUDED.updated_at,
228
+ expires_at=EXCLUDED.expires_at, tags_json=EXCLUDED.tags_json,
229
+ related_ids_json=EXCLUDED.related_ids_json, status=EXCLUDED.status,
230
+ tenant_id=EXCLUDED.tenant_id, project_id=EXCLUDED.project_id,
231
+ user_id=EXCLUDED.user_id, privacy_level=EXCLUDED.privacy_level
232
+ """,
233
+ self._row_values(record),
234
+ )
235
+ await self.audit.append("memory_imported", {
236
+ "memory_id": record.memory_id, "key": record.key, "namespace": record.namespace,
237
+ }, connection=connection)
238
+ return record
239
+
240
+ async def get(self, memory_id: str, *, include_inactive: bool = False) -> MemoryRecord | None:
241
+ async with self._pool.connection() as connection:
242
+ return await self._get_on(connection, memory_id, include_inactive=include_inactive)
243
+
244
+ @staticmethod
245
+ async def _get_on(connection: Any, memory_id: str, *, include_inactive: bool) -> MemoryRecord | None:
246
+ query = "SELECT * FROM memories WHERE memory_id = %s"
247
+ if not include_inactive:
248
+ query += " AND status = 'active'"
249
+ cursor = await connection.execute(query, (memory_id,))
250
+ row = await cursor.fetchone()
251
+ return memory_from_row(row) if row else None
252
+
253
+ async def search(
254
+ self,
255
+ *,
256
+ namespace: str | None = None,
257
+ memory_type: str | None = None,
258
+ scope: str | None = None,
259
+ tags: list[str] | None = None,
260
+ key: str | None = None,
261
+ text: str | None = None,
262
+ tenant_id: str | None = None,
263
+ project_id: str | None = None,
264
+ user_id: str | None = None,
265
+ privacy_levels: list[str] | None = None,
266
+ include_inactive: bool = False,
267
+ limit: int = 50,
268
+ ) -> list[MemoryRecord]:
269
+ clauses: list[str] = []
270
+ params: list[Any] = []
271
+ if not include_inactive:
272
+ clauses.append("status = 'active'")
273
+ for column, value in (("namespace", namespace), ("memory_type", memory_type), ("scope", scope),
274
+ ("key", key), ("tenant_id", tenant_id), ("project_id", project_id),
275
+ ("user_id", user_id)):
276
+ if value:
277
+ clauses.append(f"{column} = %s")
278
+ params.append(value)
279
+ if privacy_levels:
280
+ clauses.append("privacy_level = ANY(%s)")
281
+ params.append(privacy_levels)
282
+ if tags:
283
+ for tag in tags:
284
+ clauses.append("tags_json ILIKE %s")
285
+ params.append(f"%{tag}%")
286
+ text_query = _postgres_search_query(text or "")
287
+ if text and text_query:
288
+ clauses.append("""
289
+ to_tsvector('simple', COALESCE(key, '') || ' ' || COALESCE(summary, '') || ' ' ||
290
+ COALESCE(value_json, '') || ' ' || COALESCE(evidence_refs_json, '') || ' ' ||
291
+ COALESCE(tags_json, '')) @@ plainto_tsquery('simple', %s)
292
+ """)
293
+ params.append(text_query)
294
+ order = """
295
+ ts_rank_cd(to_tsvector('simple', COALESCE(key, '') || ' ' || COALESCE(summary, '') || ' ' ||
296
+ COALESCE(value_json, '') || ' ' || COALESCE(evidence_refs_json, '') || ' ' || COALESCE(tags_json, '')),
297
+ plainto_tsquery('simple', %s)) DESC, updated_at DESC
298
+ """
299
+ params.append(text_query)
300
+ else:
301
+ if text:
302
+ clauses.append("(summary ILIKE %s OR key ILIKE %s OR value_json ILIKE %s)")
303
+ like = f"%{text}%"
304
+ params.extend([like, like, like])
305
+ order = "updated_at DESC"
306
+ where = " WHERE " + " AND ".join(clauses) if clauses else ""
307
+ async with self._pool.connection() as connection:
308
+ cursor = await connection.execute(
309
+ f"SELECT * FROM memories{where} ORDER BY {order} LIMIT %s",
310
+ [*params, int(limit)],
311
+ )
312
+ return [memory_from_row(row) for row in await cursor.fetchall()]
313
+
314
+ async def recent(self, *, namespace: str | None = None, limit: int = 20) -> list[MemoryRecord]:
315
+ return await self.search(namespace=namespace, limit=limit)
316
+
317
+ async def list_active(self, *, limit: int = 100) -> list[MemoryRecord]:
318
+ return await self.search(limit=limit)
319
+
320
+ async def iter_records(
321
+ self, *, include_inactive: bool = True, batch_size: int = 500,
322
+ ) -> AsyncIterator[MemoryRecord]:
323
+ offset = 0
324
+ while True:
325
+ where = "" if include_inactive else " WHERE status = 'active'"
326
+ async with self._pool.connection() as connection:
327
+ cursor = await connection.execute(
328
+ f"SELECT * FROM memories{where} ORDER BY updated_at ASC, memory_id ASC LIMIT %s OFFSET %s",
329
+ (int(batch_size), offset),
330
+ )
331
+ batch = [memory_from_row(row) for row in await cursor.fetchall()]
332
+ if not batch:
333
+ return
334
+ for record in batch:
335
+ yield record
336
+ offset += len(batch)
337
+
338
+ async def mark_superseded(self, memory_id: str, *, superseded_by: str | None = None) -> bool:
339
+ return await self._mark(memory_id, "superseded", {"superseded_by": superseded_by})
340
+
341
+ async def mark_deleted(self, memory_id: str, *, reason: str | None = None) -> bool:
342
+ return await self._mark(memory_id, "deleted", {"reason": reason})
343
+
344
+ async def _mark(self, memory_id: str, status: str, payload: dict[str, Any]) -> bool:
345
+ async with self._pool.connection() as connection:
346
+ cursor = await connection.execute(
347
+ "UPDATE memories SET status = %s, updated_at = %s WHERE memory_id = %s",
348
+ (status, utc_now(), memory_id),
349
+ )
350
+ changed = bool(cursor.rowcount)
351
+ if changed:
352
+ await self.audit.append(f"memory_{status}", {"memory_id": memory_id, **payload}, connection=connection)
353
+ return changed
354
+
355
+ async def expire_old_records(self, *, now: str | None = None) -> int:
356
+ timestamp = now or utc_now()
357
+ async with self._pool.connection() as connection:
358
+ cursor = await connection.execute(
359
+ """UPDATE memories SET status = 'expired', updated_at = %s
360
+ WHERE expires_at IS NOT NULL AND expires_at <= %s AND status = 'active'""",
361
+ (timestamp, timestamp),
362
+ )
363
+ count = int(cursor.rowcount or 0)
364
+ if count:
365
+ await self.audit.append("memory_expired", {"count": count}, connection=connection)
366
+ return count
367
+
368
+ async def stats(self) -> dict[str, Any]:
369
+ async with self._pool.connection() as connection:
370
+ cursor = await connection.execute(
371
+ "SELECT status, memory_type, COUNT(*) AS count FROM memories GROUP BY status, memory_type"
372
+ )
373
+ rows = await cursor.fetchall()
374
+ total = sum(int(row["count"]) for row in rows)
375
+ return {
376
+ "backend": "postgres", "db_path": _redact_dsn(self.dsn), "total": total,
377
+ "by_status_type": [dict(row) for row in rows], "audit_path": self.audit.path,
378
+ "fts_available": self.fts_available, "fts_indexed_rows": total, "healthy": True,
379
+ "connection_pool": {"max_size": self.pool_size},
380
+ }
381
+
382
+ async def _supersede_duplicate_claims(self, connection: Any, record: MemoryRecord) -> None:
383
+ if record.memory_type != "rag_retrieval_memory" or record.key != "claim_to_source":
384
+ return
385
+ fingerprint = record.value.get("claim_fingerprint")
386
+ if not fingerprint:
387
+ return
388
+ cursor = await connection.execute(
389
+ """SELECT * FROM memories WHERE namespace = %s AND memory_type = 'rag_retrieval_memory'
390
+ AND key = 'claim_to_source' AND status = 'active'
391
+ AND tenant_id IS NOT DISTINCT FROM %s AND project_id IS NOT DISTINCT FROM %s
392
+ AND user_id IS NOT DISTINCT FROM %s LIMIT 500""",
393
+ (record.namespace, record.tenant_id, record.project_id, record.user_id),
394
+ )
395
+ for row in await cursor.fetchall():
396
+ candidate = memory_from_row(row)
397
+ if candidate.memory_id == record.memory_id or candidate.value.get("claim_fingerprint") != fingerprint:
398
+ continue
399
+ await connection.execute(
400
+ "UPDATE memories SET status='superseded', updated_at=%s WHERE memory_id=%s",
401
+ (utc_now(), candidate.memory_id),
402
+ )
403
+ await self.audit.append("memory_superseded", {
404
+ "memory_id": candidate.memory_id, "superseded_by": record.memory_id,
405
+ }, connection=connection)
406
+
407
+ @staticmethod
408
+ def _row_values(record: MemoryRecord) -> tuple[Any, ...]:
409
+ return (
410
+ record.memory_id, record.memory_type, record.scope, record.namespace, record.key,
411
+ json_dumps(record.value), record.summary, record.source, json_dumps(record.evidence_refs),
412
+ record.confidence, record.trust_level, record.created_at, record.updated_at, record.expires_at,
413
+ json_dumps(record.tags), json_dumps(record.related_ids), record.status, record.tenant_id,
414
+ record.project_id, record.user_id, record.privacy_level,
415
+ )
416
+
417
+
418
+ def _postgres_search_query(value: str) -> str:
419
+ terms = re.findall(r"[a-z0-9_]+", value.casefold())
420
+ return " ".join([term for term in terms if len(term) > 1][:12])
421
+
422
+
423
+ def _redact_dsn(value: str) -> str:
424
+ return re.sub(r"(://[^:/@]+:)[^@]+(@)", r"\1[REDACTED]\2", value)