albert-memory 0.4.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 (74) hide show
  1. albert/__init__.py +3 -0
  2. albert/admin.py +532 -0
  3. albert/api.py +698 -0
  4. albert/automatic_memory_release.json +14 -0
  5. albert/benchmark.py +272 -0
  6. albert/benchmark_cli.py +37 -0
  7. albert/capture.py +1051 -0
  8. albert/capture_installer.py +1000 -0
  9. albert/capture_promotion.py +298 -0
  10. albert/capture_retention.py +72 -0
  11. albert/capture_sdk.py +558 -0
  12. albert/capture_security.py +79 -0
  13. albert/chunking.py +79 -0
  14. albert/classifier.py +263 -0
  15. albert/claude_adapter.py +357 -0
  16. albert/claude_lifecycle.py +418 -0
  17. albert/claude_package.json +19 -0
  18. albert/claude_plugin/.claude-plugin/plugin.json +11 -0
  19. albert/claude_plugin/.mcp.json +13 -0
  20. albert/claude_plugin/hooks/hooks.json +70 -0
  21. albert/clusters.py +140 -0
  22. albert/codex_adapter.py +308 -0
  23. albert/codex_hooks/hooks.json +49 -0
  24. albert/codex_lifecycle.py +485 -0
  25. albert/codex_package.json +19 -0
  26. albert/compatibility.py +121 -0
  27. albert/config.py +144 -0
  28. albert/console.py +508 -0
  29. albert/console_backends.py +236 -0
  30. albert/console_map.py +518 -0
  31. albert/console_ops.py +919 -0
  32. albert/credentials.py +616 -0
  33. albert/cursor_adapter.py +320 -0
  34. albert/cursor_hooks/hooks.json +11 -0
  35. albert/cursor_rules/albert-memory.mdc +11 -0
  36. albert/db.py +68 -0
  37. albert/embeddings.py +91 -0
  38. albert/graph.py +623 -0
  39. albert/graph_builders.py +879 -0
  40. albert/graph_cypher.py +669 -0
  41. albert/graph_store.py +376 -0
  42. albert/host_targets/claude-code.json +45 -0
  43. albert/host_targets/codex.json +45 -0
  44. albert/host_targets/openclaw.json +45 -0
  45. albert/host_targets.py +271 -0
  46. albert/links.py +428 -0
  47. albert/mcp_server.py +457 -0
  48. albert/memory_safety.py +111 -0
  49. albert/models.py +611 -0
  50. albert/openclaw_adapter.py +326 -0
  51. albert/openclaw_adapter_trust.json +5 -0
  52. albert/openclaw_package.json +22 -0
  53. albert/openclaw_plugin/index.js +135 -0
  54. albert/openclaw_plugin/openclaw.plugin.json +25 -0
  55. albert/openclaw_plugin/package.json +12 -0
  56. albert/portability.py +291 -0
  57. albert/provenance.py +105 -0
  58. albert/recorder.py +166 -0
  59. albert/release_gate.py +83 -0
  60. albert/schemas.py +617 -0
  61. albert/scope.py +26 -0
  62. albert/search.py +447 -0
  63. albert/security.py +150 -0
  64. albert/services.py +1316 -0
  65. albert/session_context.py +162 -0
  66. albert/trace_feed.py +165 -0
  67. albert/trace_writer.py +131 -0
  68. albert/tracing.py +75 -0
  69. albert/worker.py +202 -0
  70. albert/workspaces.py +256 -0
  71. albert_memory-0.4.0.dist-info/METADATA +554 -0
  72. albert_memory-0.4.0.dist-info/RECORD +74 -0
  73. albert_memory-0.4.0.dist-info/WHEEL +4 -0
  74. albert_memory-0.4.0.dist-info/entry_points.txt +14 -0
albert/mcp_server.py ADDED
@@ -0,0 +1,457 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import os
5
+ from contextvars import ContextVar
6
+ from typing import Any
7
+
8
+ import httpx
9
+ import uvicorn
10
+ from mcp.server import MCPServer
11
+ from starlette.responses import JSONResponse
12
+
13
+ from albert import __version__
14
+
15
+ mcp = MCPServer(
16
+ "Albert",
17
+ description="Independent hybrid memory service for AI agents",
18
+ version=__version__,
19
+ )
20
+
21
+ _request_api_key: ContextVar[str | None] = ContextVar("albert_mcp_request_api_key", default=None)
22
+
23
+
24
+ class ForwardBearerAuth:
25
+ """Require an Albert bearer key and make it available to the REST adapter."""
26
+
27
+ def __init__(self, app): # type: ignore[no-untyped-def]
28
+ self.app = app
29
+
30
+ async def __call__(self, scope, receive, send): # type: ignore[no-untyped-def]
31
+ if scope["type"] != "http":
32
+ await self.app(scope, receive, send)
33
+ return
34
+ headers = {key.lower(): value for key, value in scope.get("headers", [])}
35
+ authorization = headers.get(b"authorization", b"").decode("latin-1")
36
+ scheme, _, value = authorization.partition(" ")
37
+ if scheme.casefold() != "bearer" or not value:
38
+ response = JSONResponse(
39
+ {"detail": "Bearer API key required"},
40
+ status_code=401,
41
+ headers={"WWW-Authenticate": "Bearer"},
42
+ )
43
+ await response(scope, receive, send)
44
+ return
45
+ token = _request_api_key.set(value)
46
+ try:
47
+ await self.app(scope, receive, send)
48
+ finally:
49
+ _request_api_key.reset(token)
50
+
51
+
52
+ def _settings() -> tuple[str, str]:
53
+ url = os.environ.get("ALBERT_API_URL", "http://127.0.0.1:8080").rstrip("/")
54
+ key = _request_api_key.get() or os.environ.get("ALBERT_MCP_API_KEY", "")
55
+ if not key:
56
+ raise RuntimeError(
57
+ "An HTTP Authorization bearer key or ALBERT_MCP_API_KEY for stdio is required"
58
+ )
59
+ return url, key
60
+
61
+
62
+ async def _request(
63
+ method: str,
64
+ path: str,
65
+ payload: dict[str, Any] | None = None,
66
+ headers: dict[str, str] | None = None,
67
+ ) -> Any:
68
+ base_url, api_key = _settings()
69
+ async with httpx.AsyncClient(timeout=120) as client:
70
+ response = await client.request(
71
+ method,
72
+ f"{base_url}{path}",
73
+ headers={"Authorization": f"Bearer {api_key}", **(headers or {})},
74
+ json=payload,
75
+ )
76
+ if response.status_code >= 400:
77
+ raise RuntimeError(f"Albert API returned {response.status_code}: {response.text[:2000]}")
78
+ return None if response.status_code == 204 else response.json()
79
+
80
+
81
+ def _shared(shared: bool) -> dict[str, str]:
82
+ return {"scope": "organization"} if shared else {}
83
+
84
+
85
+ @mcp.tool()
86
+ async def memory_remember(
87
+ content: str,
88
+ subject: str = "",
89
+ memory_type: str = "fact",
90
+ project_ref: str | None = None,
91
+ task_ref: str | None = None,
92
+ sensitivity: str = "internal",
93
+ shared: bool = False,
94
+ ) -> dict[str, Any]:
95
+ """Store an explicit durable memory and queue semantic/graph enrichment.
96
+
97
+ shared=True stores it organization-wide, for every workspace to read; a
98
+ workspace-scoped key needs the memory.write.organization capability.
99
+ """
100
+ return await _request(
101
+ "POST",
102
+ "/v1/memories",
103
+ {
104
+ "content": content,
105
+ "subject": subject,
106
+ "memory_type": memory_type,
107
+ "project_ref": project_ref,
108
+ "task_ref": task_ref,
109
+ "sensitivity": sensitivity,
110
+ **_shared(shared),
111
+ },
112
+ )
113
+
114
+
115
+ @mcp.tool()
116
+ async def memory_ingest(
117
+ content: str,
118
+ source_type: str = "agent",
119
+ source_uri: str = "",
120
+ project_ref: str | None = None,
121
+ task_ref: str | None = None,
122
+ sensitivity: str = "internal",
123
+ wait_seconds: float = 0,
124
+ shared: bool = False,
125
+ ) -> dict[str, Any]:
126
+ """Ingest a canonical episode for asynchronous classification and indexing.
127
+
128
+ The result's `indexing.state` says whether it is searchable yet. Pass
129
+ wait_seconds (up to the server's limit, 30 by default) to return only once
130
+ it is searchable or has failed, so a search straight afterwards finds it.
131
+ shared=True stores it organization-wide, as for memory_remember.
132
+ """
133
+ return await _request(
134
+ "POST",
135
+ "/v1/episodes",
136
+ {
137
+ "content": content,
138
+ "source_type": source_type,
139
+ "source_uri": source_uri,
140
+ "project_ref": project_ref,
141
+ "task_ref": task_ref,
142
+ "sensitivity": sensitivity,
143
+ **_shared(shared),
144
+ },
145
+ headers={"Prefer": f"wait={wait_seconds:g}"} if wait_seconds > 0 else None,
146
+ )
147
+
148
+
149
+ @mcp.tool()
150
+ async def memory_get(memory_id: str) -> dict[str, Any]:
151
+ """Read one authorized memory by UUID."""
152
+ return await _request("GET", f"/v1/memories/{memory_id}")
153
+
154
+
155
+ @mcp.tool()
156
+ async def memory_update(
157
+ memory_id: str,
158
+ subject: str | None = None,
159
+ content: str | None = None,
160
+ memory_type: str | None = None,
161
+ sensitivity: str | None = None,
162
+ confidence: float | None = None,
163
+ ) -> dict[str, Any]:
164
+ """Update an authorized durable memory and re-enrich changed content."""
165
+ payload = {
166
+ key: value
167
+ for key, value in {
168
+ "subject": subject,
169
+ "content": content,
170
+ "memory_type": memory_type,
171
+ "sensitivity": sensitivity,
172
+ "confidence": confidence,
173
+ }.items()
174
+ if value is not None
175
+ }
176
+ return await _request("PATCH", f"/v1/memories/{memory_id}", payload)
177
+
178
+
179
+ @mcp.tool()
180
+ async def memory_get_episode(episode_id: str, wait_seconds: float = 0) -> dict[str, Any]:
181
+ """Read one authorized canonical episode by UUID, with its indexing status.
182
+
183
+ Pass wait_seconds to return only once it is searchable or has failed.
184
+ """
185
+ return await _request(
186
+ "GET",
187
+ f"/v1/episodes/{episode_id}",
188
+ headers={"Prefer": f"wait={wait_seconds:g}"} if wait_seconds > 0 else None,
189
+ )
190
+
191
+
192
+ @mcp.tool()
193
+ async def memory_search(
194
+ query: str,
195
+ limit: int = 10,
196
+ project_ref: str | None = None,
197
+ task_ref: str | None = None,
198
+ include_graph: bool = True,
199
+ ) -> dict[str, Any]:
200
+ """Hybrid lexical, vector, and temporal-graph memory retrieval."""
201
+ return await _request(
202
+ "POST",
203
+ "/v1/search",
204
+ {
205
+ "query": query,
206
+ "limit": limit,
207
+ "project_ref": project_ref,
208
+ "task_ref": task_ref,
209
+ "include_graph": include_graph,
210
+ },
211
+ )
212
+
213
+
214
+ @mcp.tool()
215
+ async def memory_assemble_context(
216
+ query: str,
217
+ limit: int = 10,
218
+ max_characters: int = 12000,
219
+ project_ref: str | None = None,
220
+ task_ref: str | None = None,
221
+ ) -> dict[str, Any]:
222
+ """Build a bounded, cited context block using Albert's hybrid retrieval."""
223
+ return await _request(
224
+ "POST",
225
+ "/v1/context/assemble",
226
+ {
227
+ "query": query,
228
+ "limit": limit,
229
+ "max_characters": max_characters,
230
+ "project_ref": project_ref,
231
+ "task_ref": task_ref,
232
+ },
233
+ )
234
+
235
+
236
+ @mcp.tool()
237
+ async def memory_forget(memory_id: str) -> dict[str, bool]:
238
+ """Delete an authorized memory and invalidate its derived relationships."""
239
+ await _request("DELETE", f"/v1/memories/{memory_id}")
240
+ return {"deleted": True}
241
+
242
+
243
+ @mcp.tool()
244
+ async def memory_forget_episode(episode_id: str) -> dict[str, bool]:
245
+ """Delete a canonical episode together with every memory and edge derived from it."""
246
+ await _request("DELETE", f"/v1/episodes/{episode_id}")
247
+ return {"deleted": True}
248
+
249
+
250
+ @mcp.tool()
251
+ async def memory_query_graph(query: str, limit: int = 50) -> list[dict[str, Any]]:
252
+ """Search temporally valid entity relationships."""
253
+ return await _request("POST", "/v1/graph/query", {"query": query, "limit": limit})
254
+
255
+
256
+ @mcp.tool()
257
+ async def memory_get_subgraph(
258
+ entity_id: str, hops: int = 2, limit: int = 50
259
+ ) -> list[dict[str, Any]]:
260
+ """Traverse the authorized temporal subgraph around an entity."""
261
+ return await _request(
262
+ "GET", f"/v1/graph/entities/{entity_id}/subgraph?hops={hops}&limit={limit}"
263
+ )
264
+
265
+
266
+ @mcp.tool()
267
+ async def memory_add_relationship(
268
+ source_name: str,
269
+ relation_type: str,
270
+ target_name: str,
271
+ source_type: str = "concept",
272
+ target_type: str = "concept",
273
+ sensitivity: str = "internal",
274
+ source_memory_id: str | None = None,
275
+ shared: bool = False,
276
+ ) -> dict[str, Any]:
277
+ """Create an explicit typed relationship in the authorized memory graph.
278
+
279
+ shared=True makes it organization-wide, as for memory_remember.
280
+ """
281
+ return await _request(
282
+ "POST",
283
+ "/v1/relationships",
284
+ {
285
+ "source": {"name": source_name, "entity_type": source_type},
286
+ "relation_type": relation_type,
287
+ "target": {"name": target_name, "entity_type": target_type},
288
+ "sensitivity": sensitivity,
289
+ "source_memory_id": source_memory_id,
290
+ **_shared(shared),
291
+ },
292
+ )
293
+
294
+
295
+ @mcp.tool()
296
+ async def working_memory_start(
297
+ task_id: str,
298
+ description: str,
299
+ resource_type: str | None = None,
300
+ resource_ref: str | None = None,
301
+ expires_in_seconds: int = 7200,
302
+ acquire_lock: bool = False,
303
+ ) -> dict[str, Any]:
304
+ """Start mutable task coordination state."""
305
+ return await _request(
306
+ "POST",
307
+ "/v1/working-memory",
308
+ {
309
+ "task_id": task_id,
310
+ "description": description,
311
+ "resource_type": resource_type,
312
+ "resource_ref": resource_ref,
313
+ "expires_in_seconds": expires_in_seconds,
314
+ "acquire_lock": acquire_lock,
315
+ },
316
+ )
317
+
318
+
319
+ @mcp.tool()
320
+ async def memory_export(workspace_id: str | None = None) -> dict[str, Any]:
321
+ """Export authorized durable memories and explicit graph relationships."""
322
+ suffix = f"?workspace_id={workspace_id}" if workspace_id else ""
323
+ return await _request("GET", f"/v1/export{suffix}")
324
+
325
+
326
+ @mcp.tool()
327
+ async def memory_import(bundle: dict[str, Any], workspace_id: str | None = None) -> dict[str, Any]:
328
+ """Import an Albert export bundle, optionally flattening it into one workspace."""
329
+ return await _request("POST", "/v1/import", {"bundle": bundle, "workspace_id": workspace_id})
330
+
331
+
332
+ @mcp.tool()
333
+ async def working_memory_update(
334
+ working_id: str, progress: dict[str, Any], expires_in_seconds: int | None = None
335
+ ) -> dict[str, Any]:
336
+ """Update task progress and optionally extend its expiration."""
337
+ return await _request(
338
+ "PATCH",
339
+ f"/v1/working-memory/{working_id}",
340
+ {"progress": progress, "expires_in_seconds": expires_in_seconds},
341
+ )
342
+
343
+
344
+ @mcp.tool()
345
+ async def working_memory_get(working_id: str) -> dict[str, Any]:
346
+ """Read current task coordination state by UUID."""
347
+ return await _request("GET", f"/v1/working-memory/{working_id}")
348
+
349
+
350
+ @mcp.tool()
351
+ async def working_memory_complete(
352
+ working_id: str,
353
+ consolidation_notes: str = "",
354
+ record: bool = True,
355
+ record_sensitivity: str = "internal",
356
+ project_ref: str | None = None,
357
+ ) -> dict[str, Any]:
358
+ """Complete task coordination state and release associated locks.
359
+
360
+ Also writes a task-record episode (source_type "task-record", source_uri
361
+ "working-memory://<task_id>") from the task and its consolidation notes,
362
+ so the task is searchable afterwards. Pass record=False to skip it.
363
+ """
364
+ return await _request(
365
+ "POST",
366
+ f"/v1/working-memory/{working_id}/complete",
367
+ {
368
+ "consolidation_notes": consolidation_notes,
369
+ "record": record,
370
+ "record_sensitivity": record_sensitivity,
371
+ "project_ref": project_ref,
372
+ },
373
+ )
374
+
375
+
376
+ @mcp.tool()
377
+ async def working_memory_fail(
378
+ working_id: str,
379
+ consolidation_notes: str = "",
380
+ record: bool = True,
381
+ record_sensitivity: str = "internal",
382
+ project_ref: str | None = None,
383
+ ) -> dict[str, Any]:
384
+ """Mark task coordination state failed and release associated locks.
385
+
386
+ A failed task leaves a task-record episode too (status "failed"), unless
387
+ record=False.
388
+ """
389
+ return await _request(
390
+ "POST",
391
+ f"/v1/working-memory/{working_id}/fail",
392
+ {
393
+ "consolidation_notes": consolidation_notes,
394
+ "record": record,
395
+ "record_sensitivity": record_sensitivity,
396
+ "project_ref": project_ref,
397
+ },
398
+ )
399
+
400
+
401
+ @mcp.tool()
402
+ async def memory_lock_acquire(
403
+ resource_type: str,
404
+ resource_ref: str,
405
+ working_memory_id: str | None = None,
406
+ ttl_seconds: int = 900,
407
+ ) -> dict[str, Any]:
408
+ """Acquire a fenced, expiring exclusive resource lease."""
409
+ return await _request(
410
+ "POST",
411
+ "/v1/locks/acquire",
412
+ {
413
+ "resource_type": resource_type,
414
+ "resource_ref": resource_ref,
415
+ "working_memory_id": working_memory_id,
416
+ "ttl_seconds": ttl_seconds,
417
+ },
418
+ )
419
+
420
+
421
+ @mcp.tool()
422
+ async def memory_lock_renew(
423
+ lock_id: str, token: str, fence: int, ttl_seconds: int = 900
424
+ ) -> dict[str, Any]:
425
+ """Renew a resource lease if its secret token and fencing value are current."""
426
+ return await _request(
427
+ "POST",
428
+ f"/v1/locks/{lock_id}/renew",
429
+ {"token": token, "fence": fence, "ttl_seconds": ttl_seconds},
430
+ )
431
+
432
+
433
+ @mcp.tool()
434
+ async def memory_lock_release(lock_id: str, token: str, fence: int) -> dict[str, bool]:
435
+ """Release a resource lease."""
436
+ await _request("POST", f"/v1/locks/{lock_id}/release", {"token": token, "fence": fence})
437
+ return {"released": True}
438
+
439
+
440
+ def run() -> None:
441
+ parser = argparse.ArgumentParser()
442
+ parser.add_argument("--transport", choices=("stdio", "sse", "streamable-http"), default="stdio")
443
+ parser.add_argument("--host", default="127.0.0.1")
444
+ parser.add_argument("--port", type=int, default=8081)
445
+ args = parser.parse_args()
446
+ if args.transport == "stdio":
447
+ mcp.run("stdio")
448
+ else:
449
+ if args.transport == "sse":
450
+ app = mcp.sse_app(host=args.host)
451
+ else:
452
+ app = mcp.streamable_http_app(host=args.host)
453
+ uvicorn.run(ForwardBearerAuth(app), host=args.host, port=args.port)
454
+
455
+
456
+ if __name__ == "__main__":
457
+ run()
@@ -0,0 +1,111 @@
1
+ from __future__ import annotations
2
+
3
+ import re
4
+ from typing import Any
5
+
6
+ TRUST_LEVELS = ("untrusted", "verified", "trusted")
7
+ CONFIDENCE_CEILINGS = {"untrusted": 0.45, "verified": 0.80, "trusted": 1.0}
8
+ SAFETY_METADATA_KEYS = frozenset(
9
+ {
10
+ "capture_source_trust",
11
+ "confidence_ceiling",
12
+ "confidence_corroborated",
13
+ "contradiction_memory_ids",
14
+ "contradiction_flagged",
15
+ "quarantine_reason_codes",
16
+ "quarantined",
17
+ "suspicious_instruction",
18
+ }
19
+ )
20
+
21
+ _INSTRUCTION_PATTERNS: tuple[tuple[str, re.Pattern[str]], ...] = (
22
+ (
23
+ "instruction_override",
24
+ re.compile(
25
+ r"\b(?:ignore|disregard|override|replace)\b.{0,60}"
26
+ r"\b(?:previous|prior|system|developer|workspace|instruction|policy|rules?)\b",
27
+ re.I | re.S,
28
+ ),
29
+ ),
30
+ (
31
+ "privileged_role_impersonation",
32
+ re.compile(
33
+ r"(?:<\/?(?:system|developer|assistant)>|\[(?:system|developer)\]|"
34
+ r"\b(?:system prompt|developer message)\b)",
35
+ re.I,
36
+ ),
37
+ ),
38
+ (
39
+ "agent_control_language",
40
+ re.compile(
41
+ r"\b(?:you (?:must|shall|are required to)|do not follow|never reveal|"
42
+ r"execute (?:this|the following) command)\b",
43
+ re.I,
44
+ ),
45
+ ),
46
+ (
47
+ "reference_delimiter_escape",
48
+ re.compile(r"[\u27e6\u27e7]|ALBERT[_ -]REFERENCE|END[_ -]REFERENCE", re.I),
49
+ ),
50
+ )
51
+
52
+
53
+ def suspicious_instruction_reasons(content: str) -> list[str]:
54
+ """Return stable reason codes only; callers must not log the body."""
55
+ return [name for name, pattern in _INSTRUCTION_PATTERNS if pattern.search(content)]
56
+
57
+
58
+ def trust_level(metadata: dict[str, Any] | None, *, default: str = "verified") -> str:
59
+ value = str((metadata or {}).get("capture_source_trust", default))
60
+ return value if value in TRUST_LEVELS else default
61
+
62
+
63
+ def sanitize_client_metadata(metadata: dict[str, Any] | None) -> dict[str, Any]:
64
+ """Remove review-owned assertions; clients may only downgrade their own trust."""
65
+ supplied = dict(metadata or {})
66
+ requested_trust = trust_level(supplied)
67
+ safe = {key: value for key, value in supplied.items() if key not in SAFETY_METADATA_KEYS}
68
+ safe["capture_source_trust"] = (
69
+ "untrusted" if requested_trust == "untrusted" else "verified"
70
+ )
71
+ if supplied.get("quarantined") is True:
72
+ safe["quarantined"] = True
73
+ return safe
74
+
75
+
76
+ def apply_memory_safety(
77
+ content: str,
78
+ confidence: float,
79
+ metadata: dict[str, Any] | None,
80
+ *,
81
+ default_trust: str = "verified",
82
+ ) -> tuple[float, dict[str, Any]]:
83
+ """Apply deterministic quarantine and confidence controls to untrusted data."""
84
+ safe = dict(metadata or {})
85
+ trust = trust_level(safe, default=default_trust)
86
+ reasons = suspicious_instruction_reasons(content)
87
+ ceiling = CONFIDENCE_CEILINGS[trust]
88
+ corroborated = bool(safe.get("confidence_corroborated"))
89
+ effective = confidence if corroborated else min(confidence, ceiling)
90
+ safe.update(
91
+ {
92
+ "capture_source_trust": trust,
93
+ "confidence_ceiling": ceiling,
94
+ "confidence_corroborated": corroborated,
95
+ "suspicious_instruction": bool(reasons),
96
+ "quarantined": bool(reasons) or bool(safe.get("quarantined", False)),
97
+ "quarantine_reason_codes": reasons or list(safe.get("quarantine_reason_codes", [])),
98
+ }
99
+ )
100
+ return effective, safe
101
+
102
+
103
+ def preserve_safety_metadata(
104
+ existing: dict[str, Any] | None, replacement: dict[str, Any] | None
105
+ ) -> dict[str, Any]:
106
+ """Prevent ordinary memory updates from editing review-owned safety state."""
107
+ merged = dict(replacement or {})
108
+ for key in SAFETY_METADATA_KEYS:
109
+ if key in (existing or {}):
110
+ merged[key] = existing[key] # type: ignore[index]
111
+ return merged