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/__init__.py +69 -0
- agent_memory/cli.py +116 -0
- agent_memory/compressor.py +43 -0
- agent_memory/config.py +114 -0
- agent_memory/conflict.py +61 -0
- agent_memory/context_packer.py +100 -0
- agent_memory/conversation.py +252 -0
- agent_memory/defaults/memory.yaml +17 -0
- agent_memory/diagnostics.py +21 -0
- agent_memory/extractors.py +438 -0
- agent_memory/jsonl_audit.py +40 -0
- agent_memory/migration.py +144 -0
- agent_memory/models.py +183 -0
- agent_memory/policy.py +81 -0
- agent_memory/postgres_store.py +424 -0
- agent_memory/privacy.py +114 -0
- agent_memory/rag.py +196 -0
- agent_memory/ranker.py +120 -0
- agent_memory/retriever.py +213 -0
- agent_memory/serializers.py +87 -0
- agent_memory/sqlite_store.py +392 -0
- agent_memory/store.py +109 -0
- agent_memory/token_budget.py +18 -0
- agent_memory/vector_index.py +149 -0
- data_analytics_agent_memory-0.1.0.dist-info/METADATA +141 -0
- data_analytics_agent_memory-0.1.0.dist-info/RECORD +28 -0
- data_analytics_agent_memory-0.1.0.dist-info/WHEEL +4 -0
- data_analytics_agent_memory-0.1.0.dist-info/entry_points.txt +3 -0
|
@@ -0,0 +1,438 @@
|
|
|
1
|
+
"""Memory extractors that turn product events into MemoryRecord objects."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import re
|
|
7
|
+
from typing import Any, Protocol
|
|
8
|
+
|
|
9
|
+
from .models import MemoryRecord
|
|
10
|
+
from .rag import RAGSourceReference
|
|
11
|
+
from .serializers import stable_memory_id
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class MemoryExtractor(Protocol):
|
|
15
|
+
def extract(self, event: dict[str, Any]) -> list[MemoryRecord]:
|
|
16
|
+
...
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class AnalyticsRunMemoryExtractor:
|
|
20
|
+
"""Extract compact memories from analytics run events/artifacts."""
|
|
21
|
+
|
|
22
|
+
namespace = "analytics"
|
|
23
|
+
active_state_keys = {
|
|
24
|
+
"active_dataset",
|
|
25
|
+
"active_cleaned_dataset",
|
|
26
|
+
"previous_task",
|
|
27
|
+
"last_analytics_tasks",
|
|
28
|
+
"last_run_id",
|
|
29
|
+
"last_chart_request",
|
|
30
|
+
"last_chart_spec",
|
|
31
|
+
"last_rendered_chart",
|
|
32
|
+
"last_result_table",
|
|
33
|
+
"last_ranking_result",
|
|
34
|
+
"last_export",
|
|
35
|
+
"last_exported_table",
|
|
36
|
+
"last_insight",
|
|
37
|
+
"last_evidence_table",
|
|
38
|
+
"last_report",
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
def extract(self, event: dict[str, Any]) -> list[MemoryRecord]:
|
|
42
|
+
run_id = str(event.get("run_id") or "")
|
|
43
|
+
source_path = str(event.get("source_path") or "")
|
|
44
|
+
question = str(event.get("question") or "")
|
|
45
|
+
records: list[MemoryRecord] = []
|
|
46
|
+
if source_path:
|
|
47
|
+
records.append(self._record(
|
|
48
|
+
"task_state",
|
|
49
|
+
"dataset",
|
|
50
|
+
"active_dataset",
|
|
51
|
+
{"source_path": source_path, "dataset_path": source_path, "run_id": run_id},
|
|
52
|
+
f"Active analytics dataset is {source_path}.",
|
|
53
|
+
event,
|
|
54
|
+
tags=["dataset", "active", "analytics", *([run_id] if run_id else [])],
|
|
55
|
+
))
|
|
56
|
+
if event.get("cleaned_dataset_path"):
|
|
57
|
+
path = str(event["cleaned_dataset_path"])
|
|
58
|
+
records.append(self._record(
|
|
59
|
+
"task_state",
|
|
60
|
+
"dataset",
|
|
61
|
+
"active_cleaned_dataset",
|
|
62
|
+
{"source_path": path, "dataset_path": path, "run_id": run_id},
|
|
63
|
+
f"Active cleaned dataset is {path}.",
|
|
64
|
+
event,
|
|
65
|
+
tags=["dataset", "cleaned", "active"],
|
|
66
|
+
))
|
|
67
|
+
if run_id:
|
|
68
|
+
records.append(self._record(
|
|
69
|
+
"run_summary",
|
|
70
|
+
"run",
|
|
71
|
+
"last_run_id",
|
|
72
|
+
{"run_id": run_id, "question": question, "source_path": source_path},
|
|
73
|
+
f"Last analytics run {run_id}: {question}",
|
|
74
|
+
event,
|
|
75
|
+
tags=["run", run_id, "last_run"],
|
|
76
|
+
))
|
|
77
|
+
tasks = event.get("tasks") if isinstance(event.get("tasks"), list) else []
|
|
78
|
+
if tasks:
|
|
79
|
+
records.append(self._record(
|
|
80
|
+
"task_state",
|
|
81
|
+
"task",
|
|
82
|
+
"last_analytics_tasks",
|
|
83
|
+
{"run_id": run_id, "question": question, "tasks": tasks},
|
|
84
|
+
f"Last analytics task set contained {len(tasks)} task(s) for: {question}",
|
|
85
|
+
event,
|
|
86
|
+
tags=["tasks", "analytics", run_id],
|
|
87
|
+
))
|
|
88
|
+
first = next((task for task in tasks if isinstance(task, dict)), None)
|
|
89
|
+
if first:
|
|
90
|
+
records.append(self._record(
|
|
91
|
+
"task_state",
|
|
92
|
+
"task",
|
|
93
|
+
"previous_task",
|
|
94
|
+
{"run_id": run_id, "question": first.get("question"), "task": first, "source_path": source_path},
|
|
95
|
+
f"Previous analytics task: {first.get('question') or question}",
|
|
96
|
+
event,
|
|
97
|
+
tags=["previous_task", "followup", run_id],
|
|
98
|
+
))
|
|
99
|
+
chart_requests = [chart for chart in (event.get("chart_requests") or []) if isinstance(chart, dict)]
|
|
100
|
+
if chart_requests:
|
|
101
|
+
latest_chart = dict(chart_requests[-1])
|
|
102
|
+
records.append(self._record(
|
|
103
|
+
"artifact_memory",
|
|
104
|
+
"run",
|
|
105
|
+
"last_chart_request",
|
|
106
|
+
{"run_id": run_id, **latest_chart, "latest_chart_request": latest_chart, "chart_requests": chart_requests},
|
|
107
|
+
f"Last chart request: {latest_chart.get('chart_request')}",
|
|
108
|
+
event,
|
|
109
|
+
tags=["chart", "chart_request", run_id],
|
|
110
|
+
))
|
|
111
|
+
if event.get("last_chart_spec"):
|
|
112
|
+
records.append(self._record(
|
|
113
|
+
"artifact_memory",
|
|
114
|
+
"run",
|
|
115
|
+
"last_chart_spec",
|
|
116
|
+
{"run_id": run_id, "run_dir": str(event.get("run_dir") or ""), "chart_spec": event.get("last_chart_spec")},
|
|
117
|
+
"Last chart spec is available as an artifact pointer.",
|
|
118
|
+
event,
|
|
119
|
+
tags=["chart", "chart_spec", run_id],
|
|
120
|
+
))
|
|
121
|
+
if event.get("last_rendered_chart"):
|
|
122
|
+
rendered = event.get("last_rendered_chart")
|
|
123
|
+
records.append(self._record(
|
|
124
|
+
"artifact_memory",
|
|
125
|
+
"run",
|
|
126
|
+
"last_rendered_chart",
|
|
127
|
+
{"run_id": run_id, "run_dir": str(event.get("run_dir") or ""), **(rendered if isinstance(rendered, dict) else {"rendered_chart": rendered})},
|
|
128
|
+
f"Last rendered chart: {(rendered or {}).get('chart_request') if isinstance(rendered, dict) else rendered}",
|
|
129
|
+
event,
|
|
130
|
+
tags=["chart", "rendered_chart", run_id],
|
|
131
|
+
))
|
|
132
|
+
for table in event.get("table_execution") or []:
|
|
133
|
+
if isinstance(table, dict) and table.get("path"):
|
|
134
|
+
records.append(self._record(
|
|
135
|
+
"artifact_memory",
|
|
136
|
+
"run",
|
|
137
|
+
"last_result_table",
|
|
138
|
+
{"run_id": run_id, "run_dir": str(table.get("run_dir") or event.get("run_dir") or ""), **table},
|
|
139
|
+
f"Last result table for {table.get('task_id')}: {table.get('path')}",
|
|
140
|
+
event,
|
|
141
|
+
tags=["table", "result_table", run_id],
|
|
142
|
+
))
|
|
143
|
+
ranking_answer = event.get("ranking_answer") if isinstance(event.get("ranking_answer"), dict) else {}
|
|
144
|
+
if ranking_answer.get("status") == "answered":
|
|
145
|
+
records.append(self._record(
|
|
146
|
+
"artifact_memory",
|
|
147
|
+
"run",
|
|
148
|
+
"last_ranking_result",
|
|
149
|
+
{"run_id": run_id, "run_dir": str(event.get("run_dir") or ""), **ranking_answer},
|
|
150
|
+
f"Last ranking result: {ranking_answer.get('answer')}",
|
|
151
|
+
event,
|
|
152
|
+
tags=["ranking", "result", run_id],
|
|
153
|
+
))
|
|
154
|
+
export_manifest = event.get("table_export_manifest") if isinstance(event.get("table_export_manifest"), dict) else {}
|
|
155
|
+
if export_manifest.get("status") == "exported":
|
|
156
|
+
records.append(self._record(
|
|
157
|
+
"artifact_memory",
|
|
158
|
+
"run",
|
|
159
|
+
"last_export",
|
|
160
|
+
{"run_id": run_id, "run_dir": str(event.get("run_dir") or ""), **export_manifest},
|
|
161
|
+
f"Last table export: {', '.join(str(item) for item in export_manifest.get('exported_files') or [])}",
|
|
162
|
+
event,
|
|
163
|
+
tags=["export", "table_export", run_id],
|
|
164
|
+
))
|
|
165
|
+
records.append(self._record(
|
|
166
|
+
"artifact_memory",
|
|
167
|
+
"run",
|
|
168
|
+
"last_exported_table",
|
|
169
|
+
{
|
|
170
|
+
"run_id": run_id,
|
|
171
|
+
"run_dir": str(event.get("run_dir") or ""),
|
|
172
|
+
"source_table": export_manifest.get("source_table"),
|
|
173
|
+
"exported_files": list(export_manifest.get("exported_files") or []),
|
|
174
|
+
"format": export_manifest.get("format"),
|
|
175
|
+
"row_count": export_manifest.get("row_count"),
|
|
176
|
+
"columns": list(export_manifest.get("columns") or []),
|
|
177
|
+
"source_task_id": export_manifest.get("source_task_id"),
|
|
178
|
+
},
|
|
179
|
+
f"Last exported table: {export_manifest.get('source_table')}",
|
|
180
|
+
event,
|
|
181
|
+
tags=["export", "table", "last_exported_table", run_id],
|
|
182
|
+
))
|
|
183
|
+
insight_answer = event.get("insight_answer") if isinstance(event.get("insight_answer"), dict) else {}
|
|
184
|
+
if insight_answer.get("status") == "answered":
|
|
185
|
+
records.append(self._record(
|
|
186
|
+
"artifact_memory",
|
|
187
|
+
"run",
|
|
188
|
+
"last_insight",
|
|
189
|
+
{"run_id": run_id, "run_dir": str(event.get("run_dir") or ""), **insight_answer},
|
|
190
|
+
f"Last insight answer: {insight_answer.get('main_finding') or insight_answer.get('answer_type')}",
|
|
191
|
+
event,
|
|
192
|
+
tags=["insight", "explanation", run_id],
|
|
193
|
+
))
|
|
194
|
+
evidence = event.get("insight_evidence_resolution") if isinstance(event.get("insight_evidence_resolution"), dict) else {}
|
|
195
|
+
if evidence.get("status") == "resolved" and evidence.get("evidence_table"):
|
|
196
|
+
records.append(self._record(
|
|
197
|
+
"artifact_memory",
|
|
198
|
+
"run",
|
|
199
|
+
"last_evidence_table",
|
|
200
|
+
{
|
|
201
|
+
"run_id": run_id,
|
|
202
|
+
"run_dir": str(event.get("run_dir") or ""),
|
|
203
|
+
"path": evidence.get("evidence_table"),
|
|
204
|
+
"absolute_path": evidence.get("absolute_path"),
|
|
205
|
+
"source": evidence.get("source"),
|
|
206
|
+
"task_id": evidence.get("target_task_id"),
|
|
207
|
+
"row_count": evidence.get("row_count"),
|
|
208
|
+
"columns": list(evidence.get("columns") or []),
|
|
209
|
+
},
|
|
210
|
+
f"Last insight evidence table: {evidence.get('evidence_table')}",
|
|
211
|
+
event,
|
|
212
|
+
tags=["insight", "evidence", "table", run_id],
|
|
213
|
+
))
|
|
214
|
+
if event.get("final_report_path"):
|
|
215
|
+
records.append(self._record(
|
|
216
|
+
"artifact_memory",
|
|
217
|
+
"run",
|
|
218
|
+
"last_report",
|
|
219
|
+
{"run_id": run_id, "path": event.get("final_report_path")},
|
|
220
|
+
f"Last analytics report: {event.get('final_report_path')}",
|
|
221
|
+
event,
|
|
222
|
+
tags=["report", run_id],
|
|
223
|
+
))
|
|
224
|
+
return records
|
|
225
|
+
|
|
226
|
+
def _record(
|
|
227
|
+
self,
|
|
228
|
+
memory_type: str,
|
|
229
|
+
scope: str,
|
|
230
|
+
key: str,
|
|
231
|
+
value: dict[str, Any],
|
|
232
|
+
summary: str,
|
|
233
|
+
event: dict[str, Any],
|
|
234
|
+
*,
|
|
235
|
+
tags: list[str],
|
|
236
|
+
) -> MemoryRecord:
|
|
237
|
+
run_id = str(event.get("run_id") or "")
|
|
238
|
+
evidence_refs = list(event.get("evidence_refs") or [])
|
|
239
|
+
if run_id and not evidence_refs:
|
|
240
|
+
evidence_refs = [{
|
|
241
|
+
"type": "artifact",
|
|
242
|
+
"run_id": run_id,
|
|
243
|
+
"path": str(event.get("run_dir") or ""),
|
|
244
|
+
"claim": summary,
|
|
245
|
+
}]
|
|
246
|
+
id_source = "" if key in self.active_state_keys else run_id
|
|
247
|
+
return MemoryRecord(
|
|
248
|
+
memory_id=stable_memory_id(self.namespace, scope, key, id_source),
|
|
249
|
+
memory_type=memory_type,
|
|
250
|
+
scope=scope,
|
|
251
|
+
namespace=self.namespace,
|
|
252
|
+
key=key,
|
|
253
|
+
value=value,
|
|
254
|
+
summary=summary,
|
|
255
|
+
source=str(event.get("source") or "analytics_run"),
|
|
256
|
+
evidence_refs=evidence_refs,
|
|
257
|
+
confidence=0.95,
|
|
258
|
+
trust_level="source_grounded",
|
|
259
|
+
tags=tags,
|
|
260
|
+
)
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
class ClarificationMemoryExtractor:
|
|
264
|
+
namespace = "analytics"
|
|
265
|
+
|
|
266
|
+
def extract(self, event: dict[str, Any]) -> list[MemoryRecord]:
|
|
267
|
+
records: list[MemoryRecord] = []
|
|
268
|
+
run_id = str(event.get("run_id") or "")
|
|
269
|
+
for policy in event.get("accepted_policies") or []:
|
|
270
|
+
if isinstance(policy, dict):
|
|
271
|
+
key = str(policy.get("key") or policy.get("policy") or "accepted_policy")
|
|
272
|
+
records.append(MemoryRecord(
|
|
273
|
+
memory_id=stable_memory_id(self.namespace, "task", f"policy:{key}", run_id),
|
|
274
|
+
memory_type="decision_memory",
|
|
275
|
+
scope="task",
|
|
276
|
+
namespace=self.namespace,
|
|
277
|
+
key=key,
|
|
278
|
+
value=policy,
|
|
279
|
+
summary=f"Accepted clarification policy: {key}.",
|
|
280
|
+
source="clarification",
|
|
281
|
+
evidence_refs=list(event.get("evidence_refs") or []),
|
|
282
|
+
confidence=1.0,
|
|
283
|
+
trust_level="user_provided",
|
|
284
|
+
tags=["clarification", "accepted_policy", key],
|
|
285
|
+
))
|
|
286
|
+
for question in event.get("unresolved_questions") or []:
|
|
287
|
+
records.append(MemoryRecord(
|
|
288
|
+
memory_id=stable_memory_id(self.namespace, "task", f"unresolved:{question}", run_id),
|
|
289
|
+
memory_type="clarification_memory",
|
|
290
|
+
scope="task",
|
|
291
|
+
namespace=self.namespace,
|
|
292
|
+
key="unresolved_clarification",
|
|
293
|
+
value={"question": question, "run_id": run_id, "unresolved": True},
|
|
294
|
+
summary=f"Unresolved clarification: {question}",
|
|
295
|
+
source="clarification",
|
|
296
|
+
evidence_refs=list(event.get("evidence_refs") or []),
|
|
297
|
+
confidence=1.0,
|
|
298
|
+
trust_level="user_provided",
|
|
299
|
+
tags=["clarification", "unresolved"],
|
|
300
|
+
))
|
|
301
|
+
return records
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
class UserPreferenceMemoryExtractor:
|
|
305
|
+
namespace = "analytics"
|
|
306
|
+
|
|
307
|
+
def extract(self, event: dict[str, Any]) -> list[MemoryRecord]:
|
|
308
|
+
preferences = event.get("preferences") if isinstance(event.get("preferences"), dict) else {}
|
|
309
|
+
records: list[MemoryRecord] = []
|
|
310
|
+
for key, value in preferences.items():
|
|
311
|
+
records.append(MemoryRecord(
|
|
312
|
+
memory_id=stable_memory_id(self.namespace, "user", f"preference:{key}"),
|
|
313
|
+
memory_type="user_preference",
|
|
314
|
+
scope="user",
|
|
315
|
+
namespace=self.namespace,
|
|
316
|
+
key=str(key),
|
|
317
|
+
value={"preference": value},
|
|
318
|
+
summary=f"User preference for {key}: {value}",
|
|
319
|
+
source="user_preference",
|
|
320
|
+
confidence=0.9,
|
|
321
|
+
trust_level="user_provided",
|
|
322
|
+
tags=["preference", str(key)],
|
|
323
|
+
))
|
|
324
|
+
return records
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
class RAGRetrievalMemoryExtractor:
|
|
328
|
+
namespace = "rag"
|
|
329
|
+
|
|
330
|
+
def extract(self, event: dict[str, Any]) -> list[MemoryRecord]:
|
|
331
|
+
records: list[MemoryRecord] = []
|
|
332
|
+
question = str(event.get("question") or "")
|
|
333
|
+
if question:
|
|
334
|
+
records.append(MemoryRecord(
|
|
335
|
+
memory_id=stable_memory_id(self.namespace, "session", "last_research_question", question),
|
|
336
|
+
memory_type="rag_retrieval_memory",
|
|
337
|
+
scope="session",
|
|
338
|
+
namespace=self.namespace,
|
|
339
|
+
key="last_research_question",
|
|
340
|
+
value={"question": question},
|
|
341
|
+
summary=f"Last research question: {question}",
|
|
342
|
+
source="rag_retrieval",
|
|
343
|
+
confidence=0.9,
|
|
344
|
+
trust_level="system_observed",
|
|
345
|
+
tags=["rag", "question"],
|
|
346
|
+
tenant_id=_event_id(event, "tenant_id"),
|
|
347
|
+
project_id=_event_id(event, "project_id"),
|
|
348
|
+
user_id=_event_id(event, "user_id"),
|
|
349
|
+
))
|
|
350
|
+
for document in event.get("documents") or []:
|
|
351
|
+
if not isinstance(document, dict):
|
|
352
|
+
continue
|
|
353
|
+
document_id = str(document.get("document_id") or "")
|
|
354
|
+
chunk_id = str(document.get("chunk_id") or "")
|
|
355
|
+
claim = str(document.get("claim") or document.get("summary") or "")
|
|
356
|
+
source_ref = RAGSourceReference.from_dict({
|
|
357
|
+
"document_id": document_id,
|
|
358
|
+
"chunk_id": chunk_id,
|
|
359
|
+
"uri": document.get("uri") or document.get("url") or document.get("source_uri"),
|
|
360
|
+
"title": document.get("title") or document.get("source_title"),
|
|
361
|
+
"source_hash": document.get("source_hash") or document.get("content_hash"),
|
|
362
|
+
"chunk_hash": document.get("chunk_hash"),
|
|
363
|
+
"version": document.get("version") or document.get("source_version"),
|
|
364
|
+
"updated_at": document.get("updated_at") or document.get("source_updated_at"),
|
|
365
|
+
"citation": document.get("citation"),
|
|
366
|
+
"page_start": document.get("page_start") or document.get("page") or document.get("page_number"),
|
|
367
|
+
"page_end": document.get("page_end") or document.get("page") or document.get("page_number"),
|
|
368
|
+
"section": document.get("section"),
|
|
369
|
+
"metadata": document.get("metadata") or {},
|
|
370
|
+
})
|
|
371
|
+
evidence = [{"type": "document_chunk", **source_ref.to_dict()}]
|
|
372
|
+
retrieval_score = document.get("retrieval_score", document.get("score"))
|
|
373
|
+
claim_fingerprint = _rag_fingerprint(self.namespace, document_id, chunk_id, claim)
|
|
374
|
+
version_identity = source_ref.version or source_ref.chunk_hash or source_ref.source_hash or ""
|
|
375
|
+
memory_source = f"{claim}:{document_id}:{chunk_id}:{version_identity}"
|
|
376
|
+
records.append(MemoryRecord(
|
|
377
|
+
memory_id=stable_memory_id(self.namespace, "session", f"claim_source:{document_id}:{chunk_id}", memory_source),
|
|
378
|
+
memory_type="rag_retrieval_memory",
|
|
379
|
+
scope="session",
|
|
380
|
+
namespace=self.namespace,
|
|
381
|
+
key="claim_to_source",
|
|
382
|
+
value={
|
|
383
|
+
"claim": claim,
|
|
384
|
+
"claim_fingerprint": claim_fingerprint,
|
|
385
|
+
"canonical_claim": _canonical_text(claim),
|
|
386
|
+
"source_fingerprint": _source_fingerprint(document_id, chunk_id),
|
|
387
|
+
"document_id": document_id,
|
|
388
|
+
"chunk_id": chunk_id,
|
|
389
|
+
"uri": source_ref.uri,
|
|
390
|
+
"title": source_ref.title,
|
|
391
|
+
"source_hash": source_ref.source_hash,
|
|
392
|
+
"chunk_hash": source_ref.chunk_hash,
|
|
393
|
+
"version": source_ref.version,
|
|
394
|
+
"page_start": source_ref.page_start,
|
|
395
|
+
"page_end": source_ref.page_end,
|
|
396
|
+
"section": source_ref.section,
|
|
397
|
+
"retrieved_at": document.get("retrieved_at") or event.get("retrieved_at"),
|
|
398
|
+
"retrieval_score": retrieval_score,
|
|
399
|
+
"rank": document.get("rank"),
|
|
400
|
+
"quote": document.get("quote"),
|
|
401
|
+
},
|
|
402
|
+
summary=f"Claim source: {claim}",
|
|
403
|
+
source="rag_retrieval",
|
|
404
|
+
evidence_refs=evidence,
|
|
405
|
+
confidence=float(document.get("confidence", 0.8)),
|
|
406
|
+
trust_level="source_grounded",
|
|
407
|
+
expires_at=document.get("expires_at") or event.get("expires_at"),
|
|
408
|
+
tenant_id=_event_id(document, "tenant_id") or _event_id(event, "tenant_id"),
|
|
409
|
+
project_id=_event_id(document, "project_id") or _event_id(event, "project_id"),
|
|
410
|
+
user_id=_event_id(document, "user_id") or _event_id(event, "user_id"),
|
|
411
|
+
tags=[
|
|
412
|
+
item
|
|
413
|
+
for item in ["rag", "citation", document_id, chunk_id, source_ref.title, source_ref.uri]
|
|
414
|
+
if item
|
|
415
|
+
],
|
|
416
|
+
))
|
|
417
|
+
return records
|
|
418
|
+
|
|
419
|
+
|
|
420
|
+
def _event_id(event: dict[str, Any], key: str) -> str | None:
|
|
421
|
+
value = event.get(key)
|
|
422
|
+
if value in (None, ""):
|
|
423
|
+
return None
|
|
424
|
+
return str(value)
|
|
425
|
+
|
|
426
|
+
|
|
427
|
+
def _canonical_text(value: object) -> str:
|
|
428
|
+
return re.sub(r"\s+", " ", str(value).casefold()).strip()
|
|
429
|
+
|
|
430
|
+
|
|
431
|
+
def _rag_fingerprint(namespace: str, document_id: str, chunk_id: str, claim: str) -> str:
|
|
432
|
+
raw = f"{namespace}\0{document_id}\0{chunk_id}\0{_canonical_text(claim)}".encode("utf-8", errors="replace")
|
|
433
|
+
return hashlib.sha256(raw).hexdigest()[:24]
|
|
434
|
+
|
|
435
|
+
|
|
436
|
+
def _source_fingerprint(document_id: str, chunk_id: str) -> str:
|
|
437
|
+
raw = f"{document_id}\0{chunk_id}".encode("utf-8", errors="replace")
|
|
438
|
+
return hashlib.sha256(raw).hexdigest()[:24]
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
"""Async append-only JSONL audit trail for memory writes."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import json
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
import aiofiles
|
|
11
|
+
|
|
12
|
+
from .models import utc_now
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class JSONLAuditLog:
|
|
16
|
+
def __init__(self, path: str | Path) -> None:
|
|
17
|
+
self.path = Path(path)
|
|
18
|
+
self._lock = asyncio.Lock()
|
|
19
|
+
|
|
20
|
+
async def append(self, event_type: str, payload: dict[str, Any]) -> None:
|
|
21
|
+
self.path.parent.mkdir(parents=True, exist_ok=True)
|
|
22
|
+
record = {"timestamp": utc_now(), "event_type": event_type, **payload}
|
|
23
|
+
async with self._lock:
|
|
24
|
+
async with aiofiles.open(self.path, "a", encoding="utf-8") as handle:
|
|
25
|
+
await handle.write(json.dumps(record, ensure_ascii=False, default=str) + "\n")
|
|
26
|
+
|
|
27
|
+
async def read_recent(self, limit: int = 100) -> list[dict[str, Any]]:
|
|
28
|
+
if limit <= 0 or not self.path.exists():
|
|
29
|
+
return []
|
|
30
|
+
async with aiofiles.open(self.path, "r", encoding="utf-8", errors="replace") as handle:
|
|
31
|
+
lines = (await handle.readlines())[-limit:]
|
|
32
|
+
records: list[dict[str, Any]] = []
|
|
33
|
+
for line in lines:
|
|
34
|
+
try:
|
|
35
|
+
item = json.loads(line)
|
|
36
|
+
except json.JSONDecodeError:
|
|
37
|
+
continue
|
|
38
|
+
if isinstance(item, dict):
|
|
39
|
+
records.append(item)
|
|
40
|
+
return records
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
"""Memory store migration helpers and CLI."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import asyncio
|
|
7
|
+
import json
|
|
8
|
+
import os
|
|
9
|
+
from dataclasses import asdict, dataclass, field
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
from .postgres_store import PostgresMemoryStore
|
|
14
|
+
from .sqlite_store import SQLiteMemoryStore
|
|
15
|
+
from .store import MemoryStore, default_memory_root
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass
|
|
19
|
+
class MemoryMigrationReport:
|
|
20
|
+
scanned: int = 0
|
|
21
|
+
inserted: int = 0
|
|
22
|
+
updated: int = 0
|
|
23
|
+
skipped_existing: int = 0
|
|
24
|
+
failed: int = 0
|
|
25
|
+
dry_run: bool = False
|
|
26
|
+
overwrite: bool = False
|
|
27
|
+
include_inactive: bool = True
|
|
28
|
+
failures: list[dict[str, Any]] = field(default_factory=list)
|
|
29
|
+
|
|
30
|
+
def to_dict(self) -> dict[str, Any]:
|
|
31
|
+
return asdict(self)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
async def migrate_memory_store(
|
|
35
|
+
source: MemoryStore,
|
|
36
|
+
target: MemoryStore,
|
|
37
|
+
*,
|
|
38
|
+
include_inactive: bool = True,
|
|
39
|
+
overwrite: bool = False,
|
|
40
|
+
dry_run: bool = False,
|
|
41
|
+
batch_size: int = 500,
|
|
42
|
+
limit: int | None = None,
|
|
43
|
+
) -> MemoryMigrationReport:
|
|
44
|
+
report = MemoryMigrationReport(
|
|
45
|
+
dry_run=dry_run,
|
|
46
|
+
overwrite=overwrite,
|
|
47
|
+
include_inactive=include_inactive,
|
|
48
|
+
)
|
|
49
|
+
async for record in source.iter_records(include_inactive=include_inactive, batch_size=batch_size):
|
|
50
|
+
if limit is not None and report.scanned >= int(limit):
|
|
51
|
+
break
|
|
52
|
+
report.scanned += 1
|
|
53
|
+
try:
|
|
54
|
+
existing = await target.get(record.memory_id, include_inactive=True)
|
|
55
|
+
if existing and not overwrite:
|
|
56
|
+
report.skipped_existing += 1
|
|
57
|
+
continue
|
|
58
|
+
if dry_run:
|
|
59
|
+
if existing:
|
|
60
|
+
report.updated += 1
|
|
61
|
+
else:
|
|
62
|
+
report.inserted += 1
|
|
63
|
+
continue
|
|
64
|
+
await target.import_record(record)
|
|
65
|
+
if existing:
|
|
66
|
+
report.updated += 1
|
|
67
|
+
else:
|
|
68
|
+
report.inserted += 1
|
|
69
|
+
except Exception as exc: # noqa: BLE001
|
|
70
|
+
report.failed += 1
|
|
71
|
+
report.failures.append({
|
|
72
|
+
"memory_id": record.memory_id,
|
|
73
|
+
"key": record.key,
|
|
74
|
+
"error": str(exc),
|
|
75
|
+
})
|
|
76
|
+
return report
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
async def migrate_sqlite_to_postgres(
|
|
80
|
+
sqlite_root: str | Path,
|
|
81
|
+
postgres_dsn: str,
|
|
82
|
+
*,
|
|
83
|
+
include_inactive: bool = True,
|
|
84
|
+
overwrite: bool = False,
|
|
85
|
+
dry_run: bool = False,
|
|
86
|
+
batch_size: int = 500,
|
|
87
|
+
limit: int | None = None,
|
|
88
|
+
) -> MemoryMigrationReport:
|
|
89
|
+
source = SQLiteMemoryStore(sqlite_root)
|
|
90
|
+
target = PostgresMemoryStore(postgres_dsn)
|
|
91
|
+
try:
|
|
92
|
+
await source.open()
|
|
93
|
+
await target.open()
|
|
94
|
+
return await migrate_memory_store(
|
|
95
|
+
source,
|
|
96
|
+
target,
|
|
97
|
+
include_inactive=include_inactive,
|
|
98
|
+
overwrite=overwrite,
|
|
99
|
+
dry_run=dry_run,
|
|
100
|
+
batch_size=batch_size,
|
|
101
|
+
limit=limit,
|
|
102
|
+
)
|
|
103
|
+
finally:
|
|
104
|
+
await source.close()
|
|
105
|
+
await target.close()
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def main(argv: list[str] | None = None) -> int:
|
|
109
|
+
parser = argparse.ArgumentParser(description="Migrate durable agent memory from SQLite to Postgres.")
|
|
110
|
+
parser.add_argument(
|
|
111
|
+
"--sqlite-root",
|
|
112
|
+
default=str(default_memory_root(".analytics-agent")),
|
|
113
|
+
help="SQLite memory root containing memory.sqlite.",
|
|
114
|
+
)
|
|
115
|
+
parser.add_argument(
|
|
116
|
+
"--postgres-dsn",
|
|
117
|
+
default=os.environ.get("AGENT_MEMORY_POSTGRES_DSN") or os.environ.get("DATABASE_URL"),
|
|
118
|
+
help="Postgres DSN. Defaults to AGENT_MEMORY_POSTGRES_DSN or DATABASE_URL.",
|
|
119
|
+
)
|
|
120
|
+
parser.add_argument("--active-only", action="store_true", help="Migrate only active memories.")
|
|
121
|
+
parser.add_argument("--overwrite", action="store_true", help="Overwrite matching memory_id records in Postgres.")
|
|
122
|
+
parser.add_argument("--dry-run", action="store_true", help="Count what would migrate without writing.")
|
|
123
|
+
parser.add_argument("--batch-size", type=int, default=500)
|
|
124
|
+
parser.add_argument("--limit", type=int)
|
|
125
|
+
args = parser.parse_args(argv)
|
|
126
|
+
|
|
127
|
+
if not args.postgres_dsn:
|
|
128
|
+
parser.error("--postgres-dsn or AGENT_MEMORY_POSTGRES_DSN is required")
|
|
129
|
+
|
|
130
|
+
report = asyncio.run(migrate_sqlite_to_postgres(
|
|
131
|
+
args.sqlite_root,
|
|
132
|
+
args.postgres_dsn,
|
|
133
|
+
include_inactive=not args.active_only,
|
|
134
|
+
overwrite=args.overwrite,
|
|
135
|
+
dry_run=args.dry_run,
|
|
136
|
+
batch_size=args.batch_size,
|
|
137
|
+
limit=args.limit,
|
|
138
|
+
))
|
|
139
|
+
print(json.dumps(report.to_dict(), ensure_ascii=False, indent=2))
|
|
140
|
+
return 1 if report.failed else 0
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
if __name__ == "__main__":
|
|
144
|
+
raise SystemExit(main())
|