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/services.py ADDED
@@ -0,0 +1,1316 @@
1
+ from __future__ import annotations
2
+
3
+ import hashlib
4
+ import json
5
+ import secrets
6
+ import time
7
+ from collections.abc import Sequence
8
+ from datetime import UTC, datetime, timedelta
9
+ from typing import Any
10
+ from uuid import UUID
11
+
12
+ from fastapi import HTTPException
13
+ from sqlalchemy import select
14
+ from sqlalchemy.exc import IntegrityError
15
+ from sqlalchemy.orm import Session
16
+
17
+ from albert.chunking import chunk_text
18
+ from albert.classifier import (
19
+ ExtractedEntity,
20
+ ExtractedRelationship,
21
+ classify,
22
+ contains_likely_secret,
23
+ )
24
+ from albert.config import get_settings
25
+ from albert.embeddings import get_embedder
26
+ from albert.graph_builders import (
27
+ BuildRequest,
28
+ BuiltRelationship,
29
+ get_graph_builder,
30
+ graphiti_episode_id,
31
+ )
32
+ from albert.graph_store import StoredRelationship, get_graph_store
33
+ from albert.links import drop_links_for_memory, drop_similar_links, refresh_links_for_memory
34
+ from albert.memory_safety import (
35
+ apply_memory_safety,
36
+ preserve_safety_metadata,
37
+ sanitize_client_metadata,
38
+ trust_level,
39
+ )
40
+ from albert.models import (
41
+ AuditEvent,
42
+ Episode,
43
+ Job,
44
+ Memory,
45
+ MemoryChunk,
46
+ MemoryRecall,
47
+ MemoryStat,
48
+ ResourceLock,
49
+ WorkingMemory,
50
+ Workspace,
51
+ utcnow,
52
+ )
53
+ from albert.recorder import set_workspace, span
54
+ from albert.schemas import (
55
+ EpisodeCreate,
56
+ EpisodeRead,
57
+ IndexingStatus,
58
+ LockAcquire,
59
+ MemoryCreate,
60
+ MemorySafetyReview,
61
+ MemoryUpdate,
62
+ RelationshipCreate,
63
+ WorkingMemoryCreate,
64
+ WorkingMemoryFinish,
65
+ WorkingMemoryUpdate,
66
+ )
67
+ from albert.scope import in_workspace
68
+ from albert.security import AuthContext, hash_lock_token, verify_lock_token
69
+
70
+ SENSITIVITY_ORDER = ("public", "internal", "confidential", "restricted")
71
+ # Attempts the worker makes at a job before marking it failed.
72
+ MAX_JOB_ATTEMPTS = 5
73
+ INDEXING_POLL_SECONDS = 0.25
74
+
75
+
76
+ def _as_utc(value: datetime) -> datetime:
77
+ return value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)
78
+
79
+
80
+ def _highest_sensitivity(*values: str) -> str:
81
+ """Classification may raise a record's sensitivity but never lower it."""
82
+ return max(values, key=SENSITIVITY_ORDER.index)
83
+
84
+
85
+ def reject_secrets(*parts: str | dict | None, what: str = "Content") -> None:
86
+ """Refuse to persist anything that looks like a credential.
87
+
88
+ Every text or JSON field Albert stores or exports goes through here, not
89
+ only memory bodies: working-memory notes, graph descriptions and metadata
90
+ are retrievable too.
91
+ """
92
+ for part in parts:
93
+ if part is None:
94
+ continue
95
+ text = part if isinstance(part, str) else json.dumps(part, default=str)
96
+ if contains_likely_secret(text):
97
+ raise HTTPException(
98
+ status_code=422, detail=f"{what} appears to contain a credential or secret"
99
+ )
100
+
101
+
102
+ def resolve_workspace(session: Session, auth: AuthContext, requested: UUID | None) -> UUID | None:
103
+ with span("resolve_scope", requested=str(requested) if requested else None) as handle:
104
+ if auth.workspace_id is not None and requested not in (None, auth.workspace_id):
105
+ raise HTTPException(status_code=403, detail="Workspace is outside the API key scope")
106
+ workspace_id = requested if requested is not None else auth.workspace_id
107
+ if workspace_id is not None:
108
+ exists = session.scalar(
109
+ select(Workspace.id).where(
110
+ Workspace.id == workspace_id,
111
+ Workspace.organization_id == auth.organization_id,
112
+ )
113
+ )
114
+ if exists is None:
115
+ raise HTTPException(status_code=404, detail="Workspace not found")
116
+ handle.set(workspace_id=str(workspace_id) if workspace_id else None)
117
+ return workspace_id
118
+
119
+
120
+ def require_shared_write(auth: AuthContext) -> None:
121
+ """Writing or changing an organization-wide record from inside a workspace needs a grant."""
122
+ if auth.workspace_id is not None:
123
+ auth.require("memory.write.organization")
124
+
125
+
126
+ def write_workspace(
127
+ session: Session, auth: AuthContext, requested: UUID | None, scope: str | None
128
+ ) -> UUID | None:
129
+ """Where a write lands: organization-wide when asked, else the requested or own workspace."""
130
+ if scope == "organization":
131
+ require_shared_write(auth)
132
+ return None
133
+ return resolve_workspace(session, auth, requested)
134
+
135
+
136
+ def audit(
137
+ session: Session,
138
+ auth: AuthContext,
139
+ event_type: str,
140
+ *,
141
+ resource_type: str | None = None,
142
+ resource_id: str | None = None,
143
+ detail: dict | None = None,
144
+ ) -> None:
145
+ session.add(
146
+ AuditEvent(
147
+ organization_id=auth.organization_id,
148
+ workspace_id=auth.workspace_id,
149
+ principal_id=auth.principal_id,
150
+ event_type=event_type,
151
+ resource_type=resource_type,
152
+ resource_id=resource_id,
153
+ detail=detail or {},
154
+ )
155
+ )
156
+
157
+
158
+ def enqueue(session: Session, organization_id: UUID, job_type: str, payload: dict) -> Job:
159
+ job = Job(organization_id=organization_id, job_type=job_type, payload=payload)
160
+ session.add(job)
161
+ return job
162
+
163
+
164
+ def create_episode(
165
+ session: Session, auth: AuthContext, data: EpisodeCreate
166
+ ) -> tuple[Episode, bool]:
167
+ """Persist a canonical episode; returns (episode, created).
168
+
169
+ Deduplication is scoped to the calling principal so one principal can never
170
+ learn about, or be handed, another principal's episode by re-posting text.
171
+ """
172
+ auth.require("memory.write")
173
+ reject_secrets(data.content, data.metadata)
174
+ workspace_id = write_workspace(session, auth, data.workspace_id, data.scope)
175
+ digest = hashlib.sha256(data.content.encode()).hexdigest()
176
+ duplicate_of = select(Episode).where(
177
+ Episode.organization_id == auth.organization_id,
178
+ Episode.workspace_id == workspace_id,
179
+ Episode.owner_principal_id == auth.principal_id,
180
+ Episode.content_hash == digest,
181
+ Episode.source_uri == data.source_uri,
182
+ )
183
+ existing = session.scalar(duplicate_of)
184
+ if existing is not None:
185
+ return existing, False
186
+ episode = Episode(
187
+ organization_id=auth.organization_id,
188
+ workspace_id=workspace_id,
189
+ project_ref=data.project_ref,
190
+ task_ref=data.task_ref,
191
+ run_ref=data.run_ref,
192
+ owner_principal_id=auth.principal_id,
193
+ source_type=data.source_type,
194
+ source_uri=data.source_uri,
195
+ content=data.content,
196
+ content_hash=digest,
197
+ sensitivity=data.sensitivity,
198
+ occurred_at=data.occurred_at or utcnow(),
199
+ extra=data.metadata,
200
+ )
201
+ session.add(episode)
202
+ try:
203
+ session.flush()
204
+ except IntegrityError as exc:
205
+ session.rollback()
206
+ existing = session.scalar(duplicate_of)
207
+ if existing is not None:
208
+ return existing, False
209
+ raise HTTPException(status_code=409, detail="Episode was concurrently ingested") from exc
210
+ job = enqueue(session, auth.organization_id, "enrich_episode", {"episode_id": str(episode.id)})
211
+ session.flush()
212
+ episode.enrichment_job_id = job.id
213
+ audit(session, auth, "episode.created", resource_type="episode", resource_id=str(episode.id))
214
+ session.commit()
215
+ session.refresh(episode)
216
+ return episode, True
217
+
218
+
219
+ def create_memory(session: Session, auth: AuthContext, data: MemoryCreate) -> Memory:
220
+ auth.require("memory.write")
221
+ reject_secrets(data.subject, data.content, data.metadata)
222
+ workspace_id = write_workspace(session, auth, data.workspace_id, data.scope)
223
+ confidence, metadata = apply_memory_safety(
224
+ data.content, data.confidence, sanitize_client_metadata(data.metadata)
225
+ )
226
+ memory = Memory(
227
+ organization_id=auth.organization_id,
228
+ workspace_id=workspace_id,
229
+ project_ref=data.project_ref,
230
+ task_ref=data.task_ref,
231
+ run_ref=data.run_ref,
232
+ owner_principal_id=auth.principal_id,
233
+ subject=data.subject,
234
+ content=data.content,
235
+ memory_type=data.memory_type,
236
+ sensitivity=data.sensitivity,
237
+ confidence=confidence,
238
+ valid_from=data.valid_from or utcnow(),
239
+ valid_until=data.valid_until,
240
+ metadata_=metadata,
241
+ )
242
+ session.add(memory)
243
+ session.flush()
244
+ if not metadata.get("quarantined"):
245
+ enqueue(
246
+ session,
247
+ auth.organization_id,
248
+ "enrich_memory",
249
+ {
250
+ "memory_id": str(memory.id),
251
+ "content_fingerprint": _content_fingerprint(memory.subject, memory.content),
252
+ },
253
+ )
254
+ audit(session, auth, "memory.created", resource_type="memory", resource_id=str(memory.id))
255
+ session.commit()
256
+ session.refresh(memory)
257
+ return memory
258
+
259
+
260
+ def get_memory(session: Session, auth: AuthContext, memory_id: UUID) -> Memory:
261
+ auth.require("memory.read")
262
+ statement = select(Memory).where(
263
+ Memory.id == memory_id,
264
+ Memory.organization_id == auth.organization_id,
265
+ Memory.status != "deleted",
266
+ )
267
+ statement = statement.where(in_workspace(Memory.workspace_id, auth.workspace_id))
268
+ memory = session.scalar(statement)
269
+ if memory is None:
270
+ raise HTTPException(status_code=404, detail="Memory not found")
271
+ if memory.sensitivity not in auth.allowed_sensitivities():
272
+ raise HTTPException(status_code=404, detail="Memory not found")
273
+ return memory
274
+
275
+
276
+ def update_memory(
277
+ session: Session, auth: AuthContext, memory_id: UUID, data: MemoryUpdate
278
+ ) -> Memory:
279
+ auth.require("memory.write")
280
+ memory = get_memory(session, auth, memory_id)
281
+ if memory.workspace_id is None:
282
+ require_shared_write(auth)
283
+ changes = data.model_dump(exclude_unset=True)
284
+ if "valid_until" in changes:
285
+ valid_until = changes["valid_until"]
286
+ if valid_until is not None and _as_utc(valid_until) <= _as_utc(memory.valid_from):
287
+ raise HTTPException(status_code=422, detail="valid_until must be after valid_from")
288
+ metadata = changes.pop("metadata", None)
289
+ reject_secrets(changes.get("subject"), changes.get("content"), metadata)
290
+ for name, value in changes.items():
291
+ setattr(memory, name, value)
292
+ if metadata is not None:
293
+ memory.metadata_ = preserve_safety_metadata(memory.metadata_, metadata)
294
+ text_changed = data.content is not None or data.subject is not None
295
+ if text_changed or data.confidence is not None or metadata is not None:
296
+ memory.confidence, memory.metadata_ = apply_memory_safety(
297
+ memory.content, memory.confidence, memory.metadata_
298
+ )
299
+ graph = get_graph_store()
300
+ if text_changed:
301
+ revision_at = utcnow()
302
+ # Old chunks describe text that no longer exists; drop them now rather
303
+ # than serve them from vector search until the worker catches up.
304
+ _drop_chunks(session, memory.id)
305
+ drop_similar_links(session, memory.id)
306
+ memory.embedding_model = None
307
+ # The facts themselves may have changed: close the old edges now and let
308
+ # re-enrichment extract the current ones.
309
+ graph.close_memory_edges(
310
+ session,
311
+ organization_id=auth.organization_id,
312
+ memory_id=memory.id,
313
+ at=revision_at,
314
+ extracted_only=True,
315
+ )
316
+ if not memory.metadata_.get("quarantined"):
317
+ enqueue(
318
+ session,
319
+ auth.organization_id,
320
+ "enrich_memory",
321
+ {
322
+ "memory_id": str(memory.id),
323
+ "content_fingerprint": _content_fingerprint(memory.subject, memory.content),
324
+ "revision_at": revision_at.isoformat(),
325
+ },
326
+ )
327
+ elif {"sensitivity", "valid_until"}.intersection(changes):
328
+ # The facts are unchanged; their visibility window follows the memory.
329
+ graph.retarget_memory_edges(
330
+ session,
331
+ organization_id=auth.organization_id,
332
+ memory_id=memory.id,
333
+ sensitivity=memory.sensitivity,
334
+ valid_until=memory.valid_until,
335
+ )
336
+ audit(session, auth, "memory.updated", resource_type="memory", resource_id=str(memory.id))
337
+ session.commit()
338
+ session.refresh(memory)
339
+ return memory
340
+
341
+
342
+ def review_memory_safety(
343
+ session: Session, auth: AuthContext, memory_id: UUID, data: MemorySafetyReview
344
+ ) -> Memory:
345
+ """Review quarantine state without placing restricted bodies in audit telemetry."""
346
+ auth.require("memory.review")
347
+ memory = get_memory(session, auth, memory_id)
348
+ corroborators: list[Memory] = []
349
+ if data.corroborating_memory_ids:
350
+ corroborators = list(
351
+ session.scalars(
352
+ select(Memory).where(
353
+ Memory.id.in_(data.corroborating_memory_ids),
354
+ Memory.organization_id == auth.organization_id,
355
+ Memory.workspace_id == memory.workspace_id,
356
+ Memory.status == "active",
357
+ )
358
+ )
359
+ )
360
+ usable = [
361
+ item
362
+ for item in corroborators
363
+ if not (item.metadata_ or {}).get("quarantined")
364
+ and (item.metadata_ or {}).get("capture_source_trust", "verified")
365
+ in {"verified", "trusted"}
366
+ ]
367
+ if len(usable) != len(set(data.corroborating_memory_ids)):
368
+ raise HTTPException(status_code=422, detail="Corroboration is not eligible")
369
+ corroborators = usable
370
+
371
+ metadata = dict(memory.metadata_ or {})
372
+ if data.action == "reject":
373
+ memory.status = "rejected"
374
+ metadata["quarantined"] = True
375
+ else:
376
+ requested = data.confidence if data.confidence is not None else memory.confidence
377
+ ceiling = float(metadata.get("confidence_ceiling", 0.8))
378
+ if requested > ceiling and not corroborators:
379
+ raise HTTPException(
380
+ status_code=422,
381
+ detail="Confidence above the trust ceiling requires corroboration",
382
+ )
383
+ memory.confidence = requested
384
+ metadata.update(
385
+ {
386
+ "quarantined": False,
387
+ "quarantine_reviewed": True,
388
+ "confidence_corroborated": bool(corroborators),
389
+ "corroborating_memory_ids": sorted(str(item.id) for item in corroborators),
390
+ }
391
+ )
392
+ if memory.embedding_model is None:
393
+ enqueue(
394
+ session,
395
+ auth.organization_id,
396
+ "enrich_memory",
397
+ {
398
+ "memory_id": str(memory.id),
399
+ "content_fingerprint": _content_fingerprint(memory.subject, memory.content),
400
+ },
401
+ )
402
+ memory.metadata_ = metadata
403
+ audit(
404
+ session,
405
+ auth,
406
+ f"memory.quarantine_{data.action}",
407
+ resource_type="memory",
408
+ resource_id=str(memory.id),
409
+ detail={
410
+ "reason_codes": list(metadata.get("quarantine_reason_codes", [])),
411
+ "corroboration_count": len(corroborators),
412
+ },
413
+ )
414
+ session.commit()
415
+ session.refresh(memory)
416
+ return memory
417
+
418
+
419
+ def _classify_traced(text: str): # type: ignore[no-untyped-def]
420
+ with span("classify", provider=get_settings().llm_provider) as handle:
421
+ result = classify(text)
422
+ handle.set(
423
+ memory_type=result.memory_type,
424
+ sensitivity=result.sensitivity,
425
+ confidence=result.confidence,
426
+ entities=len(result.entities),
427
+ relationships=len(result.relationships),
428
+ )
429
+ return result
430
+
431
+
432
+ def _drop_chunks(session: Session, memory_id: UUID) -> None:
433
+ session.query(MemoryChunk).filter(MemoryChunk.memory_id == memory_id).delete(
434
+ synchronize_session=False
435
+ )
436
+
437
+
438
+ def index_memory_chunks(session: Session, memory: Memory) -> None:
439
+ """Replace a memory's chunks and embeddings with ones for its current text."""
440
+ settings = get_settings()
441
+ embedder = get_embedder()
442
+ _drop_chunks(session, memory.id)
443
+ with span("chunk", max_characters=settings.chunk_characters) as chunk_span:
444
+ chunks = chunk_text(
445
+ memory.content,
446
+ max_characters=settings.chunk_characters,
447
+ overlap_characters=settings.chunk_overlap_characters,
448
+ )
449
+ truncated = len(chunks) > settings.max_chunks_per_memory
450
+ chunks = chunks[: settings.max_chunks_per_memory]
451
+ chunk_span.set(chunks=len(chunks), truncated=truncated)
452
+ with span("embed", embedding_model=embedder.name, dimensions=embedder.dimensions) as embed_span:
453
+ for index, chunk in enumerate(chunks):
454
+ text = f"{memory.subject}\n{chunk}" if memory.subject else chunk
455
+ session.add(
456
+ MemoryChunk(
457
+ memory_id=memory.id,
458
+ organization_id=memory.organization_id,
459
+ workspace_id=memory.workspace_id,
460
+ chunk_index=index,
461
+ content=chunk,
462
+ embedding=embedder.embed(text),
463
+ embedding_model=embedder.name,
464
+ )
465
+ )
466
+ embed_span.set(vectors=len(chunks))
467
+ memory.embedding_model = embedder.name
468
+ memory.metadata_ = {
469
+ **(memory.metadata_ or {}),
470
+ "embedding": {"model": embedder.name, "chunks": len(chunks), "truncated": truncated},
471
+ }
472
+
473
+
474
+ def forget_built_graph(
475
+ session: Session,
476
+ *,
477
+ organization_id: UUID,
478
+ workspace_id: UUID | None,
479
+ source_ids: list[UUID],
480
+ episode_ids: list[str],
481
+ memory_id: UUID | None = None,
482
+ ) -> None:
483
+ """Queue removal of what a builder keeps of its own about forgotten sources.
484
+
485
+ Only Graphiti keeps a store of its own. Its episodes are found by the source
486
+ they were tagged with, by the episode ids given, and, for episodes built
487
+ before tagging, by the provenance on the memory's edges in Albert's store.
488
+ A queued job retries until the builder's store is reachable.
489
+ """
490
+ if not getattr(get_graph_builder(), "keeps_own_store", False):
491
+ return
492
+ found = set(episode_ids)
493
+ if memory_id is not None:
494
+ for metadata in get_graph_store().memory_edge_metadata(
495
+ session, organization_id=organization_id, memory_id=memory_id
496
+ ):
497
+ if isinstance(metadata.get("graphiti_episode_id"), str):
498
+ found.add(metadata["graphiti_episode_id"])
499
+ enqueue(
500
+ session,
501
+ organization_id,
502
+ "graph_forget",
503
+ {
504
+ "workspace_id": str(workspace_id) if workspace_id else None,
505
+ "source_ids": sorted({str(source_id) for source_id in source_ids}),
506
+ "episode_ids": sorted(found),
507
+ },
508
+ )
509
+
510
+
511
+ def forget_episode_graph(session: Session, episode: Episode) -> None:
512
+ """Queue removal of the builder's copy of an episode; call before blanking it."""
513
+ forget_built_graph(
514
+ session,
515
+ organization_id=episode.organization_id,
516
+ workspace_id=episode.workspace_id,
517
+ source_ids=[episode.id],
518
+ episode_ids=[graphiti_episode_id(episode.id, episode.content_hash)],
519
+ )
520
+
521
+
522
+ def _scrub_memory(session: Session, memory: Memory, now: datetime) -> None:
523
+ """Forget a memory: keep the row for audit identity, drop everything it said."""
524
+ sources = [memory.id]
525
+ if memory.episode_id is not None and (memory.metadata_ or {}).get("derived_from_episode"):
526
+ # The episode's text is the memory's text: the builder's copy goes too.
527
+ sources.append(memory.episode_id)
528
+ forget_built_graph(
529
+ session,
530
+ organization_id=memory.organization_id,
531
+ workspace_id=memory.workspace_id,
532
+ source_ids=sources,
533
+ episode_ids=[
534
+ graphiti_episode_id(memory.id, _content_fingerprint(memory.subject, memory.content))
535
+ ],
536
+ memory_id=memory.id,
537
+ )
538
+ memory.status = "deleted"
539
+ memory.subject = ""
540
+ memory.content = ""
541
+ memory.embedding_model = None
542
+ memory.metadata_ = {}
543
+ _drop_chunks(session, memory.id)
544
+ drop_links_for_memory(session, memory.id)
545
+ session.query(MemoryRecall).filter(MemoryRecall.memory_id == memory.id).delete(
546
+ synchronize_session=False
547
+ )
548
+ session.query(MemoryStat).filter(MemoryStat.memory_id == memory.id).delete(
549
+ synchronize_session=False
550
+ )
551
+ get_graph_store().close_memory_edges(
552
+ session,
553
+ organization_id=memory.organization_id,
554
+ memory_id=memory.id,
555
+ at=now,
556
+ extracted_only=False,
557
+ )
558
+
559
+
560
+ def delete_memory(session: Session, auth: AuthContext, memory_id: UUID) -> None:
561
+ auth.require("memory.delete")
562
+ memory = get_memory(session, auth, memory_id)
563
+ if memory.workspace_id is None:
564
+ require_shared_write(auth)
565
+ _scrub_memory(session, memory, utcnow())
566
+ audit(session, auth, "memory.deleted", resource_type="memory", resource_id=str(memory.id))
567
+ session.commit()
568
+
569
+
570
+ def get_episode(session: Session, auth: AuthContext, episode_id: UUID) -> Episode:
571
+ auth.require("memory.read")
572
+ statement = select(Episode).where(
573
+ Episode.id == episode_id,
574
+ Episode.organization_id == auth.organization_id,
575
+ Episode.deleted_at.is_(None),
576
+ )
577
+ statement = statement.where(in_workspace(Episode.workspace_id, auth.workspace_id))
578
+ episode = session.scalar(statement)
579
+ if episode is None or episode.sensitivity not in auth.allowed_sensitivities():
580
+ raise HTTPException(status_code=404, detail="Episode not found")
581
+ return episode
582
+
583
+
584
+ def _short_error(value: str | None) -> str | None:
585
+ """First line of a worker error, bounded: enough to tell a timeout from a bad config."""
586
+ if not value:
587
+ return None
588
+ return value.strip().splitlines()[0][:300]
589
+
590
+
591
+ def indexing_status(session: Session, episode: Episode) -> IndexingStatus:
592
+ job = session.get(Job, episode.enrichment_job_id) if episode.enrichment_job_id else None
593
+ attempt = job.attempts if job is not None else 0
594
+ if episode.enrichment_status == "complete":
595
+ memory_id = session.scalar(
596
+ select(Memory.id)
597
+ .where(Memory.episode_id == episode.id, Memory.status == "active")
598
+ .order_by(Memory.created_at.desc())
599
+ .limit(1)
600
+ )
601
+ return IndexingStatus(
602
+ state="complete",
603
+ searchable=True,
604
+ attempt=attempt,
605
+ max_attempts=MAX_JOB_ATTEMPTS,
606
+ memory_id=memory_id,
607
+ )
608
+ if episode.enrichment_status == "failed" or (job is not None and job.status == "failed"):
609
+ return IndexingStatus(
610
+ state="failed",
611
+ searchable=False,
612
+ attempt=attempt,
613
+ max_attempts=MAX_JOB_ATTEMPTS,
614
+ last_error=_short_error(episode.enrichment_error or (job and job.last_error)),
615
+ )
616
+ if job is not None and job.status == "running":
617
+ state = "running"
618
+ elif job is not None and job.attempts > 0:
619
+ state = "retrying"
620
+ else:
621
+ state = "queued"
622
+ return IndexingStatus(
623
+ state=state,
624
+ searchable=False,
625
+ attempt=attempt,
626
+ max_attempts=MAX_JOB_ATTEMPTS,
627
+ last_error=_short_error(job.last_error) if job is not None else None,
628
+ next_attempt_at=job.available_at if state == "retrying" else None,
629
+ )
630
+
631
+
632
+ def episode_read(session: Session, episode: Episode) -> EpisodeRead:
633
+ view = EpisodeRead.model_validate(episode)
634
+ view.indexing = indexing_status(session, episode)
635
+ return view
636
+
637
+
638
+ def wait_for_indexing(session: Session, episode: Episode, seconds: float) -> EpisodeRead:
639
+ """Poll until the episode is searchable or has failed, for at most `seconds`.
640
+
641
+ Each poll runs in its own short transaction, so the worker's commits are
642
+ visible and no pooled connection is held while sleeping.
643
+ """
644
+ deadline = time.monotonic() + seconds
645
+ while True:
646
+ session.commit()
647
+ session.refresh(episode)
648
+ view = episode_read(session, episode)
649
+ session.commit()
650
+ state = view.indexing.state if view.indexing else "queued"
651
+ if state in ("complete", "failed") or time.monotonic() >= deadline:
652
+ return view
653
+ time.sleep(INDEXING_POLL_SECONDS)
654
+
655
+
656
+ def delete_episode(session: Session, auth: AuthContext, episode_id: UUID) -> None:
657
+ """Delete a canonical episode together with everything derived from it."""
658
+ auth.require("memory.delete")
659
+ episode = get_episode(session, auth, episode_id)
660
+ if episode.workspace_id is None:
661
+ require_shared_write(auth)
662
+ now = utcnow()
663
+ for memory in session.scalars(
664
+ select(Memory).where(Memory.episode_id == episode.id, Memory.status != "deleted")
665
+ ):
666
+ _scrub_memory(session, memory, now)
667
+ forget_episode_graph(session, episode)
668
+ episode.content = ""
669
+ episode.extra = {}
670
+ episode.enrichment_error = None
671
+ episode.deleted_at = now
672
+ from albert.capture_retention import delete_capture_for_episode
673
+
674
+ delete_capture_for_episode(session, episode.id, now)
675
+ audit(session, auth, "episode.deleted", resource_type="episode", resource_id=str(episode.id))
676
+ session.commit()
677
+
678
+
679
+ def add_explicit_relationship(
680
+ session: Session, auth: AuthContext, data: RelationshipCreate
681
+ ) -> StoredRelationship:
682
+ auth.require("graph.write")
683
+ reject_secrets(
684
+ data.source.name,
685
+ data.source.description,
686
+ data.target.name,
687
+ data.target.description,
688
+ data.metadata,
689
+ what="Relationship",
690
+ )
691
+ workspace_id = write_workspace(session, auth, data.workspace_id, data.scope)
692
+ if data.source_memory_id is not None:
693
+ get_memory(session, auth, data.source_memory_id)
694
+ extracted = ExtractedRelationship(
695
+ source=ExtractedEntity(
696
+ data.source.name,
697
+ data.source.entity_type,
698
+ data.source.description,
699
+ data.source.confidence,
700
+ ),
701
+ relation_type=data.relation_type,
702
+ target=ExtractedEntity(
703
+ data.target.name,
704
+ data.target.entity_type,
705
+ data.target.description,
706
+ data.target.confidence,
707
+ ),
708
+ confidence=data.confidence,
709
+ )
710
+ relationship, _created = get_graph_store().add_relationship(
711
+ session,
712
+ organization_id=auth.organization_id,
713
+ workspace_id=workspace_id,
714
+ extracted=extracted,
715
+ source_memory_id=data.source_memory_id,
716
+ sensitivity=data.sensitivity,
717
+ valid_from=data.valid_from or utcnow(),
718
+ valid_until=data.valid_until,
719
+ metadata=data.metadata,
720
+ )
721
+ audit(
722
+ session,
723
+ auth,
724
+ "relationship.created",
725
+ resource_type="relationship",
726
+ resource_id=str(relationship.id),
727
+ )
728
+ session.commit()
729
+ return relationship
730
+
731
+
732
+ def create_working_memory(
733
+ session: Session, auth: AuthContext, data: WorkingMemoryCreate
734
+ ) -> tuple[WorkingMemory, tuple[ResourceLock, str] | None]:
735
+ auth.require("working_memory.write")
736
+ reject_secrets(data.description, what="Working memory")
737
+ workspace_id = resolve_workspace(session, auth, data.workspace_id)
738
+ working = WorkingMemory(
739
+ organization_id=auth.organization_id,
740
+ workspace_id=workspace_id,
741
+ owner_principal_id=auth.principal_id,
742
+ task_id=data.task_id,
743
+ description=data.description,
744
+ resource_type=data.resource_type,
745
+ resource_ref=data.resource_ref,
746
+ expires_at=utcnow() + timedelta(seconds=data.expires_in_seconds),
747
+ )
748
+ session.add(working)
749
+ try:
750
+ session.flush()
751
+ except IntegrityError as exc:
752
+ session.rollback()
753
+ raise HTTPException(status_code=409, detail="Task ID already exists") from exc
754
+ lock = None
755
+ if data.acquire_lock:
756
+ if not data.resource_type or not data.resource_ref:
757
+ raise HTTPException(status_code=422, detail="Resource type and reference are required")
758
+ lock = acquire_lock(
759
+ session,
760
+ auth,
761
+ LockAcquire(
762
+ workspace_id=workspace_id,
763
+ working_memory_id=working.id,
764
+ resource_type=data.resource_type,
765
+ resource_ref=data.resource_ref,
766
+ ttl_seconds=min(data.expires_in_seconds, 86400),
767
+ ),
768
+ commit=False,
769
+ )
770
+ audit(
771
+ session,
772
+ auth,
773
+ "working_memory.created",
774
+ resource_type="working_memory",
775
+ resource_id=str(working.id),
776
+ )
777
+ session.commit()
778
+ session.refresh(working)
779
+ return working, lock
780
+
781
+
782
+ def get_working_memory(session: Session, auth: AuthContext, working_id: UUID) -> WorkingMemory:
783
+ statement = select(WorkingMemory).where(
784
+ WorkingMemory.id == working_id,
785
+ WorkingMemory.organization_id == auth.organization_id,
786
+ )
787
+ if auth.workspace_id is not None:
788
+ statement = statement.where(WorkingMemory.workspace_id == auth.workspace_id)
789
+ working = session.scalar(statement)
790
+ if working is None:
791
+ raise HTTPException(status_code=404, detail="Working memory not found")
792
+ return working
793
+
794
+
795
+ def update_working_memory(
796
+ session: Session, auth: AuthContext, working_id: UUID, data: WorkingMemoryUpdate
797
+ ) -> WorkingMemory:
798
+ auth.require("working_memory.write")
799
+ working = get_working_memory(session, auth, working_id)
800
+ if working.owner_principal_id != auth.principal_id and "admin" not in auth.capabilities:
801
+ raise HTTPException(status_code=403, detail="Working memory is owned by another principal")
802
+ if working.status != "active":
803
+ raise HTTPException(status_code=409, detail="Working memory is not active")
804
+ reject_secrets(data.progress, what="Working memory progress")
805
+ if data.progress is not None:
806
+ working.progress = data.progress
807
+ if data.expires_in_seconds is not None:
808
+ working.expires_at = utcnow() + timedelta(seconds=data.expires_in_seconds)
809
+ session.commit()
810
+ session.refresh(working)
811
+ return working
812
+
813
+
814
+ def finish_working_memory(
815
+ session: Session,
816
+ auth: AuthContext,
817
+ working_id: UUID,
818
+ data: WorkingMemoryFinish,
819
+ *,
820
+ failed: bool,
821
+ ) -> WorkingMemory:
822
+ auth.require("working_memory.write")
823
+ working = get_working_memory(session, auth, working_id)
824
+ if working.owner_principal_id != auth.principal_id and "admin" not in auth.capabilities:
825
+ raise HTTPException(status_code=403, detail="Working memory is owned by another principal")
826
+ if working.status != "active":
827
+ raise HTTPException(status_code=409, detail="Working memory is not active")
828
+ reject_secrets(data.consolidation_notes, what="Consolidation notes")
829
+ working.status = "failed" if failed else "completed"
830
+ working.completed_at = utcnow()
831
+ working.consolidation_notes = data.consolidation_notes
832
+ session.query(ResourceLock).filter(
833
+ ResourceLock.organization_id == auth.organization_id,
834
+ ResourceLock.working_memory_id == working.id,
835
+ ResourceLock.released_at.is_(None),
836
+ ).update({ResourceLock.released_at: working.completed_at})
837
+ audit(
838
+ session,
839
+ auth,
840
+ f"working_memory.{working.status}",
841
+ resource_type="working_memory",
842
+ resource_id=str(working.id),
843
+ )
844
+ session.commit()
845
+ if data.record and "memory.write" in auth.capabilities:
846
+ record, _created = create_episode(session, auth, task_record_episode(working, data))
847
+ working.record_episode_id = record.id
848
+ session.commit()
849
+ session.refresh(working)
850
+ return working
851
+
852
+
853
+ def task_record_episode(working: WorkingMemory, data: WorkingMemoryFinish) -> EpisodeCreate:
854
+ """The canonical account of a finished task.
855
+
856
+ Finishing a task used to leave only ``consolidation_notes`` on the working
857
+ row, which nothing searches. Every completed or failed task now also
858
+ becomes an episode, so the worker classifies and indexes it like any other
859
+ source and later work can find what was done, by whom, and how it ended.
860
+ The episode is keyed by ``working-memory://<task_id>`` and ``task_ref`` so
861
+ it links back to the task and to memories stored under the same task.
862
+ """
863
+ started = working.created_at.isoformat() if working.created_at else "unknown"
864
+ finished = working.completed_at.isoformat() if working.completed_at else "unknown"
865
+ lines = [
866
+ f"# Task record: {working.task_id}",
867
+ "",
868
+ f"Status: {working.status}",
869
+ f"Started: {started}",
870
+ f"Finished: {finished}",
871
+ ]
872
+ if working.resource_type or working.resource_ref:
873
+ resource = f"{working.resource_type or ''} {working.resource_ref or ''}".strip()
874
+ lines.append(f"Resource: {resource}")
875
+ lines += ["", "## Task", "", working.description]
876
+ if working.progress:
877
+ lines += ["", "## Progress", "", json.dumps(working.progress, indent=2, sort_keys=True)]
878
+ lines += [
879
+ "",
880
+ "## Consolidation notes",
881
+ "",
882
+ data.consolidation_notes.strip() or "(none recorded)",
883
+ ]
884
+ return EpisodeCreate(
885
+ workspace_id=working.workspace_id,
886
+ project_ref=data.project_ref,
887
+ task_ref=working.task_id,
888
+ content="\n".join(lines),
889
+ source_type="task-record",
890
+ source_uri=f"working-memory://{working.task_id}",
891
+ sensitivity=data.record_sensitivity,
892
+ occurred_at=working.completed_at,
893
+ metadata={"working_memory_id": str(working.id), "status": working.status},
894
+ )
895
+
896
+
897
+ def acquire_lock(
898
+ session: Session, auth: AuthContext, data: LockAcquire, *, commit: bool = True
899
+ ) -> tuple[ResourceLock, str]:
900
+ auth.require("locks.acquire")
901
+ working = None
902
+ if data.working_memory_id is not None:
903
+ working = session.scalar(
904
+ select(WorkingMemory).where(
905
+ WorkingMemory.id == data.working_memory_id,
906
+ WorkingMemory.organization_id == auth.organization_id,
907
+ )
908
+ )
909
+ if working is None:
910
+ raise HTTPException(status_code=404, detail="Working memory not found")
911
+ if working.owner_principal_id != auth.principal_id and "admin" not in auth.capabilities:
912
+ raise HTTPException(
913
+ status_code=403, detail="Working memory is owned by another principal"
914
+ )
915
+ if working.status != "active" or _as_utc(working.expires_at) <= utcnow():
916
+ raise HTTPException(status_code=409, detail="Working memory is not active")
917
+ if working.resource_type and working.resource_type != data.resource_type:
918
+ raise HTTPException(status_code=409, detail="Lock resource type does not match task")
919
+ if working.resource_ref and working.resource_ref != data.resource_ref:
920
+ raise HTTPException(
921
+ status_code=409, detail="Lock resource reference does not match task"
922
+ )
923
+ requested_workspace = data.workspace_id
924
+ if requested_workspace is None and working is not None:
925
+ requested_workspace = working.workspace_id
926
+ workspace_id = resolve_workspace(session, auth, requested_workspace)
927
+ if working is not None and working.workspace_id != workspace_id:
928
+ raise HTTPException(status_code=409, detail="Lock workspace does not match task")
929
+ now = utcnow()
930
+ statement = select(ResourceLock).where(
931
+ ResourceLock.organization_id == auth.organization_id,
932
+ ResourceLock.resource_type == data.resource_type,
933
+ ResourceLock.resource_ref == data.resource_ref,
934
+ )
935
+ if session.bind is not None and session.bind.dialect.name == "postgresql":
936
+ statement = statement.with_for_update()
937
+ existing = session.scalar(statement)
938
+ if existing is not None and existing.released_at is None and _as_utc(existing.expires_at) > now:
939
+ raise HTTPException(
940
+ status_code=409,
941
+ detail={
942
+ "message": "Resource is locked",
943
+ "owner_principal_id": str(existing.owner_principal_id),
944
+ "expires_at": existing.expires_at.isoformat(),
945
+ },
946
+ )
947
+ token = secrets.token_urlsafe(32)
948
+ if existing is None:
949
+ lock = ResourceLock(
950
+ organization_id=auth.organization_id,
951
+ workspace_id=workspace_id,
952
+ owner_principal_id=auth.principal_id,
953
+ working_memory_id=data.working_memory_id,
954
+ resource_type=data.resource_type,
955
+ resource_ref=data.resource_ref,
956
+ fence=1,
957
+ token_hash=hash_lock_token(token),
958
+ expires_at=now + timedelta(seconds=data.ttl_seconds),
959
+ )
960
+ session.add(lock)
961
+ else:
962
+ lock = existing
963
+ lock.workspace_id = workspace_id
964
+ lock.owner_principal_id = auth.principal_id
965
+ lock.working_memory_id = data.working_memory_id
966
+ lock.fence += 1
967
+ lock.token_hash = hash_lock_token(token)
968
+ lock.expires_at = now + timedelta(seconds=data.ttl_seconds)
969
+ lock.released_at = None
970
+ try:
971
+ session.flush()
972
+ except IntegrityError as exc:
973
+ session.rollback()
974
+ raise HTTPException(status_code=409, detail="Resource was concurrently locked") from exc
975
+ audit(session, auth, "lock.acquired", resource_type="lock", resource_id=str(lock.id))
976
+ if commit:
977
+ session.commit()
978
+ session.refresh(lock)
979
+ return lock, token
980
+
981
+
982
+ def renew_lock(
983
+ session: Session,
984
+ auth: AuthContext,
985
+ lock_id: UUID,
986
+ *,
987
+ token: str,
988
+ fence: int,
989
+ ttl_seconds: int,
990
+ ) -> ResourceLock:
991
+ auth.require("locks.acquire")
992
+ statement = select(ResourceLock).where(
993
+ ResourceLock.id == lock_id, ResourceLock.organization_id == auth.organization_id
994
+ )
995
+ if session.bind is not None and session.bind.dialect.name == "postgresql":
996
+ statement = statement.with_for_update()
997
+ lock = session.scalar(statement)
998
+ now = utcnow()
999
+ if (
1000
+ lock is None
1001
+ or lock.owner_principal_id != auth.principal_id
1002
+ or lock.fence != fence
1003
+ or lock.released_at is not None
1004
+ or _as_utc(lock.expires_at) <= now
1005
+ or not verify_lock_token(token, lock.token_hash)
1006
+ ):
1007
+ raise HTTPException(status_code=409, detail="Lock lease is invalid or stale")
1008
+ lock.expires_at = now + timedelta(seconds=ttl_seconds)
1009
+ session.commit()
1010
+ session.refresh(lock)
1011
+ return lock
1012
+
1013
+
1014
+ def release_lock(
1015
+ session: Session, auth: AuthContext, lock_id: UUID, *, token: str, fence: int
1016
+ ) -> None:
1017
+ auth.require("locks.acquire")
1018
+ statement = select(ResourceLock).where(
1019
+ ResourceLock.id == lock_id, ResourceLock.organization_id == auth.organization_id
1020
+ )
1021
+ if session.bind is not None and session.bind.dialect.name == "postgresql":
1022
+ statement = statement.with_for_update()
1023
+ lock = session.scalar(statement)
1024
+ if (
1025
+ lock is None
1026
+ or lock.owner_principal_id != auth.principal_id
1027
+ or lock.fence != fence
1028
+ or lock.released_at is not None
1029
+ or not verify_lock_token(token, lock.token_hash)
1030
+ ):
1031
+ raise HTTPException(status_code=409, detail="Lock lease is invalid or stale")
1032
+ lock.released_at = utcnow()
1033
+ audit(session, auth, "lock.released", resource_type="lock", resource_id=str(lock.id))
1034
+ session.commit()
1035
+
1036
+
1037
+ def _release_before_model_calls(session: Session) -> None:
1038
+ """End the read transaction before an enrichment's external model calls.
1039
+
1040
+ Classification and graph extraction can run for minutes. Holding the
1041
+ enrichment transaction across them keeps a row lock and a pooled
1042
+ connection open for that whole time, and the worker's 15-minute stale-job
1043
+ reaper will requeue the job while the first attempt is still working. The
1044
+ write phase re-reads the row afterwards, so nothing is lost by releasing
1045
+ it here.
1046
+ """
1047
+ if session.new or session.dirty or session.deleted:
1048
+ raise RuntimeError(
1049
+ "enrichment requires a session with no pending changes; "
1050
+ "commit before calling enrich_memory or enrich_episode"
1051
+ )
1052
+ session.rollback()
1053
+
1054
+
1055
+ def _content_fingerprint(subject: str, content: str) -> str:
1056
+ return hashlib.sha256(f"{subject}\n{content}".encode()).hexdigest()
1057
+
1058
+
1059
+ def _apply_built_relationships(
1060
+ session: Session,
1061
+ built_relationships: Sequence[BuiltRelationship],
1062
+ *,
1063
+ organization_id: UUID,
1064
+ workspace_id: UUID | None,
1065
+ source_memory_id: UUID,
1066
+ sensitivity: str,
1067
+ fallback_valid_until: datetime | None = None,
1068
+ extra_metadata: dict[str, Any] | None = None,
1069
+ at: datetime,
1070
+ ) -> tuple[int, int]:
1071
+ """Write the edges a builder owns and close the ones it superseded.
1072
+
1073
+ Returns ``(closed, written)``. Supersessions are grouped by builder and
1074
+ close time so each distinct group costs one store call instead of one call
1075
+ per edge.
1076
+ """
1077
+ graph = get_graph_store()
1078
+ superseded: dict[tuple[str, datetime], list[str]] = {}
1079
+ written = 0
1080
+ for built in built_relationships:
1081
+ if built.close_only:
1082
+ key = (str(built.metadata.get("builder", "")), built.valid_until or at)
1083
+ superseded.setdefault(key, []).append(str(built.metadata["graphiti_edge_id"]))
1084
+ continue
1085
+ if built.relationship is None:
1086
+ continue
1087
+ _edge, created = graph.add_relationship(
1088
+ session,
1089
+ organization_id=organization_id,
1090
+ workspace_id=workspace_id,
1091
+ extracted=built.relationship,
1092
+ source_memory_id=source_memory_id,
1093
+ sensitivity=sensitivity,
1094
+ valid_from=built.valid_from,
1095
+ valid_until=built.valid_until or fallback_valid_until,
1096
+ metadata={"extracted": True, **(extra_metadata or {}), **built.metadata},
1097
+ )
1098
+ written += int(created)
1099
+ closed = 0
1100
+ for (builder, close_at), external_ids in superseded.items():
1101
+ closed += graph.close_external_edges(
1102
+ session,
1103
+ organization_id=organization_id,
1104
+ workspace_id=workspace_id,
1105
+ builder=builder,
1106
+ external_ids=external_ids,
1107
+ at=close_at,
1108
+ )
1109
+ return closed, written
1110
+
1111
+
1112
+ def enrich_memory(
1113
+ session: Session,
1114
+ memory_id: UUID,
1115
+ *,
1116
+ revision_at: datetime | None = None,
1117
+ expected_fingerprint: str | None = None,
1118
+ ) -> None:
1119
+ memory = session.get(Memory, memory_id)
1120
+ if memory is None or memory.status != "active":
1121
+ return
1122
+ set_workspace(memory.workspace_id)
1123
+ current_fingerprint = _content_fingerprint(memory.subject, memory.content)
1124
+ if expected_fingerprint is not None and current_fingerprint != expected_fingerprint:
1125
+ return
1126
+ request = BuildRequest(
1127
+ memory_id=memory.id,
1128
+ organization_id=memory.organization_id,
1129
+ workspace_id=memory.workspace_id,
1130
+ subject=memory.subject,
1131
+ content=memory.content,
1132
+ occurred_at=revision_at or memory.valid_from,
1133
+ content_fingerprint=current_fingerprint,
1134
+ )
1135
+ _release_before_model_calls(session)
1136
+
1137
+ result = _classify_traced(f"{request.subject}\n{request.content}")
1138
+ builder = get_graph_builder()
1139
+ built_relationships = builder.build(request, result.relationships)
1140
+
1141
+ memory = session.get(Memory, memory_id, with_for_update=True)
1142
+ if memory is None or memory.status != "active":
1143
+ if memory is not None and memory.status == "deleted":
1144
+ # Forgotten while the builder ran: whatever it just stored goes too.
1145
+ forget_built_graph(
1146
+ session,
1147
+ organization_id=request.organization_id,
1148
+ workspace_id=request.workspace_id,
1149
+ source_ids=[memory.id],
1150
+ episode_ids=[graphiti_episode_id(memory.id, request.content_fingerprint)],
1151
+ )
1152
+ session.commit()
1153
+ return
1154
+ if _content_fingerprint(memory.subject, memory.content) != request.content_fingerprint:
1155
+ # The memory was edited while extraction ran, so this result describes a
1156
+ # revision that no longer exists. update_memory already queued a fresh
1157
+ # enrichment job for the current one.
1158
+ return
1159
+ index_memory_chunks(session, memory)
1160
+ if memory.memory_type == "fact" and result.memory_type != "fact":
1161
+ memory.memory_type = result.memory_type
1162
+ original_sensitivity = memory.sensitivity
1163
+ memory.sensitivity = _highest_sensitivity(memory.sensitivity, result.sensitivity)
1164
+ memory.metadata_ = {
1165
+ **(memory.metadata_ or {}),
1166
+ "classification": {
1167
+ "provider": get_settings().llm_provider,
1168
+ "graph_builder": get_settings().graph_builder,
1169
+ "confidence": result.confidence,
1170
+ "suggested_sensitivity": result.sensitivity,
1171
+ "original_sensitivity": original_sensitivity,
1172
+ },
1173
+ }
1174
+ now = utcnow()
1175
+ with span("write_edges") as edges_span:
1176
+ closed = get_graph_store().close_memory_edges(
1177
+ session,
1178
+ organization_id=memory.organization_id,
1179
+ memory_id=memory.id,
1180
+ at=now,
1181
+ extracted_only=True,
1182
+ )
1183
+ superseded, written = _apply_built_relationships(
1184
+ session,
1185
+ built_relationships,
1186
+ organization_id=memory.organization_id,
1187
+ workspace_id=memory.workspace_id,
1188
+ source_memory_id=memory.id,
1189
+ sensitivity=memory.sensitivity,
1190
+ fallback_valid_until=memory.valid_until,
1191
+ at=now,
1192
+ )
1193
+ edges_span.set(
1194
+ edges_closed=closed + superseded, edges_written=written, builder=builder.name
1195
+ )
1196
+ refresh_links_for_memory(session, memory)
1197
+
1198
+
1199
+ def _episode_trust(episode: Episode) -> str:
1200
+ """Source trust for a memory derived from an episode.
1201
+
1202
+ Capture episodes carry the trust their capture profile assigned. Any other
1203
+ episode (documents, connector content, memory_ingest) is client-submitted:
1204
+ the client may lower it to untrusted, as for direct writes, but never raise
1205
+ it above verified.
1206
+ """
1207
+ if episode.source_type == "automatic_capture":
1208
+ return trust_level(episode.extra, default="untrusted")
1209
+ return "untrusted" if trust_level(episode.extra) == "untrusted" else "verified"
1210
+
1211
+
1212
+ def enrich_episode(session: Session, episode_id: UUID) -> None:
1213
+ episode = session.get(Episode, episode_id)
1214
+ if episode is None or episode.deleted_at is not None or episode.enrichment_status == "complete":
1215
+ return
1216
+ if episode.extra.get("capture_promotion_decision") == "discard":
1217
+ episode.enrichment_status = "complete"
1218
+ episode.enrichment_error = None
1219
+ session.commit()
1220
+ return
1221
+ set_workspace(episode.workspace_id)
1222
+ subject = episode.content.strip().splitlines()[0][:500]
1223
+ request = BuildRequest(
1224
+ memory_id=episode.id,
1225
+ organization_id=episode.organization_id,
1226
+ workspace_id=episode.workspace_id,
1227
+ subject=subject,
1228
+ content=episode.content,
1229
+ occurred_at=episode.occurred_at,
1230
+ content_fingerprint=episode.content_hash,
1231
+ )
1232
+ _release_before_model_calls(session)
1233
+
1234
+ result = _classify_traced(request.content)
1235
+ builder = get_graph_builder()
1236
+ built_relationships = builder.build(request, result.relationships)
1237
+
1238
+ episode = session.get(Episode, episode_id)
1239
+ if episode is not None and episode.deleted_at is not None:
1240
+ # Forgotten while the builder ran: whatever it just stored goes too.
1241
+ forget_built_graph(
1242
+ session,
1243
+ organization_id=request.organization_id,
1244
+ workspace_id=request.workspace_id,
1245
+ source_ids=[episode.id],
1246
+ episode_ids=[graphiti_episode_id(episode.id, request.content_fingerprint)],
1247
+ )
1248
+ session.commit()
1249
+ return
1250
+ if episode is None or episode.enrichment_status == "complete":
1251
+ return
1252
+ if episode.content_hash != request.content_fingerprint:
1253
+ return
1254
+ confidence, metadata = apply_memory_safety(
1255
+ episode.content,
1256
+ result.confidence,
1257
+ {
1258
+ "derived_from_episode": True,
1259
+ **(
1260
+ {"provenance": episode.extra["provenance"]}
1261
+ if isinstance(episode.extra.get("provenance"), dict)
1262
+ else {}
1263
+ ),
1264
+ "capture_source_trust": _episode_trust(episode),
1265
+ },
1266
+ )
1267
+ memory = Memory(
1268
+ episode_id=episode.id,
1269
+ organization_id=episode.organization_id,
1270
+ workspace_id=episode.workspace_id,
1271
+ project_ref=episode.project_ref,
1272
+ task_ref=episode.task_ref,
1273
+ run_ref=episode.run_ref,
1274
+ owner_principal_id=episode.owner_principal_id,
1275
+ subject=subject,
1276
+ content=episode.content,
1277
+ memory_type=result.memory_type,
1278
+ sensitivity=_highest_sensitivity(episode.sensitivity, result.sensitivity),
1279
+ confidence=confidence,
1280
+ valid_from=episode.occurred_at,
1281
+ metadata_=metadata,
1282
+ )
1283
+ session.add(memory)
1284
+ # The episode holds the same text, so it must be at least as hard to read:
1285
+ # otherwise GET /v1/episodes serves what classification just restricted.
1286
+ episode.sensitivity = memory.sensitivity
1287
+ session.flush()
1288
+ from albert.models import CaptureCheckpoint, CaptureEvent
1289
+
1290
+ session.query(CaptureEvent).filter(CaptureEvent.episode_id == episode.id).update(
1291
+ {CaptureEvent.derived_memory_id: memory.id}, synchronize_session=False
1292
+ )
1293
+ session.query(CaptureCheckpoint).filter(CaptureCheckpoint.episode_id == episode.id).update(
1294
+ {CaptureCheckpoint.derived_memory_id: memory.id}, synchronize_session=False
1295
+ )
1296
+ index_memory_chunks(session, memory)
1297
+ with span("write_edges") as edges_span:
1298
+ closed, written = _apply_built_relationships(
1299
+ session,
1300
+ built_relationships,
1301
+ organization_id=episode.organization_id,
1302
+ workspace_id=episode.workspace_id,
1303
+ source_memory_id=memory.id,
1304
+ sensitivity=memory.sensitivity,
1305
+ extra_metadata={"episode_id": str(episode.id)},
1306
+ at=utcnow(),
1307
+ )
1308
+ edges_span.set(
1309
+ edges_closed=closed,
1310
+ edges_written=written,
1311
+ memory_id=str(memory.id),
1312
+ builder=builder.name,
1313
+ )
1314
+ refresh_links_for_memory(session, memory)
1315
+ episode.enrichment_status = "complete"
1316
+ episode.enrichment_error = None