ltcai 3.6.0 → 4.0.1

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 (238) hide show
  1. package/README.md +39 -31
  2. package/docs/CHANGELOG.md +64 -0
  3. package/docs/REALTIME_COLLABORATION.md +3 -3
  4. package/docs/V3_FRONTEND.md +9 -8
  5. package/docs/V4_BRAIN_ARCHITECTURE.md +322 -0
  6. package/docs/V4_DIGITAL_BRAIN_RECOVERY.md +552 -0
  7. package/docs/V4_IMPLEMENTATION_PLAN.md +470 -0
  8. package/docs/kg-schema.md +51 -53
  9. package/docs/spec-vs-impl.md +10 -10
  10. package/kg_schema.py +2 -520
  11. package/knowledge_graph.py +37 -4629
  12. package/knowledge_graph_api.py +11 -127
  13. package/latticeai/__init__.py +1 -1
  14. package/latticeai/api/admin.py +16 -17
  15. package/latticeai/api/agents.py +20 -7
  16. package/latticeai/api/auth.py +46 -15
  17. package/latticeai/api/chat.py +112 -76
  18. package/latticeai/api/health.py +1 -1
  19. package/latticeai/api/hooks.py +1 -1
  20. package/latticeai/api/invitations.py +100 -0
  21. package/latticeai/api/knowledge_graph.py +139 -0
  22. package/latticeai/api/local_files.py +1 -1
  23. package/latticeai/api/mcp.py +23 -11
  24. package/latticeai/api/memory.py +1 -1
  25. package/latticeai/api/models.py +1 -1
  26. package/latticeai/api/network.py +81 -0
  27. package/latticeai/api/plugins.py +3 -6
  28. package/latticeai/api/realtime.py +5 -8
  29. package/latticeai/api/search.py +26 -2
  30. package/latticeai/api/security_dashboard.py +2 -3
  31. package/latticeai/api/setup.py +2 -2
  32. package/latticeai/api/static_routes.py +11 -16
  33. package/latticeai/api/tools.py +3 -0
  34. package/latticeai/api/ui_redirects.py +26 -0
  35. package/latticeai/api/workflow_designer.py +85 -6
  36. package/latticeai/api/workspace.py +93 -57
  37. package/latticeai/app_factory.py +1781 -0
  38. package/latticeai/brain/__init__.py +18 -0
  39. package/latticeai/brain/_kg_common.py +1123 -0
  40. package/latticeai/brain/context.py +213 -0
  41. package/latticeai/brain/conversations.py +236 -0
  42. package/latticeai/brain/discovery.py +1455 -0
  43. package/latticeai/brain/documents.py +218 -0
  44. package/latticeai/brain/identity.py +175 -0
  45. package/latticeai/brain/ingest.py +644 -0
  46. package/latticeai/brain/memory.py +102 -0
  47. package/latticeai/brain/network.py +205 -0
  48. package/latticeai/brain/projection.py +561 -0
  49. package/latticeai/brain/provenance.py +401 -0
  50. package/latticeai/brain/retrieval.py +1316 -0
  51. package/latticeai/brain/schema.py +640 -0
  52. package/latticeai/brain/store.py +216 -0
  53. package/latticeai/brain/write_master.py +225 -0
  54. package/latticeai/core/agent.py +31 -7
  55. package/latticeai/core/audit.py +0 -7
  56. package/latticeai/core/config.py +1 -1
  57. package/latticeai/core/context_builder.py +1 -2
  58. package/latticeai/core/enterprise.py +1 -1
  59. package/latticeai/core/graph_curator.py +2 -2
  60. package/latticeai/core/invitations.py +131 -0
  61. package/latticeai/core/marketplace.py +1 -1
  62. package/latticeai/core/mcp_registry.py +791 -0
  63. package/latticeai/core/model_compat.py +1 -1
  64. package/latticeai/core/model_resolution.py +0 -1
  65. package/latticeai/core/multi_agent.py +238 -4
  66. package/latticeai/core/policy.py +54 -0
  67. package/latticeai/core/realtime.py +65 -44
  68. package/latticeai/core/security.py +1 -1
  69. package/latticeai/core/sessions.py +66 -10
  70. package/latticeai/core/users.py +147 -0
  71. package/latticeai/core/workflow_engine.py +114 -2
  72. package/latticeai/core/workspace_os.py +477 -29
  73. package/latticeai/models/__init__.py +7 -0
  74. package/latticeai/models/router.py +779 -0
  75. package/latticeai/server_app.py +29 -1536
  76. package/latticeai/services/agent_runtime.py +243 -4
  77. package/latticeai/services/app_context.py +75 -14
  78. package/latticeai/services/ingestion.py +47 -0
  79. package/latticeai/services/kg_portability.py +33 -3
  80. package/latticeai/services/memory_service.py +39 -11
  81. package/latticeai/services/model_runtime.py +2 -5
  82. package/latticeai/services/platform_runtime.py +100 -23
  83. package/latticeai/services/run_executor.py +328 -0
  84. package/latticeai/services/search_service.py +17 -8
  85. package/latticeai/services/tool_dispatch.py +12 -2
  86. package/latticeai/services/triggers.py +241 -0
  87. package/latticeai/services/upload_service.py +37 -12
  88. package/latticeai/services/workspace_service.py +55 -16
  89. package/llm_router.py +29 -772
  90. package/ltcai_cli.py +1 -2
  91. package/mcp_registry.py +25 -788
  92. package/p_reinforce.py +124 -14
  93. package/package.json +10 -20
  94. package/scripts/bump_version.py +99 -0
  95. package/scripts/generate_diagrams.py +0 -1
  96. package/scripts/lint_v3.mjs +105 -18
  97. package/scripts/validate_release_artifacts.py +0 -1
  98. package/scripts/wheel_smoke.py +142 -0
  99. package/server.py +11 -7
  100. package/setup_wizard.py +1142 -0
  101. package/static/sw.js +81 -52
  102. package/static/v3/asset-manifest.json +33 -25
  103. package/static/v3/css/{lattice.base.e4cdd05d.css → lattice.base.49deefb5.css} +1 -1
  104. package/static/v3/css/lattice.base.css +1 -1
  105. package/static/v3/css/{lattice.components.9b49d614.css → lattice.components.cde18231.css} +1 -1
  106. package/static/v3/css/lattice.components.css +1 -1
  107. package/static/v3/css/{lattice.shell.8fcc9d33.css → lattice.shell.29d36d85.css} +1 -1
  108. package/static/v3/css/lattice.shell.css +1 -1
  109. package/static/v3/css/{lattice.tokens.e7018963.css → lattice.tokens.304cbc40.css} +3 -0
  110. package/static/v3/css/lattice.tokens.css +3 -0
  111. package/static/v3/css/{lattice.views.22f69117.css → lattice.views.0a18b6c5.css} +2 -2
  112. package/static/v3/css/lattice.views.css +2 -2
  113. package/static/v3/index.html +3 -4
  114. package/static/v3/js/{app.c541f955.js → app.c5c80c46.js} +1 -1
  115. package/static/v3/js/core/{api.33d6320e.js → api.ba0fbf14.js} +58 -1
  116. package/static/v3/js/core/api.js +57 -0
  117. package/static/v3/js/core/i18n.880e1fec.js +575 -0
  118. package/static/v3/js/core/i18n.js +575 -0
  119. package/static/v3/js/core/routes.37522821.js +101 -0
  120. package/static/v3/js/core/routes.js +71 -63
  121. package/static/v3/js/core/{shell.8c163e0e.js → shell.e3f6bbfa.js} +68 -39
  122. package/static/v3/js/core/shell.js +66 -37
  123. package/static/v3/js/core/{store.34ebd5e6.js → store.7b2aa044.js} +11 -1
  124. package/static/v3/js/core/store.js +11 -1
  125. package/static/v3/js/views/account.eff40715.js +143 -0
  126. package/static/v3/js/views/account.js +143 -0
  127. package/static/v3/js/views/activity.0d271ef9.js +67 -0
  128. package/static/v3/js/views/activity.js +67 -0
  129. package/static/v3/js/views/{admin-users.03bac88c.js → admin-users.f7ac7b43.js} +4 -6
  130. package/static/v3/js/views/admin-users.js +4 -6
  131. package/static/v3/js/views/{agents.014d0b74.js → agents.17c5288d.js} +35 -12
  132. package/static/v3/js/views/agents.js +35 -12
  133. package/static/v3/js/views/{chat.e6dd7dd0.js → chat.e250e2cc.js} +23 -0
  134. package/static/v3/js/views/chat.js +23 -0
  135. package/static/v3/js/views/graph-canvas.17c15d65.js +509 -0
  136. package/static/v3/js/views/graph-canvas.js +509 -0
  137. package/static/v3/js/views/{hybrid-search.b22b97e0.js → hybrid-search.2fb63ed9.js} +1 -2
  138. package/static/v3/js/views/hybrid-search.js +1 -2
  139. package/static/v3/js/views/{knowledge-graph.a96040a5.js → knowledge-graph.4d09c537.js} +60 -44
  140. package/static/v3/js/views/knowledge-graph.js +60 -44
  141. package/static/v3/js/views/network.52a4f181.js +97 -0
  142. package/static/v3/js/views/network.js +97 -0
  143. package/static/v3/js/views/{planning.9ac3e313.js → planning.4876fd77.js} +26 -5
  144. package/static/v3/js/views/planning.js +26 -5
  145. package/static/v3/js/views/runs.b63b2afa.js +144 -0
  146. package/static/v3/js/views/runs.js +144 -0
  147. package/static/v3/js/views/{settings.8631fa5e.js → settings.b7140634.js} +7 -8
  148. package/static/v3/js/views/settings.js +7 -8
  149. package/static/v3/js/views/snapshots.6f5db095.js +135 -0
  150. package/static/v3/js/views/snapshots.js +135 -0
  151. package/static/v3/js/views/{workflows.26c57290.js → workflows.7752225a.js} +87 -2
  152. package/static/v3/js/views/workflows.js +87 -2
  153. package/static/v3/js/views/workspace-admin.c466029b.js +156 -0
  154. package/static/v3/js/views/workspace-admin.js +156 -0
  155. package/static/vendor/chart.umd.min.js +20 -0
  156. package/static/vendor/fonts/inter-latin-300-normal.woff2 +0 -0
  157. package/static/vendor/fonts/inter-latin-400-normal.woff2 +0 -0
  158. package/static/vendor/fonts/inter-latin-500-normal.woff2 +0 -0
  159. package/static/vendor/fonts/inter-latin-600-normal.woff2 +0 -0
  160. package/static/vendor/fonts/inter-latin-700-normal.woff2 +0 -0
  161. package/static/vendor/fonts/inter-latin-800-normal.woff2 +0 -0
  162. package/static/vendor/fonts/inter.css +44 -0
  163. package/static/vendor/icons/tabler-icons.min.css +4 -0
  164. package/static/vendor/icons/tabler-icons.woff2 +0 -0
  165. package/static/vendor/marked.min.js +69 -0
  166. package/telegram_bot.py +1 -2
  167. package/tools/commands.py +4 -2
  168. package/tools/computer.py +1 -1
  169. package/tools/documents.py +1 -3
  170. package/tools/filesystem.py +0 -4
  171. package/tools/knowledge.py +1 -3
  172. package/tools/network.py +1 -3
  173. package/codex_telegram_bot.py +0 -195
  174. package/docs/assets/v3.4.0/agent-run.png +0 -0
  175. package/docs/assets/v3.4.0/agents.png +0 -0
  176. package/docs/assets/v3.4.0/before/chat-before.png +0 -0
  177. package/docs/assets/v3.4.0/before/files-before.png +0 -0
  178. package/docs/assets/v3.4.0/chat.png +0 -0
  179. package/docs/assets/v3.4.0/connect-folder.png +0 -0
  180. package/docs/assets/v3.4.0/files.png +0 -0
  181. package/docs/assets/v3.4.0/home.png +0 -0
  182. package/docs/assets/v3.4.0/hooks-dispatch.png +0 -0
  183. package/docs/assets/v3.4.0/knowledge-graph.png +0 -0
  184. package/docs/assets/v3.4.0/local-agent.png +0 -0
  185. package/docs/assets/v3.4.0/memory.png +0 -0
  186. package/docs/assets/v3.4.0/settings.png +0 -0
  187. package/docs/assets/v3.4.0/vision-input.png +0 -0
  188. package/docs/assets/v3.4.0/workflows.png +0 -0
  189. package/docs/assets/v3.4.1/e2e_runtime_log.txt +0 -42
  190. package/docs/assets/v3.4.1/hooks-dispatch.png +0 -0
  191. package/docs/assets/v3.4.1/local-agent.png +0 -0
  192. package/docs/images/admin-dashboard.png +0 -0
  193. package/docs/images/architecture.png +0 -0
  194. package/docs/images/enterprise.png +0 -0
  195. package/docs/images/graph.png +0 -0
  196. package/docs/images/hero.gif +0 -0
  197. package/docs/images/knowledge-graph.png +0 -0
  198. package/docs/images/lattice-ai-demo.gif +0 -0
  199. package/docs/images/lattice-ai-hero.png +0 -0
  200. package/docs/images/logo.svg +0 -33
  201. package/docs/images/mobile-responsive.png +0 -0
  202. package/docs/images/model-recommendation.png +0 -0
  203. package/docs/images/onboarding.png +0 -0
  204. package/docs/images/organization.png +0 -0
  205. package/docs/images/pipeline.png +0 -0
  206. package/docs/images/screenshot-admin.png +0 -0
  207. package/docs/images/screenshot-chat.png +0 -0
  208. package/docs/images/screenshot-graph.png +0 -0
  209. package/docs/images/skills.png +0 -0
  210. package/docs/images/workspace-dark.png +0 -0
  211. package/docs/images/workspace-light.png +0 -0
  212. package/docs/images/workspace.png +0 -0
  213. package/requirements.txt +0 -16
  214. package/static/account.html +0 -115
  215. package/static/activity.html +0 -73
  216. package/static/admin.html +0 -488
  217. package/static/agents.html +0 -139
  218. package/static/chat.html +0 -844
  219. package/static/css/reference/account.css +0 -439
  220. package/static/css/reference/admin.css +0 -610
  221. package/static/css/reference/base.css +0 -1661
  222. package/static/css/reference/chat.css +0 -4623
  223. package/static/css/reference/graph.css +0 -1016
  224. package/static/css/responsive.css +0 -861
  225. package/static/graph.html +0 -124
  226. package/static/platform.css +0 -104
  227. package/static/plugins.html +0 -136
  228. package/static/scripts/account.js +0 -238
  229. package/static/scripts/admin.js +0 -1614
  230. package/static/scripts/chat.js +0 -5081
  231. package/static/scripts/graph.js +0 -1804
  232. package/static/scripts/platform.js +0 -64
  233. package/static/scripts/ux.js +0 -167
  234. package/static/scripts/workspace.js +0 -948
  235. package/static/v3/js/core/routes.2ce3815a.js +0 -93
  236. package/static/workflows.html +0 -146
  237. package/static/workspace.css +0 -1121
  238. package/static/workspace.html +0 -357
@@ -0,0 +1,216 @@
1
+ from __future__ import annotations
2
+
3
+ # ruff: noqa: F403,F405
4
+
5
+ from ._kg_common import * # noqa: F403,F401
6
+ from .documents import KnowledgeGraphDocumentsMixin
7
+ from .discovery import KnowledgeGraphDiscoveryMixin
8
+ from .ingest import KnowledgeGraphIngestMixin
9
+ from .projection import KnowledgeGraphProjectionMixin
10
+ from .provenance import KnowledgeGraphProvenanceMixin
11
+ from .retrieval import KnowledgeGraphRetrievalMixin
12
+ from .write_master import KnowledgeGraphWriteMixin
13
+
14
+
15
+ class KnowledgeGraphStore(
16
+ KnowledgeGraphProjectionMixin,
17
+ KnowledgeGraphWriteMixin,
18
+ KnowledgeGraphDiscoveryMixin,
19
+ KnowledgeGraphIngestMixin,
20
+ KnowledgeGraphProvenanceMixin,
21
+ KnowledgeGraphDocumentsMixin,
22
+ KnowledgeGraphRetrievalMixin,
23
+ ):
24
+ def __init__(self, db_path: Path, blob_dir: Path, embedder: Any = None):
25
+ self.db_path = Path(db_path)
26
+ self.blob_dir = Path(blob_dir)
27
+ self.db_path.parent.mkdir(parents=True, exist_ok=True)
28
+ self.blob_dir.mkdir(parents=True, exist_ok=True)
29
+ # The embedder is swappable behind a fixed interface
30
+ # (model_id/dim/embed/encode/decode/similarity). Defaults to the
31
+ # deterministic, offline hash model so the store works with no config;
32
+ # server_app injects a provider-backed embedder from Config.
33
+ self._embedding_model = (
34
+ embedder if embedder is not None else LocalEmbeddingModel()
35
+ )
36
+ self._init_db()
37
+ # Read graph queries from the v2 projection (kgv2_* views) when available.
38
+ # Toggle off (e.g. in tests) to compare against the legacy tables.
39
+ self._read_from_v2 = KGStoreV2 is not None and _READ_FROM_V2_DEFAULT
40
+
41
+ def _read_tables(self) -> tuple:
42
+ """Return (nodes_table, edges_table) for read queries.
43
+
44
+ Same read code runs against the legacy tables or the v2 reconstruction
45
+ views, so the two paths are equivalent by construction.
46
+ """
47
+ if self._read_from_v2:
48
+ return ("kgv2_nodes", "kgv2_edges")
49
+ return ("nodes", "edges")
50
+
51
+ def _connect(self) -> sqlite3.Connection:
52
+ conn = sqlite3.connect(str(self.db_path))
53
+ conn.row_factory = sqlite3.Row
54
+ conn.execute("PRAGMA journal_mode=WAL")
55
+ conn.execute("PRAGMA foreign_keys=ON")
56
+ return conn
57
+
58
+ def _init_db(self) -> None:
59
+ with self._connect() as conn:
60
+ db_format = int(conn.execute("PRAGMA user_version").fetchone()[0] or 0)
61
+ if db_format > _KG_DB_FORMAT_VERSION:
62
+ raise RuntimeError(
63
+ f"Knowledge Graph DB format {db_format} is newer than this build "
64
+ f"({_KG_DB_FORMAT_VERSION}); restore a pre-upgrade backup or upgrade Lattice AI."
65
+ )
66
+ conn.executescript(
67
+ """
68
+ CREATE TABLE IF NOT EXISTS graph_meta (
69
+ key TEXT PRIMARY KEY,
70
+ value TEXT NOT NULL
71
+ );
72
+ CREATE TABLE IF NOT EXISTS nodes (
73
+ id TEXT PRIMARY KEY,
74
+ type TEXT NOT NULL,
75
+ title TEXT NOT NULL,
76
+ summary TEXT,
77
+ metadata_json TEXT NOT NULL CHECK (json_valid(metadata_json)),
78
+ raw_json TEXT NOT NULL CHECK (json_valid(raw_json)),
79
+ created_at TEXT NOT NULL,
80
+ updated_at TEXT NOT NULL
81
+ );
82
+ CREATE TABLE IF NOT EXISTS edges (
83
+ id TEXT PRIMARY KEY,
84
+ from_node TEXT NOT NULL,
85
+ to_node TEXT NOT NULL,
86
+ type TEXT NOT NULL,
87
+ weight REAL NOT NULL DEFAULT 1.0,
88
+ metadata_json TEXT NOT NULL CHECK (json_valid(metadata_json)),
89
+ created_at TEXT NOT NULL,
90
+ UNIQUE(from_node, to_node, type),
91
+ FOREIGN KEY(from_node) REFERENCES nodes(id) ON DELETE CASCADE,
92
+ FOREIGN KEY(to_node) REFERENCES nodes(id) ON DELETE CASCADE
93
+ );
94
+ CREATE TABLE IF NOT EXISTS chunks (
95
+ id TEXT PRIMARY KEY,
96
+ source_node TEXT NOT NULL,
97
+ text TEXT NOT NULL,
98
+ metadata_json TEXT NOT NULL CHECK (json_valid(metadata_json)),
99
+ created_at TEXT NOT NULL,
100
+ FOREIGN KEY(source_node) REFERENCES nodes(id) ON DELETE CASCADE
101
+ );
102
+ CREATE TABLE IF NOT EXISTS knowledge_sources (
103
+ id TEXT PRIMARY KEY,
104
+ root_path TEXT NOT NULL UNIQUE,
105
+ os_type TEXT NOT NULL,
106
+ drive_id TEXT,
107
+ label TEXT,
108
+ status TEXT NOT NULL,
109
+ include_ocr INTEGER NOT NULL DEFAULT 0,
110
+ watch_enabled INTEGER NOT NULL DEFAULT 0,
111
+ consent_json TEXT NOT NULL CHECK (json_valid(consent_json)),
112
+ created_at TEXT NOT NULL,
113
+ updated_at TEXT NOT NULL,
114
+ last_scanned_at TEXT
115
+ );
116
+ CREATE TABLE IF NOT EXISTS local_file_index (
117
+ id TEXT PRIMARY KEY,
118
+ source_id TEXT NOT NULL,
119
+ os_type TEXT NOT NULL,
120
+ drive_id TEXT,
121
+ root_path TEXT NOT NULL,
122
+ file_path TEXT NOT NULL,
123
+ relative_path TEXT NOT NULL,
124
+ file_name TEXT NOT NULL,
125
+ extension TEXT NOT NULL,
126
+ size_bytes INTEGER,
127
+ modified_at TEXT,
128
+ sha256 TEXT,
129
+ last_scanned_at TEXT,
130
+ last_indexed_at TEXT,
131
+ parser_type TEXT,
132
+ status TEXT NOT NULL,
133
+ error_message TEXT,
134
+ graph_node_id TEXT,
135
+ deleted INTEGER NOT NULL DEFAULT 0,
136
+ metadata_json TEXT NOT NULL CHECK (json_valid(metadata_json)),
137
+ UNIQUE(source_id, relative_path),
138
+ FOREIGN KEY(source_id) REFERENCES knowledge_sources(id) ON DELETE CASCADE
139
+ );
140
+ CREATE TABLE IF NOT EXISTS vector_embeddings (
141
+ item_id TEXT PRIMARY KEY,
142
+ item_type TEXT NOT NULL,
143
+ source_node TEXT NOT NULL,
144
+ text_hash TEXT NOT NULL,
145
+ embedding BLOB NOT NULL,
146
+ embedding_dim INTEGER NOT NULL,
147
+ embedding_model TEXT NOT NULL,
148
+ metadata_json TEXT NOT NULL CHECK (json_valid(metadata_json)),
149
+ indexed_at TEXT NOT NULL,
150
+ FOREIGN KEY(source_node) REFERENCES nodes(id) ON DELETE CASCADE
151
+ );
152
+ CREATE TABLE IF NOT EXISTS vector_index_operations (
153
+ id TEXT PRIMARY KEY,
154
+ operation TEXT NOT NULL,
155
+ status TEXT NOT NULL,
156
+ requested_at TEXT NOT NULL,
157
+ started_at TEXT,
158
+ completed_at TEXT,
159
+ items_total INTEGER NOT NULL DEFAULT 0,
160
+ items_indexed INTEGER NOT NULL DEFAULT 0,
161
+ items_skipped INTEGER NOT NULL DEFAULT 0,
162
+ error_message TEXT,
163
+ metadata_json TEXT NOT NULL CHECK (json_valid(metadata_json))
164
+ );
165
+ -- v3.6.0 Knowledge Graph First: per-ingestion provenance trail.
166
+ -- Append-only audit of where every graph node came from, when it
167
+ -- was captured, how it was processed, and whether it was embedded /
168
+ -- linked / used by an agent. get_provenance() returns the latest row.
169
+ CREATE TABLE IF NOT EXISTS ingestion_provenance (
170
+ id TEXT PRIMARY KEY,
171
+ node_id TEXT NOT NULL,
172
+ source_type TEXT NOT NULL,
173
+ source_uri TEXT,
174
+ content_hash TEXT,
175
+ title TEXT,
176
+ pipeline TEXT NOT NULL,
177
+ owner TEXT,
178
+ workspace_id TEXT,
179
+ captured_at TEXT,
180
+ modified_at TEXT,
181
+ embedded INTEGER NOT NULL DEFAULT 0,
182
+ linked INTEGER NOT NULL DEFAULT 0,
183
+ duplicate INTEGER NOT NULL DEFAULT 0,
184
+ agent_used TEXT,
185
+ chunk_count INTEGER NOT NULL DEFAULT 0,
186
+ permissions_json TEXT NOT NULL DEFAULT '{}' CHECK (json_valid(permissions_json)),
187
+ metadata_json TEXT NOT NULL DEFAULT '{}' CHECK (json_valid(metadata_json)),
188
+ created_at TEXT NOT NULL
189
+ );
190
+ CREATE INDEX IF NOT EXISTS idx_nodes_type ON nodes(type);
191
+ CREATE INDEX IF NOT EXISTS idx_edges_from ON edges(from_node);
192
+ CREATE INDEX IF NOT EXISTS idx_edges_to ON edges(to_node);
193
+ CREATE INDEX IF NOT EXISTS idx_chunks_source ON chunks(source_node);
194
+ CREATE INDEX IF NOT EXISTS idx_knowledge_sources_root ON knowledge_sources(root_path);
195
+ CREATE INDEX IF NOT EXISTS idx_local_file_index_source ON local_file_index(source_id);
196
+ CREATE INDEX IF NOT EXISTS idx_local_file_index_status ON local_file_index(status);
197
+ CREATE INDEX IF NOT EXISTS idx_local_file_index_graph_node ON local_file_index(graph_node_id);
198
+ CREATE INDEX IF NOT EXISTS idx_vector_embeddings_type ON vector_embeddings(item_type);
199
+ CREATE INDEX IF NOT EXISTS idx_vector_embeddings_source ON vector_embeddings(source_node);
200
+ CREATE INDEX IF NOT EXISTS idx_vector_embeddings_model ON vector_embeddings(embedding_model);
201
+ CREATE INDEX IF NOT EXISTS idx_vector_index_operations_requested ON vector_index_operations(requested_at);
202
+ CREATE INDEX IF NOT EXISTS idx_provenance_node ON ingestion_provenance(node_id);
203
+ CREATE INDEX IF NOT EXISTS idx_provenance_source_type ON ingestion_provenance(source_type);
204
+ CREATE INDEX IF NOT EXISTS idx_provenance_hash ON ingestion_provenance(content_hash);
205
+ CREATE INDEX IF NOT EXISTS idx_provenance_created ON ingestion_provenance(created_at);
206
+ """
207
+ )
208
+ conn.execute(
209
+ "INSERT OR REPLACE INTO graph_meta(key, value) VALUES (?, ?)",
210
+ ("schema_version", str(GRAPH_SCHEMA_VERSION)),
211
+ )
212
+ self._init_v2_schema()
213
+ self._init_fts()
214
+
215
+
216
+ __all__ = ["KnowledgeGraphStore"]
@@ -0,0 +1,225 @@
1
+ from __future__ import annotations
2
+
3
+ # ruff: noqa: F403,F405
4
+
5
+ from ._kg_common import * # noqa: F403,F401
6
+
7
+
8
+ class KnowledgeGraphWriteMixin:
9
+ def _upsert_node(
10
+ self,
11
+ conn: sqlite3.Connection,
12
+ node_id: str,
13
+ node_type: str,
14
+ title: str,
15
+ summary: str = "",
16
+ metadata: Optional[Dict[str, Any]] = None,
17
+ raw: Optional[Dict[str, Any]] = None,
18
+ owner: Optional[str] = None,
19
+ workspace_id: Optional[str] = None,
20
+ visibility: Optional[str] = None,
21
+ ) -> str:
22
+ now = _now()
23
+ # v4 write-mastering: nodes_v2 is authoritative; the legacy nodes
24
+ # table is maintained as the compatibility projection.
25
+ title_s = title[:240]
26
+ summary_s = summary[:1000]
27
+ meta_json = _json(metadata)
28
+ self._v2_project_node(
29
+ conn,
30
+ node_id,
31
+ node_type,
32
+ title_s,
33
+ summary_s,
34
+ meta_json,
35
+ created_at=now,
36
+ updated_at=now,
37
+ owner=owner,
38
+ workspace_id=workspace_id,
39
+ visibility=visibility,
40
+ strict=True,
41
+ )
42
+ conn.execute(
43
+ """
44
+ INSERT INTO nodes(id, type, title, summary, metadata_json, raw_json, created_at, updated_at)
45
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
46
+ ON CONFLICT(id) DO UPDATE SET
47
+ title=excluded.title,
48
+ summary=excluded.summary,
49
+ metadata_json=excluded.metadata_json,
50
+ raw_json=excluded.raw_json,
51
+ updated_at=excluded.updated_at
52
+ """,
53
+ (node_id, node_type, title_s, summary_s, meta_json, _json(raw), now, now),
54
+ )
55
+ if node_type != "Chunk":
56
+ self._upsert_vector_item(
57
+ conn,
58
+ item_id=node_id,
59
+ item_type="node",
60
+ source_node=node_id,
61
+ text=self._vector_text_for_node(
62
+ title=title_s, summary=summary_s, metadata=metadata
63
+ ),
64
+ metadata={"node_type": node_type, **(metadata or {})},
65
+ )
66
+ return node_id
67
+
68
+ def _upsert_edge(
69
+ self,
70
+ conn: sqlite3.Connection,
71
+ from_node: str,
72
+ to_node: str,
73
+ edge_type: str,
74
+ weight: float = 1.0,
75
+ metadata: Optional[Dict[str, Any]] = None,
76
+ ) -> str:
77
+ # v4 write door: every new edge stores the canonical EdgeType value —
78
+ # free-string types (e.g. '포함함', '언급함') are normalized here, so no
79
+ # caller can mint new legacy taxonomy. The original label survives in
80
+ # metadata.legacy_label for traceability.
81
+ if EdgeType is not None:
82
+ canonical = EdgeType.from_legacy(edge_type).value
83
+ if canonical != edge_type:
84
+ metadata = dict(metadata or {})
85
+ metadata.setdefault("legacy_label", edge_type)
86
+ edge_type = canonical
87
+ edge_id = f"edge:{_sha256_text(f'{from_node}|{edge_type}|{to_node}')[:24]}"
88
+ now = _now()
89
+ meta_json = _json(metadata) # canonical string shared with the projection
90
+ self._v2_project_edge(
91
+ conn,
92
+ from_node,
93
+ to_node,
94
+ edge_type,
95
+ float(weight),
96
+ meta_json,
97
+ edge_id=edge_id,
98
+ created_at=now,
99
+ strict=True,
100
+ )
101
+ conn.execute(
102
+ """
103
+ INSERT INTO edges(id, from_node, to_node, type, weight, metadata_json, created_at)
104
+ VALUES (?, ?, ?, ?, ?, ?, ?)
105
+ ON CONFLICT(from_node, to_node, type) DO UPDATE SET
106
+ weight=max(edges.weight, excluded.weight),
107
+ metadata_json=excluded.metadata_json
108
+ """,
109
+ (edge_id, from_node, to_node, edge_type, float(weight), meta_json, now),
110
+ )
111
+ return edge_id
112
+
113
+ def _vector_text_for_node(
114
+ self,
115
+ *,
116
+ title: str,
117
+ summary: str = "",
118
+ metadata: Optional[Dict[str, Any]] = None,
119
+ ) -> str:
120
+ metadata = metadata or {}
121
+ meta_parts = []
122
+ for key in (
123
+ "filename",
124
+ "relative_path",
125
+ "file_path",
126
+ "conversation_id",
127
+ "source",
128
+ "category",
129
+ "ext",
130
+ "role",
131
+ ):
132
+ value = metadata.get(key)
133
+ if value:
134
+ meta_parts.append(str(value))
135
+ return _clean_text(
136
+ "\n".join([str(title or ""), str(summary or ""), " ".join(meta_parts)])
137
+ )
138
+
139
+ def _upsert_vector_item(
140
+ self,
141
+ conn: sqlite3.Connection,
142
+ *,
143
+ item_id: str,
144
+ item_type: str,
145
+ source_node: str,
146
+ text: str,
147
+ metadata: Optional[Dict[str, Any]] = None,
148
+ ) -> bool:
149
+ text = _clean_text(text)
150
+ if len(text) < 2:
151
+ conn.execute("DELETE FROM vector_embeddings WHERE item_id=?", (item_id,))
152
+ return False
153
+ text_hash = _sha256_text(text)
154
+ existing = conn.execute(
155
+ """
156
+ SELECT text_hash, embedding_dim, embedding_model
157
+ FROM vector_embeddings
158
+ WHERE item_id=?
159
+ """,
160
+ (item_id,),
161
+ ).fetchone()
162
+ if (
163
+ existing
164
+ and existing["text_hash"] == text_hash
165
+ and existing["embedding_dim"] == self._embedding_model.dim
166
+ and existing["embedding_model"] == self._embedding_model.model_id
167
+ ):
168
+ return False
169
+ embedding = self._embedding_model.encode(
170
+ self._embedding_model.embed(text[:50_000])
171
+ )
172
+ conn.execute(
173
+ """
174
+ INSERT INTO vector_embeddings(
175
+ item_id, item_type, source_node, text_hash, embedding,
176
+ embedding_dim, embedding_model, metadata_json, indexed_at
177
+ )
178
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
179
+ ON CONFLICT(item_id) DO UPDATE SET
180
+ item_type=excluded.item_type,
181
+ source_node=excluded.source_node,
182
+ text_hash=excluded.text_hash,
183
+ embedding=excluded.embedding,
184
+ embedding_dim=excluded.embedding_dim,
185
+ embedding_model=excluded.embedding_model,
186
+ metadata_json=excluded.metadata_json,
187
+ indexed_at=excluded.indexed_at
188
+ """,
189
+ (
190
+ item_id,
191
+ item_type,
192
+ source_node,
193
+ text_hash,
194
+ embedding,
195
+ self._embedding_model.dim,
196
+ self._embedding_model.model_id,
197
+ _json(metadata),
198
+ _now(),
199
+ ),
200
+ )
201
+ return True
202
+
203
+ def _upsert_chunk(
204
+ self,
205
+ conn: sqlite3.Connection,
206
+ *,
207
+ chunk_id: str,
208
+ source_node: str,
209
+ text: str,
210
+ metadata: Optional[Dict[str, Any]] = None,
211
+ ) -> None:
212
+ metadata = metadata or {}
213
+ conn.execute(
214
+ "INSERT OR REPLACE INTO chunks(id, source_node, text, metadata_json, created_at) "
215
+ "VALUES (?, ?, ?, ?, ?)",
216
+ (chunk_id, source_node, text, _json(metadata), _now()),
217
+ )
218
+ self._upsert_vector_item(
219
+ conn,
220
+ item_id=chunk_id,
221
+ item_type="chunk",
222
+ source_node=chunk_id,
223
+ text=text,
224
+ metadata={**metadata, "parent_source_node": source_node},
225
+ )
@@ -21,6 +21,7 @@ only owns the state machine.
21
21
  from __future__ import annotations
22
22
 
23
23
  import json
24
+ import logging
24
25
  import re
25
26
  import subprocess
26
27
  from dataclasses import dataclass
@@ -128,6 +129,12 @@ class AgentDeps:
128
129
  # lifecycle, so the agent tool path no longer bypasses hooks.
129
130
  hooks: Any = None
130
131
 
132
+ # ── brain memory port (optional) ─────────────────────────────────
133
+ # When present, completed-run learnings become typed Experience records
134
+ # through the unified ingestion pipeline (with provenance), replacing
135
+ # the vault markdown dump.
136
+ brain_memory: Any = None
137
+
131
138
 
132
139
  class AgentRuntime:
133
140
  """Drives the agent state machine over injected :class:`AgentDeps`."""
@@ -429,13 +436,30 @@ class AgentRuntime:
429
436
  )
430
437
  mem = extract_action(str(raw))
431
438
  if mem.get("save_to_knowledge") and mem.get("learnings"):
432
- d.knowledge_save(
433
- "\n".join(mem["learnings"]),
434
- folder="30_Projects",
435
- title=f"Agent: {req.message[:60]}",
436
- )
437
- except Exception:
438
- pass
439
+ learnings = "\n".join(mem["learnings"])
440
+ if d.brain_memory is not None:
441
+ # This runtime is LLM-driven — its learnings are real
442
+ # experiences and enter the brain with provenance.
443
+ d.brain_memory.record_experience(
444
+ f"Agent: {req.message[:60]}",
445
+ learnings,
446
+ run={
447
+ "mode": "llm",
448
+ "status": "ok",
449
+ "agent_id": "agent:executor",
450
+ "steps": len(ctx.transcript),
451
+ },
452
+ user_email=current_user or None,
453
+ )
454
+ else:
455
+ d.knowledge_save(
456
+ learnings,
457
+ folder="30_Projects",
458
+ title=f"Agent: {req.message[:60]}",
459
+ )
460
+ except Exception as exc:
461
+ # Never crash a completed run, but never swallow silently either.
462
+ logging.warning("agent memory update failed: %s", exc)
439
463
 
440
464
  # ── DRIVE LOOP ───────────────────────────────────────────────────
441
465
  async def run_to_completion(
@@ -5,7 +5,6 @@ import logging
5
5
  import os
6
6
  import re
7
7
  import threading
8
- from datetime import datetime
9
8
  from pathlib import Path
10
9
  from typing import Any, Callable, Dict, List, Optional
11
10
 
@@ -217,12 +216,6 @@ def build_admin_audit_report(
217
216
  u["high_sensitive_events"] += 1
218
217
  sensitive_events.append(_public_audit_event(event))
219
218
 
220
- allowed_keys = {
221
- "event_type", "timestamp", "role", "user_email", "user_nickname", "source",
222
- "conversation_id", "command", "scope", "target_email", "filename", "mime_type",
223
- "ext", "bytes", "extracted_chars", "graph_node", "keep_last", "removed", "kept",
224
- "started_at", "sensitivity", "sensitive_labels", "content_preview", "content_chars",
225
- }
226
219
  recent = [_public_audit_event(e) for e in events[-50:]]
227
220
 
228
221
  result: Dict[str, Any] = {
@@ -19,7 +19,7 @@ concept and are read dynamically at call time.
19
19
  from __future__ import annotations
20
20
 
21
21
  import sys
22
- from dataclasses import dataclass, field
22
+ from dataclasses import dataclass
23
23
  from pathlib import Path
24
24
  from typing import List, Mapping, Optional
25
25
 
@@ -7,9 +7,8 @@ retrieve_context_for_generation() 파이프라인:
7
7
  Step 3: Top-K 결과를 구조화된 Markdown Context로 변환
8
8
  """
9
9
 
10
- import logging
11
10
  import re
12
- from typing import Any, Dict, List, Optional
11
+ from typing import Any, Dict, List
13
12
 
14
13
  _CLEAN_RE = re.compile(r"\s+")
15
14
 
@@ -22,7 +22,7 @@ from __future__ import annotations
22
22
 
23
23
  import os
24
24
  from enum import Enum
25
- from typing import Dict, List, Optional, Protocol, runtime_checkable
25
+ from typing import Dict, List, Protocol, runtime_checkable
26
26
 
27
27
 
28
28
  class Edition(str, Enum):
@@ -20,8 +20,8 @@ import logging
20
20
  import math
21
21
  import re
22
22
  import time
23
- from dataclasses import dataclass, field, asdict
24
- from typing import Any, Dict, Iterable, List, Optional, Sequence, Set, Tuple
23
+ from dataclasses import dataclass, field
24
+ from typing import Any, Dict, Iterable, List, Optional, Sequence, Set
25
25
 
26
26
  logger = logging.getLogger(__name__)
27
27