data-analytics-agent-memory 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,114 @@
1
+ """Privacy classification and redaction for durable agent memory."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from dataclasses import asdict, dataclass, field
7
+ from typing import Any
8
+
9
+
10
+ @dataclass(frozen=True)
11
+ class PrivacyPolicy:
12
+ redact_pii: bool = True
13
+ block_secrets: bool = True
14
+ allowed_pii_keys: set[str] = field(default_factory=set)
15
+
16
+
17
+ @dataclass
18
+ class PrivacyReport:
19
+ privacy_level: str
20
+ findings: list[dict[str, Any]] = field(default_factory=list)
21
+ blocked: bool = False
22
+ reasons: list[str] = field(default_factory=list)
23
+
24
+ def to_dict(self) -> dict[str, Any]:
25
+ return asdict(self)
26
+
27
+
28
+ SECRET_PATTERN = re.compile(
29
+ r"(?i)\b(api[_-]?key|access[_-]?token|refresh[_-]?token|password|passwd|secret|bearer|private[_-]?key)\b\s*[:=]\s*([^\s,;]+)"
30
+ )
31
+ EMAIL_PATTERN = re.compile(r"\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b", re.I)
32
+ SSN_PATTERN = re.compile(r"\b\d{3}-\d{2}-\d{4}\b")
33
+ PHONE_PATTERN = re.compile(r"(?<!\d)(?:\+?1[-.\s]?)?(?:\(?\d{3}\)?[-.\s]?)\d{3}[-.\s]?\d{4}(?!\d)")
34
+ CARD_PATTERN = re.compile(r"\b(?:\d[ -]*?){13,19}\b")
35
+
36
+
37
+ class PrivacyGuard:
38
+ """Classify and redact sensitive memory before it is stored."""
39
+
40
+ def __init__(self, policy: PrivacyPolicy | None = None) -> None:
41
+ self.policy = policy or PrivacyPolicy()
42
+
43
+ def inspect(self, value: Any) -> PrivacyReport:
44
+ findings = _find_sensitive(value)
45
+ blocked = self.policy.block_secrets and any(item["kind"] == "secret" for item in findings)
46
+ privacy_level = "restricted" if any(item["kind"] == "secret" for item in findings) else "sensitive" if findings else "internal"
47
+ reasons = ["Secret-like value was detected."] if blocked else []
48
+ return PrivacyReport(privacy_level=privacy_level, findings=findings, blocked=blocked, reasons=reasons)
49
+
50
+ def scrub(self, value: Any) -> Any:
51
+ return redact_sensitive(value, redact_pii=self.policy.redact_pii,
52
+ allowed_pii_keys=self.policy.allowed_pii_keys)
53
+
54
+
55
+ def redact_sensitive(value: Any, *, redact_pii: bool = True, allowed_pii_keys: set[str] | None = None) -> Any:
56
+ if isinstance(value, dict):
57
+ return {key: redact_sensitive(item, redact_pii=redact_pii and key not in (allowed_pii_keys or set()),
58
+ allowed_pii_keys=allowed_pii_keys) for key, item in value.items()}
59
+ if isinstance(value, list):
60
+ return [redact_sensitive(item, redact_pii=redact_pii, allowed_pii_keys=allowed_pii_keys) for item in value]
61
+ if not isinstance(value, str):
62
+ return value
63
+ redacted = SECRET_PATTERN.sub(r"\1=[REDACTED]", value)
64
+ if not redact_pii:
65
+ return redacted
66
+ redacted = EMAIL_PATTERN.sub("[REDACTED_EMAIL]", redacted)
67
+ redacted = SSN_PATTERN.sub("[REDACTED_SSN]", redacted)
68
+ redacted = PHONE_PATTERN.sub("[REDACTED_PHONE]", redacted)
69
+ return CARD_PATTERN.sub(_redact_card_match, redacted)
70
+
71
+
72
+ def _find_sensitive(value: Any, *, path: str = "$") -> list[dict[str, Any]]:
73
+ findings: list[dict[str, Any]] = []
74
+ if isinstance(value, dict):
75
+ for key, item in value.items():
76
+ findings.extend(_find_sensitive(item, path=f"{path}.{key}"))
77
+ return findings
78
+ if isinstance(value, list):
79
+ for index, item in enumerate(value):
80
+ findings.extend(_find_sensitive(item, path=f"{path}[{index}]"))
81
+ return findings
82
+ if not isinstance(value, str):
83
+ return findings
84
+ for pattern, kind in (
85
+ (SECRET_PATTERN, "secret"),
86
+ (EMAIL_PATTERN, "email"),
87
+ (SSN_PATTERN, "ssn"),
88
+ (PHONE_PATTERN, "phone"),
89
+ ):
90
+ if pattern.search(value):
91
+ findings.append({"kind": kind, "path": path})
92
+ if any(_valid_luhn(candidate) for candidate in CARD_PATTERN.findall(value)):
93
+ findings.append({"kind": "payment_card", "path": path})
94
+ return findings
95
+
96
+
97
+ def _redact_card_match(match: re.Match[str]) -> str:
98
+ value = match.group(0)
99
+ return "[REDACTED_CARD]" if _valid_luhn(value) else value
100
+
101
+
102
+ def _valid_luhn(value: str) -> bool:
103
+ digits = [int(char) for char in re.sub(r"\D", "", value)]
104
+ if len(digits) < 13:
105
+ return False
106
+ checksum = 0
107
+ parity = len(digits) % 2
108
+ for index, digit in enumerate(digits):
109
+ if index % 2 == parity:
110
+ digit *= 2
111
+ if digit > 9:
112
+ digit -= 9
113
+ checksum += digit
114
+ return checksum % 10 == 0
agent_memory/rag.py ADDED
@@ -0,0 +1,196 @@
1
+ """RAG-specific validation and source freshness utilities."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import asdict, dataclass, field
6
+ from typing import Any, Mapping
7
+
8
+ from .models import MemoryConflict, MemoryRecord
9
+
10
+
11
+ @dataclass(frozen=True)
12
+ class RAGSourceReference:
13
+ """Canonical source identity for a RAG citation or retrieved chunk."""
14
+
15
+ document_id: str
16
+ chunk_id: str | None = None
17
+ uri: str | None = None
18
+ title: str | None = None
19
+ source_hash: str | None = None
20
+ chunk_hash: str | None = None
21
+ version: str | None = None
22
+ updated_at: str | None = None
23
+ citation: str | None = None
24
+ page_start: int | None = None
25
+ page_end: int | None = None
26
+ section: str | None = None
27
+ metadata: dict[str, Any] = field(default_factory=dict)
28
+
29
+ @property
30
+ def key(self) -> str:
31
+ return f"{self.document_id}:{self.chunk_id}" if self.chunk_id else self.document_id
32
+
33
+ def to_dict(self) -> dict[str, Any]:
34
+ return {key: value for key, value in asdict(self).items() if value not in (None, "", {})}
35
+
36
+ @classmethod
37
+ def from_dict(cls, value: Mapping[str, Any]) -> "RAGSourceReference":
38
+ source_hash = value.get("source_hash") or value.get("content_hash")
39
+ return cls(
40
+ document_id=str(value.get("document_id") or ""),
41
+ chunk_id=str(value.get("chunk_id")) if value.get("chunk_id") not in (None, "") else None,
42
+ uri=str(value.get("uri")) if value.get("uri") not in (None, "") else None,
43
+ title=str(value.get("title")) if value.get("title") not in (None, "") else None,
44
+ source_hash=str(source_hash) if source_hash not in (None, "") else None,
45
+ chunk_hash=str(value.get("chunk_hash")) if value.get("chunk_hash") not in (None, "") else None,
46
+ version=str(value.get("version")) if value.get("version") not in (None, "") else None,
47
+ updated_at=str(value.get("updated_at")) if value.get("updated_at") not in (None, "") else None,
48
+ citation=str(value.get("citation")) if value.get("citation") not in (None, "") else None,
49
+ page_start=_optional_int(value.get("page_start") or value.get("page") or value.get("page_number")),
50
+ page_end=_optional_int(value.get("page_end") or value.get("page") or value.get("page_number")),
51
+ section=str(value.get("section")) if value.get("section") not in (None, "") else None,
52
+ metadata=dict(value.get("metadata") or {}),
53
+ )
54
+
55
+
56
+ class RAGEvidenceValidator:
57
+ """Validate that RAG memories can be traced back to concrete source chunks."""
58
+
59
+ def validate(self, record: MemoryRecord) -> dict[str, Any]:
60
+ refs = [_source_ref(ref) for ref in record.evidence_refs if _is_document_ref(ref)]
61
+ errors: list[str] = []
62
+ warnings: list[str] = []
63
+ checks = {
64
+ "is_rag_memory": record.memory_type == "rag_retrieval_memory",
65
+ "source_grounded": record.trust_level == "source_grounded",
66
+ "has_document_evidence": bool(refs),
67
+ "has_claim": bool(str(record.value.get("claim") or record.summary).strip()),
68
+ }
69
+ if record.memory_type == "rag_retrieval_memory" and record.key == "claim_to_source":
70
+ for name, passed in checks.items():
71
+ if not passed:
72
+ errors.append(name)
73
+ for index, ref in enumerate(refs):
74
+ if not ref.document_id:
75
+ errors.append(f"evidence_refs[{index}].document_id")
76
+ if not ref.chunk_id:
77
+ errors.append(f"evidence_refs[{index}].chunk_id")
78
+ if not ref.citation and not ref.uri:
79
+ warnings.append(f"evidence_refs[{index}] should include citation or uri")
80
+ if not ref.source_hash and not ref.chunk_hash and not ref.version:
81
+ warnings.append(f"evidence_refs[{index}] should include source_hash, chunk_hash, or version")
82
+ return {
83
+ "status": "passed" if not errors else "failed",
84
+ "passed": not errors,
85
+ "checks": checks,
86
+ "errors": list(dict.fromkeys(errors)),
87
+ "warnings": list(dict.fromkeys(warnings)),
88
+ "source_refs": [ref.to_dict() for ref in refs],
89
+ }
90
+
91
+ def validate_many(self, records: list[MemoryRecord]) -> dict[str, Any]:
92
+ results = [self.validate(record) for record in records]
93
+ return {
94
+ "status": "passed" if all(item["passed"] for item in results) else "failed",
95
+ "passed": all(item["passed"] for item in results),
96
+ "records": results,
97
+ }
98
+
99
+
100
+ class RAGFreshnessChecker:
101
+ """Compare remembered citations with the current source catalog."""
102
+
103
+ def check(
104
+ self,
105
+ memories: list[MemoryRecord],
106
+ current_sources: Mapping[str, Mapping[str, Any]],
107
+ ) -> dict[str, Any]:
108
+ conflicts: list[MemoryConflict] = []
109
+ checked_refs: list[dict[str, Any]] = []
110
+ for record in memories:
111
+ for ref_value in record.evidence_refs:
112
+ if not _is_document_ref(ref_value):
113
+ continue
114
+ ref = _source_ref(ref_value)
115
+ if not ref.document_id:
116
+ continue
117
+ current = _lookup_current_source(current_sources, ref)
118
+ checked_refs.append({"memory_id": record.memory_id, **ref.to_dict(), "current_found": bool(current)})
119
+ if not current:
120
+ conflicts.append(MemoryConflict(
121
+ record.memory_id,
122
+ "source",
123
+ "medium",
124
+ "Remembered source is missing from the current source catalog.",
125
+ current_value=None,
126
+ memory_value=ref.to_dict(),
127
+ ))
128
+ continue
129
+ for field in ("source_hash", "chunk_hash", "version"):
130
+ remembered = getattr(ref, field)
131
+ current_value = current.get(field) or (current.get("content_hash") if field == "source_hash" else None)
132
+ if remembered and current_value and str(remembered) != str(current_value):
133
+ conflicts.append(MemoryConflict(
134
+ record.memory_id,
135
+ field,
136
+ "high" if field.endswith("hash") else "medium",
137
+ f"Remembered RAG source {field} does not match current source evidence.",
138
+ current_value=current_value,
139
+ memory_value=remembered,
140
+ ))
141
+ return {
142
+ "status": "stale_or_conflicting" if conflicts else "fresh",
143
+ "checked_ref_count": len(checked_refs),
144
+ "checked_refs": checked_refs,
145
+ "conflicts": [conflict.to_dict() for conflict in conflicts],
146
+ }
147
+
148
+
149
+ def build_source_manifest(records: list[dict[str, Any] | MemoryRecord]) -> list[dict[str, Any]]:
150
+ """Return unique source refs for included RAG memories."""
151
+
152
+ seen: set[str] = set()
153
+ manifest: list[dict[str, Any]] = []
154
+ for item in records:
155
+ evidence_refs = item.evidence_refs if isinstance(item, MemoryRecord) else item.get("evidence_refs", [])
156
+ for ref_value in evidence_refs or []:
157
+ if not _is_document_ref(ref_value):
158
+ continue
159
+ ref = _source_ref(ref_value)
160
+ if not ref.document_id or ref.key in seen:
161
+ continue
162
+ seen.add(ref.key)
163
+ manifest.append(ref.to_dict())
164
+ return manifest
165
+
166
+
167
+ def _source_ref(value: Mapping[str, Any]) -> RAGSourceReference:
168
+ return RAGSourceReference.from_dict(value)
169
+
170
+
171
+ def _optional_int(value: Any) -> int | None:
172
+ if value in (None, ""):
173
+ return None
174
+ try:
175
+ return int(value)
176
+ except (TypeError, ValueError):
177
+ return None
178
+
179
+
180
+ def _is_document_ref(value: Any) -> bool:
181
+ return isinstance(value, Mapping) and (
182
+ value.get("type") == "document_chunk" or bool(value.get("document_id"))
183
+ )
184
+
185
+
186
+ def _lookup_current_source(
187
+ current_sources: Mapping[str, Mapping[str, Any]],
188
+ ref: RAGSourceReference,
189
+ ) -> Mapping[str, Any] | None:
190
+ keys = [ref.key, ref.document_id]
191
+ if ref.chunk_id:
192
+ keys.extend([f"{ref.document_id}#{ref.chunk_id}", f"{ref.document_id}/{ref.chunk_id}"])
193
+ for key in keys:
194
+ if key in current_sources:
195
+ return current_sources[key]
196
+ return None
agent_memory/ranker.py ADDED
@@ -0,0 +1,120 @@
1
+ """Memory ranking heuristics."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from datetime import datetime, timezone
6
+
7
+ from .models import MemoryRecord, RankedMemory, RetrievalQuery
8
+
9
+
10
+ TRUST_SCORE = {
11
+ "user_provided": 1.0,
12
+ "source_grounded": 0.92,
13
+ "system_observed": 0.82,
14
+ "inferred": 0.55,
15
+ "stale": 0.2,
16
+ "conflicting": 0.05,
17
+ }
18
+ SCOPE_SCORE = {
19
+ "session": 1.0,
20
+ "project": 0.9,
21
+ "dataset": 0.86,
22
+ "run": 0.78,
23
+ "task": 0.74,
24
+ "user": 0.65,
25
+ "global": 0.45,
26
+ }
27
+
28
+
29
+ class MemoryRanker:
30
+ def rank(self, records: list[MemoryRecord], query: RetrievalQuery) -> list[RankedMemory]:
31
+ ranked = [self.score(record, query) for record in records if record.status == "active"]
32
+ ranked.sort(key=lambda item: item.score, reverse=True)
33
+ return ranked
34
+
35
+ def score(self, record: MemoryRecord, query: RetrievalQuery) -> RankedMemory:
36
+ reasons: list[str] = []
37
+ score = 0.0
38
+ lexical = _lexical_score(query.request, " ".join([record.key, record.summary, " ".join(record.tags)]))
39
+ if lexical:
40
+ reasons.append(f"lexical={lexical:.2f}")
41
+ score += lexical * 3.0
42
+ if record.namespace == query.namespace:
43
+ score += 1.5
44
+ reasons.append("same_namespace")
45
+ if query.scope and record.scope == query.scope:
46
+ score += 1.0
47
+ reasons.append("same_scope")
48
+ score += SCOPE_SCORE.get(record.scope, 0.3)
49
+ score += TRUST_SCORE.get(record.trust_level, 0.4)
50
+ score += max(0.0, min(1.0, record.confidence))
51
+ recency = _recency_score(record.updated_at)
52
+ score += recency
53
+ if recency > 0.5:
54
+ reasons.append("recent")
55
+ if record.trust_level in {"stale", "conflicting"}:
56
+ score -= 2.5
57
+ reasons.append(record.trust_level)
58
+ if record.memory_type == "user_preference":
59
+ score += 0.25
60
+ reasons.append("preference")
61
+ for key in query.keys:
62
+ if key and key == record.key:
63
+ score += 3.0
64
+ reasons.append("exact_key")
65
+ for tag in query.tags:
66
+ if tag in record.tags:
67
+ score += 1.0
68
+ reasons.append(f"tag:{tag}")
69
+ for entity in query.entities:
70
+ if entity.casefold() in (record.summary + " " + str(record.value)).casefold():
71
+ score += 0.75
72
+ reasons.append(f"entity:{entity}")
73
+ haystack = (record.summary + " " + str(record.value) + " " + str(record.evidence_refs)).casefold()
74
+ if record.memory_type == "rag_retrieval_memory":
75
+ score += 0.35
76
+ reasons.append("rag_memory")
77
+ if record.evidence_refs:
78
+ score += 0.35
79
+ reasons.append("evidence_refs")
80
+ if query.require_source_grounded and record.trust_level == "source_grounded":
81
+ score += 0.5
82
+ reasons.append("source_grounded")
83
+ for document_id in query.document_ids:
84
+ if document_id.casefold() in haystack:
85
+ score += 2.0
86
+ reasons.append(f"document:{document_id}")
87
+ for source_hash in query.source_hashes:
88
+ if source_hash.casefold() in haystack:
89
+ score += 1.5
90
+ reasons.append(f"source_hash:{source_hash}")
91
+ return RankedMemory(record, round(score, 4), reasons)
92
+
93
+
94
+ def _lexical_score(request: str, text: str) -> float:
95
+ request_words = {word for word in _words(request) if len(word) > 2}
96
+ text_words = {word for word in _words(text) if len(word) > 2}
97
+ if not request_words or not text_words:
98
+ return 0.0
99
+ return len(request_words & text_words) / len(request_words)
100
+
101
+
102
+ def _words(value: str) -> list[str]:
103
+ import re
104
+
105
+ return re.findall(r"[a-z0-9_]+", value.casefold())
106
+
107
+
108
+ def _recency_score(value: str) -> float:
109
+ try:
110
+ updated = datetime.fromisoformat(value.replace("Z", "+00:00"))
111
+ except ValueError:
112
+ return 0.0
113
+ age_days = max(0.0, (datetime.now(timezone.utc) - updated).total_seconds() / 86400)
114
+ if age_days <= 1:
115
+ return 1.0
116
+ if age_days <= 7:
117
+ return 0.7
118
+ if age_days <= 30:
119
+ return 0.4
120
+ return 0.1
@@ -0,0 +1,213 @@
1
+ """Memory retrieval using exact, scoped, tag, lexical, and artifact signals."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from datetime import UTC, datetime
7
+
8
+ from .models import MemoryRecord, RankedMemory, RetrievalQuery
9
+ from .ranker import MemoryRanker
10
+ from .store import MemoryStore
11
+ from .vector_index import EmbeddingFunction, SQLiteVectorIndex
12
+
13
+
14
+ class MemoryRetriever:
15
+ def __init__(
16
+ self,
17
+ store: MemoryStore,
18
+ ranker: MemoryRanker | None = None,
19
+ *,
20
+ vector_index: SQLiteVectorIndex | None = None,
21
+ embedding_function: EmbeddingFunction | None = None,
22
+ ) -> None:
23
+ self.store = store
24
+ self.ranker = ranker or MemoryRanker()
25
+ self.vector_index = vector_index
26
+ self.embedding_function = embedding_function
27
+
28
+ async def retrieve(self, query: RetrievalQuery) -> tuple[list[RankedMemory], dict[str, object]]:
29
+ for field in ("dataset_id", "run_id"):
30
+ value = getattr(query, field)
31
+ if value is not None and (not isinstance(value, str) or not value.strip()):
32
+ raise ValueError(f"{field} must be a nonempty string or None.")
33
+ candidates: dict[str, MemoryRecord] = {}
34
+ reasons: dict[str, set[str]] = {}
35
+ vector_scores: dict[str, float] = {}
36
+
37
+ def add(records: list[MemoryRecord], reason: str) -> None:
38
+ for record in records:
39
+ if record.status != "active":
40
+ continue
41
+ candidates[record.memory_id] = record
42
+ reasons.setdefault(record.memory_id, set()).add(reason)
43
+
44
+ search_filters = _search_filters(query)
45
+ add(await self.store.search(namespace=query.namespace, limit=query.limit * 3, **search_filters), "namespace")
46
+ if query.scope:
47
+ add(await self.store.search(namespace=query.namespace, scope=query.scope, limit=query.limit * 3, **search_filters), "scope")
48
+ for key in query.keys:
49
+ add(await self.store.search(namespace=query.namespace, key=key, limit=query.limit, **search_filters), f"key:{key}")
50
+ for tag in query.tags:
51
+ add(await self.store.search(namespace=query.namespace, tags=[tag], limit=query.limit, **search_filters), f"tag:{tag}")
52
+ for memory_type in query.memory_types:
53
+ add(await self.store.search(namespace=query.namespace, memory_type=memory_type, limit=query.limit * 2, **search_filters), f"type:{memory_type}")
54
+ for token in _important_terms(query.request):
55
+ add(await self.store.search(namespace=query.namespace, text=token, limit=query.limit, **search_filters), f"lexical:{token}")
56
+ for document_id in query.document_ids:
57
+ add(await self.store.search(namespace=query.namespace, text=document_id, limit=query.limit, **search_filters), f"document:{document_id}")
58
+ for source_hash in query.source_hashes:
59
+ add(await self.store.search(namespace=query.namespace, text=source_hash, limit=query.limit, **search_filters), f"source_hash:{source_hash}")
60
+ for ref in query.artifact_refs + [query.run_id or "", query.dataset_id or "", query.task_id or ""]:
61
+ if ref:
62
+ add(await self.store.search(namespace=query.namespace, text=ref, limit=query.limit, **search_filters), f"ref:{ref}")
63
+ if self.vector_index and self.embedding_function:
64
+ embedding = self.embedding_function(query.request)
65
+ if hasattr(embedding, "__await__"):
66
+ embedding = await embedding
67
+ vector_results = await self.vector_index.search(
68
+ embedding,
69
+ filters=_vector_filters(query),
70
+ limit=query.limit,
71
+ )
72
+ for result in vector_results:
73
+ record = await self.store.get(result.memory_id)
74
+ if record:
75
+ vector_scores[record.memory_id] = result.score
76
+ add([record], f"vector={result.score:.2f}")
77
+ filtered = []
78
+ eligibility_rejections: dict[str, str] = {}
79
+ now = datetime.now(UTC)
80
+ for record in candidates.values():
81
+ reason = _binding_rejection(record, query, now)
82
+ if reason:
83
+ eligibility_rejections[record.memory_id] = reason
84
+ elif _matches_constraints(record, query):
85
+ filtered.append(record)
86
+ ranked = self.ranker.rank(filtered, query)
87
+ for item in ranked:
88
+ vector_score = vector_scores.get(item.record.memory_id)
89
+ if vector_score is not None:
90
+ item.score = round(item.score + (vector_score * 2.0), 4)
91
+ item.reasons.append(f"vector={vector_score:.2f}")
92
+ ranked.sort(key=lambda item: item.score, reverse=True)
93
+ ranked = ranked[: query.limit]
94
+ report = {
95
+ "query": {
96
+ "request": query.request,
97
+ "namespace": query.namespace,
98
+ "scope": query.scope,
99
+ "dataset_id": query.dataset_id,
100
+ "run_id": query.run_id,
101
+ "tenant_id": query.tenant_id,
102
+ "project_id": query.project_id,
103
+ "user_id": query.user_id,
104
+ "keys": query.keys,
105
+ "tags": query.tags,
106
+ "entities": query.entities,
107
+ "artifact_refs": query.artifact_refs,
108
+ "document_ids": query.document_ids,
109
+ "source_hashes": query.source_hashes,
110
+ "memory_types": query.memory_types,
111
+ "require_source_grounded": query.require_source_grounded,
112
+ "min_confidence": query.min_confidence,
113
+ "strict_isolation": query.strict_isolation,
114
+ },
115
+ "candidate_count": len(candidates),
116
+ "filtered_count": len(filtered),
117
+ "eligibility_rejections": eligibility_rejections,
118
+ "retrieval_reasons": {memory_id: sorted(value) for memory_id, value in reasons.items()},
119
+ "returned_ids": [item.record.memory_id for item in ranked],
120
+ }
121
+ return ranked, report
122
+
123
+ def _important_terms(value: str) -> list[str]:
124
+ stop = {"the", "and", "now", "that", "this", "with", "from", "over", "last", "show", "give"}
125
+ words = [word for word in re.findall(r"[a-z0-9_]+", value.casefold()) if len(word) > 2 and word not in stop]
126
+ return list(dict.fromkeys(words))[:8]
127
+
128
+
129
+ def _binding_rejection(record: MemoryRecord, query: RetrievalQuery, now: datetime) -> str | None:
130
+ """Explicit dataset/run requests are eligibility boundaries, never hints.
131
+
132
+ A record's top-level value supplies shared context for each evidence ref.
133
+ Require one coherent binding and reject contradictory explicit identities.
134
+ Text, tags, paths, and identifiers split over unrelated refs are not proof.
135
+ Unbound legacy project recall intentionally retains its mixed scopes.
136
+ This validates metadata, not source bytes or analytical evidence: callers
137
+ must still use their established verifier before publishing an answer.
138
+ """
139
+ wanted = {field: getattr(query, field) for field in ("dataset_id", "run_id")
140
+ if getattr(query, field) is not None}
141
+ if not wanted:
142
+ return None
143
+ if record.trust_level in {"stale", "conflicting"}:
144
+ return "stale_or_conflicting_memory"
145
+ if record.expires_at is not None:
146
+ try:
147
+ expiry = datetime.fromisoformat(record.expires_at.replace("Z", "+00:00"))
148
+ if expiry.tzinfo is None:
149
+ return "invalid_expiry"
150
+ if expiry <= now:
151
+ return "expired_memory"
152
+ except (AttributeError, TypeError, ValueError, OverflowError):
153
+ return "invalid_expiry"
154
+ if not isinstance(record.value, dict) or not isinstance(record.evidence_refs, list):
155
+ return "invalid_identity_metadata"
156
+ value = record.value
157
+ refs = [ref for ref in record.evidence_refs if isinstance(ref, dict)]
158
+ for field, expected in wanted.items():
159
+ observed = [binding[field] for binding in [value, *refs] if field in binding]
160
+ if not observed:
161
+ return f"missing_{field}"
162
+ if any(not isinstance(item, str) or item != expected for item in observed):
163
+ return f"mismatched_{field}"
164
+ bindings = [value, *[{**value, **ref} for ref in refs]]
165
+ if not any(all(binding.get(field) == expected for field, expected in wanted.items())
166
+ for binding in bindings):
167
+ return "incoherent_dataset_run_binding"
168
+ return None
169
+
170
+
171
+ def _matches_constraints(record: MemoryRecord, query: RetrievalQuery) -> bool:
172
+ if query.strict_isolation:
173
+ if query.tenant_id and record.tenant_id != query.tenant_id:
174
+ return False
175
+ if query.project_id and record.project_id != query.project_id:
176
+ return False
177
+ if query.user_id and record.user_id != query.user_id:
178
+ return False
179
+ if query.memory_types and record.memory_type not in query.memory_types:
180
+ return False
181
+ if query.require_source_grounded and record.trust_level != "source_grounded":
182
+ return False
183
+ if query.min_confidence is not None and record.confidence < float(query.min_confidence):
184
+ return False
185
+ haystack = (record.summary + " " + str(record.value) + " " + str(record.evidence_refs)).casefold()
186
+ if query.document_ids and not any(document_id.casefold() in haystack for document_id in query.document_ids):
187
+ return False
188
+ if query.source_hashes and not any(source_hash.casefold() in haystack for source_hash in query.source_hashes):
189
+ return False
190
+ return True
191
+
192
+
193
+ def _search_filters(query: RetrievalQuery) -> dict[str, object]:
194
+ if not query.strict_isolation:
195
+ return {}
196
+ return {
197
+ "tenant_id": query.tenant_id,
198
+ "project_id": query.project_id,
199
+ "user_id": query.user_id,
200
+ }
201
+
202
+
203
+ def _vector_filters(query: RetrievalQuery) -> dict[str, object]:
204
+ filters: dict[str, object] = {"namespace": query.namespace}
205
+ if query.memory_types:
206
+ filters["memory_type"] = query.memory_types
207
+ if query.strict_isolation:
208
+ filters.update({
209
+ "tenant_id": query.tenant_id,
210
+ "project_id": query.project_id,
211
+ "user_id": query.user_id,
212
+ })
213
+ return filters