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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
"""Tenant-namespaced long-term memory on Postgres, compatible with LangGraph's ``BaseStore``.



Namespaces always start with ``("tenant", <tenant_id>)``, e.g.

``("tenant", t, "customer", <customer_id>)``, ``("tenant", t, "prefs")`` or

``("tenant", t, "cases", "support")`` (episodic memory).



Isolation is enforced twice:



* by **RLS**: every query runs in a session bound to one tenant (``app.tenant_id``) and

  ``memory_items`` has ``FORCE ROW LEVEL SECURITY``; a row of another tenant is invisible

  and cannot be written, whatever the namespace says;

* by the store: a ``TenantMemoryStore`` is bound to one tenant at construction and refuses

  any namespace outside ``("tenant", <its tenant>)`` (a mismatch is a bug or an attack,

  never a lookup into another tenant).



Every write goes through ``core.memory.secure.prepare_write`` (lint, redaction, size cap,

expiry, checksum); every read verifies the checksum and skips expired rows.

"""

from __future__ import annotations

import logging
import uuid
from collections.abc import Iterable, Sequence
from datetime import UTC, datetime
from typing import Any

from langgraph.store.base import (
    BaseStore,
    GetOp,
    InvalidNamespaceError,
    Item,
    ListNamespacesOp,
    Op,
    PutOp,
    Result,
    SearchItem,
    SearchOp,
)
from sqlalchemy import delete, literal_column, or_, select
from sqlalchemy.dialects.postgresql import insert
from sqlalchemy.ext.asyncio import AsyncSession

from core.db.session import Database
from core.memory.models import MemoryItem
from core.memory.secure import (
    MemoryIntegrityError,
    MemoryPolicy,
    prepare_write,
    verify,
)
from core.tools.search import Embedder, HashingEmbedder

log = logging.getLogger(__name__)

KINDS = {"customer": "customer", "prefs": "prefs", "cases": "case"}
MAX_SCAN = 1000  # list_namespaces scans at most this many distinct namespaces


class NamespaceDenied(PermissionError):
    """A namespace outside the store's tenant."""


def tenant_prefix(tenant_id: uuid.UUID) -> tuple[str, str]:
    return ("tenant", str(tenant_id))


def customer_ns(tenant_id: uuid.UUID, customer_id: str) -> tuple[str, ...]:
    return (*tenant_prefix(tenant_id), "customer", str(customer_id))


def prefs_ns(tenant_id: uuid.UUID) -> tuple[str, ...]:
    return (*tenant_prefix(tenant_id), "prefs")


def cases_ns(tenant_id: uuid.UUID, topic: str) -> tuple[str, ...]:
    return (*tenant_prefix(tenant_id), "cases", topic)


def ns_text(namespace: Sequence[str]) -> str:
    return ".".join(namespace)


def _labels_ok(namespace: Sequence[str]) -> None:
    for label in namespace:
        if not isinstance(label, str) or not label or "." in label or "\x00" in label:
            raise InvalidNamespaceError(f"invalid namespace label {label!r} in {namespace}")


def check_namespace(

    tenant_id: uuid.UUID, namespace: Sequence[str], *, prefix: bool = False

) -> None:
    """Raise unless ``namespace`` lies inside this tenant's root. With ``prefix=True`` the

    tenant root itself (``("tenant", t)``) is allowed, for searches."""
    ns = tuple(namespace)
    _labels_ok(ns)
    root = tenant_prefix(tenant_id)
    if ns[:2] != root or (len(ns) == 2 and not prefix):
        raise NamespaceDenied(f"namespace {ns} is outside tenant {tenant_id}")


def kind_of(namespace: Sequence[str]) -> str:
    return KINDS.get(namespace[2], "other") if len(namespace) > 2 else "other"


def _index_text(value: dict[str, Any], index: Any) -> str | None:
    """``index=False``: not searchable; a list of field names: those fields; default: every

    string in the value."""
    if index is False:
        return None
    fields = list(index) if isinstance(index, list | tuple) else None
    parts: list[str] = []

    def walk(v: Any) -> None:
        if isinstance(v, str):
            parts.append(v)
        elif isinstance(v, dict):
            for x in v.values():
                walk(x)
        elif isinstance(v, list | tuple):
            for x in v:
                walk(x)

    if fields is not None:
        for f in fields:
            walk(value.get(f))
    else:
        walk(value)
    text = " ".join(parts).strip()
    return text or None


def _embedder_name(e: Embedder) -> str:
    return str(getattr(e, "name", type(e).__name__))


class MemoryRepo:
    """Session-level operations (the caller's session is already bound to ``tenant_id``)."""

    def __init__(self, embedder: Embedder | None = None, policy: MemoryPolicy | None = None):
        self.embedder = embedder or HashingEmbedder()
        self._policy = policy

    @property
    def policy(self) -> MemoryPolicy:
        return self._policy or MemoryPolicy.from_settings()

    async def put(

        self,

        s: AsyncSession,

        tenant_id: uuid.UUID,

        namespace: Sequence[str],

        key: str,

        value: dict[str, Any],

        *,

        ttl_minutes: float | None = None,

        index: Any = None,

        actor: str = "system",

    ) -> Item:
        ns = tuple(namespace)
        check_namespace(tenant_id, ns)
        if not key or len(key) > 200:
            raise ValueError("key must be 1-200 characters")
        w = prepare_write(ns, key, value, ttl_minutes=ttl_minutes, policy=self.policy)
        text = _index_text(w.value, index)
        embedding = self.embedder.embed(text) if text else None
        now = datetime.now(UTC)
        values = {
            "tenant_id": tenant_id,
            "namespace": ns_text(ns),
            "key": key,
            "kind": kind_of(ns),
            "value": w.value,
            "checksum": w.checksum,
            "size_bytes": w.size_bytes,
            "embedding": embedding,
            "embed_model": _embedder_name(self.embedder) if embedding else None,
            "written_by": actor[:120],
            "updated_at": now,
            "expires_at": w.expires_at,
        }
        ins = insert(MemoryItem).values(id=uuid.uuid4(), created_at=now, **values)
        stmt = ins.on_conflict_do_update(
            index_elements=["tenant_id", "namespace", "key"],
            set_={k: v for k, v in values.items() if k not in ("tenant_id", "namespace", "key")},
        ).returning(MemoryItem.created_at)
        created = (await s.execute(stmt)).scalar_one()
        return Item(value=w.value, key=key, namespace=ns, created_at=created, updated_at=now)

    @staticmethod
    def _to_item(row: MemoryItem, score: float | None = None) -> Item | None:
        ns = tuple(row.namespace.split("."))
        try:
            verify(ns, row.key, row.value, row.checksum)
        except MemoryIntegrityError:
            log.warning("memory item %s failed its checksum; not returned", row.id)
            return None
        if score is not None:
            return SearchItem(
                namespace=ns,
                key=row.key,
                value=row.value,
                created_at=row.created_at,
                updated_at=row.updated_at,
                score=score,
            )
        return Item(
            value=row.value,
            key=row.key,
            namespace=ns,
            created_at=row.created_at,
            updated_at=row.updated_at,
        )

    async def get(

        self, s: AsyncSession, tenant_id: uuid.UUID, namespace: Sequence[str], key: str

    ) -> Item | None:
        ns = tuple(namespace)
        check_namespace(tenant_id, ns)
        row = (
            await s.execute(
                select(MemoryItem).where(
                    MemoryItem.namespace == ns_text(ns),
                    MemoryItem.key == key,
                    MemoryItem.expires_at > datetime.now(UTC),
                )
            )
        ).scalar_one_or_none()
        return None if row is None else self._to_item(row)

    async def delete(

        self, s: AsyncSession, tenant_id: uuid.UUID, namespace: Sequence[str], key: str

    ) -> bool:
        ns = tuple(namespace)
        check_namespace(tenant_id, ns)
        res = await s.execute(
            delete(MemoryItem)
            .where(MemoryItem.namespace == ns_text(ns), MemoryItem.key == key)
            .returning(MemoryItem.id)
        )
        return res.first() is not None

    @staticmethod
    def _prefix_clause(prefix: Sequence[str]) -> Any:
        text = ns_text(prefix)
        escaped = text.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
        return or_(MemoryItem.namespace == text, MemoryItem.namespace.like(f"{escaped}.%"))

    async def search(

        self,

        s: AsyncSession,

        tenant_id: uuid.UUID,

        prefix: Sequence[str],

        *,

        query: str | None = None,

        filter: dict[str, Any] | None = None,

        limit: int = 10,

        offset: int = 0,

    ) -> list[SearchItem]:
        ns = tuple(prefix)
        check_namespace(tenant_id, ns, prefix=True)
        q = select(MemoryItem).where(
            self._prefix_clause(ns), MemoryItem.expires_at > datetime.now(UTC)
        )
        if filter:
            q = q.where(MemoryItem.value.contains(filter))
        if query:
            qvec = self.embedder.embed(query)
            score = (literal_column("1") - MemoryItem.embedding.cosine_distance(qvec)).label(
                "score"
            )
            q = (
                q.add_columns(score)
                .where(MemoryItem.embed_model == _embedder_name(self.embedder))
                .order_by(score.desc())
            )
        else:
            q = q.add_columns(literal_column("NULL").label("score")).order_by(
                MemoryItem.updated_at.desc()
            )
        rows = (await s.execute(q.limit(max(1, min(limit, 100))).offset(max(0, offset)))).all()
        out: list[SearchItem] = []
        for row, sc in rows:  # type: ignore[misc]
            item = self._to_item(row, score=float(sc) if sc is not None else 0.0)
            if isinstance(item, SearchItem):
                out.append(item)
        return out

    async def list_items(

        self,

        s: AsyncSession,

        tenant_id: uuid.UUID,

        prefix: Sequence[str],

        *,

        limit: int = 200,

    ) -> list[tuple[MemoryItem, bool]]:
        """Rows under ``prefix`` with their integrity flag (admin inspection, privacy)."""
        ns = tuple(prefix)
        check_namespace(tenant_id, ns, prefix=True)
        rows = (
            await s.execute(
                select(MemoryItem)
                .where(self._prefix_clause(ns), MemoryItem.expires_at > datetime.now(UTC))
                .order_by(MemoryItem.updated_at.desc())
                .limit(limit)
            )
        ).scalars()
        out: list[tuple[MemoryItem, bool]] = []
        for r in rows:
            try:
                verify(tuple(r.namespace.split(".")), r.key, r.value, r.checksum)
                ok = True
            except MemoryIntegrityError:
                ok = False
            out.append((r, ok))
        return out

    async def purge(self, s: AsyncSession, tenant_id: uuid.UUID, prefix: Sequence[str]) -> int:
        """Delete every item under ``prefix`` (e.g. a customer's memory, on request)."""
        ns = tuple(prefix)
        check_namespace(tenant_id, ns, prefix=True)
        res = await s.execute(
            delete(MemoryItem).where(self._prefix_clause(ns)).returning(MemoryItem.id)
        )
        return len(res.all())

    @staticmethod
    async def purge_expired(s: AsyncSession) -> int:
        res = await s.execute(
            delete(MemoryItem)
            .where(MemoryItem.expires_at <= datetime.now(UTC))
            .returning(MemoryItem.id)
        )
        return len(res.all())

    async def list_namespaces(

        self,

        s: AsyncSession,

        tenant_id: uuid.UUID,

        *,

        prefix: Sequence[str] | None = None,

        suffix: Sequence[str] | None = None,

        max_depth: int | None = None,

        limit: int = 100,

        offset: int = 0,

    ) -> list[tuple[str, ...]]:
        rows = (
            await s.execute(
                select(MemoryItem.namespace)
                .where(MemoryItem.expires_at > datetime.now(UTC))
                .distinct()
                .limit(MAX_SCAN)
            )
        ).scalars()
        found: set[tuple[str, ...]] = set()
        for text in rows:
            ns = tuple(text.split("."))
            if prefix is not None and not _match(ns, tuple(prefix), at_start=True):
                continue
            if suffix is not None and not _match(ns, tuple(suffix), at_start=False):
                continue
            found.add(ns[:max_depth] if max_depth is not None else ns)
        return sorted(found)[offset : offset + limit]


def _match(ns: tuple[str, ...], path: tuple[str, ...], *, at_start: bool) -> bool:
    if len(path) > len(ns):
        return False
    part = ns[: len(path)] if at_start else ns[len(ns) - len(path) :]
    return all(p == "*" or p == n for p, n in zip(path, part, strict=True))


class TenantMemoryStore(BaseStore):
    """LangGraph ``BaseStore`` bound to one tenant (async API only)."""

    supports_ttl = True

    def __init__(

        self, db: Database, tenant_id: uuid.UUID, repo: MemoryRepo, *, actor: str = "system"

    ) -> None:
        self.db = db
        self.tenant_id = tenant_id
        self.repo = repo
        self.actor = actor

    def batch(self, ops: Iterable[Op]) -> list[Result]:
        raise NotImplementedError("TenantMemoryStore is async-only; use abatch / a* methods")

    async def abatch(self, ops: Iterable[Op]) -> list[Result]:
        results: list[Result] = []
        t = self.tenant_id
        async with self.db.session(tenant_id=t) as s, s.begin():
            for op in ops:
                if isinstance(op, GetOp):
                    results.append(await self.repo.get(s, t, op.namespace, op.key))
                elif isinstance(op, PutOp):
                    if op.value is None:
                        await self.repo.delete(s, t, op.namespace, op.key)
                    else:
                        await self.repo.put(
                            s,
                            t,
                            op.namespace,
                            op.key,
                            dict(op.value),
                            ttl_minutes=op.ttl,
                            index=op.index,
                            actor=self.actor,
                        )
                    results.append(None)
                elif isinstance(op, SearchOp):
                    results.append(
                        await self.repo.search(
                            s,
                            t,
                            op.namespace_prefix,
                            query=op.query,
                            filter=op.filter,
                            limit=op.limit,
                            offset=op.offset,
                        )
                    )
                elif isinstance(op, ListNamespacesOp):
                    prefix = suffix = None
                    for c in op.match_conditions or ():
                        if c.match_type == "prefix":
                            prefix = tuple(c.path)
                        else:
                            suffix = tuple(c.path)
                    root = tenant_prefix(t)
                    if prefix is None or len(prefix) < 2:
                        prefix = root
                    check_namespace(t, tuple(prefix[:2]), prefix=True)
                    results.append(
                        await self.repo.list_namespaces(
                            s,
                            t,
                            prefix=prefix,
                            suffix=suffix,
                            max_depth=op.max_depth,
                            limit=op.limit,
                            offset=op.offset,
                        )
                    )
                else:  # pragma: no cover - future op types
                    raise NotImplementedError(f"unsupported store op {type(op).__name__}")
        return results


class MemoryStores:
    """Factory: one tenant-bound store per tenant, sharing a repo (embedder + policy)."""

    def __init__(self, db: Database, repo: MemoryRepo | None = None) -> None:
        self.db = db
        self.repo = repo or MemoryRepo()

    def for_tenant(self, tenant_id: uuid.UUID, *, actor: str = "system") -> TenantMemoryStore:
        return TenantMemoryStore(self.db, tenant_id, self.repo, actor=actor)