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
@@ -1,1177 +0,0 @@
1
- """Long-Term Memory platform + Memory Manager (v3.2.0).
2
-
3
- Parts 7, 8 and 13. Lattice AI already persists memory in several real stores;
4
- before this service they were unrelated. ``MemoryService`` unifies them behind
5
- one façade and adds a Memory Manager that reports usage / sources / health /
6
- size / type and supports recall / inspect / prune / compact / rebuild / clear.
7
-
8
- Memory tiers and their real backing store (nothing is fabricated — a tier with
9
- no backing reports ``unavailable``):
10
-
11
- * **workspace** — personal workspace memories (``WorkspaceOS`` memories)
12
- * **project** — memories scoped to a non-personal (organization) workspace
13
- * **agent** — agent memory snapshots captured during runs
14
- * **conversation** — chat history conversations
15
- * **graph** — Knowledge Graph nodes (entities + relations)
16
- * **vector** — local embedding vector index
17
-
18
- The service never invents counts or health: every number is read from the
19
- underlying store, and missing stores surface as ``unavailable``.
20
- """
21
-
22
- from __future__ import annotations
23
-
24
- import json
25
- import logging
26
- from pathlib import Path
27
- from typing import Any, Dict, List, Optional
28
-
29
- from latticeai.core.timeutil import now_iso as _now
30
- from latticeai.core.workspace_os_utils import _file_size
31
-
32
- # Personal workspace memory kinds (from WorkspaceOS.MEMORY_KINDS).
33
- WORKSPACE_KINDS = (
34
- "short_term",
35
- "workspace",
36
- "preferences",
37
- "decisions",
38
- "working_style",
39
- "frequently_used_tools",
40
- "long_term",
41
- )
42
-
43
- TIERS = ("workspace", "project", "agent", "conversation", "graph", "vector")
44
- LOGGER = logging.getLogger(__name__)
45
-
46
-
47
- #: Longest inline thumbnail a recall row will carry (see ``_visual_fields``).
48
- MAX_RECALL_THUMBNAIL_CHARS = 24_000
49
-
50
-
51
- def _visual_fields(hit: Dict[str, Any]) -> Dict[str, Any]:
52
- """Caption + inline thumbnail for a recall row, when the node has them.
53
-
54
- v11.1.0: an ``Image`` node stores a 96px ``data:`` thumbnail and — only if
55
- a vision-language model produced one — a caption. Passing them through here
56
- is what lets the Evidence panel show the picture it is citing without a new
57
- static route over the user's disk and without going around the local-file
58
- approval gate: the bytes are already inside the graph payload the user
59
- asked for. Absent keys stay absent, so every non-image row is unchanged.
60
- """
61
- metadata = hit.get("metadata")
62
- if not isinstance(metadata, dict):
63
- return {}
64
- fields: Dict[str, Any] = {}
65
- caption = str(metadata.get("caption") or "").strip()
66
- if caption:
67
- fields["caption"] = caption[:400]
68
- thumbnail = str(metadata.get("thumbnail") or "")
69
- if thumbnail.startswith("data:image/") and len(thumbnail) <= MAX_RECALL_THUMBNAIL_CHARS:
70
- fields["thumbnail"] = thumbnail
71
- return fields
72
-
73
-
74
- class MemoryServiceError(RuntimeError):
75
- """Raised when a configured memory backend cannot be read reliably."""
76
-
77
-
78
- class MemoryService:
79
- def __init__(
80
- self,
81
- *,
82
- store: Any,
83
- data_dir: Path,
84
- knowledge_graph: Any = None,
85
- enable_graph: bool = True,
86
- history_file: Optional[Path] = None,
87
- conversation_store: Any = None,
88
- ):
89
- self._store = store
90
- self._kg = knowledge_graph
91
- self._enable_graph = bool(enable_graph and knowledge_graph is not None)
92
- self._data_dir = Path(data_dir)
93
- self._history_file = Path(history_file) if history_file else (self._data_dir / "chat_history.json")
94
- # v4: the durable SQLite conversation store supersedes the JSON file
95
- # as the conversation tier's backing store when provided.
96
- self._conversation_store = conversation_store
97
-
98
- # ── helpers over the underlying stores ────────────────────────────────
99
- def _workspace_memories(self, *, user_email: Optional[str], workspace_id: Optional[str]) -> List[Dict[str, Any]]:
100
- try:
101
- return list(self._store.list_memories(user_email=user_email, workspace_id=workspace_id).get("memories", []))
102
- except Exception as exc:
103
- LOGGER.exception("workspace memory read failed")
104
- raise MemoryServiceError("workspace memory backend unavailable") from exc
105
-
106
- def _all_memories(self) -> List[Dict[str, Any]]:
107
- try:
108
- return list(self._store.list_memories().get("memories", []))
109
- except Exception as exc:
110
- LOGGER.exception("global memory read failed")
111
- raise MemoryServiceError("memory backend unavailable") from exc
112
-
113
- def _snapshots(self, *, workspace_id: Optional[str]) -> List[Dict[str, Any]]:
114
- try:
115
- return list(self._store.list_memory_snapshots(workspace_id=workspace_id, limit=200).get("snapshots", []))
116
- except Exception as exc:
117
- LOGGER.exception("memory snapshot read failed")
118
- raise MemoryServiceError("memory snapshot backend unavailable") from exc
119
-
120
- def _conversations(self) -> List[Dict[str, Any]]:
121
- if self._conversation_store is not None:
122
- try:
123
- grouped: Dict[str, List[Dict[str, Any]]] = {}
124
- for item in self._conversation_store.history():
125
- grouped.setdefault(item.get("conversation_id") or "legacy-previous-history", []).append(item)
126
- return [{"id": conv_id, "messages": msgs} for conv_id, msgs in grouped.items()]
127
- except Exception as exc:
128
- LOGGER.exception("conversation store read failed")
129
- raise MemoryServiceError("conversation backend unavailable") from exc
130
- if not self._history_file.exists():
131
- return []
132
- try:
133
- with open(self._history_file, "r", encoding="utf-8") as fh:
134
- data = json.load(fh)
135
- except (OSError, json.JSONDecodeError, TypeError, ValueError) as exc:
136
- LOGGER.exception("legacy conversation history read failed")
137
- raise MemoryServiceError("conversation history is unreadable") from exc
138
- if isinstance(data, dict):
139
- convs = data.get("conversations")
140
- if isinstance(convs, list):
141
- return convs
142
- return [{"id": k, **(v if isinstance(v, dict) else {"messages": v})} for k, v in data.items()]
143
- if isinstance(data, list):
144
- return data
145
- return []
146
-
147
- def _scoped_conversations(self, *, user_email: Optional[str], workspace_id: Optional[str]) -> List[Dict[str, Any]]:
148
- if not user_email:
149
- return self._conversations()
150
- target_workspace = workspace_id or "personal"
151
- scoped: List[Dict[str, Any]] = []
152
- for conversation in self._conversations():
153
- messages = conversation.get("messages") or []
154
- if not isinstance(messages, list):
155
- continue
156
- kept = [
157
- message
158
- for message in messages
159
- if isinstance(message, dict)
160
- and message.get("user_email") == user_email
161
- and (message.get("workspace_id") or "personal") == target_workspace
162
- ]
163
- if kept:
164
- scoped.append({**conversation, "messages": kept})
165
- return scoped
166
-
167
- def _kg_stats(self) -> Optional[Dict[str, Any]]:
168
- if not self._enable_graph:
169
- return None
170
- try:
171
- return self._kg.stats()
172
- except Exception:
173
- LOGGER.exception("knowledge graph stats read failed")
174
- return None
175
-
176
- def _kg_index(self) -> Optional[Dict[str, Any]]:
177
- if not self._enable_graph:
178
- return None
179
- try:
180
- return self._kg.index_status()
181
- except Exception:
182
- LOGGER.exception("knowledge graph index status read failed")
183
- return None
184
-
185
- # ── Memory Manager: sources / usage / health ──────────────────────────
186
- def _brain_readiness(
187
- self,
188
- *,
189
- memory_count: int,
190
- concept_count: Optional[int],
191
- relationship_count: Optional[int],
192
- healthy_sources: int,
193
- ) -> Dict[str, Any]:
194
- """Summarize how ready the user's Brain is for the product UI.
195
-
196
- The frontend should render this signal instead of re-deriving it from
197
- UI fragments. Keeping it here makes the score auditable and keeps the
198
- Memory Manager as the single owner of cross-tier Brain growth signals.
199
- """
200
- concepts = max(0, int(concept_count or 0))
201
- relationships = max(0, int(relationship_count or 0))
202
- memories = max(0, int(memory_count or 0))
203
- healthy = max(0, int(healthy_sources or 0))
204
- score = min(100, round(memories * 12 + concepts * 8 + relationships * 4 + healthy * 3))
205
-
206
- if memories < 1 and concepts < 1:
207
- state = "quiet"
208
- depth = 2
209
- title_key = "brain.readiness.quiet"
210
- action_key = "brain.readiness.start"
211
- score = max(12, score)
212
- elif concepts < 3 or relationships < 2:
213
- state = "forming"
214
- depth = 3 if concepts < 3 else 4
215
- title_key = "brain.readiness.forming"
216
- action_key = "brain.readiness.grow"
217
- score = max(38, score)
218
- else:
219
- state = "alive"
220
- depth = 5
221
- title_key = "brain.readiness.alive"
222
- action_key = "brain.readiness.map"
223
- score = max(72, score)
224
-
225
- return {
226
- "score": score,
227
- "state": state,
228
- "depth": depth,
229
- "title_key": title_key,
230
- "action_key": action_key,
231
- "signals": {
232
- "memory_count": memories,
233
- "concept_count": concepts,
234
- "relationship_count": relationships,
235
- "healthy_sources": healthy,
236
- },
237
- "source": "memory_service",
238
- }
239
-
240
- def manager(self, *, user_email: Optional[str] = None, workspace_id: Optional[str] = None) -> Dict[str, Any]:
241
- ws_mem = self._workspace_memories(user_email=user_email, workspace_id=workspace_id or "personal")
242
- if workspace_id is None:
243
- project_mem = [m for m in self._all_memories() if (m.get("workspace_id") or "personal") != "personal"]
244
- else:
245
- project_mem = self._workspace_memories(user_email=user_email, workspace_id=workspace_id)
246
- snaps = self._snapshots(workspace_id=workspace_id)
247
- convs = self._scoped_conversations(user_email=user_email, workspace_id=workspace_id)
248
- kg_stats = self._kg_stats()
249
- kg_index = self._kg_index()
250
-
251
- ws_bytes = _file_size(self._data_dir / "workspace_os.json")
252
- kg_bytes = _file_size(self._data_dir / "knowledge_graph.sqlite")
253
- if self._conversation_store is not None:
254
- conv_bytes = int(getattr(self._conversation_store, "size_bytes", lambda: 0)())
255
- else:
256
- conv_bytes = _file_size(self._history_file)
257
-
258
- node_total = sum((kg_stats or {}).get("nodes", {}).values()) if kg_stats else None
259
- edge_total = sum((kg_stats or {}).get("edges", {}).values()) if kg_stats else None
260
- vector_total = None
261
- if kg_index and isinstance(kg_index.get("vector_counts"), dict):
262
- vector_total = sum(kg_index["vector_counts"].values())
263
- elif kg_index:
264
- vector_total = kg_index.get("indexed") or kg_index.get("ready")
265
-
266
- sources: List[Dict[str, Any]] = [
267
- {
268
- "id": "workspace", "type": "workspace", "label": "Workspace Memory",
269
- "count": len(ws_mem), "size_bytes": ws_bytes if ws_mem else 0,
270
- "health": "ok", "detail": "Personal workspace knowledge, by kind.",
271
- },
272
- {
273
- "id": "project", "type": "project", "label": "Project Memory",
274
- "count": len(project_mem), "size_bytes": 0,
275
- "health": "ok", "detail": "Memory scoped to organization workspaces.",
276
- },
277
- {
278
- "id": "agent", "type": "agent", "label": "Agent Memory",
279
- "count": len(snaps), "size_bytes": 0,
280
- "health": "ok", "detail": "Per-run agent memory snapshots.",
281
- },
282
- {
283
- "id": "conversation", "type": "conversation", "label": "Conversation Memory",
284
- "count": len(convs), "size_bytes": conv_bytes,
285
- "health": "ok" if (self._conversation_store is not None or self._history_file.exists()) else "empty",
286
- "detail": "Historical interaction memory from chat.",
287
- },
288
- {
289
- "id": "graph", "type": "graph", "label": "Graph Memory",
290
- "count": node_total, "size_bytes": kg_bytes,
291
- "health": "ok" if kg_stats else "unavailable",
292
- "detail": "Knowledge Graph entities and relations." if kg_stats else "Knowledge graph disabled or unavailable.",
293
- "edges": edge_total,
294
- },
295
- {
296
- "id": "vector", "type": "vector", "label": "Vector Memory",
297
- "count": vector_total, "size_bytes": 0,
298
- "health": "ok" if kg_index else "unavailable",
299
- "detail": "Local embedding vector index." if kg_index else "Vector index unavailable.",
300
- },
301
- ]
302
- total_items = sum(int(s["count"] or 0) for s in sources)
303
- total_bytes = ws_bytes + kg_bytes + conv_bytes
304
- healthy = sum(1 for s in sources if s["health"] == "ok")
305
- overall = "ok" if healthy >= 4 else "degraded" if healthy >= 1 else "unavailable"
306
- memory_ids = {m.get("id") for m in [*ws_mem, *project_mem] if m.get("id")}
307
- memory_count = len(memory_ids) + len(snaps) + len(convs)
308
- return {
309
- "sources": sources,
310
- "recent_memories": self._manager_recent_memories([*ws_mem, *project_mem], limit=8),
311
- "tiers": list(TIERS),
312
- "usage": {"total_items": total_items, "total_bytes": total_bytes, "sources": len(sources)},
313
- "brain_readiness": self._brain_readiness(
314
- memory_count=memory_count,
315
- concept_count=node_total,
316
- relationship_count=edge_total,
317
- healthy_sources=healthy,
318
- ),
319
- "health": overall,
320
- "graph_enabled": self._enable_graph,
321
- "generated_at": _now(),
322
- }
323
-
324
- @staticmethod
325
- def _manager_recent_memories(memories: List[Dict[str, Any]], *, limit: int = 8) -> List[Dict[str, Any]]:
326
- rows: List[Dict[str, Any]] = []
327
- for item in memories[: max(1, limit)]:
328
- metadata = item.get("metadata") if isinstance(item.get("metadata"), dict) else {}
329
- rows.append({
330
- "id": item.get("id") or "",
331
- "kind": item.get("kind") or "memory",
332
- "content": str(item.get("content") or "")[:320],
333
- "tags": item.get("tags") if isinstance(item.get("tags"), list) else [],
334
- "metadata": metadata,
335
- "workspace_id": item.get("workspace_id") or "personal",
336
- "created_at": item.get("created_at"),
337
- "updated_at": item.get("updated_at"),
338
- })
339
- return rows
340
-
341
- def brain_quality_summary(self, *, user_email: Optional[str] = None, workspace_id: Optional[str] = None) -> Dict[str, Any]:
342
- """Return the backend-owned Brain readiness signal for API consumers."""
343
- return self.manager(user_email=user_email, workspace_id=workspace_id)["brain_readiness"]
344
-
345
- def brain_brief(
346
- self,
347
- *,
348
- user_email: Optional[str] = None,
349
- workspace_id: Optional[str] = None,
350
- active_model: Optional[str] = None,
351
- recall_query: str = "",
352
- limit: int = 3,
353
- ) -> Dict[str, Any]:
354
- """Return a compact, evidence-backed Brain briefing for the home screen.
355
-
356
- The brief intentionally reuses the Memory Manager and Brain Proof data
357
- instead of inventing UI-only facts. It answers three product questions:
358
- what should the user notice, why can the Brain prove it, and what is the
359
- easiest next action.
360
- """
361
- manager = self.manager(user_email=user_email, workspace_id=workspace_id)
362
- proof = self.brain_proof(
363
- user_email=user_email,
364
- workspace_id=workspace_id,
365
- active_model=active_model,
366
- recall_query=recall_query,
367
- limit=limit,
368
- )
369
- readiness = manager.get("brain_readiness") or {}
370
- state = str(readiness.get("state") or "quiet")
371
- proofs = proof.get("proofs") or {}
372
- recall = proof.get("recall") or {}
373
- recall_items = [item for item in recall.get("items") or [] if isinstance(item, dict)]
374
- durable_items = int(proofs.get("durable_items") or 0)
375
- workspace_memories = int(proofs.get("workspace_memories") or 0)
376
- conversations = int(proofs.get("conversations") or 0)
377
- graph_concepts = int(proofs.get("graph_concepts") or 0)
378
- vector_items = int(proofs.get("vector_items") or 0)
379
- healthy_sources = int(proofs.get("healthy_sources") or 0)
380
-
381
- focus = self._brain_brief_focus(
382
- user_email=user_email,
383
- workspace_id=workspace_id,
384
- recall_items=recall_items,
385
- durable_items=durable_items,
386
- graph_concepts=graph_concepts,
387
- query=str(recall.get("query") or recall_query or ""),
388
- )
389
- actions = self._brain_brief_actions(
390
- state=state,
391
- has_durable_evidence=bool(proofs.get("has_durable_evidence")),
392
- has_recall=bool(recall_items),
393
- graph_concepts=graph_concepts,
394
- )
395
- suggested_questions = self._brain_brief_suggested_questions(
396
- focus=focus,
397
- has_durable_evidence=bool(proofs.get("has_durable_evidence")),
398
- has_recall=bool(recall_items),
399
- graph_concepts=graph_concepts,
400
- conversations=conversations,
401
- )
402
- proactive_actions = self._brain_brief_proactive_actions(
403
- focus=focus,
404
- state=state,
405
- has_durable_evidence=bool(proofs.get("has_durable_evidence")),
406
- has_recall=bool(recall_items),
407
- graph_concepts=graph_concepts,
408
- vector_items=vector_items,
409
- healthy_sources=healthy_sources,
410
- )
411
- return {
412
- "status": state,
413
- "score": int(readiness.get("score") or 0),
414
- "headline_key": f"brain.brief.headline.{state if state in {'quiet', 'forming', 'alive'} else 'quiet'}",
415
- "body_key": f"brain.brief.body.{state if state in {'quiet', 'forming', 'alive'} else 'quiet'}",
416
- "focus": focus,
417
- "next_actions": actions,
418
- "suggested_questions": suggested_questions,
419
- "proactive_actions": proactive_actions,
420
- "evidence": [
421
- {
422
- "id": "durable",
423
- "label_key": "brain.brief.evidence.durable",
424
- "value": durable_items,
425
- "detail_key": "brain.brief.evidence.durable.detail",
426
- },
427
- {
428
- "id": "graph",
429
- "label_key": "brain.brief.evidence.graph",
430
- "value": graph_concepts,
431
- "detail_key": "brain.brief.evidence.graph.detail",
432
- },
433
- {
434
- "id": "sources",
435
- "label_key": "brain.brief.evidence.sources",
436
- "value": healthy_sources,
437
- "detail_key": "brain.brief.evidence.sources.detail",
438
- },
439
- ],
440
- "signals": {
441
- "workspace_memories": workspace_memories,
442
- "conversations": conversations,
443
- "graph_concepts": graph_concepts,
444
- "vector_items": vector_items,
445
- "healthy_sources": healthy_sources,
446
- },
447
- "proof": {
448
- "query": recall.get("query") or "",
449
- "items": recall_items[: max(1, min(limit, 6))],
450
- "model_continuity": proof.get("model_continuity") or {},
451
- },
452
- "generated_at": _now(),
453
- }
454
-
455
- def _brain_brief_focus(
456
- self,
457
- *,
458
- user_email: Optional[str],
459
- workspace_id: Optional[str],
460
- recall_items: List[Dict[str, Any]],
461
- durable_items: int,
462
- graph_concepts: int,
463
- query: str,
464
- ) -> Dict[str, Any]:
465
- if recall_items:
466
- first = recall_items[0]
467
- return {
468
- "kind": "recall",
469
- "title": str(first.get("title") or "Memory"),
470
- "detail": str(first.get("snippet") or query or ""),
471
- "source": str(first.get("source") or "memory"),
472
- "score": float(first.get("score") or 0),
473
- }
474
-
475
- memories = self._workspace_memories(user_email=user_email, workspace_id=workspace_id or "personal")
476
- if memories:
477
- first_memory = memories[0]
478
- return {
479
- "kind": "memory",
480
- "title": str(first_memory.get("kind") or "memory"),
481
- "detail": str(first_memory.get("content") or "")[:240],
482
- "source": "workspace",
483
- "score": 1.0,
484
- }
485
-
486
- conversations = self._scoped_conversations(user_email=user_email, workspace_id=workspace_id)
487
- if conversations:
488
- latest = conversations[-1]
489
- messages = latest.get("messages") if isinstance(latest, dict) else []
490
- last_message = next((m for m in reversed(messages or []) if isinstance(m, dict) and str(m.get("content") or "").strip()), {})
491
- return {
492
- "kind": "conversation",
493
- "title": str(latest.get("title") or latest.get("id") or "conversation"),
494
- "detail": str(last_message.get("content") or "")[:240],
495
- "source": "conversation",
496
- "score": 1.0,
497
- }
498
-
499
- if graph_concepts > 0:
500
- return {
501
- "kind": "graph",
502
- "title": "Knowledge Graph",
503
- "detail": f"{graph_concepts} graph concepts are ready to inspect.",
504
- "source": "graph",
505
- "score": 1.0,
506
- }
507
-
508
- return {
509
- "kind": "empty",
510
- "title": "",
511
- "detail": "",
512
- "source": "none",
513
- "score": 0,
514
- "empty": durable_items <= 0,
515
- }
516
-
517
- @staticmethod
518
- def _brain_brief_actions(
519
- *,
520
- state: str,
521
- has_durable_evidence: bool,
522
- has_recall: bool,
523
- graph_concepts: int,
524
- ) -> List[Dict[str, Any]]:
525
- actions: List[Dict[str, Any]] = []
526
- if not has_durable_evidence:
527
- actions.extend([
528
- {
529
- "id": "add_source",
530
- "label_key": "brain.brief.action.add",
531
- "detail_key": "brain.brief.action.add.detail",
532
- "route": "/capture",
533
- "priority": 10,
534
- },
535
- {
536
- "id": "ask_brain",
537
- "label_key": "brain.brief.action.ask",
538
- "detail_key": "brain.brief.action.ask.detail",
539
- "route": "",
540
- "priority": 9,
541
- },
542
- ])
543
- else:
544
- actions.append({
545
- "id": "ask_brain",
546
- "label_key": "brain.brief.action.ask",
547
- "detail_key": "brain.brief.action.ask.detail",
548
- "route": "",
549
- "priority": 10,
550
- })
551
- if graph_concepts > 0 or state == "alive":
552
- actions.append({
553
- "id": "inspect_topics",
554
- "label_key": "brain.brief.action.topics",
555
- "detail_key": "brain.brief.action.topics.detail",
556
- "route": "/knowledge-graph",
557
- "priority": 8,
558
- })
559
- if has_recall:
560
- actions.append({
561
- "id": "verify_model",
562
- "label_key": "brain.brief.action.verify",
563
- "detail_key": "brain.brief.action.verify.detail",
564
- "route": "",
565
- "priority": 7,
566
- })
567
- actions.append({
568
- "id": "backup_brain",
569
- "label_key": "brain.brief.action.backup",
570
- "detail_key": "brain.brief.action.backup.detail",
571
- "route": "/settings",
572
- "priority": 6,
573
- })
574
- return sorted(actions, key=lambda item: int(item.get("priority") or 0), reverse=True)[:4]
575
-
576
- @staticmethod
577
- def _brain_brief_proactive_actions(
578
- *,
579
- focus: Dict[str, Any],
580
- state: str,
581
- has_durable_evidence: bool,
582
- has_recall: bool,
583
- graph_concepts: int,
584
- vector_items: int,
585
- healthy_sources: int,
586
- ) -> List[Dict[str, Any]]:
587
- """Return concrete, one-click actions Brain can proactively suggest."""
588
- focus_title = str(focus.get("title") or "").strip() or "Brain"
589
- focus_detail = str(focus.get("detail") or "").strip()
590
- actions: List[Dict[str, Any]] = []
591
- if not has_durable_evidence:
592
- actions.append({
593
- "id": "proactive_add_source",
594
- "intent": "route",
595
- "label_key": "brain.proactive.addSource.label",
596
- "detail_key": "brain.proactive.addSource.detail",
597
- "route": "/capture",
598
- "prompt": "Add a useful source to my Brain and explain what it learned.",
599
- "priority": 100,
600
- })
601
- actions.append({
602
- "id": "proactive_seed_memory",
603
- "intent": "ask",
604
- "label_key": "brain.proactive.seed.label",
605
- "detail_key": "brain.proactive.seed.detail",
606
- "prompt": "Help me seed my Brain with the most useful personal context to remember.",
607
- "priority": 90,
608
- })
609
- return actions
610
-
611
- if has_recall:
612
- actions.append({
613
- "id": "proactive_evidence_review",
614
- "intent": "ask",
615
- "label_key": "brain.proactive.evidence.label",
616
- "detail_key": "brain.proactive.evidence.detail",
617
- "prompt": (
618
- f"Review the evidence Brain has for {focus_title}. "
619
- "Separate confirmed facts, weak signals, contradictions, and next checks."
620
- ),
621
- "priority": 100,
622
- "context": {"focus": focus_title, "detail": focus_detail},
623
- })
624
- actions.append({
625
- "id": "proactive_delegate",
626
- "intent": "delegate",
627
- "label_key": "brain.proactive.delegate.label",
628
- "detail_key": "brain.proactive.delegate.detail",
629
- "prompt": (
630
- f"Turn {focus_title} into an execution plan, verify the known context, "
631
- "and return concrete next steps with risks."
632
- ),
633
- "priority": 95,
634
- "context": {"focus": focus_title, "detail": focus_detail},
635
- })
636
- actions.append({
637
- "id": "proactive_review_draft",
638
- "intent": "review",
639
- "label_key": "brain.proactive.review.label",
640
- "detail_key": "brain.proactive.review.detail",
641
- "prompt": (
642
- f"Create a reviewable task from Brain's current focus: {focus_title}. "
643
- f"{focus_detail[:240]}"
644
- ).strip(),
645
- "priority": 90,
646
- "context": {"focus": focus_title, "detail": focus_detail},
647
- })
648
-
649
- if graph_concepts > 0:
650
- actions.append({
651
- "id": "proactive_map_connections",
652
- "intent": "route",
653
- "label_key": "brain.proactive.map.label",
654
- "detail_key": "brain.proactive.map.detail",
655
- "route": "/knowledge-graph",
656
- "prompt": f"Map the strongest Knowledge Graph connections around {focus_title}.",
657
- "priority": 82,
658
- "context": {"focus": focus_title, "graph_concepts": graph_concepts},
659
- })
660
-
661
- if state == "alive" and vector_items > 0 and healthy_sources > 0:
662
- actions.append({
663
- "id": "proactive_weekly_brief",
664
- "intent": "review",
665
- "label_key": "brain.proactive.weekly.label",
666
- "detail_key": "brain.proactive.weekly.detail",
667
- "prompt": (
668
- "Prepare a weekly Brain review: what changed, what decisions are pending, "
669
- "what should be delegated, and what evidence is stale."
670
- ),
671
- "priority": 78,
672
- "context": {"vector_items": vector_items, "healthy_sources": healthy_sources},
673
- })
674
-
675
- return sorted(actions, key=lambda item: int(item.get("priority") or 0), reverse=True)[:4]
676
-
677
- @staticmethod
678
- def _brain_brief_suggested_questions(
679
- *,
680
- focus: Dict[str, Any],
681
- has_durable_evidence: bool,
682
- has_recall: bool,
683
- graph_concepts: int,
684
- conversations: int,
685
- ) -> List[Dict[str, Any]]:
686
- """Return reusable, localized UI prompt descriptors for the Brain home."""
687
- focus_title = str(focus.get("title") or "").strip()
688
- focus_kind = str(focus.get("kind") or "empty")
689
- questions: List[Dict[str, Any]] = []
690
-
691
- if not has_durable_evidence or focus_kind == "empty":
692
- questions.extend([
693
- {
694
- "id": "start_brain",
695
- "label_key": "brain.suggestion.start.label",
696
- "detail_key": "brain.suggestion.start.detail",
697
- "prompt_key": "brain.suggestion.start.prompt",
698
- "params": {},
699
- "priority": 10,
700
- },
701
- {
702
- "id": "add_context",
703
- "label_key": "brain.suggestion.context.label",
704
- "detail_key": "brain.suggestion.context.detail",
705
- "prompt_key": "brain.suggestion.context.prompt",
706
- "params": {},
707
- "priority": 9,
708
- },
709
- ])
710
- return questions
711
-
712
- questions.append({
713
- "id": "focus_next",
714
- "label_key": "brain.suggestion.focus.label",
715
- "detail_key": "brain.suggestion.focus.detail",
716
- "prompt_key": "brain.suggestion.focus.prompt",
717
- "params": {"focus": focus_title or "Brain"},
718
- "priority": 10,
719
- })
720
-
721
- if has_recall:
722
- questions.append({
723
- "id": "evidence_check",
724
- "label_key": "brain.suggestion.evidence.label",
725
- "detail_key": "brain.suggestion.evidence.detail",
726
- "prompt_key": "brain.suggestion.evidence.prompt",
727
- "params": {"focus": focus_title or "this topic"},
728
- "priority": 9,
729
- })
730
-
731
- if graph_concepts > 0:
732
- questions.append({
733
- "id": "graph_connections",
734
- "label_key": "brain.suggestion.graph.label",
735
- "detail_key": "brain.suggestion.graph.detail",
736
- "prompt_key": "brain.suggestion.graph.prompt",
737
- "params": {"focus": focus_title or "Knowledge Graph"},
738
- "priority": 8,
739
- })
740
-
741
- if conversations > 0:
742
- questions.append({
743
- "id": "conversation_followup",
744
- "label_key": "brain.suggestion.history.label",
745
- "detail_key": "brain.suggestion.history.detail",
746
- "prompt_key": "brain.suggestion.history.prompt",
747
- "params": {"focus": focus_title or "recent conversations"},
748
- "priority": 7,
749
- })
750
-
751
- return sorted(questions, key=lambda item: int(item.get("priority") or 0), reverse=True)[:4]
752
-
753
- def brain_proof(
754
- self,
755
- *,
756
- user_email: Optional[str] = None,
757
- workspace_id: Optional[str] = None,
758
- active_model: Optional[str] = None,
759
- recall_query: str = "",
760
- limit: int = 3,
761
- ) -> Dict[str, Any]:
762
- """Return the proof points that make Brain feel model-independent.
763
-
764
- This is intentionally backend-owned instead of UI-derived: the first-run
765
- Brain screen needs to show the durable stores it can actually recall
766
- from, and the model continuity claim must be independent from whichever
767
- LLM is currently loaded.
768
- """
769
- manager = self.manager(user_email=user_email, workspace_id=workspace_id)
770
- sources = {str(source.get("id")): source for source in manager.get("sources", []) if isinstance(source, dict)}
771
- readiness = manager.get("brain_readiness") or {}
772
- conversation_count = int(sources.get("conversation", {}).get("count") or 0)
773
- workspace_count = int(sources.get("workspace", {}).get("count") or 0)
774
- graph_count = int(sources.get("graph", {}).get("count") or 0)
775
- vector_count = int(sources.get("vector", {}).get("count") or 0)
776
- query = recall_query.strip() or self._latest_recall_query(user_email=user_email, workspace_id=workspace_id)
777
- recall: Dict[str, Any] = (
778
- self.recall(query, user_email=user_email, workspace_id=workspace_id, limit=limit)
779
- if query
780
- else {"query": "", "results": [], "count": 0, "source": "live"}
781
- )
782
- recall_items = [
783
- {
784
- "id": item.get("id"),
785
- "source": item.get("source"),
786
- "title": item.get("title"),
787
- "snippet": item.get("snippet"),
788
- "score": item.get("score", 0),
789
- # Evidence explainability: why this item was recalled, so the
790
- # citation UI can show the matched terms instead of a bare score.
791
- "matched_terms": item.get("matched_terms") or [],
792
- "confidence": item.get("confidence") or "low",
793
- # v11.1.0: what kind of memory this is, and — for a picture —
794
- # the caption and inline thumbnail the Evidence panel renders.
795
- "kind": item.get("kind") or "",
796
- **({"caption": item["caption"]} if item.get("caption") else {}),
797
- **({"thumbnail": item["thumbnail"]} if item.get("thumbnail") else {}),
798
- }
799
- for item in list(recall.get("results", []))[: max(1, min(limit, 8))]
800
- ]
801
- durable_items = workspace_count + conversation_count + graph_count
802
- # Capability and proof are deliberately separated. The brain is
803
- # architecturally model-independent, so the capability is always true.
804
- # The proof stays false until there is durable evidence on disk.
805
- has_durable_evidence = durable_items > 0
806
- proven_continuity = has_durable_evidence
807
- return {
808
- "status": readiness.get("state") or "quiet",
809
- "readiness": readiness,
810
- "model_continuity": {
811
- "active_model": active_model or "",
812
- "brain_owner": "lattice_brain",
813
- # Design capability: the brain is built to outlive any model.
814
- "capability": True,
815
- # Proof: only true when durable evidence exists to recall.
816
- "survives_model_switch": proven_continuity,
817
- "proven": proven_continuity,
818
- "context_store": "workspace + conversation + graph + vector",
819
- },
820
- "proofs": {
821
- "durable_items": durable_items,
822
- "has_durable_evidence": has_durable_evidence,
823
- "workspace_memories": workspace_count,
824
- "conversations": conversation_count,
825
- "graph_concepts": graph_count,
826
- "vector_items": vector_count,
827
- "healthy_sources": readiness.get("signals", {}).get("healthy_sources", 0),
828
- },
829
- "recall": {
830
- "query": recall.get("query") or query,
831
- "items": recall_items,
832
- "count": recall.get("count", 0),
833
- },
834
- "claims": {
835
- "can_recall_user_context": bool(recall_items or durable_items > 0),
836
- # Proven, not asserted: no durable evidence means no continuity claim.
837
- "keeps_context_across_models": proven_continuity,
838
- "is_knowledge_store": bool(graph_count or vector_count or workspace_count or conversation_count),
839
- },
840
- "generated_at": _now(),
841
- }
842
-
843
- def _latest_recall_query(self, *, user_email: Optional[str], workspace_id: Optional[str]) -> str:
844
- for memory in self._workspace_memories(user_email=user_email, workspace_id=workspace_id or "personal"):
845
- content = str(memory.get("content") or "").strip()
846
- if content:
847
- return content[:96]
848
- for conversation in self._conversations():
849
- messages = conversation.get("messages") or []
850
- if not isinstance(messages, list):
851
- continue
852
- for message in reversed(messages[-8:]):
853
- if not isinstance(message, dict):
854
- continue
855
- if user_email and message.get("user_email") != user_email:
856
- continue
857
- message_workspace = message.get("workspace_id") or "personal"
858
- target_workspace = workspace_id or "personal"
859
- if message_workspace != target_workspace:
860
- continue
861
- content = str(message.get("content") or "").strip()
862
- if content:
863
- return content[:96]
864
- return ""
865
-
866
- def tiers(self) -> Dict[str, Any]:
867
- return {"tiers": list(TIERS), "workspace_kinds": list(WORKSPACE_KINDS)}
868
-
869
- # ── recall (unified retrieval over the memory tiers) ───────────────────
870
- def recall(
871
- self,
872
- query: str,
873
- *,
874
- user_email: Optional[str] = None,
875
- workspace_id: Optional[str] = None,
876
- limit: int = 20,
877
- ) -> Dict[str, Any]:
878
- q = str(query or "").strip()
879
- query_tokens = [tok for tok in q.lower().split() if tok]
880
-
881
- def _matched_terms(*texts: Any) -> List[str]:
882
- haystack = " ".join(str(t or "") for t in texts).lower()
883
- return [tok for tok in query_tokens if tok in haystack]
884
-
885
- def _lexical_score(matched: List[str]) -> float:
886
- # Honest, comparable relevance: fraction of query tokens present.
887
- # Both tiers share this scorer so the cross-tier ranking is real,
888
- # not an artifact of per-tier constants.
889
- if not query_tokens:
890
- return 0.0
891
- return round(len(matched) / len(query_tokens), 4)
892
-
893
- results: List[Dict[str, Any]] = []
894
-
895
- errors: List[Dict[str, str]] = []
896
- try:
897
- mem = self._store.search_memories(q, user_email=user_email, limit=limit, workspace_id=workspace_id).get("memories", [])
898
- except Exception as exc:
899
- LOGGER.exception("workspace memory search failed")
900
- errors.append({"source": "workspace", "detail": str(exc)})
901
- mem = []
902
- for m in mem:
903
- matched = _matched_terms(m.get("content"), " ".join(m.get("tags") or []), m.get("kind"))
904
- results.append({
905
- "source": "workspace",
906
- "id": m.get("id"),
907
- "title": (m.get("kind") or "memory"),
908
- "snippet": str(m.get("content") or "")[:240],
909
- "kind": m.get("kind"),
910
- "score": _lexical_score(matched),
911
- "matched_terms": matched,
912
- "tags": m.get("tags") or [],
913
- })
914
-
915
- if self._enable_graph and q:
916
- try:
917
- # KnowledgeGraph.search returns {"query": ..., "matches": [...]}.
918
- search_kwargs = (
919
- {"allowed_workspaces": {workspace_id}}
920
- if workspace_id is not None
921
- else {}
922
- )
923
- hits = self._kg.search(q, limit, **search_kwargs).get("matches", [])
924
- except Exception as exc:
925
- LOGGER.exception("knowledge graph memory search failed")
926
- errors.append({"source": "graph", "detail": str(exc)})
927
- hits = []
928
- for hit in hits[:limit]:
929
- matched = _matched_terms(hit.get("title"), hit.get("name"), hit.get("summary"), hit.get("content"))
930
- results.append({
931
- "source": "graph",
932
- "id": hit.get("id") or hit.get("node_id"),
933
- "title": hit.get("title") or hit.get("name") or "node",
934
- "snippet": str(hit.get("summary") or hit.get("content") or "")[:240],
935
- "kind": hit.get("type") or "node",
936
- "score": _lexical_score(matched),
937
- "matched_terms": matched,
938
- **_visual_fields(hit),
939
- })
940
-
941
- # v9.3.0 hybrid recall: blend semantic similarity from the vector
942
- # index into the lexical ranking. Vector evidence lets recall find
943
- # knowledge phrased differently from the query — the main lexical
944
- # blind spot. The vector tier is optional: any failure degrades recall
945
- # back to pure lexical instead of breaking it.
946
- vector_used = False
947
- if self._enable_graph and q and hasattr(self._kg, "vector_search"):
948
- try:
949
- vector_hits = list(
950
- self._kg.vector_search(q, limit=limit).get("matches", [])
951
- )
952
- # Workspace scoping is server-owned: the vector index is
953
- # global, so scoped calls must filter matches to visible
954
- # nodes before they can influence results.
955
- if workspace_id is not None and vector_hits and hasattr(self._kg, "filter_scoped_nodes"):
956
- vector_hits = self._kg.filter_scoped_nodes(
957
- vector_hits, {workspace_id}, id_key="node_id"
958
- )
959
- vector_used = True
960
- except Exception as exc:
961
- LOGGER.exception("vector recall failed; falling back to lexical")
962
- errors.append({"source": "vector", "detail": str(exc)})
963
- vector_hits = []
964
- by_node_id = {str(r.get("id")): r for r in results if r.get("source") == "graph"}
965
- for hit in vector_hits:
966
- node_id = str(hit.get("node_id") or hit.get("id") or "")
967
- similarity = round(float(hit.get("score") or 0.0), 4)
968
- if similarity <= 0:
969
- continue
970
- # Citation precision (v9.9.6): a chunk hit knows where in the
971
- # document it came from (section heading / page). Carry that
972
- # locator onto the recall row so the citation can say it.
973
- hit_metadata = hit.get("metadata")
974
- locator = (
975
- str(hit_metadata.get("locator") or "")
976
- if isinstance(hit_metadata, dict)
977
- else ""
978
- )
979
- existing = by_node_id.get(node_id)
980
- if existing is not None:
981
- existing["vector_score"] = max(existing.get("vector_score", 0.0), similarity)
982
- existing["score"] = round(
983
- max(existing.get("score", 0.0), 0.4 * existing.get("score", 0.0) + 0.6 * similarity),
984
- 4,
985
- )
986
- if locator and not existing.get("locator"):
987
- existing["locator"] = locator
988
- else:
989
- matched = _matched_terms(hit.get("title"), hit.get("summary"))
990
- row = {
991
- "source": "graph",
992
- "id": node_id or hit.get("id"),
993
- "title": hit.get("title") or "node",
994
- "snippet": str(hit.get("summary") or "")[:240],
995
- "kind": hit.get("type") or "node",
996
- "score": round(max(_lexical_score(matched), 0.6 * similarity), 4),
997
- "matched_terms": matched,
998
- "vector_score": similarity,
999
- **({"locator": locator} if locator else {}),
1000
- **_visual_fields(hit),
1001
- }
1002
- results.append(row)
1003
- if node_id:
1004
- by_node_id[node_id] = row
1005
-
1006
- # Quality gate: when at least one result carries real evidence
1007
- # (lexical term hits, or semantic similarity in hybrid mode),
1008
- # zero-score rows are noise relative to it and are dropped. When
1009
- # nothing scores (e.g. tokenization mismatch), everything is kept so
1010
- # the tiers' own search filters still decide — the gate never empties
1011
- # a recall.
1012
- candidates = len(results)
1013
- if query_tokens and any(r.get("score", 0) > 0 for r in results):
1014
- results = [r for r in results if r.get("score", 0) > 0]
1015
- for r in results:
1016
- r["confidence"] = "high" if r.get("score", 0) >= 0.65 else "medium" if r.get("score", 0) >= 0.3 else "low"
1017
- evidence = []
1018
- if r.get("matched_terms"):
1019
- evidence.append("lexical")
1020
- if r.get("vector_score"):
1021
- evidence.append("semantic")
1022
- r["evidence_kinds"] = evidence
1023
-
1024
- results.sort(key=lambda r: r.get("score", 0), reverse=True)
1025
- return {
1026
- "query": q,
1027
- "results": results[: max(1, min(limit, 100))],
1028
- "count": len(results),
1029
- "source": "live",
1030
- "status": "degraded" if errors else "ok",
1031
- "errors": errors,
1032
- "quality_gate": {
1033
- "candidates": candidates,
1034
- "passed": len(results),
1035
- "filtered": candidates - len(results),
1036
- "gate": "hybrid-evidence/v2" if vector_used else "lexical-evidence/v1",
1037
- },
1038
- }
1039
-
1040
- # ── inspect a single tier ─────────────────────────────────────────────
1041
- def inspect(self, source: str, *, user_email: Optional[str] = None, workspace_id: Optional[str] = None, limit: int = 50) -> Dict[str, Any]:
1042
- if source == "workspace":
1043
- items = self._workspace_memories(user_email=user_email, workspace_id=workspace_id or "personal")[:limit]
1044
- return {"source": source, "items": items, "count": len(items)}
1045
- if source == "project":
1046
- if workspace_id is None:
1047
- items = [m for m in self._all_memories() if (m.get("workspace_id") or "personal") != "personal"][:limit]
1048
- else:
1049
- items = self._workspace_memories(user_email=user_email, workspace_id=workspace_id)[:limit]
1050
- return {"source": source, "items": items, "count": len(items)}
1051
- if source == "agent":
1052
- items = self._snapshots(workspace_id=workspace_id)[:limit]
1053
- return {"source": source, "items": items, "count": len(items)}
1054
- if source == "conversation":
1055
- convs = self._scoped_conversations(user_email=user_email, workspace_id=workspace_id)
1056
- items = [{"id": c.get("id"), "title": c.get("title") or c.get("id"), "messages": len(c.get("messages") or [])} for c in convs[:limit]]
1057
- return {"source": source, "items": items, "count": len(convs)}
1058
- if source == "graph":
1059
- return {"source": source, "stats": self._kg_stats() or {}, "available": bool(self._kg_stats())}
1060
- if source == "vector":
1061
- return {"source": source, "index": self._kg_index() or {}, "available": bool(self._kg_index())}
1062
- raise KeyError(source)
1063
-
1064
- # ── mutating operations ───────────────────────────────────────────────
1065
- def prune(
1066
- self,
1067
- *,
1068
- ids: Optional[List[str]] = None,
1069
- kind: Optional[str] = None,
1070
- user_email: Optional[str] = None,
1071
- workspace_id: Optional[str] = None,
1072
- ) -> Dict[str, Any]:
1073
- # Ownership guard: a caller may only prune memories they own. Both the
1074
- # explicit-id and kind paths are intersected with the caller's own
1075
- # memories, so a forged id for another user's memory is refused, not
1076
- # silently deleted.
1077
- owned_ids = {
1078
- m["id"]
1079
- for m in self._workspace_memories(user_email=user_email, workspace_id=workspace_id)
1080
- if m.get("id")
1081
- }
1082
- removed: List[str] = []
1083
- failed: List[Dict[str, str]] = []
1084
- skipped: List[str] = []
1085
- target_ids: List[str] = []
1086
- seen: set = set()
1087
- for mid in (ids or []):
1088
- if mid in seen:
1089
- continue
1090
- seen.add(mid)
1091
- if mid in owned_ids:
1092
- target_ids.append(mid)
1093
- else:
1094
- skipped.append(mid)
1095
- if kind:
1096
- for m in self._workspace_memories(user_email=user_email, workspace_id=workspace_id):
1097
- if m.get("kind") == kind and m.get("id") and m["id"] not in seen:
1098
- seen.add(m["id"])
1099
- target_ids.append(m["id"])
1100
- for mid in target_ids:
1101
- try:
1102
- self._store.delete_memory(mid)
1103
- removed.append(mid)
1104
- except Exception as exc:
1105
- LOGGER.exception("memory deletion failed for %s", mid)
1106
- failed.append({"id": mid, "detail": str(exc)})
1107
- result: Dict[str, Any] = {"removed": removed, "count": len(removed)}
1108
- if skipped:
1109
- result["skipped"] = skipped
1110
- if failed:
1111
- result["failed"] = failed
1112
- result["status"] = "partial" if removed else "error"
1113
- return result
1114
-
1115
- def compact(
1116
- self,
1117
- *,
1118
- user_email: Optional[str] = None,
1119
- workspace_id: Optional[str] = None,
1120
- ) -> Dict[str, Any]:
1121
- """Dedupe workspace memories with identical (kind, content)."""
1122
- seen: set = set()
1123
- removed: List[str] = []
1124
- failed: List[Dict[str, str]] = []
1125
- # Oldest first so the first occurrence (oldest) is kept.
1126
- memories = list(reversed(self._workspace_memories(user_email=user_email, workspace_id=workspace_id)))
1127
- for m in memories:
1128
- key = (m.get("kind"), str(m.get("content") or "").strip())
1129
- if key in seen:
1130
- if m.get("id"):
1131
- try:
1132
- self._store.delete_memory(m["id"])
1133
- removed.append(m["id"])
1134
- except Exception as exc:
1135
- LOGGER.exception("memory compaction deletion failed for %s", m["id"])
1136
- failed.append({"id": m["id"], "detail": str(exc)})
1137
- else:
1138
- seen.add(key)
1139
- return {
1140
- "compacted": len(removed),
1141
- "removed": removed,
1142
- "remaining": len(seen),
1143
- "failed": failed,
1144
- "status": "partial" if failed and removed else "error" if failed else "ok",
1145
- }
1146
-
1147
- def rebuild(self, target: str = "vector") -> Dict[str, Any]:
1148
- if target in {"vector", "index", "vector_index"}:
1149
- if not self._enable_graph:
1150
- return {"status": "unavailable", "detail": "Knowledge graph / vector index disabled."}
1151
- try:
1152
- result = self._kg.rebuild_vector_index()
1153
- return {"status": "ok", "target": "vector_index", "result": result}
1154
- except Exception as exc:
1155
- return {"status": "error", "detail": str(exc)}
1156
- return {"status": "error", "detail": f"Unknown rebuild target: {target}"}
1157
-
1158
- def clear(
1159
- self,
1160
- *,
1161
- scope: str,
1162
- confirm: bool = False,
1163
- user_email: Optional[str] = None,
1164
- workspace_id: Optional[str] = None,
1165
- ) -> Dict[str, Any]:
1166
- if not confirm:
1167
- raise ValueError("clear requires confirm=true")
1168
- if scope in WORKSPACE_KINDS:
1169
- result = self.prune(kind=scope, user_email=user_email, workspace_id=workspace_id)
1170
- return {"cleared": scope, **result}
1171
- if scope == "workspace": # pragma: no cover — shadowed: "workspace" is itself a WORKSPACE_KINDS member, so the by-kind branch above always wins; reordering would widen what clear() deletes, which is an owner decision
1172
- ids = [m["id"] for m in self._workspace_memories(user_email=user_email, workspace_id=workspace_id) if m.get("id")]
1173
- result = self.prune(ids=ids, user_email=user_email, workspace_id=workspace_id)
1174
- return {"cleared": "workspace", **result}
1175
- if scope == "graph":
1176
- raise ValueError("graph clear is disabled from Memory Manager because it is not workspace-scoped")
1177
- raise ValueError(f"unsupported clear scope: {scope}")