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,138 @@
1
+ """The mutating half: prune, compact, rebuild, clear.
2
+
3
+ Every deletion path goes through :meth:`prune`, and :meth:`prune` intersects
4
+ its targets with the caller's *own* memories first. That ownership guard is the
5
+ point: a forged id belonging to another user is refused and reported as
6
+ ``skipped``, never silently deleted. :meth:`clear` is a thin scope router over
7
+ the same guard, and refuses ``graph`` outright because the graph is not
8
+ workspace-scoped.
9
+
10
+ Partial failure is reported, not swallowed: ``status`` becomes ``partial`` when
11
+ some deletions landed and ``error`` when none did.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ from typing import Any, Dict, List, Optional
17
+
18
+ from ._contract import MemoryCore as _Core
19
+ from .constants import LOGGER, WORKSPACE_KINDS
20
+
21
+
22
+ class MemoryMaintenanceMixin(_Core):
23
+ """Prune / compact / rebuild / clear. Mixed into ``MemoryService``."""
24
+
25
+ # ── mutating operations ───────────────────────────────────────────────
26
+ def prune(
27
+ self,
28
+ *,
29
+ ids: Optional[List[str]] = None,
30
+ kind: Optional[str] = None,
31
+ user_email: Optional[str] = None,
32
+ workspace_id: Optional[str] = None,
33
+ ) -> Dict[str, Any]:
34
+ # Ownership guard: a caller may only prune memories they own. Both the
35
+ # explicit-id and kind paths are intersected with the caller's own
36
+ # memories, so a forged id for another user's memory is refused, not
37
+ # silently deleted.
38
+ owned_ids = {
39
+ m["id"]
40
+ for m in self._workspace_memories(user_email=user_email, workspace_id=workspace_id)
41
+ if m.get("id")
42
+ }
43
+ removed: List[str] = []
44
+ failed: List[Dict[str, str]] = []
45
+ skipped: List[str] = []
46
+ target_ids: List[str] = []
47
+ seen: set = set()
48
+ for mid in (ids or []):
49
+ if mid in seen:
50
+ continue
51
+ seen.add(mid)
52
+ if mid in owned_ids:
53
+ target_ids.append(mid)
54
+ else:
55
+ skipped.append(mid)
56
+ if kind:
57
+ for m in self._workspace_memories(user_email=user_email, workspace_id=workspace_id):
58
+ if m.get("kind") == kind and m.get("id") and m["id"] not in seen:
59
+ seen.add(m["id"])
60
+ target_ids.append(m["id"])
61
+ for mid in target_ids:
62
+ try:
63
+ self._store.delete_memory(mid)
64
+ removed.append(mid)
65
+ except Exception as exc:
66
+ LOGGER.exception("memory deletion failed for %s", mid)
67
+ failed.append({"id": mid, "detail": str(exc)})
68
+ result: Dict[str, Any] = {"removed": removed, "count": len(removed)}
69
+ if skipped:
70
+ result["skipped"] = skipped
71
+ if failed:
72
+ result["failed"] = failed
73
+ result["status"] = "partial" if removed else "error"
74
+ return result
75
+
76
+ def compact(
77
+ self,
78
+ *,
79
+ user_email: Optional[str] = None,
80
+ workspace_id: Optional[str] = None,
81
+ ) -> Dict[str, Any]:
82
+ """Dedupe workspace memories with identical (kind, content)."""
83
+ seen: set = set()
84
+ removed: List[str] = []
85
+ failed: List[Dict[str, str]] = []
86
+ # Oldest first so the first occurrence (oldest) is kept.
87
+ memories = list(reversed(self._workspace_memories(user_email=user_email, workspace_id=workspace_id)))
88
+ for m in memories:
89
+ key = (m.get("kind"), str(m.get("content") or "").strip())
90
+ if key in seen:
91
+ if m.get("id"):
92
+ try:
93
+ self._store.delete_memory(m["id"])
94
+ removed.append(m["id"])
95
+ except Exception as exc:
96
+ LOGGER.exception("memory compaction deletion failed for %s", m["id"])
97
+ failed.append({"id": m["id"], "detail": str(exc)})
98
+ else:
99
+ seen.add(key)
100
+ return {
101
+ "compacted": len(removed),
102
+ "removed": removed,
103
+ "remaining": len(seen),
104
+ "failed": failed,
105
+ "status": "partial" if failed and removed else "error" if failed else "ok",
106
+ }
107
+
108
+ def rebuild(self, target: str = "vector") -> Dict[str, Any]:
109
+ if target in {"vector", "index", "vector_index"}:
110
+ if not self._enable_graph:
111
+ return {"status": "unavailable", "detail": "Knowledge graph / vector index disabled."}
112
+ try:
113
+ result = self._kg.rebuild_vector_index()
114
+ return {"status": "ok", "target": "vector_index", "result": result}
115
+ except Exception as exc:
116
+ return {"status": "error", "detail": str(exc)}
117
+ return {"status": "error", "detail": f"Unknown rebuild target: {target}"}
118
+
119
+ def clear(
120
+ self,
121
+ *,
122
+ scope: str,
123
+ confirm: bool = False,
124
+ user_email: Optional[str] = None,
125
+ workspace_id: Optional[str] = None,
126
+ ) -> Dict[str, Any]:
127
+ if not confirm:
128
+ raise ValueError("clear requires confirm=true")
129
+ if scope in WORKSPACE_KINDS:
130
+ result = self.prune(kind=scope, user_email=user_email, workspace_id=workspace_id)
131
+ return {"cleared": scope, **result}
132
+ 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
133
+ ids = [m["id"] for m in self._workspace_memories(user_email=user_email, workspace_id=workspace_id) if m.get("id")]
134
+ result = self.prune(ids=ids, user_email=user_email, workspace_id=workspace_id)
135
+ return {"cleared": "workspace", **result}
136
+ if scope == "graph":
137
+ raise ValueError("graph clear is disabled from Memory Manager because it is not workspace-scoped")
138
+ raise ValueError(f"unsupported clear scope: {scope}")
@@ -0,0 +1,186 @@
1
+ """The Memory Manager: one cross-tier report over every backing store.
2
+
3
+ :meth:`manager` is the service's centre of gravity — sources, counts, sizes,
4
+ health and the Brain readiness signal in a single read that the brief, the
5
+ proof and the API all build on. Nothing here is estimated: a tier with no
6
+ backing reports ``unavailable`` and contributes ``None``, never a zero dressed
7
+ up as a measurement.
8
+
9
+ ``_brain_readiness`` lives here rather than in the frontend so the growth score
10
+ is auditable and the Memory Manager stays the single owner of cross-tier
11
+ signals.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ from typing import Any, Dict, List, Optional
17
+
18
+ from latticeai.core.timeutil import now_iso as _now
19
+ from latticeai.core.workspace_os_utils import _file_size
20
+
21
+ from ._contract import MemoryCore as _Core
22
+ from .constants import TIERS
23
+
24
+
25
+ class MemoryManagerMixin(_Core):
26
+ """Sources / usage / health. Mixed into ``MemoryService``."""
27
+
28
+ # ── Memory Manager: sources / usage / health ──────────────────────────
29
+ def _brain_readiness(
30
+ self,
31
+ *,
32
+ memory_count: int,
33
+ concept_count: Optional[int],
34
+ relationship_count: Optional[int],
35
+ healthy_sources: int,
36
+ ) -> Dict[str, Any]:
37
+ """Summarize how ready the user's Brain is for the product UI.
38
+
39
+ The frontend should render this signal instead of re-deriving it from
40
+ UI fragments. Keeping it here makes the score auditable and keeps the
41
+ Memory Manager as the single owner of cross-tier Brain growth signals.
42
+ """
43
+ concepts = max(0, int(concept_count or 0))
44
+ relationships = max(0, int(relationship_count or 0))
45
+ memories = max(0, int(memory_count or 0))
46
+ healthy = max(0, int(healthy_sources or 0))
47
+ score = min(100, round(memories * 12 + concepts * 8 + relationships * 4 + healthy * 3))
48
+
49
+ if memories < 1 and concepts < 1:
50
+ state = "quiet"
51
+ depth = 2
52
+ title_key = "brain.readiness.quiet"
53
+ action_key = "brain.readiness.start"
54
+ score = max(12, score)
55
+ elif concepts < 3 or relationships < 2:
56
+ state = "forming"
57
+ depth = 3 if concepts < 3 else 4
58
+ title_key = "brain.readiness.forming"
59
+ action_key = "brain.readiness.grow"
60
+ score = max(38, score)
61
+ else:
62
+ state = "alive"
63
+ depth = 5
64
+ title_key = "brain.readiness.alive"
65
+ action_key = "brain.readiness.map"
66
+ score = max(72, score)
67
+
68
+ return {
69
+ "score": score,
70
+ "state": state,
71
+ "depth": depth,
72
+ "title_key": title_key,
73
+ "action_key": action_key,
74
+ "signals": {
75
+ "memory_count": memories,
76
+ "concept_count": concepts,
77
+ "relationship_count": relationships,
78
+ "healthy_sources": healthy,
79
+ },
80
+ "source": "memory_service",
81
+ }
82
+
83
+ def manager(self, *, user_email: Optional[str] = None, workspace_id: Optional[str] = None) -> Dict[str, Any]:
84
+ ws_mem = self._workspace_memories(user_email=user_email, workspace_id=workspace_id or "personal")
85
+ if workspace_id is None:
86
+ project_mem = [m for m in self._all_memories() if (m.get("workspace_id") or "personal") != "personal"]
87
+ else:
88
+ project_mem = self._workspace_memories(user_email=user_email, workspace_id=workspace_id)
89
+ snaps = self._snapshots(workspace_id=workspace_id)
90
+ convs = self._scoped_conversations(user_email=user_email, workspace_id=workspace_id)
91
+ kg_stats = self._kg_stats()
92
+ kg_index = self._kg_index()
93
+
94
+ ws_bytes = _file_size(self._data_dir / "workspace_os.json")
95
+ kg_bytes = _file_size(self._data_dir / "knowledge_graph.sqlite")
96
+ if self._conversation_store is not None:
97
+ conv_bytes = int(getattr(self._conversation_store, "size_bytes", lambda: 0)())
98
+ else:
99
+ conv_bytes = _file_size(self._history_file)
100
+
101
+ node_total = sum((kg_stats or {}).get("nodes", {}).values()) if kg_stats else None
102
+ edge_total = sum((kg_stats or {}).get("edges", {}).values()) if kg_stats else None
103
+ vector_total = None
104
+ if kg_index and isinstance(kg_index.get("vector_counts"), dict):
105
+ vector_total = sum(kg_index["vector_counts"].values())
106
+ elif kg_index:
107
+ vector_total = kg_index.get("indexed") or kg_index.get("ready")
108
+
109
+ sources: List[Dict[str, Any]] = [
110
+ {
111
+ "id": "workspace", "type": "workspace", "label": "Workspace Memory",
112
+ "count": len(ws_mem), "size_bytes": ws_bytes if ws_mem else 0,
113
+ "health": "ok", "detail": "Personal workspace knowledge, by kind.",
114
+ },
115
+ {
116
+ "id": "project", "type": "project", "label": "Project Memory",
117
+ "count": len(project_mem), "size_bytes": 0,
118
+ "health": "ok", "detail": "Memory scoped to organization workspaces.",
119
+ },
120
+ {
121
+ "id": "agent", "type": "agent", "label": "Agent Memory",
122
+ "count": len(snaps), "size_bytes": 0,
123
+ "health": "ok", "detail": "Per-run agent memory snapshots.",
124
+ },
125
+ {
126
+ "id": "conversation", "type": "conversation", "label": "Conversation Memory",
127
+ "count": len(convs), "size_bytes": conv_bytes,
128
+ "health": "ok" if (self._conversation_store is not None or self._history_file.exists()) else "empty",
129
+ "detail": "Historical interaction memory from chat.",
130
+ },
131
+ {
132
+ "id": "graph", "type": "graph", "label": "Graph Memory",
133
+ "count": node_total, "size_bytes": kg_bytes,
134
+ "health": "ok" if kg_stats else "unavailable",
135
+ "detail": "Knowledge Graph entities and relations." if kg_stats else "Knowledge graph disabled or unavailable.",
136
+ "edges": edge_total,
137
+ },
138
+ {
139
+ "id": "vector", "type": "vector", "label": "Vector Memory",
140
+ "count": vector_total, "size_bytes": 0,
141
+ "health": "ok" if kg_index else "unavailable",
142
+ "detail": "Local embedding vector index." if kg_index else "Vector index unavailable.",
143
+ },
144
+ ]
145
+ total_items = sum(int(s["count"] or 0) for s in sources)
146
+ total_bytes = ws_bytes + kg_bytes + conv_bytes
147
+ healthy = sum(1 for s in sources if s["health"] == "ok")
148
+ overall = "ok" if healthy >= 4 else "degraded" if healthy >= 1 else "unavailable"
149
+ memory_ids = {m.get("id") for m in [*ws_mem, *project_mem] if m.get("id")}
150
+ memory_count = len(memory_ids) + len(snaps) + len(convs)
151
+ return {
152
+ "sources": sources,
153
+ "recent_memories": self._manager_recent_memories([*ws_mem, *project_mem], limit=8),
154
+ "tiers": list(TIERS),
155
+ "usage": {"total_items": total_items, "total_bytes": total_bytes, "sources": len(sources)},
156
+ "brain_readiness": self._brain_readiness(
157
+ memory_count=memory_count,
158
+ concept_count=node_total,
159
+ relationship_count=edge_total,
160
+ healthy_sources=healthy,
161
+ ),
162
+ "health": overall,
163
+ "graph_enabled": self._enable_graph,
164
+ "generated_at": _now(),
165
+ }
166
+
167
+ @staticmethod
168
+ def _manager_recent_memories(memories: List[Dict[str, Any]], *, limit: int = 8) -> List[Dict[str, Any]]:
169
+ rows: List[Dict[str, Any]] = []
170
+ for item in memories[: max(1, limit)]:
171
+ metadata = item.get("metadata") if isinstance(item.get("metadata"), dict) else {}
172
+ rows.append({
173
+ "id": item.get("id") or "",
174
+ "kind": item.get("kind") or "memory",
175
+ "content": str(item.get("content") or "")[:320],
176
+ "tags": item.get("tags") if isinstance(item.get("tags"), list) else [],
177
+ "metadata": metadata,
178
+ "workspace_id": item.get("workspace_id") or "personal",
179
+ "created_at": item.get("created_at"),
180
+ "updated_at": item.get("updated_at"),
181
+ })
182
+ return rows
183
+
184
+ def brain_quality_summary(self, *, user_email: Optional[str] = None, workspace_id: Optional[str] = None) -> Dict[str, Any]:
185
+ """Return the backend-owned Brain readiness signal for API consumers."""
186
+ return self.manager(user_email=user_email, workspace_id=workspace_id)["brain_readiness"]
@@ -0,0 +1,136 @@
1
+ """Brain Proof: the durable evidence behind "your Brain outlives the model".
2
+
3
+ Backend-owned on purpose. The first-run Brain screen must show the stores it
4
+ can actually recall from, and the model-continuity claim has to be independent
5
+ of whichever LLM happens to be loaded — a UI-derived version of this would be
6
+ an assertion, not a proof.
7
+
8
+ The two are deliberately separated: ``capability`` is always true (the design
9
+ is model-independent), while ``proven`` stays false until there is durable
10
+ evidence on disk to recall from.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from typing import Any, Dict, Optional
16
+
17
+ from latticeai.core.timeutil import now_iso as _now
18
+
19
+ from ._contract import MemoryCore as _Core
20
+
21
+
22
+ class MemoryProofMixin(_Core):
23
+ """The proof points and the query they are demonstrated with."""
24
+
25
+ def brain_proof(
26
+ self,
27
+ *,
28
+ user_email: Optional[str] = None,
29
+ workspace_id: Optional[str] = None,
30
+ active_model: Optional[str] = None,
31
+ recall_query: str = "",
32
+ limit: int = 3,
33
+ ) -> Dict[str, Any]:
34
+ """Return the proof points that make Brain feel model-independent.
35
+
36
+ This is intentionally backend-owned instead of UI-derived: the first-run
37
+ Brain screen needs to show the durable stores it can actually recall
38
+ from, and the model continuity claim must be independent from whichever
39
+ LLM is currently loaded.
40
+ """
41
+ manager = self.manager(user_email=user_email, workspace_id=workspace_id)
42
+ sources = {str(source.get("id")): source for source in manager.get("sources", []) if isinstance(source, dict)}
43
+ readiness = manager.get("brain_readiness") or {}
44
+ conversation_count = int(sources.get("conversation", {}).get("count") or 0)
45
+ workspace_count = int(sources.get("workspace", {}).get("count") or 0)
46
+ graph_count = int(sources.get("graph", {}).get("count") or 0)
47
+ vector_count = int(sources.get("vector", {}).get("count") or 0)
48
+ query = recall_query.strip() or self._latest_recall_query(user_email=user_email, workspace_id=workspace_id)
49
+ recall: Dict[str, Any] = (
50
+ self.recall(query, user_email=user_email, workspace_id=workspace_id, limit=limit)
51
+ if query
52
+ else {"query": "", "results": [], "count": 0, "source": "live"}
53
+ )
54
+ recall_items = [
55
+ {
56
+ "id": item.get("id"),
57
+ "source": item.get("source"),
58
+ "title": item.get("title"),
59
+ "snippet": item.get("snippet"),
60
+ "score": item.get("score", 0),
61
+ # Evidence explainability: why this item was recalled, so the
62
+ # citation UI can show the matched terms instead of a bare score.
63
+ "matched_terms": item.get("matched_terms") or [],
64
+ "confidence": item.get("confidence") or "low",
65
+ # v11.1.0: what kind of memory this is, and — for a picture —
66
+ # the caption and inline thumbnail the Evidence panel renders.
67
+ "kind": item.get("kind") or "",
68
+ **({"caption": item["caption"]} if item.get("caption") else {}),
69
+ **({"thumbnail": item["thumbnail"]} if item.get("thumbnail") else {}),
70
+ }
71
+ for item in list(recall.get("results", []))[: max(1, min(limit, 8))]
72
+ ]
73
+ durable_items = workspace_count + conversation_count + graph_count
74
+ # Capability and proof are deliberately separated. The brain is
75
+ # architecturally model-independent, so the capability is always true.
76
+ # The proof stays false until there is durable evidence on disk.
77
+ has_durable_evidence = durable_items > 0
78
+ proven_continuity = has_durable_evidence
79
+ return {
80
+ "status": readiness.get("state") or "quiet",
81
+ "readiness": readiness,
82
+ "model_continuity": {
83
+ "active_model": active_model or "",
84
+ "brain_owner": "lattice_brain",
85
+ # Design capability: the brain is built to outlive any model.
86
+ "capability": True,
87
+ # Proof: only true when durable evidence exists to recall.
88
+ "survives_model_switch": proven_continuity,
89
+ "proven": proven_continuity,
90
+ "context_store": "workspace + conversation + graph + vector",
91
+ },
92
+ "proofs": {
93
+ "durable_items": durable_items,
94
+ "has_durable_evidence": has_durable_evidence,
95
+ "workspace_memories": workspace_count,
96
+ "conversations": conversation_count,
97
+ "graph_concepts": graph_count,
98
+ "vector_items": vector_count,
99
+ "healthy_sources": readiness.get("signals", {}).get("healthy_sources", 0),
100
+ },
101
+ "recall": {
102
+ "query": recall.get("query") or query,
103
+ "items": recall_items,
104
+ "count": recall.get("count", 0),
105
+ },
106
+ "claims": {
107
+ "can_recall_user_context": bool(recall_items or durable_items > 0),
108
+ # Proven, not asserted: no durable evidence means no continuity claim.
109
+ "keeps_context_across_models": proven_continuity,
110
+ "is_knowledge_store": bool(graph_count or vector_count or workspace_count or conversation_count),
111
+ },
112
+ "generated_at": _now(),
113
+ }
114
+
115
+ def _latest_recall_query(self, *, user_email: Optional[str], workspace_id: Optional[str]) -> str:
116
+ for memory in self._workspace_memories(user_email=user_email, workspace_id=workspace_id or "personal"):
117
+ content = str(memory.get("content") or "").strip()
118
+ if content:
119
+ return content[:96]
120
+ for conversation in self._conversations():
121
+ messages = conversation.get("messages") or []
122
+ if not isinstance(messages, list):
123
+ continue
124
+ for message in reversed(messages[-8:]):
125
+ if not isinstance(message, dict):
126
+ continue
127
+ if user_email and message.get("user_email") != user_email:
128
+ continue
129
+ message_workspace = message.get("workspace_id") or "personal"
130
+ target_workspace = workspace_id or "personal"
131
+ if message_workspace != target_workspace:
132
+ continue
133
+ content = str(message.get("content") or "").strip()
134
+ if content:
135
+ return content[:96]
136
+ return ""