ltcai 11.2.0 → 11.4.0

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 (247) hide show
  1. package/README.md +46 -53
  2. package/docs/CHANGELOG.md +61 -0
  3. package/docs/COMMUNITY_AND_PLUGINS.md +1 -1
  4. package/docs/DEVELOPMENT.md +1 -1
  5. package/docs/MULTI_AGENT_RUNTIME.md +1 -1
  6. package/docs/ONBOARDING.md +1 -1
  7. package/docs/OPERATIONS.md +6 -2
  8. package/docs/PERMISSION_MODE.md +1 -1
  9. package/docs/TRUST_MODEL.md +1 -1
  10. package/docs/WHY_LATTICE.md +1 -1
  11. package/docs/kg-schema.md +2 -2
  12. package/docs/v11.3.0_PLAN.md +202 -0
  13. package/docs/v11.4.0_RUST_FOUNDATION_PLAN.md +176 -0
  14. package/lattice_brain/__init__.py +1 -1
  15. package/lattice_brain/graph/_kg_common/__init__.py +287 -0
  16. package/lattice_brain/graph/_kg_common/extraction.py +516 -0
  17. package/lattice_brain/graph/_kg_common/relations.py +161 -0
  18. package/lattice_brain/graph/_kg_common/text.py +479 -0
  19. package/lattice_brain/graph/discovery_index/__init__.py +35 -0
  20. package/lattice_brain/graph/discovery_index/cleanup.py +182 -0
  21. package/lattice_brain/graph/discovery_index/extract.py +137 -0
  22. package/lattice_brain/graph/discovery_index/scan.py +411 -0
  23. package/lattice_brain/graph/discovery_index/upsert.py +495 -0
  24. package/lattice_brain/graph/projection/__init__.py +42 -0
  25. package/lattice_brain/graph/projection/curation.py +500 -0
  26. package/lattice_brain/graph/{projection.py → projection/v2_schema.py} +15 -477
  27. package/lattice_brain/graph/retrieval/__init__.py +54 -0
  28. package/lattice_brain/graph/retrieval/context.py +197 -0
  29. package/lattice_brain/graph/retrieval/graph_view.py +319 -0
  30. package/lattice_brain/graph/retrieval/hybrid.py +488 -0
  31. package/lattice_brain/graph/retrieval/maintenance.py +121 -0
  32. package/lattice_brain/graph/retrieval/signals.py +95 -0
  33. package/lattice_brain/graph/retrieval_vector/__init__.py +42 -0
  34. package/lattice_brain/graph/retrieval_vector/fingerprint.py +97 -0
  35. package/lattice_brain/graph/retrieval_vector/indexing.py +347 -0
  36. package/lattice_brain/graph/retrieval_vector/search.py +560 -0
  37. package/lattice_brain/graph/retrieval_vector/status.py +374 -0
  38. package/lattice_brain/ingestion/__init__.py +130 -0
  39. package/lattice_brain/ingestion/_contract.py +90 -0
  40. package/lattice_brain/ingestion/constants.py +127 -0
  41. package/lattice_brain/ingestion/folder_scan.py +57 -0
  42. package/lattice_brain/ingestion/folders.py +258 -0
  43. package/lattice_brain/ingestion/hashing.py +26 -0
  44. package/lattice_brain/ingestion/jobs_api.py +107 -0
  45. package/lattice_brain/ingestion/models.py +80 -0
  46. package/lattice_brain/ingestion/pipeline.py +486 -0
  47. package/lattice_brain/ingestion/quality.py +209 -0
  48. package/lattice_brain/ingestion/routing.py +295 -0
  49. package/lattice_brain/multimodal/__init__.py +164 -0
  50. package/lattice_brain/multimodal/audio.py +77 -0
  51. package/lattice_brain/multimodal/common.py +118 -0
  52. package/lattice_brain/multimodal/images.py +498 -0
  53. package/lattice_brain/multimodal/ports.py +169 -0
  54. package/lattice_brain/multimodal/video.py +410 -0
  55. package/lattice_brain/portability/__init__.py +90 -0
  56. package/lattice_brain/portability/_contract.py +42 -0
  57. package/lattice_brain/portability/backups.py +338 -0
  58. package/lattice_brain/portability/bundles.py +136 -0
  59. package/lattice_brain/portability/constants.py +93 -0
  60. package/lattice_brain/portability/fsops.py +138 -0
  61. package/lattice_brain/portability/service.py +41 -0
  62. package/lattice_brain/{portability.py → portability/sharing.py} +44 -677
  63. package/lattice_brain/runtime/__init__.py +1 -1
  64. package/lattice_brain/runtime/multi_agent.py +1 -1
  65. package/latticeai/__init__.py +1 -1
  66. package/latticeai/api/chronicle.py +63 -0
  67. package/latticeai/core/agent/__init__.py +93 -0
  68. package/latticeai/core/agent/_contract.py +79 -0
  69. package/latticeai/core/agent/context.py +57 -0
  70. package/latticeai/core/agent/deps.py +125 -0
  71. package/latticeai/core/agent/execution.py +622 -0
  72. package/latticeai/core/agent/planning.py +145 -0
  73. package/latticeai/core/agent/recovery.py +157 -0
  74. package/latticeai/core/agent/runtime.py +210 -0
  75. package/latticeai/core/agent/verification.py +231 -0
  76. package/latticeai/core/embedding_providers/__init__.py +151 -0
  77. package/latticeai/core/embedding_providers/base.py +199 -0
  78. package/latticeai/core/embedding_providers/captions.py +162 -0
  79. package/latticeai/core/embedding_providers/profiles.py +126 -0
  80. package/latticeai/core/embedding_providers/text.py +350 -0
  81. package/latticeai/core/embedding_providers/vision.py +352 -0
  82. package/latticeai/core/file_generation/__init__.py +115 -0
  83. package/latticeai/core/file_generation/bundles.py +76 -0
  84. package/latticeai/core/file_generation/extraction.py +154 -0
  85. package/latticeai/core/file_generation/inference.py +235 -0
  86. package/latticeai/core/file_generation/orchestration.py +152 -0
  87. package/latticeai/core/file_generation/prompting.py +117 -0
  88. package/latticeai/core/file_generation/repair.py +114 -0
  89. package/latticeai/core/file_generation/sanitize.py +61 -0
  90. package/latticeai/core/file_generation/validation.py +201 -0
  91. package/latticeai/core/legacy_compatibility.py +1 -1
  92. package/latticeai/core/marketplace.py +1 -1
  93. package/latticeai/core/messages.py +9 -0
  94. package/latticeai/core/workspace_os_constants.py +1 -1
  95. package/latticeai/integrations/telegram_bot/__init__.py +123 -0
  96. package/latticeai/integrations/telegram_bot/__main__.py +17 -0
  97. package/latticeai/integrations/telegram_bot/config.py +86 -0
  98. package/latticeai/integrations/telegram_bot/dispatch.py +311 -0
  99. package/latticeai/integrations/telegram_bot/flows.py +478 -0
  100. package/latticeai/integrations/telegram_bot/helpers.py +322 -0
  101. package/latticeai/integrations/telegram_bot/screens.py +394 -0
  102. package/latticeai/models/router/__init__.py +88 -0
  103. package/latticeai/models/router/_contract.py +66 -0
  104. package/latticeai/models/router/branding.py +56 -0
  105. package/latticeai/models/router/catalog.py +69 -0
  106. package/latticeai/models/router/documents.py +199 -0
  107. package/latticeai/models/router/errors.py +37 -0
  108. package/latticeai/models/router/generation.py +258 -0
  109. package/latticeai/models/router/loading.py +291 -0
  110. package/latticeai/models/router/local_models.py +85 -0
  111. package/latticeai/models/router/registry.py +147 -0
  112. package/latticeai/runtime/build_phases/__init__.py +82 -0
  113. package/latticeai/runtime/build_phases/features.py +407 -0
  114. package/latticeai/runtime/build_phases/foundation.py +555 -0
  115. package/latticeai/runtime/build_phases/web.py +492 -0
  116. package/latticeai/runtime/runtime_context.py +1 -0
  117. package/latticeai/services/architecture_readiness.py +48 -19
  118. package/latticeai/services/brain_intelligence/__init__.py +58 -0
  119. package/latticeai/services/brain_intelligence/_contract.py +71 -0
  120. package/latticeai/services/brain_intelligence/consistency.py +193 -0
  121. package/latticeai/services/brain_intelligence/constants.py +47 -0
  122. package/latticeai/services/brain_intelligence/digest.py +258 -0
  123. package/latticeai/services/brain_intelligence/health.py +331 -0
  124. package/latticeai/services/brain_intelligence/proposals.py +264 -0
  125. package/latticeai/services/brain_intelligence/sampling.py +84 -0
  126. package/latticeai/services/brain_intelligence/service.py +48 -0
  127. package/latticeai/services/chronicle.py +557 -0
  128. package/latticeai/services/memory_service/__init__.py +52 -0
  129. package/latticeai/services/memory_service/_contract.py +100 -0
  130. package/latticeai/services/memory_service/brief.py +431 -0
  131. package/latticeai/services/memory_service/constants.py +57 -0
  132. package/latticeai/services/memory_service/maintenance.py +138 -0
  133. package/latticeai/services/memory_service/manager.py +186 -0
  134. package/latticeai/services/memory_service/proof.py +136 -0
  135. package/latticeai/services/memory_service/recall.py +225 -0
  136. package/latticeai/services/memory_service/service.py +48 -0
  137. package/latticeai/services/memory_service/stores.py +110 -0
  138. package/latticeai/services/model_runtime/__init__.py +322 -0
  139. package/latticeai/services/model_runtime/cloud.py +87 -0
  140. package/latticeai/services/model_runtime/download.py +282 -0
  141. package/latticeai/services/model_runtime/engines.py +341 -0
  142. package/latticeai/services/model_runtime/loading.py +178 -0
  143. package/latticeai/services/model_runtime/service.py +129 -0
  144. package/latticeai/services/model_runtime/state.py +131 -0
  145. package/latticeai/services/model_runtime/status.py +255 -0
  146. package/latticeai/services/product_readiness.py +15 -7
  147. package/latticeai/setup/wizard/__init__.py +126 -0
  148. package/latticeai/setup/wizard/catalog.py +172 -0
  149. package/latticeai/setup/wizard/detect.py +323 -0
  150. package/latticeai/setup/wizard/install.py +348 -0
  151. package/latticeai/setup/wizard/paths.py +168 -0
  152. package/latticeai/setup/wizard/plans.py +74 -0
  153. package/latticeai/setup/wizard/recommend.py +320 -0
  154. package/package.json +6 -2
  155. package/scripts/bump_version.py +14 -0
  156. package/scripts/capture_release_evidence.mjs +33 -21
  157. package/scripts/check_current_release_docs.mjs +1 -1
  158. package/scripts/check_i18n_namespace_coverage.mjs +41 -4
  159. package/scripts/check_max_file_lines.mjs +102 -0
  160. package/scripts/check_release_evidence_bound.mjs +30 -15
  161. package/scripts/check_screenshot_pixel_delta.py +34 -4
  162. package/scripts/check_server_i18n.mjs +1 -0
  163. package/scripts/generate_rust_parity_fixtures.py +562 -0
  164. package/scripts/lib/mock_server_fingerprint.mjs +94 -0
  165. package/scripts/release_screen_claims.json +31 -2
  166. package/src-tauri/Cargo.lock +361 -3
  167. package/src-tauri/Cargo.toml +6 -1
  168. package/src-tauri/src/backend.rs +349 -0
  169. package/src-tauri/src/folder.rs +33 -0
  170. package/src-tauri/src/main.rs +97 -399
  171. package/src-tauri/tauri.conf.json +1 -1
  172. package/static/app/asset-manifest.json +41 -37
  173. package/static/app/assets/Act-yYpYnn0v.js +1 -0
  174. package/static/app/assets/AdminConsole-DL3Cr5pL.js +1 -0
  175. package/static/app/assets/{Brain-tuhI4sOC.js → Brain-C1HBN0Wf.js} +2 -2
  176. package/static/app/assets/BrainHome-DoXRhUUC.js +2 -0
  177. package/static/app/assets/BrainSignals-6yR6ir5t.js +1 -0
  178. package/static/app/assets/Capture-CFIRsFNE.js +1 -0
  179. package/static/app/assets/Chronicle-BZbEgiwN.js +1 -0
  180. package/static/app/assets/CommandPalette-D2pMxC2I.js +1 -0
  181. package/static/app/assets/Library-DwO3yZST.js +1 -0
  182. package/static/app/assets/{LivingBrain-DBwhto14.js → LivingBrain-Jn1GK0-S.js} +1 -1
  183. package/static/app/assets/ProductFlow-B-w1R4Oo.js +1 -0
  184. package/static/app/assets/ReviewCard-6B27X8Vg.js +3 -0
  185. package/static/app/assets/System-DW8F-2xL.js +1 -0
  186. package/static/app/assets/arrow-left-DXvKg9U6.js +1 -0
  187. package/static/app/assets/{bot-Cia42c2h.js → bot-IM_E_Y12.js} +1 -1
  188. package/static/app/assets/brain-Ci1CkWjM.js +1 -0
  189. package/static/app/assets/{button-2j2Ijzgq.js → button-COwyqfHM.js} +1 -1
  190. package/static/app/assets/circle-check-DfInj-qD.js +1 -0
  191. package/static/app/assets/{circle-pause-BEFeWpVW.js → circle-pause-DEM4A1Y5.js} +1 -1
  192. package/static/app/assets/{circle-play-ujXMcHxl.js → circle-play-C9djDuLd.js} +1 -1
  193. package/static/app/assets/{cpu-k4awryFq.js → cpu-DFdo1gw-.js} +1 -1
  194. package/static/app/assets/{download-DFbLJ_ig.js → download-SnJL6oqk.js} +1 -1
  195. package/static/app/assets/{folder-open-7y_b6xkM.js → folder-open-CqZeDkjE.js} +1 -1
  196. package/static/app/assets/{hard-drive-Bidh02Kr.js → hard-drive-j1jJXYYf.js} +1 -1
  197. package/static/app/assets/{index-DwDl9-8Y.css → index-BLPb5lmE.css} +1 -1
  198. package/static/app/assets/index-_u5iUHDr.js +10 -0
  199. package/static/app/assets/input-B0lPdRQZ.js +1 -0
  200. package/static/app/assets/link-2-CoFbooHS.js +1 -0
  201. package/static/app/assets/{permissionCopy-Bpb83Hx9.js → permissionCopy-BsyLxtao.js} +1 -1
  202. package/static/app/assets/primitives-DEbN-d6p.js +1 -0
  203. package/static/app/assets/search-BybIWPNd.js +1 -0
  204. package/static/app/assets/{share-2-BH1M-WNi.js → share-2-CVtZ_ewX.js} +1 -1
  205. package/static/app/assets/{shield-alert-BlKdBXcG.js → shield-alert-CBi2GNWM.js} +1 -1
  206. package/static/app/assets/{textarea-CCWbUfFB.js → textarea-DNMpB5ih.js} +1 -1
  207. package/static/app/assets/{useFocusTrap-YdHQ7pJ1.js → useFocusTrap-C83t3GXF.js} +1 -1
  208. package/static/app/assets/useMutation-DtbJDoyz.js +1 -0
  209. package/static/app/assets/{useQuery-CXQiwbVT.js → useQuery-Dcp1OChy.js} +1 -1
  210. package/static/app/assets/utils-BlZr7Pd4.js +4 -0
  211. package/static/app/assets/workspace-jJY4RuAV.js +1 -0
  212. package/static/app/index.html +4 -4
  213. package/static/sw.js +1 -1
  214. package/lattice_brain/graph/_kg_common.py +0 -1331
  215. package/lattice_brain/graph/discovery_index.py +0 -1141
  216. package/lattice_brain/graph/retrieval.py +0 -1120
  217. package/lattice_brain/graph/retrieval_vector.py +0 -1293
  218. package/lattice_brain/ingestion.py +0 -1525
  219. package/lattice_brain/multimodal.py +0 -1258
  220. package/latticeai/core/agent.py +0 -1465
  221. package/latticeai/core/embedding_providers.py +0 -1196
  222. package/latticeai/core/file_generation.py +0 -1047
  223. package/latticeai/integrations/telegram_bot.py +0 -1390
  224. package/latticeai/models/router.py +0 -1007
  225. package/latticeai/runtime/build_phases.py +0 -1450
  226. package/latticeai/services/brain_intelligence.py +0 -1083
  227. package/latticeai/services/memory_service.py +0 -1177
  228. package/latticeai/services/model_runtime.py +0 -1281
  229. package/latticeai/setup/wizard.py +0 -1310
  230. package/static/app/assets/Act-AWf0SAKp.js +0 -1
  231. package/static/app/assets/AdminConsole-D0u8Tiyj.js +0 -1
  232. package/static/app/assets/BrainHome-Ts7G_Ila.js +0 -2
  233. package/static/app/assets/BrainSignals-jMYgQ2Ar.js +0 -1
  234. package/static/app/assets/Capture-CqOSzyPr.js +0 -1
  235. package/static/app/assets/CommandPalette-DC0Bzh-I.js +0 -1
  236. package/static/app/assets/Library-CX-bbhmK.js +0 -1
  237. package/static/app/assets/ProductFlow-BHA2cfKI.js +0 -1
  238. package/static/app/assets/ReviewCard-BUhCKRNM.js +0 -3
  239. package/static/app/assets/System-Bu2t5hn1.js +0 -1
  240. package/static/app/assets/arrow-left-Dzwa5zRb.js +0 -1
  241. package/static/app/assets/brain-DJMoqrwx.js +0 -1
  242. package/static/app/assets/index-BpYkzcVm.js +0 -10
  243. package/static/app/assets/input-DSlJJxRs.js +0 -1
  244. package/static/app/assets/primitives-BCx6TvfG.js +0 -1
  245. package/static/app/assets/search-Cgy8cCFJ.js +0 -1
  246. package/static/app/assets/utils-zqPZJxdx.js +0 -4
  247. package/static/app/assets/workspace-DXTihhfU.js +0 -1
@@ -0,0 +1,560 @@
1
+ """Vector search: backend selection, the candidate cap, and scoring.
2
+
3
+ The module-level knobs live **here**, next to the only code that reads them —
4
+ ``VECTOR_SCAN_BATCH`` in particular, whose patch target is therefore
5
+ ``lattice_brain.graph.retrieval_vector.search``. Moved verbatim out of
6
+ ``retrieval_vector.py`` (v11.3.0 decomposition).
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import dataclasses
12
+ from typing import TYPE_CHECKING
13
+
14
+ # ruff: noqa: F403,F405
15
+ from .._kg_common import * # noqa: F403,F401
16
+ from ..vector_index import (
17
+ DEFAULT_VECTOR_INDEX,
18
+ HNSW_BACKEND,
19
+ VECTOR_INDEX_ENV,
20
+ BackendSelection,
21
+ HnswIndex,
22
+ IndexItem,
23
+ VectorIndex,
24
+ build_index,
25
+ resolve_vector_index,
26
+ )
27
+
28
+ # The cross-mixin surface (`_connect`, `_upsert_node`, …) is declared in
29
+ # `_kg_contract.KnowledgeGraphCore`. It is a typing-only base: at runtime this
30
+ # is `object`, so the MRO of `KnowledgeGraphStore` is unchanged.
31
+ if TYPE_CHECKING:
32
+ from .._kg_contract import KnowledgeGraphCore as _Core
33
+ else:
34
+ _Core = object
35
+
36
+
37
+ # ── brute-force recall cap (review 2026-08 P1 #2) ────────────────────────────
38
+ # There is no ANN index in the default build: sqlite-vec is an optional
39
+ # dependency and, when it is absent, `index_status()["storage"]` honestly
40
+ # reports ``vector_search_backend: "bruteforce-cosine"``. Brute force scores
41
+ # every candidate in Python, so *some* cap is unavoidable on a large graph.
42
+ #
43
+ # What is not acceptable is a SILENT cap. The pre-10.7 code took the 10 000
44
+ # most recently indexed rows — ordered by ``indexed_at``, i.e. by recency, not
45
+ # by similarity — and returned them as if they were the whole index, so recall
46
+ # on a 200 000-row brain quietly became "the newest 5%". The cap is now
47
+ # explicit, configurable, and reported back to the caller in ``recall``.
48
+ #
49
+ # ``LATTICEAI_VECTOR_MAX_CANDIDATES`` overrides the default; ``0`` means "no
50
+ # cap — scan the whole index" (exact recall, paid for in latency).
51
+ VECTOR_MAX_CANDIDATES_ENV = "LATTICEAI_VECTOR_MAX_CANDIDATES"
52
+ DEFAULT_VECTOR_MAX_CANDIDATES = 10_000
53
+ #: Upper bound for a configured cap; ``0``/``None`` still means uncapped.
54
+ VECTOR_MAX_CANDIDATES_CEILING = 500_000
55
+
56
+ # ── scan batching (v11.1.0) ──────────────────────────────────────────────────
57
+ # The exact scan hands its candidates to a VectorIndex, which by definition
58
+ # holds what it is given. Handing it the whole result set would make peak
59
+ # memory O(rows × dim) floats, so the scan feeds it in fixed batches instead:
60
+ # exhaustive backends score every batch independently, so the union is
61
+ # identical to one big pass, at O(batch × dim) resident cost.
62
+ VECTOR_SCAN_BATCH = 512
63
+
64
+
65
+ def _configured_vector_max_candidates() -> Optional[int]:
66
+ """Resolve the candidate cap from the environment (None = uncapped).
67
+
68
+ Never raises: an unparseable value falls back to the documented default
69
+ rather than breaking every search.
70
+ """
71
+ raw = os.getenv(VECTOR_MAX_CANDIDATES_ENV)
72
+ if raw is None or not raw.strip():
73
+ return DEFAULT_VECTOR_MAX_CANDIDATES
74
+ try:
75
+ value = int(raw.strip())
76
+ except ValueError:
77
+ logging.warning(
78
+ "%s=%r is not an integer — using the default cap of %d",
79
+ VECTOR_MAX_CANDIDATES_ENV, raw, DEFAULT_VECTOR_MAX_CANDIDATES,
80
+ )
81
+ return DEFAULT_VECTOR_MAX_CANDIDATES
82
+ if value <= 0:
83
+ return None # explicit opt-in to an exhaustive scan
84
+ return min(value, VECTOR_MAX_CANDIDATES_CEILING)
85
+
86
+
87
+ class _VectorSearchMixin(_Core):
88
+ """Vector search + scoring. Composed into the public mixin."""
89
+
90
+ def _vector_index_selection(self) -> BackendSelection:
91
+ """The configured in-process index backend (``LATTICEAI_VECTOR_INDEX``).
92
+
93
+ Resolved per call rather than cached: the env var is the whole control
94
+ surface, and a cached selection would make a config change look like
95
+ it had no effect. The only expensive part — importing ``hnswlib`` —
96
+ is already cached by ``sys.modules``.
97
+ """
98
+ return resolve_vector_index()
99
+
100
+ def _vector_search_backend(self) -> str:
101
+ """Which backend actually scores the vectors.
102
+
103
+ An explicitly selected in-process index (quantized / hnsw) wins,
104
+ because it is the thing that will do the scoring. Otherwise this is
105
+ the storage layer's answer: sqlite-vec exposes an ANN index; without
106
+ it this store scores rows in Python (``bruteforce-cosine``). Never
107
+ raises — a capability probe failure means "we cannot claim ANN",
108
+ which is the brute-force answer.
109
+ """
110
+ selection = self._vector_index_selection()
111
+ if selection.name != DEFAULT_VECTOR_INDEX:
112
+ return selection.backend
113
+ try:
114
+ capabilities = self.storage_engine.capabilities().as_dict()
115
+ except Exception: # noqa: BLE001 — a probe failure is not an ANN index
116
+ return "bruteforce-cosine"
117
+ backend = (capabilities or {}).get("vector_backend")
118
+ return str(backend) if backend else "bruteforce-cosine"
119
+
120
+ @staticmethod
121
+ def _recall_report(
122
+ *,
123
+ backend: str,
124
+ cap: Optional[int],
125
+ candidates_total: int,
126
+ candidates_scanned: int,
127
+ approx_detail: Optional[str] = None,
128
+ ) -> Dict[str, Any]:
129
+ """The honest answer to "did this search see the whole index?".
130
+
131
+ ``approx_detail`` covers the second way recall can be incomplete: an
132
+ ANN backend *visits* the whole index but is not guaranteed to return
133
+ its true top-k. "Scanned N of N" with no detail would read as an exact
134
+ answer, so the approximate backends supply their caveat here.
135
+ """
136
+ truncated = candidates_scanned < candidates_total
137
+ detail: Optional[str] = None
138
+ if truncated:
139
+ detail = (
140
+ f"partial recall: scored the {candidates_scanned} most recently "
141
+ f"indexed vectors of {candidates_total}. The cut is by index "
142
+ f"recency, not similarity, so older matches were never compared. "
143
+ f"Raise {VECTOR_MAX_CANDIDATES_ENV} (0 = scan everything), or "
144
+ f"switch to an index that covers the whole set: "
145
+ f"{VECTOR_INDEX_ENV}=hnsw (needs the optional hnsw extra) or "
146
+ f"install sqlite-vec."
147
+ )
148
+ elif approx_detail:
149
+ detail = approx_detail
150
+ return {
151
+ "backend": backend,
152
+ "max_candidates": cap,
153
+ "candidates_total": candidates_total,
154
+ "candidates_scanned": candidates_scanned,
155
+ "truncated": truncated,
156
+ "detail": detail,
157
+ }
158
+
159
+ def _vector_candidate_cap(
160
+ self, requested: Optional[int], *, limit: int
161
+ ) -> Optional[int]:
162
+ """Resolve the effective candidate cap (None = scan everything).
163
+
164
+ ``requested is None`` uses the configured/default cap; an explicit
165
+ ``<= 0`` is the caller asking for an exhaustive scan. Note the
166
+ ``is None`` test: ``0`` is a meaningful value here, so truthiness
167
+ would silently turn "no cap" into "the default cap".
168
+ """
169
+ if requested is None:
170
+ cap = _configured_vector_max_candidates()
171
+ elif int(requested) <= 0:
172
+ cap = None
173
+ else:
174
+ cap = min(int(requested), VECTOR_MAX_CANDIDATES_CEILING)
175
+ if cap is None:
176
+ return None
177
+ # Never scan fewer rows than the caller intends to receive.
178
+ return max(limit, cap)
179
+
180
+ # One row shape feeds every vector match, so both the exact scan and the
181
+ # ANN lookup project exactly the same columns; only the WHERE/ORDER tail
182
+ # differs. Bound values are always parameters — the interpolation below is
183
+ # a placeholder list, never data.
184
+ _VECTOR_ROW_SELECT = """
185
+ SELECT
186
+ ve.item_id, ve.item_type, ve.source_node, ve.embedding,
187
+ ve.embedding_dim, ve.embedding_model, ve.metadata_json AS vector_metadata,
188
+ n.type AS node_type, n.title AS node_title, n.summary AS node_summary,
189
+ n.metadata_json AS node_metadata, n.updated_at AS node_updated_at,
190
+ c.text AS chunk_text, c.source_node AS parent_node_id,
191
+ c.metadata_json AS chunk_metadata,
192
+ pn.type AS parent_type, pn.title AS parent_title,
193
+ pn.summary AS parent_summary, pn.metadata_json AS parent_metadata,
194
+ pn.updated_at AS parent_updated_at
195
+ FROM vector_embeddings ve
196
+ LEFT JOIN nodes n ON n.id=ve.source_node
197
+ LEFT JOIN chunks c ON c.id=ve.item_id
198
+ LEFT JOIN nodes pn ON pn.id=c.source_node
199
+ WHERE ve.embedding_model=? AND ve.embedding_dim=?
200
+ """
201
+
202
+ @staticmethod
203
+ def _vector_match(row: sqlite3.Row, score: float) -> Dict[str, Any]:
204
+ """One scored embedding row → one search match (pure projection)."""
205
+ is_chunk = row["item_type"] == "chunk"
206
+ summary = (
207
+ row["chunk_text"] if is_chunk and row["chunk_text"] else row["node_summary"]
208
+ )
209
+ parent_metadata = _safe_loads(row["parent_metadata"])
210
+ node_metadata = _safe_loads(row["node_metadata"])
211
+ # Citation precision (review 2026-07-27 P1 #4): a chunk hit used to
212
+ # cite only its parent document, so a 200-page PDF answered with
213
+ # "from report.pdf". The chunk's own provenance (section heading,
214
+ # page, offset) now rides along, and `locator` is the one-line
215
+ # human form — absent when the chunk carries no such metadata.
216
+ chunk_metadata = _safe_loads(row["chunk_metadata"]) if is_chunk else {}
217
+ locator = citation_locator(chunk_metadata)
218
+ return {
219
+ "id": row["item_id"],
220
+ "node_id": row["parent_node_id"]
221
+ if is_chunk and row["parent_node_id"]
222
+ else row["source_node"],
223
+ "item_type": row["item_type"],
224
+ "type": "Chunk" if is_chunk else row["node_type"],
225
+ "title": row["parent_title"]
226
+ if is_chunk and row["parent_title"]
227
+ else row["node_title"],
228
+ "summary": _clean_text(summary or "")[:1000],
229
+ "score": round(float(score), 6),
230
+ "metadata": {
231
+ **(parent_metadata if is_chunk else node_metadata),
232
+ "vector": _safe_loads(row["vector_metadata"]),
233
+ "parent_node_id": row["parent_node_id"],
234
+ "parent_type": row["parent_type"],
235
+ **({"chunk": chunk_metadata} if chunk_metadata else {}),
236
+ **({"locator": locator} if locator else {}),
237
+ },
238
+ "updated_at": row["parent_updated_at"]
239
+ if is_chunk and row["parent_updated_at"]
240
+ else row["node_updated_at"],
241
+ }
242
+
243
+ @staticmethod
244
+ def _flush_scan_batch(
245
+ index: VectorIndex,
246
+ batch: List[IndexItem],
247
+ query_vector: List[float],
248
+ min_score: float,
249
+ scores: Dict[str, float],
250
+ ) -> None:
251
+ """Score one batch into ``scores`` and empty it."""
252
+ if not batch:
253
+ return
254
+ index.rebuild(batch)
255
+ scores.update(
256
+ index.search(query_vector, len(batch), filter={"min_score": min_score})
257
+ )
258
+ batch.clear()
259
+
260
+ def _score_vector_rows(
261
+ self,
262
+ rows: List[sqlite3.Row],
263
+ query_vector: List[float],
264
+ selection: BackendSelection,
265
+ *,
266
+ min_score: float,
267
+ ) -> Dict[str, float]:
268
+ """``item_id -> score`` for every row that clears ``min_score``."""
269
+ index = build_index(
270
+ selection,
271
+ dim=int(self._embedding_model.dim),
272
+ similarity=self._embedding_model.similarity,
273
+ )
274
+ scores: Dict[str, float] = {}
275
+ batch: List[IndexItem] = []
276
+ for row in rows:
277
+ batch.append(
278
+ (
279
+ str(row["item_id"]),
280
+ self._embedding_model.decode(
281
+ row["embedding"], row["embedding_dim"]
282
+ ),
283
+ {"item_type": row["item_type"]},
284
+ )
285
+ )
286
+ if len(batch) >= VECTOR_SCAN_BATCH:
287
+ self._flush_scan_batch(index, batch, query_vector, min_score, scores)
288
+ self._flush_scan_batch(index, batch, query_vector, min_score, scores)
289
+ return scores
290
+
291
+ def _vector_search_scan(
292
+ self,
293
+ query: str,
294
+ query_vector: List[float],
295
+ selection: BackendSelection,
296
+ *,
297
+ limit: int,
298
+ min_score: float,
299
+ backend: str,
300
+ cap: Optional[int],
301
+ ) -> Dict[str, Any]:
302
+ """Exhaustive scan of (at most ``cap``) rows — the historical path."""
303
+ sql = self._VECTOR_ROW_SELECT + " ORDER BY ve.indexed_at DESC"
304
+ params: List[Any] = [
305
+ self._embedding_model.model_id,
306
+ self._embedding_model.dim,
307
+ ]
308
+ if cap is not None:
309
+ sql += " LIMIT ?"
310
+ params.append(cap)
311
+ with self._connect() as conn:
312
+ # Counted in the same transaction as the scan so "scanned N of M"
313
+ # cannot describe two different index states.
314
+ candidates_total = int(
315
+ conn.execute(
316
+ "SELECT COUNT(*) AS c FROM vector_embeddings "
317
+ "WHERE embedding_model=? AND embedding_dim=?",
318
+ (self._embedding_model.model_id, self._embedding_model.dim),
319
+ ).fetchone()["c"]
320
+ )
321
+ rows = conn.execute(sql, tuple(params)).fetchall()
322
+ recall = self._recall_report(
323
+ backend=backend,
324
+ cap=cap,
325
+ candidates_total=candidates_total,
326
+ candidates_scanned=len(rows),
327
+ approx_detail=(
328
+ "approximate backend: every candidate was compared, but the "
329
+ "scores are estimates, so near-ties can reorder"
330
+ if selection.approx
331
+ else None
332
+ ),
333
+ )
334
+ scores = self._score_vector_rows(
335
+ rows, query_vector, selection, min_score=min_score
336
+ )
337
+ # Rows are walked in index order (not score order) so the sort below
338
+ # sees exactly the input ordering the pre-11.1.0 inline loop produced:
339
+ # a stable sort makes that the tie-break of last resort.
340
+ scored = [
341
+ self._vector_match(row, scores[str(row["item_id"])])
342
+ for row in rows
343
+ if str(row["item_id"]) in scores
344
+ ]
345
+ scored.sort(
346
+ key=lambda item: (item["score"], item.get("updated_at") or ""), reverse=True
347
+ )
348
+ return {
349
+ "query": query,
350
+ "embedding_model": self._embedding_model.model_id,
351
+ "embedding_dim": self._embedding_model.dim,
352
+ "matches": scored[:limit],
353
+ "recall": recall,
354
+ "index": selection.as_dict(),
355
+ }
356
+
357
+ def _iter_vector_index_items(
358
+ self, conn: sqlite3.Connection, model_id: str, dim: int
359
+ ) -> Iterator[IndexItem]:
360
+ """Every embedding for ``model_id``/``dim`` as index items."""
361
+ for row in conn.execute(
362
+ "SELECT item_id, embedding, embedding_dim FROM vector_embeddings "
363
+ "WHERE embedding_model=? AND embedding_dim=? ORDER BY item_id ASC",
364
+ (model_id, dim),
365
+ ):
366
+ yield (
367
+ str(row["item_id"]),
368
+ self._embedding_model.decode(row["embedding"], row["embedding_dim"]),
369
+ {},
370
+ )
371
+
372
+ def _vector_rows_by_id(
373
+ self, conn: sqlite3.Connection, item_ids: List[str]
374
+ ) -> List[sqlite3.Row]:
375
+ """Full match rows for the ids an ANN lookup returned."""
376
+ if not item_ids:
377
+ return []
378
+ placeholders = ",".join("?" * len(item_ids))
379
+ return conn.execute(
380
+ self._VECTOR_ROW_SELECT + f" AND ve.item_id IN ({placeholders})",
381
+ (self._embedding_model.model_id, self._embedding_model.dim, *item_ids),
382
+ ).fetchall()
383
+
384
+ def _hnsw_index(
385
+ self,
386
+ conn: sqlite3.Connection,
387
+ fingerprint: str,
388
+ model_id: str,
389
+ dim: int,
390
+ ) -> HnswIndex:
391
+ """The live ANN graph for ``fingerprint`` — cache, sidecar, or rebuild.
392
+
393
+ Held on the store for the process's lifetime, because reading a
394
+ 50 000-vector graph off disk costs roughly as much as the search it
395
+ enables: paying it per query gave back most of the speedup (105 ms
396
+ instead of 15 ms at 50k). The fingerprint — model, dimension, row
397
+ count, newest ``indexed_at`` — is what makes the cache safe: any write
398
+ to ``vector_embeddings`` changes it, and a changed fingerprint is
399
+ never served from the cache or from the sidecar.
400
+ """
401
+ cached = getattr(self, "_hnsw_cached", None)
402
+ if cached is not None and cached[0] == fingerprint:
403
+ return cached[1]
404
+ index = HnswIndex(dim=dim)
405
+ if not index.load(self.db_path, fingerprint=fingerprint):
406
+ index.rebuild(self._iter_vector_index_items(conn, model_id, dim))
407
+ index.save(self.db_path, fingerprint=fingerprint)
408
+ self._hnsw_cached = (fingerprint, index)
409
+ return index
410
+
411
+ def _vector_search_ann(
412
+ self,
413
+ query: str,
414
+ query_vector: List[float],
415
+ selection: BackendSelection,
416
+ *,
417
+ limit: int,
418
+ min_score: float,
419
+ backend: str,
420
+ ) -> Optional[Dict[str, Any]]:
421
+ """Approximate top-k via the persisted HNSW sidecar.
422
+
423
+ Two phases instead of one: ask the graph for ids, then read only those
424
+ rows. That is where the speed comes from — the exact scan pays to
425
+ decode every embedding on every query, and this pays it once per
426
+ index generation.
427
+
428
+ The sidecar is keyed by ``model:dim:rows:newest`` so any write to
429
+ ``vector_embeddings`` invalidates it and the next search rebuilds.
430
+ Returns ``None`` when the index is empty, which the caller answers
431
+ with the ordinary (equally empty, but honestly reported) scan.
432
+ """
433
+ model_id = self._embedding_model.model_id
434
+ dim = int(self._embedding_model.dim)
435
+ with self._connect() as conn:
436
+ head = conn.execute(
437
+ "SELECT COUNT(*) AS c, MAX(indexed_at) AS newest FROM vector_embeddings "
438
+ "WHERE embedding_model=? AND embedding_dim=?",
439
+ (model_id, dim),
440
+ ).fetchone()
441
+ candidates_total = int(head["c"])
442
+ if candidates_total == 0:
443
+ return None
444
+ fingerprint = f"{model_id}:{dim}:{candidates_total}:{head['newest']}"
445
+ index = self._hnsw_index(conn, fingerprint, model_id, dim)
446
+ pairs = index.search(query_vector, limit, filter={"min_score": min_score})
447
+ rows = {
448
+ str(row["item_id"]): row
449
+ for row in self._vector_rows_by_id(
450
+ conn, [item_id for item_id, _ in pairs]
451
+ )
452
+ }
453
+ scored = [
454
+ self._vector_match(rows[item_id], score)
455
+ for item_id, score in pairs
456
+ if item_id in rows
457
+ ]
458
+ scored.sort(
459
+ key=lambda item: (item["score"], item.get("updated_at") or ""), reverse=True
460
+ )
461
+ return {
462
+ "query": query,
463
+ "embedding_model": model_id,
464
+ "embedding_dim": dim,
465
+ "matches": scored[:limit],
466
+ "recall": self._recall_report(
467
+ backend=backend,
468
+ cap=None,
469
+ candidates_total=candidates_total,
470
+ candidates_scanned=candidates_total,
471
+ approx_detail=(
472
+ "approximate nearest-neighbour search: the whole index is "
473
+ "reachable but the true top-k is not guaranteed — compare "
474
+ "with scripts/bench_vector_index.py"
475
+ ),
476
+ ),
477
+ "index": {**selection.as_dict(), "sidecar": index.loaded_from_sidecar},
478
+ }
479
+
480
+ def vector_search(
481
+ self,
482
+ query: str,
483
+ *,
484
+ limit: int = 30,
485
+ min_score: float = 0.0,
486
+ max_candidates: Optional[int] = None,
487
+ ) -> Dict[str, Any]:
488
+ """Cosine search over the vector index (exact by default).
489
+
490
+ ``max_candidates`` bounds how many indexed rows are scored; ``None``
491
+ (the default) resolves it from ``LATTICEAI_VECTOR_MAX_CANDIDATES``
492
+ (default 10 000), and ``0`` or a negative value scans the whole index.
493
+ When the cap bites, the rows kept are the most recently indexed ones —
494
+ recency, not similarity — so the result is *partial recall*. That is
495
+ reported in the additive ``recall`` block
496
+ (``{backend, max_candidates, candidates_total, candidates_scanned,
497
+ truncated, detail}``) instead of being hidden, and callers/UIs are
498
+ expected to surface ``recall.truncated``.
499
+
500
+ v11.1.0: the scoring itself now lives in
501
+ :mod:`lattice_brain.graph.vector_index`. ``LATTICEAI_VECTOR_INDEX``
502
+ picks the backend — ``brute`` (default, exact, byte-compatible with
503
+ every previous release), ``quantized`` (int8, exhaustive, approximate
504
+ scores) or ``hnsw`` (approximate nearest neighbour, needs the optional
505
+ ``hnsw`` extra). The resolved backend and any fallback reason ride
506
+ along in the additive ``index`` block, whose ``approx`` flag is the
507
+ one bit a caller needs to know whether "not found" is a fact or an
508
+ estimate. The empty-query early return is deliberately unchanged: no
509
+ query means no index was consulted, so there is nothing to report.
510
+ """
511
+ query = str(query or "").strip()
512
+ limit = max(1, min(int(limit or 30), 100))
513
+ min_score = float(min_score or 0.0)
514
+ cap = self._vector_candidate_cap(max_candidates, limit=limit)
515
+ backend = self._vector_search_backend()
516
+ if not query:
517
+ return {
518
+ "query": query,
519
+ "matches": [],
520
+ "recall": {
521
+ "backend": backend,
522
+ "max_candidates": cap,
523
+ "candidates_total": 0,
524
+ "candidates_scanned": 0,
525
+ "truncated": False,
526
+ "detail": None,
527
+ },
528
+ }
529
+ selection = self._vector_index_selection()
530
+ query_vector = self._embedding_model.embed(query)
531
+ if selection.name == HNSW_BACKEND:
532
+ try:
533
+ approximate = self._vector_search_ann(
534
+ query,
535
+ query_vector,
536
+ selection,
537
+ limit=limit,
538
+ min_score=min_score,
539
+ backend=backend,
540
+ )
541
+ except Exception as exc: # noqa: BLE001 — a broken ANN must not lose the answer
542
+ logging.warning("hnsw vector search failed: %s", exc)
543
+ selection = dataclasses.replace(
544
+ resolve_vector_index(DEFAULT_VECTOR_INDEX),
545
+ requested=HNSW_BACKEND,
546
+ detail=f"hnsw search failed ({exc}); used the exact scan instead",
547
+ )
548
+ backend = selection.backend
549
+ else:
550
+ if approximate is not None:
551
+ return approximate
552
+ return self._vector_search_scan(
553
+ query,
554
+ query_vector,
555
+ selection,
556
+ limit=limit,
557
+ min_score=min_score,
558
+ backend=backend,
559
+ cap=cap,
560
+ )