dandelion-memory 1.0.0rc15__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 (232) hide show
  1. benchmarks/__init__.py +3 -0
  2. benchmarks/adapters/__init__.py +29 -0
  3. benchmarks/adapters/ablations.py +406 -0
  4. benchmarks/adapters/base.py +72 -0
  5. benchmarks/adapters/controlled/__init__.py +13 -0
  6. benchmarks/adapters/controlled/core_archival.py +115 -0
  7. benchmarks/adapters/controlled/extract_resolve.py +130 -0
  8. benchmarks/adapters/controlled/hybrid_rag.py +120 -0
  9. benchmarks/adapters/controlled/no_late_binding.py +113 -0
  10. benchmarks/adapters/dandelion.py +94 -0
  11. benchmarks/adapters/native/__init__.py +31 -0
  12. benchmarks/adapters/native/base.py +45 -0
  13. benchmarks/adapters/native/dandelion_native.py +164 -0
  14. benchmarks/adapters/native/dandelion_native_b0.py +165 -0
  15. benchmarks/adapters/native/dandelion_native_b1.py +170 -0
  16. benchmarks/adapters/native/dandelion_native_b2.py +169 -0
  17. benchmarks/adapters/native/dandelion_native_b3.py +171 -0
  18. benchmarks/adapters/native/dandelion_native_c4.py +261 -0
  19. benchmarks/adapters/native/dandelion_native_c4_1.py +281 -0
  20. benchmarks/adapters/native/dandelion_native_c4_2.py +435 -0
  21. benchmarks/adapters/native/event_evidence_b2.py +616 -0
  22. benchmarks/adapters/native/evidence_b2.py +609 -0
  23. benchmarks/adapters/native/letta_native.py +253 -0
  24. benchmarks/adapters/native/mem0_native.py +219 -0
  25. benchmarks/adapters/native/store_vector_b0.py +792 -0
  26. benchmarks/adapters/native/store_vector_b2.py +808 -0
  27. benchmarks/agent_adapter_stdio_acceptance.py +86 -0
  28. benchmarks/bootstrap_cross_stack.py +218 -0
  29. benchmarks/canonical_profile_instrumentation.py +167 -0
  30. benchmarks/canonical_public_baseline.py +288 -0
  31. benchmarks/cli.py +525 -0
  32. benchmarks/collector_public30_offline.py +1653 -0
  33. benchmarks/datasets/__init__.py +45 -0
  34. benchmarks/datasets/conversational_generator.py +238 -0
  35. benchmarks/datasets/generator.py +283 -0
  36. benchmarks/datasets/holdout_topology_generator.py +290 -0
  37. benchmarks/datasets/holdout_topology_generator_v2.py +294 -0
  38. benchmarks/datasets/multi_world.py +1643 -0
  39. benchmarks/datasets/scale_generator.py +289 -0
  40. benchmarks/datasets/schema.py +57 -0
  41. benchmarks/deep_collision_stress.py +199 -0
  42. benchmarks/evaluators/__init__.py +12 -0
  43. benchmarks/evaluators/manifest.py +142 -0
  44. benchmarks/evaluators/metrics.py +277 -0
  45. benchmarks/evaluators/runner.py +258 -0
  46. benchmarks/f1_step0/build_dev_measurement_manifest_v1.py +127 -0
  47. benchmarks/f1_step0/build_dev_measurement_manifest_v2.py +127 -0
  48. benchmarks/f1_step0/build_dev_measurement_manifest_v3.py +146 -0
  49. benchmarks/f1_step0/build_ledger.py +143 -0
  50. benchmarks/f1_step0/build_ledger_v2.py +296 -0
  51. benchmarks/f1_step0/compare_dev52_readiness_v1.py +106 -0
  52. benchmarks/f1_step0/locator_public_smoke.py +172 -0
  53. benchmarks/f1_step0/prepare_dev52_owner_v1.py +133 -0
  54. benchmarks/f1_step0/prepare_dev52_owner_v2.py +133 -0
  55. benchmarks/f1_step0/public_identity_probe.py +191 -0
  56. benchmarks/f1_step0/public_response_mapper.py +101 -0
  57. benchmarks/f1_step0/real_source_public_preflight.py +244 -0
  58. benchmarks/f1_step0/run_exact_fusion_dev_experiment_v1.py +83 -0
  59. benchmarks/f1_step0/scorer.py +110 -0
  60. benchmarks/f1_step0/source_aware_dev_measurement_v1.py +627 -0
  61. benchmarks/f1_step0/source_aware_dev_measurement_v2.py +659 -0
  62. benchmarks/f1_step0/source_aware_dev_measurement_v3.py +776 -0
  63. benchmarks/f1_step0/test_public_response_mapper.py +110 -0
  64. benchmarks/f1_step0/test_real_source_public_preflight.py +25 -0
  65. benchmarks/f1_step0/test_scorer.py +158 -0
  66. benchmarks/f1_step0/test_source_aware_dev_measurement.py +189 -0
  67. benchmarks/f1_step0/test_source_aware_dev_measurement_v2.py +263 -0
  68. benchmarks/f1_step0/test_source_aware_dev_measurement_v3.py +334 -0
  69. benchmarks/f1_step0/typed_readback_public_smoke.py +181 -0
  70. benchmarks/forensic_c4_1_dev.py +258 -0
  71. benchmarks/forensic_c4_dev.py +255 -0
  72. benchmarks/forensic_deep25_c4_1.py +478 -0
  73. benchmarks/legacy_migration_acceptance.py +29 -0
  74. benchmarks/longmemeval_actor.py +497 -0
  75. benchmarks/longmemeval_agent_judge.py +593 -0
  76. benchmarks/longmemeval_budget.py +139 -0
  77. benchmarks/longmemeval_full.py +410 -0
  78. benchmarks/longmemeval_judge.py +327 -0
  79. benchmarks/longmemeval_pilot.py +316 -0
  80. benchmarks/longmemeval_s.py +318 -0
  81. benchmarks/memory_bench.py +248 -0
  82. benchmarks/memory_formation/__init__.py +1 -0
  83. benchmarks/memory_formation/audit.py +801 -0
  84. benchmarks/memory_formation/real_audit.py +688 -0
  85. benchmarks/memory_session_acceptance.py +279 -0
  86. benchmarks/native_codex_host.py +513 -0
  87. benchmarks/owner_dense_acceptance.py +126 -0
  88. benchmarks/pilot_seeker_vault.py +266 -0
  89. benchmarks/prepare_public30_ripgrep_range_owner.py +115 -0
  90. benchmarks/profile_canonical.py +373 -0
  91. benchmarks/profile_canonical_lanes.py +405 -0
  92. benchmarks/profile_search_chunks.py +351 -0
  93. benchmarks/public_ranges_faq_proof.py +121 -0
  94. benchmarks/public_repos/build_history_scope_v3.py +330 -0
  95. benchmarks/public_repos/build_oracle.py +108 -0
  96. benchmarks/public_repos/build_oracle_v2.py +169 -0
  97. benchmarks/public_repos/build_oracle_v3.py +176 -0
  98. benchmarks/public_repos/map_public_v2.py +296 -0
  99. benchmarks/public_repos/project_prompts_v2.py +31 -0
  100. benchmarks/public_repos/project_prompts_v3.py +29 -0
  101. benchmarks/public_repos/ready_admin_v2.py +214 -0
  102. benchmarks/public_repos/score_public_v2.py +258 -0
  103. benchmarks/public_repos/test_map_public_v2.py +171 -0
  104. benchmarks/public_repos/test_public_repo_v2.py +44 -0
  105. benchmarks/public_repos/test_public_repo_v3.py +46 -0
  106. benchmarks/public_repos/test_ready_admin_v2.py +117 -0
  107. benchmarks/public_repos/test_score_public_v2.py +163 -0
  108. benchmarks/public_repos/test_wire_v2.py +292 -0
  109. benchmarks/public_repos/wire_v2.py +603 -0
  110. benchmarks/real_blocker_fix_acceptance.py +155 -0
  111. benchmarks/real_scan_rescan_acceptance.py +41 -0
  112. benchmarks/recall_v2_20k_smoke.py +112 -0
  113. benchmarks/recall_v2_e1_retrieve.py +70 -0
  114. benchmarks/recall_v2_e1_score.py +271 -0
  115. benchmarks/recall_v2_e2_prepare.py +69 -0
  116. benchmarks/recall_v2_e2_public_score.py +91 -0
  117. benchmarks/recall_v2_e2_score.py +108 -0
  118. benchmarks/recall_v2_navigation_mcp_replay.py +308 -0
  119. benchmarks/recall_v2_reader_capture.py +118 -0
  120. benchmarks/recall_v2_reader_replay.py +136 -0
  121. benchmarks/run_blind_h10_holdout.py +284 -0
  122. benchmarks/run_blind_h9_holdout.py +275 -0
  123. benchmarks/run_c4_2_nightly_scale.py +446 -0
  124. benchmarks/run_context_scale_simulation.py +189 -0
  125. benchmarks/run_conversational_bench.py +170 -0
  126. benchmarks/run_h11_evaluation.py +316 -0
  127. benchmarks/run_h11_v2_evaluation.py +431 -0
  128. benchmarks/run_native_fixed12.py +469 -0
  129. benchmarks/run_native_preflight.py +280 -0
  130. benchmarks/run_scale_stress.py +225 -0
  131. benchmarks/solanazation_brownfield_01/build_oracle.py +970 -0
  132. benchmarks/solanazation_brownfield_01/check_level_a.py +78 -0
  133. benchmarks/solanazation_brownfield_01/debug_scope.py +13 -0
  134. benchmarks/solanazation_brownfield_01/evaluate_bootstrap_02.py +570 -0
  135. benchmarks/solanazation_brownfield_01/evaluate_first_pass.py +306 -0
  136. benchmarks/solanazation_brownfield_01/generate_dryrun_report.py +222 -0
  137. benchmarks/solanazation_brownfield_01/generate_manifests.py +146 -0
  138. benchmarks/solanazation_brownfield_01/inspect_misses.py +29 -0
  139. benchmarks/solanazation_brownfield_01/run_miss_forensic.py +206 -0
  140. benchmarks/solanazation_brownfield_01/test_facts.py +15 -0
  141. benchmarks/statistics/__init__.py +15 -0
  142. benchmarks/statistics/significance.py +326 -0
  143. benchmarks/test_native_mcp_preflight.py +229 -0
  144. benchmarks/test_prepare_public30_range_owner.py +35 -0
  145. benchmarks/test_public30_source_reference.py +698 -0
  146. benchmarks/test_recall_v2_e1_reader_input.py +89 -0
  147. benchmarks/test_recall_v2_navigation_mcp_replay.py +155 -0
  148. benchmarks/test_recall_v2_reader_replay.py +41 -0
  149. dandelion/__init__.py +3 -0
  150. dandelion/__main__.py +11 -0
  151. dandelion/agent_adapter.py +2369 -0
  152. dandelion/bootstrap/__init__.py +872 -0
  153. dandelion/bootstrap/alias_policy.py +50 -0
  154. dandelion/bootstrap/authority.py +225 -0
  155. dandelion/bootstrap/canonical_history.py +412 -0
  156. dandelion/bootstrap/classifier.py +403 -0
  157. dandelion/bootstrap/component_graph.py +280 -0
  158. dandelion/bootstrap/discovery.py +279 -0
  159. dandelion/bootstrap/domain_induction.py +180 -0
  160. dandelion/bootstrap/domain_topology.py +673 -0
  161. dandelion/bootstrap/evidence_envelope.py +132 -0
  162. dandelion/bootstrap/extractors/base.py +171 -0
  163. dandelion/bootstrap/extractors/exact.py +1234 -0
  164. dandelion/bootstrap/extractors/generic.py +100 -0
  165. dandelion/bootstrap/extractors/git_temporal.py +111 -0
  166. dandelion/bootstrap/extractors/registry.py +345 -0
  167. dandelion/bootstrap/extractors/relations.py +89 -0
  168. dandelion/bootstrap/extractors/semantic.py +424 -0
  169. dandelion/bootstrap/extractors/status.py +218 -0
  170. dandelion/bootstrap/git_sweeper.py +135 -0
  171. dandelion/bootstrap/manifest.py +246 -0
  172. dandelion/bootstrap/quarantine.py +264 -0
  173. dandelion/bootstrap/report.py +259 -0
  174. dandelion/bootstrap/root_resolver.py +221 -0
  175. dandelion/bootstrap/tech_profiler.py +125 -0
  176. dandelion/bootstrap/topology.py +75 -0
  177. dandelion/bootstrap/topology_index.py +110 -0
  178. dandelion/bootstrap/transaction.py +315 -0
  179. dandelion/canonical_bootstrap.py +257 -0
  180. dandelion/canonical_memory.py +4130 -0
  181. dandelion/captured_input.py +295 -0
  182. dandelion/cli.py +767 -0
  183. dandelion/config.py +40 -0
  184. dandelion/derived_index.py +745 -0
  185. dandelion/domains.py +706 -0
  186. dandelion/embedder.py +229 -0
  187. dandelion/event_evidence.py +571 -0
  188. dandelion/evidence.py +812 -0
  189. dandelion/evidence_response.py +453 -0
  190. dandelion/evidence_workspace.py +2360 -0
  191. dandelion/exact_context.py +129 -0
  192. dandelion/hydrator.py +124 -0
  193. dandelion/inspector.py +442 -0
  194. dandelion/inspector_assets/dandelion-mark.svg +33 -0
  195. dandelion/inspector_assets/dandelion_graph.js +361 -0
  196. dandelion/inspector_assets/inspector.css +223 -0
  197. dandelion/inspector_assets/inspector.html +135 -0
  198. dandelion/inspector_assets/inspector.js +1059 -0
  199. dandelion/legacy_import.py +431 -0
  200. dandelion/live_source_grants.py +133 -0
  201. dandelion/local_owner.py +114 -0
  202. dandelion/memory_client.py +252 -0
  203. dandelion/memory_contract.py +107 -0
  204. dandelion/memory_owner.py +560 -0
  205. dandelion/reader_providers.py +118 -0
  206. dandelion/recall_v2.py +767 -0
  207. dandelion/reconciler.py +219 -0
  208. dandelion/request_budget.py +125 -0
  209. dandelion/retained_basis.py +223 -0
  210. dandelion/retrieval.py +485 -0
  211. dandelion/router.py +405 -0
  212. dandelion/search_terms.py +53 -0
  213. dandelion/security.py +124 -0
  214. dandelion/server.py +810 -0
  215. dandelion/source_content_fts.py +219 -0
  216. dandelion/source_delivery.py +89 -0
  217. dandelion/source_history.py +241 -0
  218. dandelion/source_identity.py +88 -0
  219. dandelion/source_navigator.py +5 -0
  220. dandelion/source_reader.py +444 -0
  221. dandelion/source_references.py +379 -0
  222. dandelion/source_sections.py +265 -0
  223. dandelion/store_kv.py +684 -0
  224. dandelion/store_vector.py +1289 -0
  225. dandelion/studio.py +325 -0
  226. dandelion/wal.py +227 -0
  227. dandelion_memory-1.0.0rc15.dist-info/METADATA +48 -0
  228. dandelion_memory-1.0.0rc15.dist-info/RECORD +232 -0
  229. dandelion_memory-1.0.0rc15.dist-info/WHEEL +5 -0
  230. dandelion_memory-1.0.0rc15.dist-info/entry_points.txt +5 -0
  231. dandelion_memory-1.0.0rc15.dist-info/licenses/LICENSE +21 -0
  232. dandelion_memory-1.0.0rc15.dist-info/top_level.txt +2 -0
@@ -0,0 +1,792 @@
1
+ """Episodic vector memory store for Dandelion (Qdrant embedded mode).
2
+
3
+ Features:
4
+ - Hybrid retrieval: Dense vector + Lexical identifier boost + Fact reverse-lookup
5
+ - Reverse reference index integration (stores referenced_facts in payload)
6
+ - Thread-safe writes via threading.Lock
7
+ - Lifecycle management: atexit.register(close)
8
+ - Asymmetric search: passage_embed for storage, query_embed for retrieval
9
+ - Multi-domain and wildcard-resolved search
10
+ - Safe concurrency: lets Qdrant/portalocker manage locks naturally without
11
+ dangerous manual unlink calls.
12
+ """
13
+
14
+ import atexit
15
+ import logging
16
+ import os
17
+ import re
18
+ import threading
19
+ import time
20
+ import uuid
21
+ import warnings
22
+ from pathlib import Path
23
+ from typing import Optional
24
+
25
+ from qdrant_client import QdrantClient, models
26
+
27
+ from dandelion.config import (
28
+ QDRANT_DIR,
29
+ COLLECTION_NAME,
30
+ _DEFAULT_VECTOR_DIM,
31
+ ensure_dirs,
32
+ WAL_FILE,
33
+ )
34
+ from dandelion.domains import is_valid_domain_scope
35
+ from dandelion.embedder import Embedder
36
+ from dandelion.hydrator import extract_refs
37
+ from dandelion.reconciler import reconcile_stores, ReconciliationReport
38
+ from dandelion.wal import WriteAheadLog
39
+
40
+ logger = logging.getLogger(__name__)
41
+
42
+ # Multi-Tier Retrieval Evidence Gate Patterns:
43
+ # Extracts technical code identifiers, hex addresses, file paths, endpoints, dotted symbols,
44
+ # hyphenated tags, error codes, camelCase, and snake_case without false-matching TitleCase English prose.
45
+ TECHNICAL_CODE_ID: re.Pattern = re.compile(
46
+ r"\b0x[a-fA-F0-9]{4,}\b|" # Hex addresses / hashes
47
+ r"\b[a-zA-Z0-9_]+/[a-zA-Z0-9_./\-]+\b|" # File paths (src/worker.py)
48
+ r"/(?:[a-zA-Z0-9_.\-]+/)+[a-zA-Z0-9_.\-]*\b|" # Absolute endpoints (/api/v1/...)
49
+ r"\b[a-zA-Z0-9_-]+\.[a-zA-Z0-9_-]+\b|" # Dotted symbols (api.port, config.yaml)
50
+ r"\b[A-Z0-9_]{2,}-[A-Z0-9_]{2,}\b|" # Hyphenated tags (POC-157, ADR-01)
51
+ r"\b[A-Z0-9]+_[A-Z0-9_]+\b|" # ALL_CAPS with underscore (ERR_TIMEOUT, HTTP_500)
52
+ r"\b[a-z]+[A-Z][a-zA-Z0-9]*\b|" # camelCase (getUserProfile)
53
+ r"\b[a-z0-9]+_[a-z0-9_]+\b|" # snake_case (droop_control)
54
+ r"\bADR\b|\bRFC\b" # Architectural decision / request for comment tags
55
+ )
56
+ IDENTIFIER_PATTERN: re.Pattern = TECHNICAL_CODE_ID
57
+
58
+ QUERY_STOP_WORDS: set[str] = {
59
+ "why", "how", "what", "when", "where", "which", "who", "whom",
60
+ "this", "that", "with", "from", "into", "does", "have", "will",
61
+ "the", "for", "our", "and", "was", "were", "been", "about", "after",
62
+ "show", "find", "list", "check", "extract", "without", "during",
63
+ "not", "all", "can", "get", "set", "use", "has", "had", "are",
64
+ "you", "out", "per", "via", "but", "also",
65
+ "каков", "какой", "какая", "какие", "для", "после", "при", "как", "что",
66
+ }
67
+
68
+
69
+ def _to_point_id(val: str) -> str:
70
+ """Ensure a string is a valid UUID, deriving a deterministic UUID5 if not."""
71
+ try:
72
+ uuid.UUID(val)
73
+ return val
74
+ except ValueError:
75
+ return str(uuid.uuid5(uuid.NAMESPACE_DNS, val))
76
+
77
+
78
+ def _is_potential_fact_value(token: str) -> bool:
79
+ """Determine if a token has the syntactic shape of an exact fact value (port, hex, version, host)."""
80
+ t = token.strip(".:,-'\"")
81
+ if not t or len(t) < 2 or t.lower() in QUERY_STOP_WORDS:
82
+ return False
83
+ # Ports or numeric identifiers (e.g. 5432, 8080, 443, 9001)
84
+ if re.match(r"^\d{2,5}$", t):
85
+ return True
86
+ # Hex contracts / commit hashes (e.g. 0x7a250...)
87
+ if re.match(r"^0x[a-fA-F0-9]{4,}$", t):
88
+ return True
89
+ # Version tags (e.g. v1.2.0, 2.4, v15)
90
+ if re.match(r"^v?\d+(?:\.\d+)+$", t):
91
+ return True
92
+ # Hostnames / FQDNs / URLs (must contain a dot and alphanumeric characters)
93
+ if "." in t and re.match(r"^[a-zA-Z0-9_-]+(?:\.[a-zA-Z0-9_-]+)+$", t):
94
+ return True
95
+ return False
96
+
97
+
98
+ # Tier 0: Structural Revision Patterns
99
+ EXPLICIT_REV_INLINE: re.Pattern = re.compile(
100
+ r"(?:\{\{ref:)?\b([a-zA-Z0-9_.-]+)@rev:(\d+)\b(?:\}\})?"
101
+ )
102
+ EXPLICIT_REV_ADJACENT: re.Pattern = re.compile(
103
+ r"\b([a-zA-Z0-9_]+(?:\.[a-zA-Z0-9_]+)+)\b(?:\s+at\s+revision)?\s+(?:@)?rev:(\d+)\b"
104
+ )
105
+
106
+
107
+ def parse_explicit_revision_refs(query: str) -> list[tuple[str, int]]:
108
+ """Extract explicit fact revision references from a query.
109
+
110
+ Recognizes:
111
+ - 'db.port@rev:99'
112
+ - '{{ref:db.port@rev:99}}'
113
+ - 'hyperloop.primary_port at revision rev:99'
114
+ - 'hyperloop.primary_port rev:99'
115
+
116
+ Does NOT match plain natural text like 'What changed in revision 99?'.
117
+ """
118
+ refs: list[tuple[str, int]] = []
119
+ seen: set[tuple[str, int]] = set()
120
+
121
+ for m in EXPLICIT_REV_INLINE.finditer(query):
122
+ k = m.group(1).strip(".:,-")
123
+ try:
124
+ r = int(m.group(2))
125
+ if (k, r) not in seen:
126
+ seen.add((k, r))
127
+ refs.append((k, r))
128
+ except ValueError:
129
+ pass
130
+
131
+ for m in EXPLICIT_REV_ADJACENT.finditer(query):
132
+ k = m.group(1).strip(".:,-")
133
+ try:
134
+ r = int(m.group(2))
135
+ if (k, r) not in seen:
136
+ seen.add((k, r))
137
+ refs.append((k, r))
138
+ except ValueError:
139
+ pass
140
+
141
+ return refs
142
+
143
+
144
+ class VectorStore:
145
+ """Qdrant-backed episodic memory store with hybrid retrieval."""
146
+
147
+ def __init__(self, path: Optional[Path] = None, in_memory: bool = False) -> None:
148
+ """Initialize the vector store.
149
+
150
+ Args:
151
+ path: Directory for Qdrant persistent storage. Defaults to QDRANT_DIR.
152
+ in_memory: If True, use in-memory mode (for testing).
153
+ """
154
+ self._write_lock = threading.RLock()
155
+ self._known_domains: set[str] = set()
156
+ self.last_structural_reject: Optional[str] = None
157
+
158
+ if in_memory:
159
+ self._client = QdrantClient(":memory:")
160
+ self._path: Optional[Path] = None
161
+ self._wal = WriteAheadLog(path=None)
162
+ logger.info("Vector store initialized in-memory mode.")
163
+ elif os.getenv("QDRANT_URL"):
164
+ qdrant_url = os.getenv("QDRANT_URL")
165
+ api_key = os.getenv("QDRANT_API_KEY")
166
+ self._client = QdrantClient(url=qdrant_url, api_key=api_key)
167
+ self._path = None
168
+ self._wal = WriteAheadLog(path=WAL_FILE)
169
+ logger.info("Vector store connected to external Qdrant at %s", qdrant_url)
170
+ else:
171
+ storage_path = path or QDRANT_DIR
172
+ ensure_dirs()
173
+ # Standard safe Qdrant client initialization (portalocker handles locking)
174
+ self._client = QdrantClient(path=str(storage_path))
175
+ self._path = storage_path
176
+ wal_path = (storage_path.parent / "wal.jsonl") if path else WAL_FILE
177
+ self._wal = WriteAheadLog(path=wal_path)
178
+ logger.info("Vector store initialized at %s", storage_path)
179
+
180
+ self._ensure_collection()
181
+ atexit.register(self.close)
182
+
183
+ # Startup cross-store reconciliation pass
184
+ try:
185
+ self.reconcile()
186
+ except Exception as e:
187
+ logger.warning("Startup store reconciliation pass failed: %s", e)
188
+
189
+ def _ensure_collection(self) -> None:
190
+ """Create the vector collection and payload indices if they don't exist."""
191
+ if not self._client.collection_exists(COLLECTION_NAME):
192
+ # Auto-detect embedding dimension from the loaded model
193
+ try:
194
+ vector_dim = Embedder.get().dimension
195
+ except Exception:
196
+ vector_dim = _DEFAULT_VECTOR_DIM
197
+ logger.warning(
198
+ "Could not detect embedding dimension; using default %d", vector_dim
199
+ )
200
+ self._client.create_collection(
201
+ collection_name=COLLECTION_NAME,
202
+ vectors_config=models.VectorParams(
203
+ size=vector_dim,
204
+ distance=models.Distance.COSINE,
205
+ ),
206
+ )
207
+ logger.info("Created collection '%s' (dim=%d)", COLLECTION_NAME, vector_dim)
208
+
209
+ with warnings.catch_warnings():
210
+ warnings.simplefilter("ignore", UserWarning)
211
+ self._client.create_payload_index(
212
+ collection_name=COLLECTION_NAME,
213
+ field_name="domain",
214
+ field_schema=models.PayloadSchemaType.KEYWORD,
215
+ )
216
+ self._client.create_payload_index(
217
+ collection_name=COLLECTION_NAME,
218
+ field_name="is_active",
219
+ field_schema=models.PayloadSchemaType.BOOL,
220
+ )
221
+
222
+ def reconcile(self) -> ReconciliationReport:
223
+ """Perform a cross-store consistency and WAL recovery pass."""
224
+ from dandelion.store_kv import get_kv_store
225
+ with self._write_lock:
226
+ return reconcile_stores(get_kv_store(), self, self._wal)
227
+
228
+ # ── Write Operations (thread-safe) ─────────────────────────
229
+
230
+ def save_chunk(
231
+ self,
232
+ domain: str,
233
+ template: str,
234
+ supersedes: Optional[str] = None,
235
+ source: str = "agent_inferred",
236
+ created_at: Optional[float] = None,
237
+ event_id: Optional[str] = None,
238
+ ) -> str:
239
+ """Store an episodic memory chunk with fact reference indexing and WAL durability."""
240
+ from dandelion.store_kv import get_kv_store
241
+
242
+ vector = Embedder.get().embed_passage(template)
243
+ point_id = _to_point_id(event_id) if event_id else str(uuid.uuid4())
244
+ ref_keys = extract_refs(template)
245
+ now = float(created_at) if created_at is not None else time.time()
246
+
247
+ with self._write_lock:
248
+ tx_id = self._wal.begin("save_chunk", {
249
+ "point_id": point_id,
250
+ "domain": domain,
251
+ "template": template,
252
+ "supersedes": supersedes,
253
+ "source": source,
254
+ "created_at": now,
255
+ "referenced_facts": ref_keys,
256
+ "event_id": event_id or point_id,
257
+ })
258
+
259
+ qdrant_persisted = False
260
+ try:
261
+ # Deactivate superseded chunk
262
+ if supersedes:
263
+ sup_id = _to_point_id(supersedes)
264
+ try:
265
+ self._client.set_payload(
266
+ collection_name=COLLECTION_NAME,
267
+ payload={"is_active": False},
268
+ points=[sup_id],
269
+ )
270
+ get_kv_store().remove_fact_refs_for_chunk(sup_id)
271
+ logger.info("Superseded chunk %s (%s)", supersedes, sup_id)
272
+ except Exception as e:
273
+ logger.warning("Failed to supersede chunk %s: %s", supersedes, e)
274
+
275
+ # Upsert new chunk with references
276
+ self._client.upsert(
277
+ collection_name=COLLECTION_NAME,
278
+ points=[
279
+ models.PointStruct(
280
+ id=point_id,
281
+ vector=vector,
282
+ payload={
283
+ "domain": domain,
284
+ "template": template,
285
+ "is_active": True,
286
+ "created_at": now,
287
+ "supersedes": supersedes,
288
+ "source": source,
289
+ "referenced_facts": ref_keys,
290
+ "event_id": event_id or point_id,
291
+ },
292
+ )
293
+ ],
294
+ )
295
+ qdrant_persisted = True
296
+
297
+ # Register in reverse index and domain registry
298
+ self._known_domains.add(domain)
299
+ try:
300
+ get_kv_store().ensure_domain(domain)
301
+ except Exception:
302
+ pass
303
+
304
+ if ref_keys:
305
+ get_kv_store().add_fact_refs(ref_keys, point_id)
306
+
307
+ self._wal.commit(tx_id)
308
+ logger.info("Saved chunk %s in domain '%s' (refs: %s, tx: %s)", point_id, domain, ref_keys, tx_id)
309
+ return point_id
310
+ except Exception as e:
311
+ if not qdrant_persisted:
312
+ self._wal.rollback(tx_id)
313
+ else:
314
+ logger.critical(
315
+ "KVStore sync failed after Qdrant write for chunk %s (tx: %s). "
316
+ "Leaving transaction PENDING for deterministic reconciliation: %s",
317
+ point_id, tx_id, e
318
+ )
319
+ raise
320
+
321
+ def deactivate_chunk(self, chunk_id: str) -> bool:
322
+ """Soft-delete a chunk by setting is_active=False with WAL durability."""
323
+ from dandelion.store_kv import get_kv_store
324
+
325
+ target_id = _to_point_id(chunk_id)
326
+ with self._write_lock:
327
+ tx_id = self._wal.begin("deactivate_chunk", {"point_id": target_id})
328
+
329
+ qdrant_deactivated = False
330
+ try:
331
+ self._client.set_payload(
332
+ collection_name=COLLECTION_NAME,
333
+ payload={"is_active": False},
334
+ points=[target_id],
335
+ )
336
+ qdrant_deactivated = True
337
+ get_kv_store().remove_fact_refs_for_chunk(target_id)
338
+ logger.info("Deactivated chunk %s (%s, tx: %s)", chunk_id, target_id, tx_id)
339
+ self._wal.commit(tx_id)
340
+ return True
341
+ except Exception as e:
342
+ logger.warning("Failed to deactivate chunk %s: %s", chunk_id, e)
343
+ if not qdrant_deactivated:
344
+ self._wal.rollback(tx_id)
345
+ else:
346
+ logger.critical(
347
+ "KVStore cleanup failed after Qdrant deactivation for chunk %s (tx: %s). "
348
+ "Leaving transaction PENDING for deterministic reconciliation: %s",
349
+ chunk_id, tx_id, e
350
+ )
351
+ return False
352
+
353
+ # ── Read Operations (Hybrid Retrieval) ─────────────────────
354
+
355
+ def search_chunks(
356
+ self,
357
+ query: str,
358
+ domains: Optional[list[str]] = None,
359
+ limit: int = 3,
360
+ use_reverse_index: bool = True,
361
+ use_lexical_rerank: bool = True,
362
+ domain: Optional[str] = None,
363
+ ) -> list[dict]:
364
+ """Hybrid search combining:
365
+ 1. Dense semantic vectors (FastEmbed)
366
+ 2. Lexical / exact identifier matching (for code symbols, file paths, hashes)
367
+ 3. Reverse fact-value lookup (finding chunks whose {{ref:key}} matches query value)
368
+ """
369
+ from dandelion.store_kv import get_kv_store
370
+
371
+ if domain and not domains:
372
+ domains = [domain]
373
+
374
+ self.last_structural_reject = None
375
+
376
+ # ── Tier 0: Structural Impossibility Guard ───────────────
377
+ # A. Explicit Domain Structural Gate
378
+ if domains:
379
+ kv = get_kv_store()
380
+ registry = kv.get_domains()
381
+ known_domains = set(registry.keys()) | self._known_domains
382
+
383
+ has_valid_scope = any(is_valid_domain_scope(d, known_domains) for d in domains)
384
+ if not has_valid_scope:
385
+ self.last_structural_reject = "unknown_domain"
386
+ logger.debug("Tier 0 Structural Reject: unknown domain(s) %s", domains)
387
+ return []
388
+
389
+ # B. Explicit Revision Structural Gate
390
+ explicit_refs = parse_explicit_revision_refs(query)
391
+ if explicit_refs:
392
+ kv = get_kv_store()
393
+ primary_domain = domains[0] if domains and len(domains) == 1 else None
394
+ for key, rev in explicit_refs:
395
+ resolved_key = kv.resolve_fact_key(key, domain=primary_domain)
396
+ if resolved_key is None or not kv.revision_exists(resolved_key, rev):
397
+ self.last_structural_reject = "missing_revision"
398
+ logger.debug(
399
+ "Tier 0 Structural Reject: missing revision for %s@rev:%d (resolved=%s)",
400
+ key, rev, resolved_key,
401
+ )
402
+ return []
403
+
404
+ vector = Embedder.get().embed_query(query)
405
+
406
+ # Build filter: always require is_active=True
407
+ must_conditions: list[models.FieldCondition] = [
408
+ models.FieldCondition(
409
+ key="is_active",
410
+ match=models.MatchValue(value=True),
411
+ )
412
+ ]
413
+
414
+ # Domain filtering
415
+ if domains and len(domains) == 1:
416
+ must_conditions.append(
417
+ models.FieldCondition(
418
+ key="domain",
419
+ match=models.MatchValue(value=domains[0]),
420
+ )
421
+ )
422
+
423
+ should_conditions: Optional[list[models.FieldCondition]] = None
424
+ if domains and len(domains) > 1:
425
+ should_conditions = [
426
+ models.FieldCondition(
427
+ key="domain",
428
+ match=models.MatchValue(value=d),
429
+ )
430
+ for d in domains
431
+ ]
432
+
433
+ query_filter = models.Filter(
434
+ must=must_conditions,
435
+ should=should_conditions,
436
+ )
437
+
438
+ # Retrieve candidates for re-ranking
439
+ candidate_limit = max(limit * 3, 10)
440
+ results = self._client.query_points(
441
+ collection_name=COLLECTION_NAME,
442
+ query=vector,
443
+ query_filter=query_filter,
444
+ limit=candidate_limit,
445
+ with_payload=True,
446
+ )
447
+
448
+ candidates = {
449
+ str(p.id): {
450
+ "id": str(p.id),
451
+ "event_id": p.payload.get("event_id", str(p.id)),
452
+ "domain": p.payload.get("domain", "unknown"),
453
+ "template": p.payload.get("template", ""),
454
+ "vector_score": float(p.score or 0.0),
455
+ "created_at": p.payload.get("created_at", 0),
456
+ "source": p.payload.get("source", "agent_inferred"),
457
+ "referenced_facts": p.payload.get("referenced_facts", []),
458
+ }
459
+ for p in results.points
460
+ }
461
+
462
+ # ── Reverse Fact-Value Lookup (Conditional Activation) ──
463
+ boosted_chunk_ids: set[str] = set()
464
+ if use_reverse_index:
465
+ kv = get_kv_store()
466
+ query_raw_tokens = set(re.findall(r"[\w.:\-]+", query))
467
+ matching_fact_keys: set[str] = set()
468
+ for token in query_raw_tokens:
469
+ stripped = token.strip(".:,-'\"")
470
+ if _is_potential_fact_value(stripped):
471
+ matched_facts = kv.find_facts_by_value(stripped)
472
+ matching_fact_keys.update(matched_facts)
473
+
474
+ for fact_key in matching_fact_keys:
475
+ chunk_ids = kv.get_chunks_for_fact(fact_key)
476
+ boosted_chunk_ids.update(chunk_ids)
477
+
478
+ # If any chunks were found via fact reverse lookup that weren't in candidates, fetch them
479
+ if boosted_chunk_ids:
480
+ missing_ids = [cid for cid in boosted_chunk_ids if cid not in candidates]
481
+ if missing_ids:
482
+ try:
483
+ points = self._client.retrieve(
484
+ collection_name=COLLECTION_NAME,
485
+ ids=missing_ids,
486
+ with_payload=True,
487
+ )
488
+ for pt in points:
489
+ if pt.payload.get("is_active", True):
490
+ candidates[str(pt.id)] = {
491
+ "id": str(pt.id),
492
+ "event_id": pt.payload.get("event_id", str(pt.id)),
493
+ "domain": pt.payload.get("domain", "unknown"),
494
+ "template": pt.payload.get("template", ""),
495
+ "vector_score": 0.0,
496
+ "created_at": pt.payload.get("created_at", 0),
497
+ "source": pt.payload.get("source", "agent_inferred"),
498
+ "referenced_facts": pt.payload.get("referenced_facts", []),
499
+ }
500
+ except Exception as e:
501
+ logger.debug("Failed to retrieve extra chunks: %s", e)
502
+
503
+ # If pure dense vector mode
504
+ if not use_lexical_rerank and not use_reverse_index:
505
+ scored_results = [
506
+ item for item in candidates.values() if item["vector_score"] >= 0.15
507
+ ]
508
+ scored_results.sort(key=lambda x: x["vector_score"], reverse=True)
509
+ for item in scored_results:
510
+ item["score"] = round(item["vector_score"], 4)
511
+ return scored_results[:limit]
512
+
513
+ # ── Reciprocal Rank Fusion (RRF) with Multi-Tier Evidence Gate ──
514
+ # Extract explicit code identifiers from query
515
+ query_identifiers = {
516
+ ident.strip(".:,-/")
517
+ for ident in TECHNICAL_CODE_ID.findall(query)
518
+ if ident.lower() not in QUERY_STOP_WORDS
519
+ }
520
+
521
+ # Content words in query excluding stop words
522
+ raw_query_words = {
523
+ w.lower().strip(".:,-/?!\"'(){}[]")
524
+ for w in re.split(r"[\s\-._/]+", query)
525
+ if len(w) > 2 and w.lower() not in QUERY_STOP_WORDS
526
+ }
527
+
528
+ candidate_ident_hits: dict[str, int] = {}
529
+ lexical_raw: dict[str, float] = {}
530
+
531
+ if use_lexical_rerank:
532
+ for cid, item in candidates.items():
533
+ tmpl = item["template"]
534
+ domain_str = item.get("domain", "")
535
+ domain_tokens = set(re.findall(r"[\w]+", domain_str.lower()))
536
+ has_fact = cid in boosted_chunk_ids
537
+
538
+ tmpl_clean_tokens = set(re.findall(r"[\w.:/\-]+", tmpl))
539
+ tmpl_clean_tokens |= {t.strip(".:,-/?!\"'(){}[]") for t in tmpl_clean_tokens}
540
+ ref_keys = set(re.findall(r"\{\{ref:([\w.]+)(?:@rev:\d+)?\}\}", tmpl))
541
+ tmpl_idents = set(TECHNICAL_CODE_ID.findall(tmpl))
542
+ all_target_identifiers = tmpl_clean_tokens | ref_keys | tmpl_idents
543
+ # Extract base prefix for hyphenated tags (e.g. 'ADR' from 'ADR-02', 'POC' from 'POC-157')
544
+ base_prefixes = {t.split("-")[0] for t in all_target_identifiers if "-" in t and len(t.split("-")[0]) >= 2}
545
+ all_target_identifiers |= base_prefixes
546
+
547
+ id_hits = len(query_identifiers & all_target_identifiers) if query_identifiers else 0
548
+ candidate_ident_hits[cid] = id_hits
549
+ lex_val = id_hits * 2.0
550
+
551
+ tmpl_words = {
552
+ w.lower().strip(".:,-/?!\"'(){}[]")
553
+ for w in re.split(r"[\s\-._/]+", tmpl)
554
+ if len(w) > 2 and w.lower() not in QUERY_STOP_WORDS and w.lower() not in domain_tokens
555
+ }
556
+ q_words = {w for w in raw_query_words if w not in domain_tokens}
557
+ word_hits = len(q_words & tmpl_words)
558
+ if q_words and (id_hits > 0 or has_fact or item["vector_score"] >= 0.50):
559
+ lex_val += word_hits / len(q_words)
560
+ lexical_raw[cid] = lex_val
561
+
562
+ sorted_by_lexical = sorted(
563
+ candidates.keys(),
564
+ key=lambda k: lexical_raw[k],
565
+ reverse=True,
566
+ )
567
+ lexical_ranks = {cid: rank + 1 for rank, cid in enumerate(sorted_by_lexical)}
568
+ else:
569
+ lexical_ranks = {cid: 9999 for cid in candidates}
570
+
571
+ # 1. Rank by dense vector score
572
+ sorted_by_vector = sorted(
573
+ candidates.keys(),
574
+ key=lambda k: candidates[k]["vector_score"],
575
+ reverse=True,
576
+ )
577
+ dense_ranks = {cid: rank + 1 for rank, cid in enumerate(sorted_by_vector)}
578
+
579
+ # 2. Multi-Tier Retrieval Evidence Gate (Gate Evaluation)
580
+ K = 60
581
+ scored_results = []
582
+ is_cyrillic = bool(re.search(r"[\u0400-\u04FF]", query))
583
+
584
+ for cid, item in candidates.items():
585
+ dense_r = dense_ranks[cid]
586
+ lex_r = lexical_ranks[cid]
587
+ has_fact = cid in boosted_chunk_ids
588
+ id_hits = candidate_ident_hits.get(cid, 0)
589
+ v_score = item["vector_score"]
590
+
591
+ # Multi-Tier Admission Gate:
592
+ admitted = False
593
+
594
+ if has_fact:
595
+ # Tier 1: Symbolic fact reverse lookup (structural match)
596
+ admitted = True
597
+ elif query_identifiers:
598
+ # Tier 2: Explicit Code Identifier Gate
599
+ # If query specified an explicit identifier, chunk MUST contain it
600
+ if id_hits > 0:
601
+ admitted = True
602
+ else:
603
+ # Tier 3: Pure semantic query (no explicit code identifiers in query)
604
+ tmpl = item["template"]
605
+ domain_str = item.get("domain", "")
606
+ domain_tokens = set(re.findall(r"[\w]+", domain_str.lower()))
607
+ tmpl_words = {
608
+ w.lower().strip(".:,-/?!\"'(){}[]")
609
+ for w in re.split(r"[\s\-._/]+", tmpl)
610
+ if len(w) > 2 and w.lower() not in QUERY_STOP_WORDS and w.lower() not in domain_tokens
611
+ }
612
+ q_words = {w for w in raw_query_words if w not in domain_tokens}
613
+ word_hits = len(q_words & tmpl_words)
614
+
615
+ tmpl_is_cyrillic = bool(re.search(r"[\u0400-\u04FF]", tmpl))
616
+ if not is_cyrillic and tmpl_is_cyrillic:
617
+ # Cross-language: English query querying Cyrillic template.
618
+ # Require at least one non-Cyrillic technical keyword match in template
619
+ # to prevent unrelated Russian templates from matching English queries.
620
+ non_cyr_tmpl = {w for w in tmpl_words if not re.search(r"[\u0400-\u04FF]", w)}
621
+ non_cyr_hits = len(q_words & non_cyr_tmpl)
622
+ if v_score >= 0.60 and non_cyr_hits >= 1:
623
+ admitted = True
624
+ elif is_cyrillic:
625
+ cyr_q = {w for w in q_words if re.search(r"[\u0400-\u04FF]", w)}
626
+ cyr_t = {w for w in tmpl_words if re.search(r"[\u0400-\u04FF]", w)}
627
+ stem_q = {w[:4] for w in cyr_q if len(w) >= 4}
628
+ stem_t = {w[:4] for w in cyr_t if len(w) >= 4}
629
+ stem_hits = len(stem_q & stem_t)
630
+ if v_score >= 0.60 and (len(cyr_q & cyr_t) > 0 or stem_hits > 0):
631
+ admitted = True
632
+ else:
633
+ q_coverage = (word_hits / len(q_words)) if q_words else 0.0
634
+ if v_score >= 0.60:
635
+ admitted = True
636
+ elif v_score >= 0.45 and word_hits >= 1 and bool(domains):
637
+ admitted = True
638
+ elif v_score >= 0.35 and word_hits >= 2 and bool(domains):
639
+ admitted = True
640
+ elif q_coverage >= 0.5 and word_hits >= 1:
641
+ admitted = True
642
+ elif dense_r == 1 and bool(domains):
643
+ # Tier 3b: Top-rank fallback — admit best dense match for
644
+ # domain-isolated queries with lexical/substring evidence.
645
+ has_substr_hit = any(
646
+ qw in tw or tw in qw
647
+ for qw in q_words if len(qw) >= 4
648
+ for tw in tmpl_words if len(tw) >= 4
649
+ ) if q_words and tmpl_words else False
650
+ if word_hits >= 1 or has_substr_hit:
651
+ admitted = True
652
+
653
+ if not admitted:
654
+ continue
655
+
656
+ has_lex = use_lexical_rerank and (lexical_raw.get(cid, 0) > 0)
657
+ rrf_dense = 1.0 / (K + dense_r)
658
+ rrf_lex = (1.0 / (K + lex_r)) if has_lex else 0.0
659
+ rrf_fact = (2.0 / (K + 1)) if has_fact else 0.0
660
+
661
+ rrf_score = (rrf_dense + rrf_lex + rrf_fact) * 30.0
662
+ item["score"] = round(rrf_score, 4)
663
+ item["dense_rank"] = dense_r
664
+ item["lexical_rank"] = lex_r if has_lex else None
665
+ item["has_fact"] = has_fact
666
+ scored_results.append(item)
667
+
668
+ scored_results.sort(key=lambda x: x["score"], reverse=True)
669
+ return scored_results[:limit]
670
+
671
+ def list_chunks(
672
+ self,
673
+ domain: Optional[str] = None,
674
+ limit: int = 20,
675
+ active_only: bool = True,
676
+ ) -> list[dict]:
677
+ """List stored chunks for browsing/supersede workflow."""
678
+ conditions: list[models.FieldCondition] = []
679
+
680
+ if active_only:
681
+ conditions.append(
682
+ models.FieldCondition(
683
+ key="is_active",
684
+ match=models.MatchValue(value=True),
685
+ )
686
+ )
687
+
688
+ if domain:
689
+ conditions.append(
690
+ models.FieldCondition(
691
+ key="domain",
692
+ match=models.MatchValue(value=domain),
693
+ )
694
+ )
695
+
696
+ scroll_filter = models.Filter(must=conditions) if conditions else None
697
+
698
+ records, _ = self._client.scroll(
699
+ collection_name=COLLECTION_NAME,
700
+ scroll_filter=scroll_filter,
701
+ limit=limit,
702
+ with_payload=True,
703
+ with_vectors=False,
704
+ )
705
+
706
+ return [
707
+ {
708
+ "id": str(r.id),
709
+ "domain": r.payload.get("domain", "unknown"),
710
+ "template": _truncate(r.payload.get("template", ""), 120),
711
+ "created_at": r.payload.get("created_at", 0),
712
+ "is_active": r.payload.get("is_active", True),
713
+ "source": r.payload.get("source", "agent_inferred"),
714
+ "referenced_facts": r.payload.get("referenced_facts", []),
715
+ }
716
+ for r in records
717
+ ]
718
+
719
+ def count_chunks(self, active_only: bool = True) -> int:
720
+ """Count total chunks in the store."""
721
+ info = self._client.get_collection(COLLECTION_NAME)
722
+ total = info.points_count or 0
723
+
724
+ if not active_only:
725
+ return total
726
+
727
+ try:
728
+ result = self._client.count(
729
+ collection_name=COLLECTION_NAME,
730
+ count_filter=models.Filter(
731
+ must=[
732
+ models.FieldCondition(
733
+ key="is_active",
734
+ match=models.MatchValue(value=True),
735
+ )
736
+ ]
737
+ ),
738
+ exact=True,
739
+ )
740
+ return result.count
741
+ except Exception:
742
+ return total
743
+
744
+ def get_active_domains(self) -> list[str]:
745
+ """Get list of unique domain names with active chunks."""
746
+ records, _ = self._client.scroll(
747
+ collection_name=COLLECTION_NAME,
748
+ scroll_filter=models.Filter(
749
+ must=[
750
+ models.FieldCondition(
751
+ key="is_active",
752
+ match=models.MatchValue(value=True),
753
+ )
754
+ ]
755
+ ),
756
+ limit=1000,
757
+ with_payload=["domain"],
758
+ with_vectors=False,
759
+ )
760
+ domains = {r.payload.get("domain", "unknown") for r in records}
761
+ return sorted(domains)
762
+
763
+ def close(self) -> None:
764
+ """Close the Qdrant client."""
765
+ if hasattr(self, "_client") and self._client is not None:
766
+ try:
767
+ self._client.close()
768
+ logger.info("Vector store closed.")
769
+ except Exception as e:
770
+ logger.warning("Error closing vector store: %s", e)
771
+
772
+
773
+ def _truncate(text: str, max_len: int) -> str:
774
+ """Truncate text with ellipsis if too long."""
775
+ if len(text) <= max_len:
776
+ return text
777
+ return text[: max_len - 3] + "..."
778
+
779
+
780
+ # Module-level singleton
781
+ _store: Optional[VectorStore] = None
782
+ _store_lock = threading.Lock()
783
+
784
+
785
+ def get_vector_store() -> VectorStore:
786
+ """Get or create the module-level VectorStore singleton."""
787
+ global _store
788
+ if _store is None:
789
+ with _store_lock:
790
+ if _store is None:
791
+ _store = VectorStore()
792
+ return _store