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,197 @@
1
+ """Query → LLM context: the retrieval surface the chat path calls.
2
+
3
+ ``context_for_query`` picks the channel (hybrid or lexical) and returns the
4
+ nodes plus the honest quality signal that says how thin the answer's ground
5
+ is. Moved verbatim out of ``retrieval.py`` (v11.3.0).
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from typing import TYPE_CHECKING
11
+
12
+ # ruff: noqa: F403,F405
13
+ from .._kg_common import * # noqa: F403,F401
14
+ from .signals import context_quality_signal, multimodal_signal
15
+
16
+ # Typing-only base (runtime value is `object`, so the store's MRO is
17
+ # unchanged). Context assembly calls both retrieval channels through `self` —
18
+ # `hybrid_search` from .hybrid and, through it, `search` from .graph_view — so
19
+ # the sibling half is the base that states what this one may assume. The store
20
+ # contract (`_connect`, `_upsert_node`, …) arrives with it.
21
+ if TYPE_CHECKING:
22
+ from .hybrid import _HybridSearchMixin as _Core
23
+ else:
24
+ _Core = object
25
+
26
+
27
+ class _ContextMixin(_Core):
28
+ """Context assembly for a query. Composed into the public mixin."""
29
+
30
+ def context_for_query(
31
+ self,
32
+ query: str,
33
+ limit: int = 6,
34
+ *,
35
+ allowed_workspaces=None,
36
+ include_legacy_global: bool = False,
37
+ use_hybrid: bool = False,
38
+ with_meta: bool = False,
39
+ ):
40
+ """Return compact graph-backed RAG context for chat generation.
41
+
42
+ ``use_hybrid=True`` sources the matches from :meth:`hybrid_search`
43
+ (lexical + vector fusion) instead of the lexical-only :meth:`search`.
44
+ Default behavior is unchanged, and any hybrid failure silently falls
45
+ back to the legacy lexical path.
46
+
47
+ ``with_meta=True`` (additive, v9.8.0) returns
48
+ ``{"context": str, "quality": {...}}`` instead of the bare string.
49
+ ``quality`` follows :func:`context_quality_signal` and honestly
50
+ reports how the context was retrieved (hybrid vs lexical-only
51
+ fallback vs nothing). The ``context`` value is byte-identical to the
52
+ default ``with_meta=False`` return for the same arguments.
53
+ """
54
+ query = str(query or "").strip()
55
+ if not query:
56
+ if with_meta:
57
+ return {
58
+ "context": "",
59
+ "quality": context_quality_signal(
60
+ "none", 0, reason="질의가 비어 있습니다"
61
+ ),
62
+ }
63
+ return ""
64
+ matches: List[Dict[str, Any]] = []
65
+ retrieval_mode = "none"
66
+ vector_meta: Optional[Dict[str, Any]] = None
67
+ multimodal_meta: Optional[Dict[str, Any]] = None
68
+ if use_hybrid:
69
+ try:
70
+ hybrid = self.hybrid_search(
71
+ query,
72
+ top_k=limit,
73
+ allowed_workspaces=allowed_workspaces,
74
+ include_legacy_global=include_legacy_global,
75
+ )
76
+ matches = hybrid.get("matches", [])
77
+ vector_block = hybrid.get("vector") or {}
78
+ # Only a caveat is worth carrying: approximate scoring, a
79
+ # truncated candidate scan, or an already-flagged degradation.
80
+ if (
81
+ vector_block.get("approx")
82
+ or vector_block.get("truncated")
83
+ or vector_block.get("degraded")
84
+ ):
85
+ vector_meta = dict(vector_block)
86
+ if matches:
87
+ retrieval_mode = str(hybrid.get("mode") or "hybrid")
88
+ except Exception: # noqa: BLE001 — context building must never fail
89
+ matches = []
90
+ if not matches:
91
+ matches = self.search(
92
+ query,
93
+ limit,
94
+ allowed_workspaces=allowed_workspaces,
95
+ include_legacy_global=include_legacy_global,
96
+ ).get("matches", [])
97
+ if matches:
98
+ retrieval_mode = "lexical_only"
99
+ if not matches:
100
+ topics = _topic_candidates(query, limit=4)
101
+ if topics:
102
+ nt, et = self._read_tables()
103
+ with self._connect() as conn:
104
+ rows = []
105
+ for topic in topics:
106
+ rows.extend(
107
+ conn.execute(
108
+ f"""
109
+ SELECT id, type, title, summary, metadata_json
110
+ FROM {nt}
111
+ WHERE title LIKE ? OR metadata_json LIKE ?
112
+ ORDER BY updated_at DESC, id ASC
113
+ LIMIT 3
114
+ """,
115
+ (f"%{topic}%", f"%{topic}%"),
116
+ ).fetchall()
117
+ )
118
+ seen = set()
119
+ matches = []
120
+ for row in rows:
121
+ if row["id"] in seen:
122
+ continue
123
+ seen.add(row["id"])
124
+ matches.append(
125
+ {
126
+ "id": row["id"],
127
+ "type": row["type"],
128
+ "title": row["title"],
129
+ "summary": row["summary"],
130
+ "metadata": _safe_loads(row["metadata_json"]),
131
+ }
132
+ )
133
+ if len(matches) >= limit:
134
+ break
135
+ if allowed_workspaces is not None:
136
+ matches = self.filter_scoped_nodes(
137
+ matches,
138
+ allowed_workspaces,
139
+ include_legacy_global=include_legacy_global,
140
+ )
141
+ if matches:
142
+ retrieval_mode = "lexical_only"
143
+ lines = []
144
+ for match in matches[:limit]:
145
+ meta = match.get("metadata") or {}
146
+ source = (
147
+ meta.get("relative_path")
148
+ or meta.get("filename")
149
+ or meta.get("conversation_id")
150
+ or meta.get("source")
151
+ or match["id"]
152
+ )
153
+ summary = _clean_text(match.get("summary") or "")[:700]
154
+ lines.append(
155
+ f"- [{match['type']}] {match['title']} | source={source} | {summary}"
156
+ )
157
+ context = "\n".join(lines)
158
+ if not with_meta:
159
+ return context
160
+ # Only the context that actually reached the model counts as
161
+ # multimodal — matches trimmed by ``limit`` are not in the answer.
162
+ multimodal_meta = multimodal_signal(matches[:limit])
163
+ return {
164
+ "context": context,
165
+ "quality": context_quality_signal(
166
+ retrieval_mode,
167
+ len(matches[:limit]),
168
+ vector=vector_meta,
169
+ multimodal=multimodal_meta,
170
+ ),
171
+ }
172
+
173
+ def context_for_query_with_meta(
174
+ self,
175
+ query: str,
176
+ limit: int = 6,
177
+ *,
178
+ allowed_workspaces=None,
179
+ include_legacy_global: bool = False,
180
+ use_hybrid: bool = True,
181
+ ) -> Dict[str, Any]:
182
+ """Additive companion to :meth:`context_for_query` (v9.8.0).
183
+
184
+ Always returns ``{"context": str, "quality": {...}}`` so chat callers
185
+ can surface an honest retrieval signal without changing the legacy
186
+ string-returning contract. Defaults to hybrid retrieval because meta
187
+ consumers want the vector-fallback signal; pass ``use_hybrid=False``
188
+ for the legacy lexical-only sourcing.
189
+ """
190
+ return self.context_for_query(
191
+ query,
192
+ limit,
193
+ allowed_workspaces=allowed_workspaces,
194
+ include_legacy_global=include_legacy_global,
195
+ use_hybrid=use_hybrid,
196
+ with_meta=True,
197
+ )
@@ -0,0 +1,319 @@
1
+ """The graph view and the lexical search over it.
2
+
3
+ ``graph()`` renders the visible node/edge picture a UI draws; ``search()`` is
4
+ the keyword channel that ``hybrid_search`` fuses with the vector channel.
5
+ Split out of ``retrieval.py`` (v11.3.0) with both methods moved verbatim.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from typing import TYPE_CHECKING
11
+
12
+ # ruff: noqa: F403,F405
13
+ from .._kg_common import * # noqa: F403,F401
14
+
15
+ # The cross-mixin surface (`_connect`, `_upsert_node`, …) is declared in
16
+ # `_kg_contract.KnowledgeGraphCore`. It is a typing-only base: at runtime this
17
+ # is `object`, so the MRO of `KnowledgeGraphStore` is unchanged.
18
+ if TYPE_CHECKING:
19
+ from .._kg_contract import KnowledgeGraphCore as _Core
20
+ else:
21
+ _Core = object
22
+
23
+
24
+ class _GraphViewMixin(_Core):
25
+ """Graph rendering + lexical search. Composed into the public mixin."""
26
+
27
+ _GRAPH_VISIBLE_TYPES = (
28
+ "Computer", # 내 컴퓨터
29
+ "Drive", # 드라이브 / 볼륨
30
+ "Folder", # 폴더
31
+ "File", # 일반 파일
32
+ "Chat", # 대화 세션
33
+ "Document", # 파일 (PDF·PPT·Word·Excel·이미지)
34
+ "CodeFile", # 코드 파일
35
+ "Spreadsheet", # 엑셀/CSV
36
+ "SlideDeck", # 프레젠테이션
37
+ "Image", # 이미지
38
+ "ImageText", # OCR 텍스트
39
+ "Audio", # 녹음 / 음성 메모 (11.1.0)
40
+ "Concept", # 개념 / 아이디어 / 기술 용어
41
+ "Person", # 사람
42
+ "Error", # 오류 / 버그
43
+ "Code", # 코드 / 함수
44
+ "Feature", # 소프트웨어 기능
45
+ "Task", # 할 일
46
+ "Decision", # 결정 사항
47
+ # v3.6.0 Knowledge Graph First — 1급 엔티티를 그래프에 노출
48
+ "Source", # 수집 출처 (파일/URL/브라우저 탭/git)
49
+ "Repository", # git 저장소
50
+ "Meeting", # 회의
51
+ "Organization", # 조직
52
+ "Workflow", # 워크플로우
53
+ "Agent", # 에이전트
54
+ )
55
+
56
+ def graph(
57
+ self,
58
+ limit: int = 300,
59
+ *,
60
+ allowed_workspaces=None,
61
+ include_legacy_global: bool = False,
62
+ ) -> Dict[str, Any]:
63
+ limit = max(1, min(int(limit or 300), 2000))
64
+ visible = ",".join(f"'{t}'" for t in self._GRAPH_VISIBLE_TYPES)
65
+ nt, et = self._read_tables()
66
+ with self._connect() as conn:
67
+ nodes = [
68
+ {
69
+ "id": row["id"],
70
+ "type": row["type"],
71
+ "title": row["title"],
72
+ "summary": row["summary"],
73
+ "metadata": _safe_loads(row["metadata_json"]),
74
+ "updated_at": row["updated_at"],
75
+ }
76
+ for row in conn.execute(
77
+ f"SELECT id, type, title, summary, metadata_json, updated_at FROM {nt} WHERE type IN ({visible}) ORDER BY updated_at DESC, id ASC LIMIT ?",
78
+ (limit,),
79
+ )
80
+ ]
81
+ node_ids = {node["id"] for node in nodes}
82
+ edges: List[Dict[str, Any]] = []
83
+ if node_ids:
84
+ edge_rows = conn.execute(
85
+ f"""
86
+ SELECT id, from_node, to_node, type, weight, metadata_json
87
+ FROM {et}
88
+ WHERE from_node IN (
89
+ SELECT id FROM {nt} WHERE type IN ({visible})
90
+ ORDER BY updated_at DESC, id ASC LIMIT ?
91
+ )
92
+ AND to_node IN (
93
+ SELECT id FROM {nt} WHERE type IN ({visible})
94
+ ORDER BY updated_at DESC, id ASC LIMIT ?
95
+ )
96
+ ORDER BY weight DESC, created_at DESC, id ASC
97
+ """,
98
+ (limit, limit),
99
+ ).fetchall()
100
+ edges = [
101
+ {
102
+ "id": row["id"],
103
+ "from": row["from_node"],
104
+ "to": row["to_node"],
105
+ "type": row["type"],
106
+ "weight": row["weight"],
107
+ "metadata": _safe_loads(row["metadata_json"]),
108
+ }
109
+ for row in edge_rows
110
+ ]
111
+
112
+ if allowed_workspaces is not None:
113
+ nodes = self.filter_scoped_nodes(
114
+ nodes,
115
+ allowed_workspaces,
116
+ include_legacy_global=include_legacy_global,
117
+ )
118
+ kept_ids = {node["id"] for node in nodes}
119
+ edges = [e for e in edges if e["from"] in kept_ids and e["to"] in kept_ids]
120
+
121
+ degree_map: Dict[str, int] = {}
122
+ now = datetime.now()
123
+ node_by_id = {node["id"]: node for node in nodes}
124
+ topic_metrics: Dict[str, Dict[str, Any]] = {}
125
+
126
+ for edge in edges:
127
+ degree_map[edge["from"]] = degree_map.get(edge["from"], 0) + 1
128
+ degree_map[edge["to"]] = degree_map.get(edge["to"], 0) + 1
129
+ from_node = node_by_id.get(edge["from"])
130
+ to_node = node_by_id.get(edge["to"])
131
+ if not from_node or not to_node:
132
+ continue # pragma: no cover — unreachable: the edge query selects endpoints from the same node window
133
+ for topic_node, other_node in ((from_node, to_node), (to_node, from_node)):
134
+ if topic_node["type"] != "Topic":
135
+ continue
136
+ metrics = topic_metrics.setdefault(
137
+ topic_node["id"],
138
+ {
139
+ "mention_count": 0.0,
140
+ "conversation_ids": set(),
141
+ },
142
+ )
143
+ if edge["type"] in {"mentions", "discusses"}:
144
+ metrics["mention_count"] += max(
145
+ 0.5, float(edge.get("weight") or 1.0)
146
+ )
147
+ other_meta = other_node.get("metadata") or {}
148
+ conversation_id = other_meta.get("conversation_id")
149
+ if other_node["type"] == "Conversation":
150
+ conversation_id = other_node["id"]
151
+ if conversation_id:
152
+ metrics["conversation_ids"].add(str(conversation_id))
153
+
154
+ type_max_raw: Dict[str, float] = {}
155
+ for node in nodes:
156
+ degree = degree_map.get(node["id"], 0)
157
+ recency = _recency_score(node.get("updated_at"), now=now)
158
+ metrics = {
159
+ "degree": degree,
160
+ "recency_score": round(recency, 4),
161
+ }
162
+ if node["type"] == "Topic":
163
+ topic_stat = topic_metrics.get(node["id"], {})
164
+ mention_count = float(topic_stat.get("mention_count") or 0.0)
165
+ conversation_count = len(topic_stat.get("conversation_ids") or ())
166
+ raw_importance = (
167
+ math.log1p(mention_count) * 2.8
168
+ + math.log1p(conversation_count) * 2.2
169
+ + recency * 1.4
170
+ + math.sqrt(max(0, degree)) * 0.45
171
+ )
172
+ metrics.update(
173
+ {
174
+ "mention_count": round(mention_count, 2),
175
+ "conversation_count": conversation_count,
176
+ }
177
+ )
178
+ else:
179
+ raw_importance = math.log1p(max(0, degree)) * 1.4 + recency * 0.9
180
+
181
+ metrics["importance_raw"] = round(raw_importance, 4)
182
+ node["importance"] = round(raw_importance, 4)
183
+ node["_raw_importance"] = raw_importance
184
+ node["metadata"] = {
185
+ **(node.get("metadata") or {}),
186
+ "graph_metrics": metrics,
187
+ }
188
+ type_max_raw[node["type"]] = max(
189
+ type_max_raw.get(node["type"], 0.0), raw_importance
190
+ )
191
+
192
+ for node in nodes:
193
+ max_raw = max(type_max_raw.get(node["type"], 0.0), 0.0001)
194
+ importance_norm = min(1.0, (node.get("_raw_importance") or 0.0) / max_raw)
195
+ node["importance_norm"] = round(importance_norm, 4)
196
+ node["metadata"]["graph_metrics"]["importance_norm"] = node[
197
+ "importance_norm"
198
+ ]
199
+ node.pop("_raw_importance", None)
200
+ return {"nodes": nodes, "edges": edges}
201
+
202
+ def search(
203
+ self,
204
+ query: str,
205
+ limit: int = 30,
206
+ *,
207
+ allowed_workspaces=None,
208
+ include_legacy_global: bool = False,
209
+ ) -> Dict[str, Any]:
210
+ query = str(query or "").strip()
211
+ q = f"%{query}%"
212
+ limit = max(1, min(int(limit or 30), 100))
213
+ nt, et = self._read_tables()
214
+ with self._connect() as conn:
215
+ rows = []
216
+ if query:
217
+ fts_ids = self._fts_match_ids(conn, query, limit)
218
+ if fts_ids:
219
+ placeholders = ",".join("?" for _ in fts_ids)
220
+ by_id = {
221
+ row["id"]: row
222
+ for row in conn.execute(
223
+ f"""
224
+ SELECT id, type, title, summary, metadata_json, updated_at
225
+ FROM {nt} WHERE id IN ({placeholders})
226
+ """,
227
+ fts_ids,
228
+ ).fetchall()
229
+ }
230
+ # Preserve FTS bm25 rank order.
231
+ rows = [by_id[i] for i in fts_ids if i in by_id]
232
+ else:
233
+ rows = conn.execute(
234
+ f"""
235
+ SELECT id, type, title, summary, metadata_json, updated_at
236
+ FROM {nt}
237
+ WHERE title LIKE ? OR summary LIKE ? OR metadata_json LIKE ?
238
+ ORDER BY updated_at DESC, id ASC
239
+ LIMIT ?
240
+ """,
241
+ (q, q, q, limit),
242
+ ).fetchall()
243
+
244
+ if len(rows) < limit:
245
+ terms = _topic_candidates(query, limit=8)
246
+ if terms:
247
+ clauses = []
248
+ params: List[str] = []
249
+ for term in terms:
250
+ clauses.append(
251
+ "(title LIKE ? OR summary LIKE ? OR metadata_json LIKE ?)"
252
+ )
253
+ params.extend([f"%{term}%", f"%{term}%", f"%{term}%"])
254
+ extra = conn.execute(
255
+ f"""
256
+ SELECT id, type, title, summary, metadata_json, updated_at
257
+ FROM {nt}
258
+ WHERE {" OR ".join(clauses)}
259
+ ORDER BY updated_at DESC, id ASC
260
+ LIMIT ?
261
+ """,
262
+ (*params, limit * 3),
263
+ ).fetchall()
264
+ by_id = {row["id"]: row for row in rows}
265
+ for row in extra:
266
+ by_id.setdefault(row["id"], row)
267
+ rows = list(by_id.values())
268
+
269
+ terms_for_score = set(_topic_candidates(query, limit=12))
270
+
271
+ def score(row: sqlite3.Row) -> tuple:
272
+ haystack = (
273
+ f"{row['title']} {row['summary']} {row['metadata_json']}".lower()
274
+ )
275
+ hits = sum(1 for term in terms_for_score if term.lower() in haystack)
276
+ type_boost = (
277
+ 1
278
+ if row["type"]
279
+ in {
280
+ "Decision",
281
+ "Task",
282
+ "File",
283
+ "Document",
284
+ "CodeFile",
285
+ "Spreadsheet",
286
+ "SlideDeck",
287
+ "Image",
288
+ "ImageText",
289
+ "Audio",
290
+ "Page",
291
+ "Slide",
292
+ }
293
+ else 0
294
+ )
295
+ return (hits, type_boost, row["updated_at"] or "")
296
+
297
+ # Deterministic contract: rows with equal relevance order by id ASC
298
+ # (stable sort preserves the pre-sort under reverse=True), matching
299
+ # the legacy LIKE path regardless of FTS bm25 tie ordering.
300
+ rows = sorted(rows, key=lambda r: r["id"])
301
+ rows = sorted(rows, key=score, reverse=True)[:limit]
302
+ matches = [
303
+ {
304
+ "id": row["id"],
305
+ "type": row["type"],
306
+ "title": row["title"],
307
+ "summary": row["summary"],
308
+ "metadata": _safe_loads(row["metadata_json"]),
309
+ "updated_at": row["updated_at"],
310
+ }
311
+ for row in rows
312
+ ]
313
+ if allowed_workspaces is not None:
314
+ matches = self.filter_scoped_nodes(
315
+ matches,
316
+ allowed_workspaces,
317
+ include_legacy_global=include_legacy_global,
318
+ )
319
+ return {"query": query, "matches": matches}