-
-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathengine.py
More file actions
4828 lines (4613 loc) · 228 KB
/
Copy pathengine.py
File metadata and controls
4828 lines (4613 loc) · 228 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""MemoryEngine — the high-level facade the API/MCP layer calls.
Wires together store + embedder + vector index + reranker + recall engine, and exposes
everything an agent does against memory: write (``remember``, with deterministic conflict
resolution), read (``recall``, ``why``, ``timeline``, ``recall_proactive``), governance
(``retire``, ``secure_erase``, ``pin``, ``correct``), session lifecycle (with cross-session handoff), and the
A-MEM-style linking/event primitives (``link``, ``record_event``). Construct with
``MemoryEngine.create(...)`` for sensible, offline-capable defaults, or inject your own
backends for production.
"""
from __future__ import annotations
import hashlib
import json
import logging
import math
import os
import re
import tempfile
import threading
import time
from collections import defaultdict, deque
from pathlib import Path
from typing import Any, Callable, Optional
import numpy as np
from engraphis.core import scoring
from engraphis.core.adaptive_context import AdaptiveContextResult, fit_recent_history
from engraphis.core.conflicts import detect_conflicts
from engraphis.core.interfaces import (
MemoryRecord,
MemoryType,
FactSpec,
GraphTraversalPolicy,
QueryPlanner,
RetentionDecision,
Scope,
SearchFilter,
embedder_capabilities,
embedding_space_fingerprint,
vector_index_requires_sync,
vector_index_shares_store_transaction,
)
from engraphis.core.poisoning import (
REVIEW_APPROVED,
REVIEW_PENDING,
PoisoningDecision,
apply_quarantine_metadata,
assess_untrusted_payload,
inspection_eligible,
metadata_is_quarantined,
pending_llm_extraction_envelope,
prompt_eligible,
provenance_is_approved,
)
from engraphis.core.recall import RecallEngine, RecallResult
from engraphis.core.retrieval_policy import (
CANDIDATE_DEPTH_MODES,
RETRIEVAL_PROFILES,
)
from engraphis.core.retention_policy import MAX_STABILITY_DAYS, MIN_STABILITY_DAYS
from engraphis.core.resolve import (
CONFLICT_RELATION,
RELATED_SIM_FLOOR,
Resolution,
ResolutionOp,
resolve,
)
from engraphis.core.secrets import reject_secrets
from engraphis.core.store import (
Store,
_is_memory_database_path,
memory_matches_filter,
now_ts,
)
from engraphis.core.textutil import estimate_tokens, jaccard, tokenize
def _safe_upsert(index, ids, vecs, meta=None, *, commit=True):
"""Call ``index.upsert`` with backward-compatible metadata handling.
Older third-party ``VectorIndex`` implementations may predate the optional
``meta`` positional argument and accept only ``(ids, vecs, *, commit)``.
Passing metadata positionally would raise ``TypeError`` and abort engine
creation. This shim tries the full signature first and falls back to the
legacy shape when needed.
"""
try:
index.upsert(ids, vecs, meta, commit=commit)
except TypeError:
try:
index.upsert(ids, vecs, meta)
except TypeError:
try:
index.upsert(ids, vecs, commit=commit)
except TypeError:
index.upsert(ids, vecs)
logger = logging.getLogger("engraphis.core.engine")
_ENGINE_FACTORY: Optional[Callable] = None
def configure_engine_factory(factory: Callable) -> None:
"""Install the outer composition provider used by ``MemoryEngine.create``."""
if not callable(factory):
raise TypeError("engine factory must be callable")
global _ENGINE_FACTORY
_ENGINE_FACTORY = factory
BEST_EFFORT_FAILURE_WARNING_INTERVAL_SECONDS = 60.0
# Sensitivity lattice: a merge keeps the *most restrictive* label of its sources, so
# secret/sensitive content can never be laundered into a lower-sensitivity merged fact.
_SENSITIVITY_RANK = {"normal": 0, "sensitive": 1, "secret": 2}
_SCOPE_RANK = {
Scope.SESSION: 0,
Scope.REPO: 1,
Scope.WORKSPACE: 2,
Scope.USER: 3,
}
_USER_SCOPE_WRITE_ERROR = (
"user scope is not supported until owner-aware memories are implemented; "
"use workspace, repo, or session"
)
# A-MEM-style evolution: how many related neighbors a new memory auto-links to on write.
# Bounded so hub memories don't accrete unbounded link lists (link quality > quantity).
EVOLVE_MAX_LINKS = 3
# Batch writes (remember_many): maximum facts accepted per call. Matches the sync
# APPLY_BATCH ceiling; callers with more facts must chunk. Bounds the pairwise
# evidence-edge scan in _evolve_batch.
MAX_FACTS_PER_BATCH = 500
# The deterministic detector's contradiction/obsolete reports below this severity are
# too weak to justify a durable ``conflicts_with`` relation. The detector floors its
# own reports at 0.74 (numeric) / 0.78 (polarity) / 0.82 (assertion), so this only
# filters out margin-of-error edge cases, keeping the repair trigger conservative.
CONFLICT_MIN_SEVERITY = 0.7
# Deterministic confidence penalty applied to both sides of a persisted conflict
# repair. Bounded and explainable: the ``conflicts_with`` link + audit row make the
# discount auditable, and an explicit human resolution can restore confidence.
CONFLICT_CONFIDENCE_FACTOR = 0.8
# Metadata keys that feed the entity/edge graph under the *trusted*
# provenance.source="structured_extractor" label — i.e. "a configured Extractor produced
# this". See _has_structured_graph_metadata / _trusted_graph_hints.
GRAPH_HINT_KEYS = ("entities", "relations", "structured_extraction")
_INTERNAL_DERIVED_GRAPH_KEY = "unverified_derived_graph"
# Extractors produce these bounded metadata shapes. Everything else in an
# ``ExtractedFact.metadata`` mapping is untrusted extension data and must not
# override the service-owned ingress envelope (notably provenance/quarantine).
EXTRACTOR_METADATA_KEYS = frozenset(
(*GRAPH_HINT_KEYS, "chunking", "llm_extraction", "extraction_fallback")
)
# code↔memory linking (see _CodeSymbolMatcher / _link_memory_to_code)
CODE_LINK_MAX_LINKS = 200 # per-memory fan-out cap (unchanged behaviour)
EMBEDDING_REBUILD_BATCH = 200
CODE_MATCHER_CACHE_SIZE = 4 # compiled matchers kept in memory, keyed by repo
# Alternatives per compiled sub-pattern. One giant alternation risks `re`'s internal
# code-size limit on a big repo, so the alternation is chunked; chunking cannot change
# the result because matches are resolved per *offset*, not per pattern (see below).
CODE_ALTERNATION_CHUNK = 500
# Exactly the `\w` class the per-symbol regexes used for their word boundaries, so the
# compiled-alternation path and the old per-symbol path agree character for character.
_WORD_CHAR_RE = re.compile(r"\w")
# Default payload caps for export_code_graph — mirrors MemoryService.graph(), which caps
# nodes and edges because the export is reachable at the lowest ('viewer') role.
CODE_EXPORT_DEFAULT_LIMIT = 5_000
CODE_TRAVERSAL_DEFAULT_CAPACITY = 10_000
CODE_TRAVERSAL_MAX_CAPACITY = 50_000
def _code_traversal_capacity(value: Any) -> int:
if isinstance(value, bool):
raise ValueError("capacity must be an integer between 1 and 50000")
try:
capacity = int(value)
except (TypeError, ValueError, OverflowError) as exc:
raise ValueError("capacity must be an integer between 1 and 50000") from exc
if capacity < 1 or capacity > CODE_TRAVERSAL_MAX_CAPACITY:
raise ValueError("capacity must be between 1 and 50000")
return capacity
CODE_EXPORT_MAX_LIMIT = 20_000
def _approved_local_index_roots() -> tuple[str, ...]:
"""Return canonical roots available to the explicit local indexing capability.
``ENGRAPHIS_INDEX_ROOTS`` is an operator-owned, path-separator-delimited allow-list.
``ENGRAPHIS_HTTP_INDEX_ROOT`` is a separately configured, single HTTP boundary;
include it here too so the checked path handed off by the HTTP route remains usable
by the engine. Configured paths must be absolute: silently resolving a relative
operator setting against the process working directory would make the boundary
deployment-dependent.
When it is unset, the working directory, home directory, and system temporary
directory preserve the local-first defaults used by ordinary agent/project checkouts.
"""
def canonical_configured_root(value: str, setting: str) -> str:
if not os.path.isabs(value):
raise ValueError(f"{setting} must contain only absolute paths")
return os.path.normcase(os.path.realpath(os.path.expanduser(value)))
configured = [
canonical_configured_root(value.strip(), "ENGRAPHIS_INDEX_ROOTS")
for value in os.environ.get("ENGRAPHIS_INDEX_ROOTS", "").split(os.pathsep)
if value.strip()
]
if configured:
roots = configured
else:
roots = [
os.path.normcase(os.path.realpath(os.getcwd())),
os.path.normcase(os.path.realpath(os.path.expanduser("~"))),
os.path.normcase(os.path.realpath(tempfile.gettempdir())),
]
http_root = os.environ.get("ENGRAPHIS_HTTP_INDEX_ROOT", "").strip()
if http_root:
roots.append(canonical_configured_root(http_root, "ENGRAPHIS_HTTP_INDEX_ROOT"))
return tuple(dict.fromkeys(roots))
def _bounded_finite(value, *, default: float, minimum: float, maximum: float) -> float:
try:
number = float(value)
except (TypeError, ValueError):
return default
if not math.isfinite(number):
return default
return max(minimum, min(maximum, number))
def _rehome_untrusted_graph_hints(metadata: dict,
trusted: Optional[frozenset] = None) -> dict:
"""Strip forged extractor provenance out of a write's metadata.
``GRAPH_HINT_KEYS`` are how a configured ``Extractor`` hands the engine graph hints,
and the engine feeds them into the entity/edge graph tagged
``provenance.source="structured_extractor"``. But ``metadata`` is caller-controlled on
every direct engine path (MCP tool, HTTP route, the sync apply path), and by the time
it reaches ``_resolve_and_store`` a caller's value is indistinguishable from the
extractor's own output — so anyone who can write a memory could mint graph edges
wearing the trusted label for content no extractor ever saw.
Vouching therefore has to be **out of band**. ``ingest()`` alone knows which keys came
from ``ExtractedFact.metadata`` rather than from its own ``metadata`` argument, and
says so through a *keyword argument* — a channel untrusted JSON cannot reach;
``consolidate()`` marks its sweep the same way. No in-band signal would do: every
field a caller can see is a field a caller can set (``metadata["provenance"]["source"]``
included — ``service.remember(source=...)`` writes it verbatim). Every unvouched hint
is re-homed (preserved, never dropped) under a key the structured-graph check does not
recognize, with an honest source label.
``engraphis/service.py::_clean_metadata`` does the same at the service boundary; this
is the defense-in-depth copy for callers that bypass it. Both are idempotent — a value
re-homed at either layer has no hint keys left to relabel at the other.
"""
vouched = trusted or frozenset()
# The deferred review envelope is also internal. A direct caller must not be able
# to pre-seed it and have a genuine LLM activity marker relabel that payload as
# model-derived evidence. Internal producers vouch for it out of band just like
# executable graph hints.
caller_graph_keys = (*GRAPH_HINT_KEYS, _INTERNAL_DERIVED_GRAPH_KEY)
untrusted = [
key for key in caller_graph_keys
if key in metadata and key not in vouched
]
if not untrusted:
return metadata
out = {k: v for k, v in metadata.items() if k not in untrusted}
existing = out.get("client_supplied_graph")
hints = dict(existing) if isinstance(existing, dict) else {}
hints.update({k: metadata[k] for k in untrusted})
hints["source"] = "client_supplied"
out["client_supplied_graph"] = hints
return out
def _required_resolution_target(decision: Resolution) -> str:
"""Return a resolver target only when the selected operation requires one."""
target_id = decision.target_id
if not isinstance(target_id, str) or not target_id:
raise RuntimeError(f"{decision.op.value} resolution requires a target memory id")
return target_id
def _required_memory_workspace_id(record: MemoryRecord) -> str:
"""Defend the persisted workspace invariant at engine-to-engine boundaries."""
workspace_id = record.workspace_id
if not isinstance(workspace_id, str) or not workspace_id:
raise RuntimeError(f"memory {record.id!r} has no workspace id")
return workspace_id
def _governable_source(record: MemoryRecord, *, at: float) -> bool:
"""Accept current truth and quarantined evidence for governed derivations."""
if record.expired_at is not None:
return False
if (
metadata_is_quarantined(record.metadata)
or bool((record.provenance or {}).get("quarantined"))
):
return True
return (
(record.valid_from is None or record.valid_from <= at)
and (record.valid_to is None or record.valid_to > at)
)
def _writable_scope(scope: Scope, repo_id: Optional[str]) -> Scope:
"""The nearest scope ``remember()`` will actually accept for ``repo_id``.
``repo`` scope with no repo (a cross-repo ``merge``, or a record the sync apply path
wrote without going through ``remember``'s validation) is not a storable combination
— ``remember`` raises ``ValueError('repo scope requires repo_id')``. Rewriting it as
``workspace`` keeps the memory reachable instead of failing the whole operation; a
``repo``-scoped row with a NULL ``repo_id`` matches no repo read anyway.
Deliberately narrow: no other scope is rewritten. ``session`` scope without a session
still raises, because silently widening a session-private memory to repo/workspace
visibility is a worse outcome than an explicit error — and with the write now
happening *before* the source is retired, that error is no longer destructive.
"""
return Scope.WORKSPACE if (Scope(scope) == Scope.REPO and not repo_id) else Scope(scope)
class _CodeSymbolMatcher:
"""Precompiled, repo-wide index behind ``MemoryEngine._link_memory_to_code``.
The naive path walked *every* symbol for *every* memory and ran ``re.compile`` twice
per symbol — O(symbols) regex compiles per repo-scoped write, and
O(records × symbols) on every ``index_repo()``, even a one-file incremental change.
This builds the equivalent state once per repo:
* a chunked alternation over every candidate name/fqname, matched against the memory
text in one C-level pass;
* ``name → symbol positions`` and ``token → symbol positions`` inverted indexes, so
only symbols that *can* link are scored.
Two details keep the produced links byte-identical to the old per-symbol loop:
1. The alternation is wrapped in a **zero-width lookahead**. A plain ``finditer``
returns non-overlapping matches, so a long fqname would swallow a shorter name
nested inside it (``engraphis.core.engine`` hides ``engine``) and silently
downgrade that symbol's confidence from 0.9 to the 0.75 token fallback. The
lookahead reports every offset instead, and every candidate length is then tested
at that offset — so overlapping names all still match.
2. Candidate positions are returned **in ``store.list_symbols`` order**, so the
``CODE_LINK_MAX_LINKS`` cutoff keeps the same first-N links.
The 0.75 fallback (``tokenize(name) <= tokenize(text)``) is indexed on each symbol's
*rarest* name token: a subset match implies that token is present, so the candidate
set is complete while staying small.
"""
__slots__ = ("symbols", "_by_len", "_lengths", "_patterns", "_by_name", "_by_token")
def __init__(self, symbols: list) -> None:
self.symbols = symbols
by_len: dict[int, set] = {}
by_name: dict[str, list] = {}
by_token: dict[str, list] = {}
token_freq: dict[str, int] = {}
pending: list[tuple[int, set]] = []
for position, symbol in enumerate(symbols):
name = str(symbol.get("name") or "").strip()
fqname = str(symbol.get("fqname") or "").strip()
if len(name) < 3:
continue # exactly the per-symbol skip in _link_memory_to_code
# fqname first, mirroring the elif-chain's precedence; both gates copy the
# original's length checks on the *pre-lowercase* string.
candidates = ([fqname] if (fqname and len(fqname) >= 3) else []) + [name]
for raw in candidates:
lowered = raw.lower()
if not lowered:
continue
by_len.setdefault(len(lowered), set()).add(lowered)
by_name.setdefault(lowered, []).append(position)
name_tokens = tokenize(name)
if name_tokens:
pending.append((position, name_tokens))
for token in name_tokens:
token_freq[token] = token_freq.get(token, 0) + 1
for position, name_tokens in pending:
key = min(name_tokens, key=lambda token: (token_freq[token], token))
by_token.setdefault(key, []).append(position)
self._by_len = by_len
self._lengths = sorted(by_len, reverse=True)
self._by_name = by_name
self._by_token = by_token
ordered = sorted((s for group in by_len.values() for s in group),
key=lambda s: (-len(s), s))
self._patterns = [
re.compile(r"(?<!\w)(?=(?:"
+ "|".join(re.escape(s) for s in ordered[i:i + CODE_ALTERNATION_CHUNK])
+ r")(?!\w))")
for i in range(0, len(ordered), CODE_ALTERNATION_CHUNK)
]
def match(self, hay_lower: str, hay_tokens: set) -> tuple[set, list]:
"""``(matched lowercase names, candidate symbol positions)`` for one memory."""
matched: set = set()
offsets: set = set()
for pattern in self._patterns:
for hit in pattern.finditer(hay_lower):
offsets.add(hit.start())
size = len(hay_lower)
for offset in offsets:
for length in self._lengths:
end = offset + length
if end > size or (end < size and _WORD_CHAR_RE.match(hay_lower, end)):
continue
candidate = hay_lower[offset:end]
if candidate in self._by_len[length]:
matched.add(candidate)
positions: set = set()
for name in matched:
positions.update(self._by_name.get(name, ()))
for token in hay_tokens:
positions.update(self._by_token.get(token, ()))
return matched, sorted(positions)
class MemoryEngine:
def __init__(
self,
store: Store,
embedder,
vector_index,
reranker=None,
*,
auto_evolve: bool = True,
extractor=None,
graph_extractor=None,
graph_feeder: Optional[Callable] = None,
retention_supervisor=None,
allow_automatic_critical_retention: bool = False,
graph_traversal_policy: Optional[GraphTraversalPolicy] = None,
query_planner: Optional[QueryPlanner] = None,
code_indexer_factory: Optional[Callable] = None,
code_language_detector: Optional[Callable] = None,
code_source_iterator: Optional[Callable] = None,
code_source_policy: Optional[Callable] = None,
code_walk_limit_error=RuntimeError,
) -> None:
self.store = store
self.embedder = embedder
self.embedding_space = embedding_space_fingerprint(embedder)
self.index = vector_index
self.reranker = reranker
self.recall_engine = RecallEngine(
store,
embedder,
vector_index,
reranker,
graph_traversal_policy=graph_traversal_policy,
query_planner=query_planner,
)
# Memory evolution (A-MEM-style): writing a new note also updates
# how its neighbors are connected, so the network improves bidirectionally.
self.auto_evolve = auto_evolve
# Optional implementations are injected by the outer package factory. Core owns
# policy and orchestration, never concrete backend selection.
self.extractor = extractor
self.graph_extractor = graph_extractor
self.graph_feeder = graph_feeder
if graph_extractor is not None and graph_feeder is None:
raise ValueError("graph_extractor requires an injected graph_feeder")
self.retention_supervisor = retention_supervisor
self._code_indexer_factory = code_indexer_factory
self._code_language_detector = code_language_detector
self._code_source_iterator = code_source_iterator
self._code_source_policy = code_source_policy
self._code_walk_limit_error = code_walk_limit_error
# A remote classifier is advisory. It cannot silently grant the long-lived
# "critical" class unless the host deliberately opts into that policy.
self.allow_automatic_critical_retention = bool(
allow_automatic_critical_retention
)
# Serializes the resolve→insert critical section of the write path (see
# remember_with_resolution). RLock: ingest()/import paths may nest writes.
self._write_lock = threading.RLock()
# Best-effort derivations can fail repeatedly while a backend is unavailable.
# Keep their payload-redacted warnings useful without letting one outage flood logs.
self._failure_warning_lock = threading.Lock()
self._failure_warning_last_emitted: dict[str, float] = {}
self._failure_warning_suppressed: dict[str, int] = {}
self._failure_warning_clock = time.monotonic
# repo_id -> (symbol-set fingerprint, _CodeSymbolMatcher). Bounded; see
# _code_matcher for the invalidation contract.
self._code_matchers: dict = {}
self._resource_lock = threading.Lock()
self._owned_resources: tuple[Any, ...] = (store,)
self._closed = False
def _adopt_resources(self, resources: list[Any]) -> None:
"""Take ownership of factory-created collaborators after composition succeeds."""
with self._resource_lock:
if self._closed:
raise RuntimeError("cannot transfer resources to a closed MemoryEngine")
self._owned_resources = tuple(resources)
def close(self) -> None:
"""Close every owned collaborator exactly once, with the Store last."""
with self._resource_lock:
if self._closed:
return
self._closed = True
resources = self._owned_resources
self._owned_resources = ()
first_error: Optional[BaseException] = None
seen: set[int] = set()
for resource in reversed(resources):
identity = id(resource)
if identity in seen:
continue
seen.add(identity)
close = getattr(resource, "close", None)
if not callable(close):
continue
try:
close()
except BaseException as exc:
if first_error is None:
first_error = exc
if first_error is not None:
raise first_error
def _warn_redacted_failure(self, operation: str, exc: Exception) -> None:
"""Log bounded, payload-free warnings for non-fatal derived-work failures."""
now = self._failure_warning_clock()
with self._failure_warning_lock:
last_emitted = self._failure_warning_last_emitted.get(operation)
if (
last_emitted is not None
and now - last_emitted < BEST_EFFORT_FAILURE_WARNING_INTERVAL_SECONDS
):
self._failure_warning_suppressed[operation] = (
self._failure_warning_suppressed.get(operation, 0) + 1
)
return
suppressed = self._failure_warning_suppressed.pop(operation, 0)
self._failure_warning_last_emitted[operation] = now
if suppressed:
logger.warning(
"%s failed (%s); suppressed %d similar failures",
operation,
type(exc).__name__,
suppressed,
)
else:
logger.warning("%s failed (%s)", operation, type(exc).__name__)
@classmethod
def create(
cls,
db_path: str = ":memory:",
*,
embed_model: Optional[str] = None,
embed_revision: Optional[str] = None,
require_immutable_models: Optional[bool] = None,
embed_dim: int = 384,
vector_backend: str = "numpy",
rerank_model: Optional[str] = None,
rerank_revision: Optional[str] = None,
extractor: str = "none",
graph_extractor: str = "none",
retention_supervisor: str = "none",
allow_automatic_critical_retention: bool = False,
auto_evolve: bool = True,
connect=None,
graph_traversal_policy: Optional[GraphTraversalPolicy] = None,
query_planner: Optional[QueryPlanner] = None,
read_only: bool = False,
require_exact_backends: bool = False,
) -> "MemoryEngine":
"""Compose the default engine through the package-level backend provider."""
if _ENGINE_FACTORY is None:
raise RuntimeError(
"no MemoryEngine factory is configured; import the engraphis package "
"or inject dependencies into MemoryEngine directly"
)
return _ENGINE_FACTORY(
engine_cls=cls,
db_path=db_path,
embed_model=embed_model,
embed_revision=embed_revision,
require_immutable_models=require_immutable_models,
embed_dim=embed_dim,
vector_backend=vector_backend,
rerank_model=rerank_model,
rerank_revision=rerank_revision,
extractor=extractor,
graph_extractor=graph_extractor,
retention_supervisor=retention_supervisor,
allow_automatic_critical_retention=allow_automatic_critical_retention,
auto_evolve=auto_evolve,
connect=connect,
graph_traversal_policy=graph_traversal_policy,
query_planner=query_planner,
read_only=read_only,
require_exact_backends=require_exact_backends,
)
def _rebuild_versioned_embeddings(self) -> None:
"""Re-embed records when an opt-in backend changes its vector mapping.
Backends advertise a durable ``embedding_identity`` and ``embedding_version``
only when their stored vectors need this lifecycle. The marker is committed
*after* every eligible record is indexed, so an interrupted rebuild safely
repeats on the next startup rather than leaving a mixed mapping marked current.
Paging covers only records whose canonical vector is missing or stamped with
another fingerprint, so a restart resumes where the previous pass stopped
instead of re-embedding the whole store from scratch.
"""
identity = str(getattr(self.embedder, "embedding_identity", "") or "").strip()
version = str(getattr(self.embedder, "embedding_version", "") or "").strip()
fingerprint = self.embedding_space
if not identity or not version or not fingerprint:
logger.warning(
"embedder has no durable identity/version; persistent vector recall "
"will remain disabled"
)
return
if self.store.embedding_space_ready(fingerprint):
self._hydrate_separate_vector_index(fingerprint)
return
# Guard: never let a degraded/fallback embedder overwrite a semantic space
# that was previously built by a real semantic model. A transient missing
# dependency, model download failure, or provider outage must not
# permanently downgrade semantic recall to lexical hashing.
#
# Legacy markers (e.g. ``"legacy-unverified"``) are excluded: they indicate
# vectors from before proper model tracking, so rebuilding them with the
# current deterministic version is the intended upgrade path — there is no
# semantic information to lose.
active = self.store.active_embedding_space()
if (
active
and active != fingerprint
and active.startswith("emb:v1:")
):
caps = embedder_capabilities(self.embedder)
if caps.get("degraded_mode"):
logger.warning(
"skipping embedding rebuild: active space %s was built by a "
"semantic embedder but the current embedder is degraded (%s); "
"vector recall remains available under the existing space",
active, caps.get("degraded_reason", "unknown"),
)
return
self.store.begin_embedding_rebuild(fingerprint)
rebuilt = 0
removed = 0
after_id = ""
try:
while True:
records = self.store.list_memories_needing_vectors_page(
fingerprint=fingerprint, after_id=after_id,
limit=EMBEDDING_REBUILD_BATCH,
)
if not records:
break
after_id = records[-1].id
eligible = [
record for record in records
if inspection_eligible(record.provenance, record.metadata)
]
excluded_ids = [
record.id for record in records
if not inspection_eligible(record.provenance, record.metadata)
]
vectors = None
ids = []
metadata = []
if eligible:
texts = [
f"{record.title}\n{record.content}" if record.title else record.content
for record in eligible
]
vectors = np.asarray(self.embedder.embed(texts), dtype=np.float32)
if vectors.ndim != 2 or vectors.shape != (
len(eligible), int(self.embedder.dim)):
raise ValueError(
"embedder returned an invalid batch shape during rebuild"
)
if not np.all(np.isfinite(vectors)):
raise ValueError(
"embedder returned non-finite values during rebuild"
)
ids = [record.id for record in eligible]
metadata = [{"model": fingerprint} for _ in eligible]
# Embed outside the database lock, then atomically verify that this
# process still owns the target marker before publishing one batch.
# A competing process can supersede the marker, but the loser cannot
# write vectors or clear the winner's rebuild gate.
self.store.conn.execute("BEGIN IMMEDIATE")
if self.store.embedding_rebuild_target() != fingerprint:
self.store.conn.rollback()
if self.store.embedding_space_ready(fingerprint):
return
raise RuntimeError(
"embedding rebuild was superseded by another process"
)
if excluded_ids:
if vector_index_requires_sync(self.index, self.store):
self.index.delete(excluded_ids, commit=False)
marks = ",".join("?" for _ in excluded_ids)
self.store.conn.execute(
f"DELETE FROM mem_vectors WHERE id IN ({marks})", excluded_ids
)
# Keep the portable mirror current even when the active index is
# sqlite-vec. A later NumPy fallback must see the same vector space.
if vectors is not None:
for record, vector in zip(eligible, vectors):
self.store.put_vector(record.id, vector, model=fingerprint)
if vector_index_requires_sync(self.index, self.store):
_safe_upsert(self.index, ids, vectors, metadata, commit=False)
self.store.conn.commit()
removed += len(excluded_ids)
rebuilt += len(eligible)
self.store.conn.execute("BEGIN IMMEDIATE")
if self.store.embedding_rebuild_target() != fingerprint:
self.store.conn.rollback()
if self.store.embedding_space_ready(fingerprint):
return
raise RuntimeError(
"embedding rebuild was superseded by another process"
)
stale_row = self.store.conn.execute(
"SELECT COUNT(*) AS n FROM mem_vectors "
"WHERE COALESCE(model, '') <> ?",
(fingerprint,),
).fetchone()
stale = int(stale_row["n"]) if stale_row is not None else 0
if stale:
self.store.conn.rollback()
raise RuntimeError(
f"embedding rebuild left {stale} stale vector rows"
)
self.store.finish_embedding_rebuild(
fingerprint, identity=identity, version=version
)
self._mark_separate_vector_index_rebuild_complete()
except BaseException as exc:
if self.store.conn.transaction_owned_by_current_thread():
self.store.conn.rollback()
logger.error(
"embedding rebuild failed; vector recall remains disabled (%s)",
type(exc).__name__,
)
raise
if rebuilt:
self.store.audit(
"system", "embedding_rebuild", identity,
f"version={version}; fingerprint={fingerprint}; "
f"records={rebuilt}; removed={removed}",
)
def _hydrate_separate_vector_index(self, fingerprint: str) -> None:
"""Repair a separate ANN backend from the canonical Store mirror.
Historical/superseded vectors intentionally retained in ``mem_vectors``
for ``valid_at``/``as_of`` recall must also be hydrated into separate
indexes like sqlite-vec. Using ``include_invalid=False`` would omit
closed-but-inspection-eligible memories, making historical semantic
recall through the separate index incomplete until a full rebuild.
"""
if not vector_index_requires_sync(self.index, self.store):
return
ids: list[str] = []
vectors: list[np.ndarray] = []
for memory_id, vector in self.store.iter_vectors(
include_invalid=True, dim=int(self.embedder.dim)):
ids.append(memory_id)
vectors.append(vector)
if len(ids) < EMBEDDING_REBUILD_BATCH:
continue
_safe_upsert(
self.index,
ids, np.asarray(vectors, dtype=np.float32),
[{"model": fingerprint} for _ in ids],
commit=True,
)
ids, vectors = [], []
if ids:
_safe_upsert(
self.index,
ids, np.asarray(vectors, dtype=np.float32),
[{"model": fingerprint} for _ in ids],
commit=True,
)
self._mark_separate_vector_index_rebuild_complete()
def _mark_separate_vector_index_rebuild_complete(self) -> None:
"""Publish an optional ANN backend's readiness after full hydration."""
if getattr(self.index, "requires_rebuild", False) is not True:
return
mark_complete = getattr(self.index, "mark_rebuild_complete", None)
if callable(mark_complete):
mark_complete()
# ── write ─────────────────────────────────────────────────────────────────
def remember(self, content: str, *, workspace_id: str, repo_id: Optional[str] = None,
session_id: Optional[str] = None, mtype: MemoryType = MemoryType.SEMANTIC,
scope: Optional[Scope] = None, title: str = "", importance: float = 0.0,
confidence: Optional[float] = None, keywords: Optional[list] = None,
metadata: Optional[dict] = None,
valid_from: Optional[float] = None, resolve_conflicts: bool = True,
candidate_k: int = 5, subject_key: str = "", claim_kind: str = "",
_trusted_graph_keys: Optional[frozenset] = None,
_transactional_finalizer: Optional[Callable[[str], None]] = None) -> str:
"""Store one memory. Returns the resulting record id: a new id for ADD/
INVALIDATE/quarantine, or the existing memory's id if this was resolved as a
NOOP (near-duplicate). See ``remember_with_resolution`` for decision detail.
"""
return self.remember_with_resolution(
content, workspace_id=workspace_id, repo_id=repo_id, session_id=session_id,
mtype=mtype, scope=scope, title=title, importance=importance,
confidence=confidence, keywords=keywords,
metadata=metadata, valid_from=valid_from, resolve_conflicts=resolve_conflicts,
candidate_k=candidate_k, subject_key=subject_key, claim_kind=claim_kind,
_trusted_graph_keys=_trusted_graph_keys,
_transactional_finalizer=_transactional_finalizer,
)["id"]
def remember_with_resolution(self, content: str, *, workspace_id: str,
repo_id: Optional[str] = None, session_id: Optional[str] = None,
mtype: MemoryType = MemoryType.SEMANTIC, scope: Optional[Scope] = None,
title: str = "", importance: float = 0.0,
confidence: Optional[float] = None, keywords: Optional[list] = None,
metadata: Optional[dict] = None, valid_from: Optional[float] = None,
resolve_conflicts: bool = True, candidate_k: int = 5,
subject_key: str = "", claim_kind: str = "",
_trusted_graph_keys: Optional[frozenset] = None,
_approval_override: bool = False,
_transactional_finalizer: Optional[Callable[[str], None]] = None,
extra_neighbors: Optional[list] = None) -> dict:
"""Store one memory with deterministic conflict resolution.
Returns ``{"id", "op", ...}`` where ``op`` is one of:
* ``"add"`` — genuinely new; inserted.
* ``"noop"`` — a near-duplicate of an existing memory; that memory was
reinforced instead of inserting a copy. ``id`` is the *existing* memory's id.
* ``"invalidate"`` — same subject as an existing memory but new content; the old
one's validity was closed (never deleted) and this was inserted. ``superseded``
lists the closed id(s).
* ``"relate"`` — evidence shows a nearby claim but not a safe contradiction;
both remain live and a semantic relation is persisted.
* ``"quarantined"`` — an explicitly untrusted payload matched the deterministic
poisoning policy; retained only for governed historical inspection.
"""
# Reject credentials before embedding, conflict resolution, graph extraction, or
# any SQLite mirror sees them. Store.add_memory repeats this for direct callers.
reject_secrets((("title", title), ("content", content), ("keywords", keywords),
("metadata", metadata), ("subject_key", subject_key),
("claim_kind", claim_kind)))
if valid_from is not None:
if isinstance(valid_from, bool):
raise ValueError("valid_from must be a finite timestamp")
try:
valid_from = float(valid_from)
except (TypeError, ValueError) as exc:
raise ValueError("valid_from must be a finite timestamp") from exc
if not math.isfinite(valid_from):
raise ValueError("valid_from must be a finite timestamp")
subject_key = str(subject_key or "").strip()
claim_kind = str(claim_kind or "").strip()
scope_was_omitted = scope is None
scope = (
Scope.REPO if (repo_id or session_id) else Scope.WORKSPACE
) if scope is None else Scope(scope)
if scope == Scope.USER:
raise ValueError(_USER_SCOPE_WRITE_ERROR)
if session_id:
session = self.store.get_session(session_id)
if session is None:
raise ValueError(f"no session with id '{session_id}'")
if session["workspace_id"] != workspace_id or (
repo_id is not None and session.get("repo_id") != repo_id):
raise ValueError("session_id does not belong to that workspace/repo")
if scope in (Scope.SESSION, Scope.REPO) and repo_id is None:
repo_id = session.get("repo_id")
if scope == Scope.SESSION and not session_id:
raise ValueError("session scope requires session_id")
if scope == Scope.REPO and not repo_id:
if scope_was_omitted:
scope = Scope.WORKSPACE
else:
raise ValueError("repo scope requires repo_id")
if scope in (Scope.WORKSPACE, Scope.USER) and repo_id:
raise ValueError(f"{scope.value} scope requires repo_id to be omitted")
# Every new record carries an explicit trust assertion. The direct engine is
# a local, programmatic capability; external entry points set their own
# canonical ``trusted: false`` provenance before reaching this layer. Keeping
# the default here preserves the core's offline API while making recall fail
# closed for genuinely legacy/unlabelled records.
write_metadata = dict(metadata or {})
provenance = write_metadata.get("provenance")
provenance = dict(provenance) if isinstance(provenance, dict) else {}
if "trusted" not in provenance:
provenance["trusted"] = True
provenance.setdefault("trust_origin", "local_engine")
provenance.setdefault("source", "local_engine")
# The direct engine is an in-process capability. Public transports set an
# explicit pending state before reaching it; a direct trusted write remains
# compatible and is the only implicit local approval boundary.
if provenance.get("trusted") is True:
provenance.setdefault("review_state", REVIEW_APPROVED)
else:
provenance.setdefault("review_state", REVIEW_PENDING)
write_metadata["provenance"] = provenance
poisoning = (
PoisoningDecision(False)
if _approval_override else
assess_untrusted_payload(content, title=title, metadata=write_metadata)
)
# Resolution changes existing validity and links. It therefore runs only for
# content that already satisfies the full prompt/derived-state predicate;
# pending evidence is stored passively and cannot reinforce or supersede it.
trusted_write = prompt_eligible(provenance, write_metadata)
text = f"{title}\n{content}" if title else content
persistent_store = not _is_memory_database_path(self.store.path)
if not poisoning.quarantined and persistent_store:
if not self.embedding_space:
raise RuntimeError(
"persistent writes require an embedder with a durable "
"embedding_identity and embedding_version"
)
if not self.store.embedding_space_ready(self.embedding_space):
raise RuntimeError(
"the configured embedding space is not active; restart through "
"MemoryEngine.create() to complete the guarded rebuild"
)
if self.embedding_space:
write_metadata["embed_model"] = self.embedding_space
# Embedding is the expensive, thread-safe part — compute it BEFORE taking the
# write lock so concurrent writers only serialize the fast resolve+insert step.
# Quarantine happens before embedding: payloads retained only for inspection
# must never consume a vector slot or become semantic retrieval candidates.
vec = None if poisoning.quarantined else self.embedder.embed([text])[0]
# One writer at a time from neighbor-lookup through insert/invalidate: without
# this, two concurrent near-duplicate remembers can BOTH observe "no neighbor"
# and both resolve ADD — duplicating instead of NOOP/INVALIDATE — because the
# store's per-statement serialization cannot span this read-decide-write
# sequence. Same single-process posture as the rest of the engine (the store is
# one shared connection); multi-process writers are out of scope by design.
with self._write_lock:
caller_owned_transaction = (
self.store.conn.transaction_owned_by_current_thread()
)
if (
caller_owned_transaction
and vec is not None
and vector_index_requires_sync(self.index, self.store)
and not vector_index_shares_store_transaction(self.index, self.store)
):
# A separate backend has no hook into a caller's later commit/rollback.
# Publishing now can orphan a vector; waiting would silently leave a
# committed memory unindexed. Fail before any Store mutation and leave
# ownership and rollback policy entirely with the caller.
raise RuntimeError(
"caller-owned transactions cannot write through a separate vector "
"index; commit or roll back before remembering"
)
owns_session_transaction = False
owns_lifecycle_transaction = False
try:
if (_transactional_finalizer is not None
and not self.store.conn.transaction_owned_by_current_thread()):
self.store.conn.execute("BEGIN IMMEDIATE")
owns_lifecycle_transaction = True
if session_id:
owns_session_transaction = self.store.begin_session_write(
session_id, workspace_id=workspace_id, repo_id=repo_id
)
# A separate index cannot participate in the Store transaction. Delay
# publication until every remaining engine mutation has succeeded; an
# engine-owned session/lifecycle transaction is committed first.
# Caller-owned transactions with a separate backend were rejected above;
# Store-sharing indexes need no duplicate publication.
defer_external_index = bool(
self.store.conn.transaction_owned_by_current_thread()