ltcai 11.1.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 (289) hide show
  1. package/README.md +47 -54
  2. package/docs/CHANGELOG.md +94 -0
  3. package/docs/COMMUNITY_AND_PLUGINS.md +1 -1
  4. package/docs/DEVELOPMENT.md +1 -1
  5. package/docs/FEATURE_AUDIT_v11.2.0.md +393 -0
  6. package/docs/LAYOUT_REBUILD_SPEC.md +9 -1
  7. package/docs/MULTI_AGENT_RUNTIME.md +1 -1
  8. package/docs/ONBOARDING.md +1 -1
  9. package/docs/OPERATIONS.md +6 -2
  10. package/docs/PERMISSION_MODE.md +1 -1
  11. package/docs/TRUST_MODEL.md +1 -1
  12. package/docs/WHY_LATTICE.md +1 -1
  13. package/docs/architecture.md +6 -2
  14. package/docs/kg-schema.md +2 -2
  15. package/docs/v11.3.0_PLAN.md +202 -0
  16. package/docs/v11.4.0_RUST_FOUNDATION_PLAN.md +176 -0
  17. package/lattice_brain/__init__.py +1 -1
  18. package/lattice_brain/gates.py +125 -0
  19. package/lattice_brain/graph/_kg_common/__init__.py +287 -0
  20. package/lattice_brain/graph/_kg_common/extraction.py +516 -0
  21. package/lattice_brain/graph/_kg_common/relations.py +161 -0
  22. package/lattice_brain/graph/_kg_common/text.py +479 -0
  23. package/lattice_brain/graph/discovery_index/__init__.py +35 -0
  24. package/lattice_brain/graph/discovery_index/cleanup.py +182 -0
  25. package/lattice_brain/graph/discovery_index/extract.py +137 -0
  26. package/lattice_brain/graph/discovery_index/scan.py +411 -0
  27. package/lattice_brain/graph/discovery_index/upsert.py +495 -0
  28. package/lattice_brain/graph/fusion.py +35 -4
  29. package/lattice_brain/graph/projection/__init__.py +42 -0
  30. package/lattice_brain/graph/projection/curation.py +500 -0
  31. package/lattice_brain/graph/{projection.py → projection/v2_schema.py} +81 -485
  32. package/lattice_brain/graph/retrieval/__init__.py +54 -0
  33. package/lattice_brain/graph/retrieval/context.py +197 -0
  34. package/lattice_brain/graph/retrieval/graph_view.py +319 -0
  35. package/lattice_brain/graph/retrieval/hybrid.py +488 -0
  36. package/lattice_brain/graph/retrieval/maintenance.py +121 -0
  37. package/lattice_brain/graph/retrieval/signals.py +95 -0
  38. package/lattice_brain/graph/retrieval_vector/__init__.py +42 -0
  39. package/lattice_brain/graph/retrieval_vector/fingerprint.py +97 -0
  40. package/lattice_brain/graph/retrieval_vector/indexing.py +347 -0
  41. package/lattice_brain/graph/retrieval_vector/search.py +560 -0
  42. package/lattice_brain/graph/retrieval_vector/status.py +374 -0
  43. package/lattice_brain/graph/schema.py +9 -0
  44. package/lattice_brain/graph/store.py +9 -0
  45. package/lattice_brain/graph/vector_index/selector.py +32 -2
  46. package/lattice_brain/ingestion/__init__.py +130 -0
  47. package/lattice_brain/ingestion/_contract.py +90 -0
  48. package/lattice_brain/ingestion/constants.py +127 -0
  49. package/lattice_brain/ingestion/folder_scan.py +57 -0
  50. package/lattice_brain/ingestion/folders.py +258 -0
  51. package/lattice_brain/ingestion/hashing.py +26 -0
  52. package/lattice_brain/ingestion/jobs_api.py +107 -0
  53. package/lattice_brain/ingestion/models.py +80 -0
  54. package/lattice_brain/ingestion/pipeline.py +486 -0
  55. package/lattice_brain/ingestion/quality.py +209 -0
  56. package/lattice_brain/ingestion/routing.py +295 -0
  57. package/lattice_brain/multimodal/__init__.py +164 -0
  58. package/lattice_brain/multimodal/audio.py +77 -0
  59. package/lattice_brain/multimodal/common.py +118 -0
  60. package/lattice_brain/{multimodal.py → multimodal/images.py} +22 -262
  61. package/lattice_brain/multimodal/ports.py +169 -0
  62. package/lattice_brain/multimodal/video.py +410 -0
  63. package/lattice_brain/portability/__init__.py +90 -0
  64. package/lattice_brain/portability/_contract.py +42 -0
  65. package/lattice_brain/portability/backups.py +338 -0
  66. package/lattice_brain/portability/bundles.py +136 -0
  67. package/lattice_brain/portability/constants.py +93 -0
  68. package/lattice_brain/portability/fsops.py +138 -0
  69. package/lattice_brain/portability/service.py +41 -0
  70. package/lattice_brain/portability/sharing.py +714 -0
  71. package/lattice_brain/runtime/__init__.py +1 -1
  72. package/lattice_brain/runtime/multi_agent.py +1 -1
  73. package/lattice_brain/sealed_box.py +244 -0
  74. package/lattice_brain/synthesis.py +24 -1
  75. package/latticeai/__init__.py +1 -1
  76. package/latticeai/api/brain_intelligence.py +4 -0
  77. package/latticeai/api/chat.py +11 -0
  78. package/latticeai/api/chat_helpers.py +16 -3
  79. package/latticeai/api/chat_hybrid.py +32 -1
  80. package/latticeai/api/chronicle.py +63 -0
  81. package/latticeai/api/features.py +70 -0
  82. package/latticeai/api/local_files.py +102 -0
  83. package/latticeai/api/portability.py +39 -4
  84. package/latticeai/api/review_queue.py +126 -0
  85. package/latticeai/api/search.py +16 -2
  86. package/latticeai/core/agent/__init__.py +93 -0
  87. package/latticeai/core/agent/_contract.py +79 -0
  88. package/latticeai/core/agent/context.py +57 -0
  89. package/latticeai/core/agent/deps.py +125 -0
  90. package/latticeai/core/agent/execution.py +622 -0
  91. package/latticeai/core/agent/planning.py +145 -0
  92. package/latticeai/core/agent/recovery.py +157 -0
  93. package/latticeai/core/agent/runtime.py +210 -0
  94. package/latticeai/core/agent/verification.py +231 -0
  95. package/latticeai/core/config.py +4 -1
  96. package/latticeai/core/context_builder.py +6 -3
  97. package/latticeai/core/embedding_providers/__init__.py +151 -0
  98. package/latticeai/core/embedding_providers/base.py +199 -0
  99. package/latticeai/core/embedding_providers/captions.py +162 -0
  100. package/latticeai/core/embedding_providers/profiles.py +126 -0
  101. package/latticeai/core/embedding_providers/text.py +350 -0
  102. package/latticeai/core/embedding_providers/vision.py +352 -0
  103. package/latticeai/core/file_generation/__init__.py +115 -0
  104. package/latticeai/core/file_generation/bundles.py +76 -0
  105. package/latticeai/core/file_generation/extraction.py +154 -0
  106. package/latticeai/core/file_generation/inference.py +235 -0
  107. package/latticeai/core/file_generation/orchestration.py +152 -0
  108. package/latticeai/core/file_generation/prompting.py +117 -0
  109. package/latticeai/core/file_generation/repair.py +114 -0
  110. package/latticeai/core/file_generation/sanitize.py +61 -0
  111. package/latticeai/core/file_generation/validation.py +201 -0
  112. package/latticeai/core/legacy_compatibility.py +1 -1
  113. package/latticeai/core/marketplace.py +1 -1
  114. package/latticeai/core/messages.py +152 -0
  115. package/latticeai/core/model_compat.py +73 -2
  116. package/latticeai/core/workspace_os_constants.py +1 -1
  117. package/latticeai/integrations/telegram_bot/__init__.py +123 -0
  118. package/latticeai/integrations/telegram_bot/__main__.py +17 -0
  119. package/latticeai/integrations/telegram_bot/config.py +86 -0
  120. package/latticeai/integrations/telegram_bot/dispatch.py +311 -0
  121. package/latticeai/integrations/telegram_bot/flows.py +478 -0
  122. package/latticeai/integrations/telegram_bot/helpers.py +322 -0
  123. package/latticeai/integrations/telegram_bot/screens.py +394 -0
  124. package/latticeai/models/model_providers.py +12 -4
  125. package/latticeai/models/router/__init__.py +88 -0
  126. package/latticeai/models/router/_contract.py +66 -0
  127. package/latticeai/models/router/branding.py +56 -0
  128. package/latticeai/models/router/catalog.py +69 -0
  129. package/latticeai/models/router/documents.py +199 -0
  130. package/latticeai/models/router/errors.py +37 -0
  131. package/latticeai/models/router/generation.py +258 -0
  132. package/latticeai/models/router/loading.py +291 -0
  133. package/latticeai/models/router/local_models.py +85 -0
  134. package/latticeai/models/router/registry.py +147 -0
  135. package/latticeai/runtime/build_phases/__init__.py +82 -0
  136. package/latticeai/runtime/build_phases/features.py +407 -0
  137. package/latticeai/runtime/build_phases/foundation.py +555 -0
  138. package/latticeai/runtime/build_phases/web.py +492 -0
  139. package/latticeai/runtime/chat_wiring.py +4 -0
  140. package/latticeai/runtime/feature_toggle_wiring.py +163 -0
  141. package/latticeai/runtime/router_registration.py +11 -0
  142. package/latticeai/runtime/runtime_context.py +1 -0
  143. package/latticeai/services/app_context.py +8 -0
  144. package/latticeai/services/architecture_readiness.py +48 -19
  145. package/latticeai/services/automation_intelligence.py +22 -2
  146. package/latticeai/services/brain_intelligence/__init__.py +58 -0
  147. package/latticeai/services/brain_intelligence/_contract.py +71 -0
  148. package/latticeai/services/brain_intelligence/consistency.py +193 -0
  149. package/latticeai/services/brain_intelligence/constants.py +47 -0
  150. package/latticeai/services/brain_intelligence/digest.py +258 -0
  151. package/latticeai/services/brain_intelligence/health.py +331 -0
  152. package/latticeai/services/brain_intelligence/proposals.py +264 -0
  153. package/latticeai/services/brain_intelligence/sampling.py +84 -0
  154. package/latticeai/services/brain_intelligence/service.py +48 -0
  155. package/latticeai/services/chronicle.py +557 -0
  156. package/latticeai/services/command_center.py +10 -4
  157. package/latticeai/services/feature_toggles.py +502 -0
  158. package/latticeai/services/folder_watch.py +122 -1
  159. package/latticeai/services/hybrid_chat.py +56 -5
  160. package/latticeai/services/interop_bridges.py +978 -0
  161. package/latticeai/services/memory_service/__init__.py +52 -0
  162. package/latticeai/services/memory_service/_contract.py +100 -0
  163. package/latticeai/services/memory_service/brief.py +431 -0
  164. package/latticeai/services/memory_service/constants.py +57 -0
  165. package/latticeai/services/memory_service/maintenance.py +138 -0
  166. package/latticeai/services/memory_service/manager.py +186 -0
  167. package/latticeai/services/memory_service/proof.py +136 -0
  168. package/latticeai/services/memory_service/recall.py +225 -0
  169. package/latticeai/services/memory_service/service.py +48 -0
  170. package/latticeai/services/memory_service/stores.py +110 -0
  171. package/latticeai/services/model_capability_registry.py +434 -261
  172. package/latticeai/services/model_catalog.py +95 -61
  173. package/latticeai/services/model_recommendation.py +18 -11
  174. package/latticeai/services/model_runtime/__init__.py +322 -0
  175. package/latticeai/services/model_runtime/cloud.py +87 -0
  176. package/latticeai/services/model_runtime/download.py +282 -0
  177. package/latticeai/services/model_runtime/engines.py +341 -0
  178. package/latticeai/services/model_runtime/loading.py +178 -0
  179. package/latticeai/services/model_runtime/service.py +129 -0
  180. package/latticeai/services/model_runtime/state.py +131 -0
  181. package/latticeai/services/model_runtime/status.py +255 -0
  182. package/latticeai/services/multimodal_ports.py +26 -1
  183. package/latticeai/services/obsidian_bridge.py +16 -25
  184. package/latticeai/services/product_readiness.py +15 -7
  185. package/latticeai/services/search_service.py +149 -2
  186. package/latticeai/services/tool_dispatch.py +4 -0
  187. package/latticeai/setup/auto_setup.py +27 -30
  188. package/latticeai/setup/wizard/__init__.py +126 -0
  189. package/latticeai/setup/wizard/catalog.py +172 -0
  190. package/latticeai/setup/wizard/detect.py +323 -0
  191. package/latticeai/setup/wizard/install.py +348 -0
  192. package/latticeai/setup/wizard/paths.py +168 -0
  193. package/latticeai/setup/wizard/plans.py +74 -0
  194. package/latticeai/setup/wizard/recommend.py +320 -0
  195. package/package.json +6 -2
  196. package/scripts/bump_version.py +14 -0
  197. package/scripts/capture_release_evidence.mjs +33 -21
  198. package/scripts/check_current_release_docs.mjs +1 -1
  199. package/scripts/check_i18n_namespace_coverage.mjs +41 -4
  200. package/scripts/check_max_file_lines.mjs +102 -0
  201. package/scripts/check_release_evidence_bound.mjs +30 -15
  202. package/scripts/check_screenshot_pixel_delta.py +34 -4
  203. package/scripts/check_server_i18n.mjs +2 -0
  204. package/scripts/generate_rust_parity_fixtures.py +562 -0
  205. package/scripts/lib/mock_server_fingerprint.mjs +94 -0
  206. package/scripts/release_screen_claims.json +44 -2
  207. package/scripts/verify_hf_model_registry.py +253 -218
  208. package/src-tauri/Cargo.lock +361 -3
  209. package/src-tauri/Cargo.toml +6 -1
  210. package/src-tauri/src/backend.rs +349 -0
  211. package/src-tauri/src/folder.rs +33 -0
  212. package/src-tauri/src/main.rs +97 -399
  213. package/src-tauri/tauri.conf.json +1 -1
  214. package/static/app/asset-manifest.json +41 -37
  215. package/static/app/assets/Act-yYpYnn0v.js +1 -0
  216. package/static/app/assets/AdminConsole-DL3Cr5pL.js +1 -0
  217. package/static/app/assets/{Brain-CzCsI1mi.js → Brain-C1HBN0Wf.js} +2 -2
  218. package/static/app/assets/BrainHome-DoXRhUUC.js +2 -0
  219. package/static/app/assets/BrainSignals-6yR6ir5t.js +1 -0
  220. package/static/app/assets/Capture-CFIRsFNE.js +1 -0
  221. package/static/app/assets/Chronicle-BZbEgiwN.js +1 -0
  222. package/static/app/assets/CommandPalette-D2pMxC2I.js +1 -0
  223. package/static/app/assets/Library-DwO3yZST.js +1 -0
  224. package/static/app/assets/{LivingBrain-BXMWIK_2.js → LivingBrain-Jn1GK0-S.js} +1 -1
  225. package/static/app/assets/ProductFlow-B-w1R4Oo.js +1 -0
  226. package/static/app/assets/ReviewCard-6B27X8Vg.js +3 -0
  227. package/static/app/assets/System-DW8F-2xL.js +1 -0
  228. package/static/app/assets/arrow-left-DXvKg9U6.js +1 -0
  229. package/static/app/assets/{bot-4BvN07ux.js → bot-IM_E_Y12.js} +1 -1
  230. package/static/app/assets/brain-Ci1CkWjM.js +1 -0
  231. package/static/app/assets/{button-CDjtnAoU.js → button-COwyqfHM.js} +1 -1
  232. package/static/app/assets/circle-check-DfInj-qD.js +1 -0
  233. package/static/app/assets/{circle-pause-D_RMn7tp.js → circle-pause-DEM4A1Y5.js} +1 -1
  234. package/static/app/assets/{circle-play-B5OpB8ae.js → circle-play-C9djDuLd.js} +1 -1
  235. package/static/app/assets/{cpu-BIlWInHf.js → cpu-DFdo1gw-.js} +1 -1
  236. package/static/app/assets/{download-BtjXfL3z.js → download-SnJL6oqk.js} +1 -1
  237. package/static/app/assets/{folder-open-DefMpxI2.js → folder-open-CqZeDkjE.js} +1 -1
  238. package/static/app/assets/{hard-drive-BQ8NZVkw.js → hard-drive-j1jJXYYf.js} +1 -1
  239. package/static/app/assets/{index-vtEfYvQY.css → index-BLPb5lmE.css} +1 -1
  240. package/static/app/assets/index-_u5iUHDr.js +10 -0
  241. package/static/app/assets/input-B0lPdRQZ.js +1 -0
  242. package/static/app/assets/link-2-CoFbooHS.js +1 -0
  243. package/static/app/assets/{permissionCopy-BqZ5tsgL.js → permissionCopy-BsyLxtao.js} +1 -1
  244. package/static/app/assets/primitives-DEbN-d6p.js +1 -0
  245. package/static/app/assets/search-BybIWPNd.js +1 -0
  246. package/static/app/assets/{share-2-D5zg_0fY.js → share-2-CVtZ_ewX.js} +1 -1
  247. package/static/app/assets/{shield-alert-B5pZzkUb.js → shield-alert-CBi2GNWM.js} +1 -1
  248. package/static/app/assets/{textarea-nEVIweKY.js → textarea-DNMpB5ih.js} +1 -1
  249. package/static/app/assets/{useFocusTrap-Cm99AHlz.js → useFocusTrap-C83t3GXF.js} +1 -1
  250. package/static/app/assets/useMutation-DtbJDoyz.js +1 -0
  251. package/static/app/assets/{useQuery-Dm__N6bL.js → useQuery-Dcp1OChy.js} +1 -1
  252. package/static/app/assets/utils-BlZr7Pd4.js +4 -0
  253. package/static/app/assets/workspace-jJY4RuAV.js +1 -0
  254. package/static/app/index.html +4 -4
  255. package/static/sw.js +1 -1
  256. package/lattice_brain/graph/_kg_common.py +0 -1331
  257. package/lattice_brain/graph/discovery_index.py +0 -1141
  258. package/lattice_brain/graph/retrieval.py +0 -1120
  259. package/lattice_brain/graph/retrieval_vector.py +0 -1293
  260. package/lattice_brain/ingestion.py +0 -1377
  261. package/lattice_brain/portability.py +0 -1210
  262. package/latticeai/core/agent.py +0 -1412
  263. package/latticeai/core/embedding_providers.py +0 -1196
  264. package/latticeai/core/file_generation.py +0 -1047
  265. package/latticeai/integrations/telegram_bot.py +0 -1390
  266. package/latticeai/models/router.py +0 -1007
  267. package/latticeai/runtime/build_phases.py +0 -1422
  268. package/latticeai/services/brain_intelligence.py +0 -967
  269. package/latticeai/services/memory_service.py +0 -1177
  270. package/latticeai/services/model_runtime.py +0 -1281
  271. package/latticeai/setup/wizard.py +0 -1277
  272. package/static/app/assets/Act-D0HWqtn0.js +0 -1
  273. package/static/app/assets/AdminConsole-D-QDW-A4.js +0 -1
  274. package/static/app/assets/BrainHome-Btns-_TA.js +0 -2
  275. package/static/app/assets/BrainSignals-2dHQNkns.js +0 -1
  276. package/static/app/assets/Capture-CT8v1StE.js +0 -1
  277. package/static/app/assets/CommandPalette-DoLXC2KH.js +0 -1
  278. package/static/app/assets/Library-DDoxFE5c.js +0 -1
  279. package/static/app/assets/ProductFlow-DOYf7JIs.js +0 -1
  280. package/static/app/assets/ReviewCard-COQsqidK.js +0 -3
  281. package/static/app/assets/System-BRllvYXd.js +0 -1
  282. package/static/app/assets/arrow-left-DnyMzss-.js +0 -1
  283. package/static/app/assets/brain-uMb_5hnO.js +0 -1
  284. package/static/app/assets/index-0AvoEBzJ.js +0 -10
  285. package/static/app/assets/input-B_5ZJ9oy.js +0 -1
  286. package/static/app/assets/primitives-CVwew78r.js +0 -1
  287. package/static/app/assets/search-DkhnOKZt.js +0 -1
  288. package/static/app/assets/utils-DcDMoZIe.js +0 -4
  289. package/static/app/assets/workspace-LtRRSKTf.js +0 -1
@@ -0,0 +1,714 @@
1
+ """Logical export/import, and the opt-in Brain Network subgraph share.
2
+
3
+ The half of :class:`~lattice_brain.portability.KGPortabilityService` that moves
4
+ *knowledge* rather than *files*: a whole-graph JSON artifact, and — behind the
5
+ ``LATTICEAI_BRAIN_NETWORK`` opt-in — a signed, encrypted slice of the graph that
6
+ arrives at the far end as review proposals, never as a merge.
7
+
8
+ The receiving X25519 key is loaded here (``load_recipient_identity``), so a test
9
+ standing in for it patches *this* module rather than the package.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import base64
15
+ import json
16
+ import os
17
+ from pathlib import Path
18
+ from typing import Any, Dict, Iterable, List, Optional
19
+
20
+ from cryptography.exceptions import InvalidTag
21
+ from cryptography.hazmat.primitives.ciphers.aead import AESGCM
22
+
23
+ from ..archive import KDF_ITERATIONS, _derive_key
24
+ from ..quiet import quiet
25
+ from ..sealed_box import (
26
+ SEALED_BOX_ALGORITHM,
27
+ load_recipient_identity,
28
+ public_key_fingerprint,
29
+ seal,
30
+ )
31
+ from ..utils import utc_now_iso
32
+ from ._contract import PortabilityCore as _Core
33
+ from .bundles import (
34
+ _canonical_digest,
35
+ _expand_neighbors,
36
+ _redact_node,
37
+ _redact_provenance_row,
38
+ _scope_node,
39
+ _select_node_ids,
40
+ _shared_node_summary,
41
+ )
42
+ from .constants import (
43
+ _OPEN_REVIEW_STATUSES,
44
+ _PAYLOAD_KEYS,
45
+ _REDACTED_FIELDS,
46
+ BRAIN_NETWORK_DISABLED_DETAIL,
47
+ BRAIN_NETWORK_ENV,
48
+ BRAIN_NETWORK_GATE,
49
+ ENCRYPTION_MODES,
50
+ FORMAT,
51
+ FORMAT_VERSION,
52
+ SUBGRAPH_ARCHIVE_FORMAT,
53
+ SUBGRAPH_FORMAT,
54
+ SUBGRAPH_FORMAT_VERSION,
55
+ SUBGRAPH_PROPOSAL_CAP,
56
+ SUBGRAPH_REVIEW_KIND,
57
+ SUBGRAPH_REVIEW_SOURCE,
58
+ _stamp,
59
+ brain_network_enabled,
60
+ require_brain_network,
61
+ )
62
+
63
+
64
+ class KGPortabilitySharingMixin(_Core):
65
+ """Export / import / share. Mixed into ``KGPortabilityService``."""
66
+
67
+ def _recipient_identity(self) -> Any:
68
+ """This Brain's X25519 receiving key, created on first use.
69
+
70
+ ``None`` when the data directory cannot hold one — reported as a state
71
+ by :meth:`recipient_key`, never raised into a status read.
72
+ """
73
+ if not self._recipient_loaded:
74
+ self._recipient = load_recipient_identity(self._data_dir)
75
+ self._recipient_loaded = True
76
+ return self._recipient
77
+
78
+ def recipient_key(self) -> Dict[str, Any]:
79
+ """The public half to hand a sender, so they can seal a bundle to us.
80
+
81
+ Publishing this is safe by construction: a public key encrypts, it does
82
+ not decrypt, and it says nothing about what this Brain contains.
83
+ """
84
+ require_brain_network()
85
+ identity = self._recipient_identity()
86
+ if identity is None:
87
+ return {
88
+ "available": False,
89
+ "detail": (
90
+ "a receiving key could not be created in the data directory; "
91
+ "sealed bundles cannot be opened on this machine"
92
+ ),
93
+ }
94
+ return {"available": True, **identity.describe()}
95
+
96
+ # ── logical export / import ──────────────────────────────────────────────
97
+ def export(
98
+ self,
99
+ *,
100
+ workspace_id: Optional[str] = None,
101
+ include_legacy_global: bool = False,
102
+ ) -> Dict[str, Any]:
103
+ self._require()
104
+ data = self._kg.export_graph_data(
105
+ workspace_id=workspace_id,
106
+ include_legacy_global=include_legacy_global,
107
+ )
108
+ header = {
109
+ "format": FORMAT,
110
+ "format_version": FORMAT_VERSION,
111
+ **self._kg.schema_versions(),
112
+ "exported_at": utc_now_iso(),
113
+ "workspace_id": workspace_id,
114
+ "include_legacy_global": bool(include_legacy_global),
115
+ "counts": data.get("counts"),
116
+ }
117
+ artifact = {"header": header, **data}
118
+ if self._identity is not None:
119
+ artifact["signature"] = self._identity.sign_manifest(header)
120
+ return artifact
121
+
122
+ def export_to_file(
123
+ self,
124
+ path=None,
125
+ *,
126
+ workspace_id: Optional[str] = None,
127
+ include_legacy_global: bool = False,
128
+ ) -> Dict[str, Any]:
129
+ artifact = self.export(
130
+ workspace_id=workspace_id,
131
+ include_legacy_global=include_legacy_global,
132
+ )
133
+ self._exports_dir.mkdir(parents=True, exist_ok=True)
134
+ path = Path(path) if path else self._exports_dir / f"kg-export-{_stamp()}.json"
135
+ path.write_text(json.dumps(artifact, ensure_ascii=False, indent=2), encoding="utf-8")
136
+ return {"path": str(path), "header": artifact["header"], "bytes": path.stat().st_size}
137
+
138
+ def import_data(self, artifact: Dict[str, Any], *, mode: str = "merge", dry_run: bool = False) -> Dict[str, Any]:
139
+ self._require()
140
+ if not isinstance(artifact, dict) or "nodes" not in artifact:
141
+ raise ValueError("Invalid Knowledge Graph export artifact.")
142
+ if mode not in ("merge", "replace"):
143
+ raise ValueError("mode must be 'merge' or 'replace'.")
144
+ origin = "unsigned-legacy"
145
+ signature = artifact.get("signature")
146
+ if signature:
147
+ from ..graph.identity import verify_manifest
148
+
149
+ if not verify_manifest(artifact.get("header") or {}, signature):
150
+ raise ValueError("Bundle signature verification failed — refusing to import.")
151
+ origin = f"device:{signature.get('fingerprint') or 'unknown'}"
152
+ result = self._kg.import_graph_data(artifact, mode=mode, dry_run=dry_run)
153
+ result["header"] = artifact.get("header")
154
+ result["origin"] = origin
155
+ result["signed"] = bool(signature)
156
+ if not dry_run:
157
+ try:
158
+ self._kg.record_provenance(
159
+ node_id="import:" + str((artifact.get("header") or {}).get("exported_at") or utc_now_iso()),
160
+ source_type="bundle_import",
161
+ pipeline="kg-portability",
162
+ owner=None,
163
+ metadata={"origin": origin, "mode": mode,
164
+ "counts": (artifact.get("header") or {}).get("counts")},
165
+ )
166
+ except Exception:
167
+ quiet()
168
+ return result
169
+
170
+ def import_from_file(self, path, *, mode: str = "merge", dry_run: bool = False) -> Dict[str, Any]:
171
+ artifact = json.loads(Path(path).read_text(encoding="utf-8"))
172
+ return self.import_data(artifact, mode=mode, dry_run=dry_run)
173
+
174
+ # ── selective subgraph share (opt-in prototype, off by default) ──────────
175
+ def share_status(self) -> Dict[str, Any]:
176
+ """Honest read of the share surface. Safe to call while it is off.
177
+
178
+ A status route that refuses while disabled cannot tell a UI *why* the
179
+ feature is missing, so this one always answers — with ``enabled:
180
+ false`` and the flag that turns it on.
181
+ """
182
+ enabled = brain_network_enabled()
183
+ return {
184
+ "enabled": enabled,
185
+ "flag": BRAIN_NETWORK_ENV,
186
+ "format": SUBGRAPH_FORMAT,
187
+ "format_version": SUBGRAPH_FORMAT_VERSION,
188
+ "graph_available": self.available(),
189
+ "signing": self._identity is not None,
190
+ "device": self._share_device(),
191
+ "proposal_cap": SUBGRAPH_PROPOSAL_CAP,
192
+ # Stated rather than implied: a bundle is always signed by this
193
+ # device, and encrypted either with a shared passphrase or — since
194
+ # 11.2.0 — to the recipient's own public key, so nothing secret has
195
+ # to travel ahead of it.
196
+ "encryption": list(ENCRYPTION_MODES),
197
+ "recipient_public_key_encryption": True,
198
+ "sealed_box_algorithm": SEALED_BOX_ALGORITHM,
199
+ "gate": BRAIN_NETWORK_GATE.describe(),
200
+ "detail": None if enabled else BRAIN_NETWORK_DISABLED_DETAIL,
201
+ }
202
+
203
+ def _share_device(self) -> Dict[str, Any]:
204
+ """Signer identity for a bundle — key material only, no storage hints."""
205
+ if self._identity is None:
206
+ return {}
207
+ described = self._identity.describe()
208
+ return {
209
+ "fingerprint": described.get("fingerprint"),
210
+ "public_key": described.get("public_key"),
211
+ "algorithm": described.get("algorithm"),
212
+ }
213
+
214
+ def export_subgraph(
215
+ self,
216
+ *,
217
+ node_ids: Optional[Iterable[str]] = None,
218
+ node_types: Optional[Iterable[str]] = None,
219
+ source_types: Optional[Iterable[str]] = None,
220
+ workspace_id: Optional[str] = None,
221
+ include_legacy_global: bool = False,
222
+ include_neighbors: bool = False,
223
+ redact_provenance: bool = True,
224
+ ) -> Dict[str, Any]:
225
+ """A chosen slice of the graph, with provenance, signed by this device.
226
+
227
+ At least one selector is required. "Share everything" already exists as
228
+ :meth:`export`; a *selective* door that silently defaults to the whole
229
+ Brain is how an accident becomes a leak.
230
+
231
+ ``include_neighbors`` widens the selection by one hop (both directions)
232
+ so "share this decision" can carry the decision's immediate relations.
233
+ ``redact_provenance`` (default on) strips the sender's local identity —
234
+ owner, source URI, permissions — from both node metadata and the
235
+ provenance rows, and records that it did so in the header.
236
+
237
+ Knowledge-source rows (connected folder registrations, with their local
238
+ paths) are never included; they describe the sender's machine, not the
239
+ knowledge.
240
+ """
241
+ require_brain_network()
242
+ self._require()
243
+ if self._identity is None:
244
+ raise RuntimeError(
245
+ "A device identity is required to share a subgraph; "
246
+ "an unsigned bundle cannot be attributed and would be refused."
247
+ )
248
+ wanted_ids = sorted({str(v) for v in (node_ids or []) if str(v).strip()})
249
+ wanted_types = sorted({str(v).strip().lower() for v in (node_types or []) if str(v).strip()})
250
+ wanted_sources = sorted({str(v).strip().lower() for v in (source_types or []) if str(v).strip()})
251
+ selection: Dict[str, Any] = {
252
+ "node_ids": wanted_ids,
253
+ "node_types": wanted_types,
254
+ "source_types": wanted_sources,
255
+ "include_neighbors": bool(include_neighbors),
256
+ "workspace_id": workspace_id,
257
+ }
258
+ if not (wanted_ids or wanted_types or wanted_sources):
259
+ raise ValueError(
260
+ "A subgraph share must name what to share "
261
+ "(node_ids, node_types, or source_types)."
262
+ )
263
+ data = self._kg.export_graph_data(
264
+ workspace_id=workspace_id, include_legacy_global=include_legacy_global,
265
+ )
266
+ all_nodes = data.get("nodes") or []
267
+ # Chunks are derived retrieval units, not shareable subjects: they are
268
+ # never selectable, but they travel with the node they belong to so the
269
+ # receiver can actually search the shared content rather than a summary.
270
+ nodes = [n for n in all_nodes if str(n.get("type")) != "Chunk"]
271
+ chunk_nodes_by_id = {
272
+ str(n.get("id")): n for n in all_nodes if str(n.get("type")) == "Chunk"
273
+ }
274
+ edges = list(data.get("edges") or [])
275
+ keep = _select_node_ids(nodes, selection)
276
+ present = {str(n.get("id")): str(n.get("type") or "") for n in nodes}
277
+ missing = [nid for nid in wanted_ids if nid not in present]
278
+ if include_neighbors:
279
+ keep = _expand_neighbors(keep, edges, present)
280
+ if not keep:
281
+ raise ValueError("The selection matched no nodes; nothing was exported.")
282
+ kept_nodes = [n for n in nodes if str(n.get("id")) in keep]
283
+ kept_chunks = [c for c in data.get("chunks") or [] if str(c.get("source_node")) in keep]
284
+ kept_chunk_nodes = [
285
+ chunk_nodes_by_id[str(c.get("id"))]
286
+ for c in kept_chunks
287
+ if str(c.get("id")) in chunk_nodes_by_id
288
+ ]
289
+ carried = keep | {str(n.get("id")) for n in kept_chunk_nodes}
290
+ kept_edges = [
291
+ e for e in edges
292
+ if str(e.get("from_node")) in carried and str(e.get("to_node")) in carried
293
+ ]
294
+ kept_prov = [p for p in data.get("provenance") or [] if str(p.get("node_id")) in keep]
295
+ if redact_provenance:
296
+ kept_nodes = [_redact_node(n) for n in kept_nodes]
297
+ kept_chunk_nodes = [_redact_node(n) for n in kept_chunk_nodes]
298
+ kept_prov = [_redact_provenance_row(p) for p in kept_prov]
299
+ payload = {
300
+ "nodes": kept_nodes,
301
+ "chunk_nodes": kept_chunk_nodes,
302
+ "edges": kept_edges,
303
+ "chunks": kept_chunks,
304
+ "knowledge_sources": [],
305
+ "provenance": kept_prov,
306
+ }
307
+ counts = {key: len(value) for key, value in payload.items()}
308
+ header = {
309
+ "format": SUBGRAPH_FORMAT,
310
+ "format_version": SUBGRAPH_FORMAT_VERSION,
311
+ **self._kg.schema_versions(),
312
+ "exported_at": utc_now_iso(),
313
+ "workspace_id": workspace_id,
314
+ "selection": selection,
315
+ "counts": counts,
316
+ "unmatched_node_ids": missing,
317
+ "redacted": sorted(_REDACTED_FIELDS) if redact_provenance else [],
318
+ "includes_knowledge_sources": False,
319
+ "device": self._share_device(),
320
+ # The signature covers the header; the header pins the payload.
321
+ "payload_sha256": _canonical_digest(payload),
322
+ }
323
+ return {
324
+ "header": header,
325
+ **payload,
326
+ "signature": self._identity.sign_manifest(header),
327
+ }
328
+
329
+ def export_subgraph_archive(
330
+ self,
331
+ dest_path=None,
332
+ *,
333
+ passphrase: Optional[str] = None,
334
+ recipient_public_key: Optional[str] = None,
335
+ **selection: Any,
336
+ ) -> Dict[str, Any]:
337
+ """Write the signed subgraph as an encrypted ``.latticebrain`` file.
338
+
339
+ Exactly one recipient mechanism, named explicitly:
340
+
341
+ * ``passphrase`` — the 11.1.0 mechanism, identical to the whole-Brain
342
+ archive (PBKDF2-SHA256 → AES-256-GCM). Simple, and it means a secret
343
+ has to reach the receiver through some other channel first.
344
+ * ``recipient_public_key`` — an X25519 sealed box (11.2.0). The
345
+ receiver publishes a public key; nothing secret travels at all.
346
+
347
+ Supplying both is refused rather than silently preferring one: which
348
+ key opens a bundle is not a detail to guess at. A different ``format``
349
+ from the whole-Brain archive keeps the two from ever being confused,
350
+ and the header and signature stay *outside* the ciphertext on purpose —
351
+ a recipient can see who sent a bundle, and how big it is, before
352
+ deciding to open it.
353
+ """
354
+ mode = self._encryption_mode(passphrase, recipient_public_key)
355
+ artifact = self.export_subgraph(**selection)
356
+ self._exports_dir.mkdir(parents=True, exist_ok=True)
357
+ dest = Path(dest_path) if dest_path else self._exports_dir / f"subgraph-{_stamp()}.latticebrain"
358
+ if dest.suffix != ".latticebrain":
359
+ dest = dest.with_suffix(".latticebrain")
360
+ body = {key: value for key, value in artifact.items() if key not in {"header", "signature"}}
361
+ plaintext = json.dumps(body, ensure_ascii=False, sort_keys=True).encode("utf-8")
362
+ envelope: Dict[str, Any] = {
363
+ "format": SUBGRAPH_ARCHIVE_FORMAT,
364
+ "format_version": SUBGRAPH_FORMAT_VERSION,
365
+ "created_at": utc_now_iso(),
366
+ "encryption": mode,
367
+ "header": artifact["header"],
368
+ "signature": artifact["signature"],
369
+ }
370
+ recipient: Optional[str] = None
371
+ if mode == "recipient_public_key":
372
+ sealed = seal(plaintext, recipient_public_key=str(recipient_public_key))
373
+ recipient = str(sealed["recipient_fingerprint"])
374
+ envelope["sealed_box"] = sealed
375
+ else:
376
+ salt = os.urandom(16)
377
+ nonce = os.urandom(12)
378
+ ciphertext = AESGCM(_derive_key(str(passphrase), salt)).encrypt(nonce, plaintext, None)
379
+ envelope["kdf"] = {
380
+ "name": "PBKDF2HMAC-SHA256",
381
+ "iterations": KDF_ITERATIONS,
382
+ "salt": base64.b64encode(salt).decode("ascii"),
383
+ }
384
+ envelope["cipher"] = {
385
+ "name": "AES-256-GCM",
386
+ "nonce": base64.b64encode(nonce).decode("ascii"),
387
+ }
388
+ envelope["payload"] = base64.b64encode(ciphertext).decode("ascii")
389
+ dest.parent.mkdir(parents=True, exist_ok=True)
390
+ dest.write_text(json.dumps(envelope, ensure_ascii=False, indent=2), encoding="utf-8")
391
+ return {
392
+ "path": str(dest),
393
+ "bytes": dest.stat().st_size,
394
+ "encrypted": True,
395
+ "encryption": mode,
396
+ "recipient_fingerprint": recipient,
397
+ "format": SUBGRAPH_ARCHIVE_FORMAT,
398
+ "header": artifact["header"],
399
+ "counts": artifact["header"]["counts"],
400
+ }
401
+
402
+ @staticmethod
403
+ def _encryption_mode(
404
+ passphrase: Optional[str], recipient_public_key: Optional[str]
405
+ ) -> str:
406
+ """``passphrase`` | ``recipient_public_key`` — exactly one, validated."""
407
+ has_passphrase = bool(str(passphrase or "").strip())
408
+ wanted_key = str(recipient_public_key or "").strip()
409
+ if has_passphrase and wanted_key:
410
+ raise ValueError(
411
+ "Choose one: a passphrase, or a recipient public key. "
412
+ "A bundle sealed both ways would hide which key really opens it."
413
+ )
414
+ if wanted_key:
415
+ public_key_fingerprint(wanted_key) # validates; raises on garbage
416
+ return "recipient_public_key"
417
+ if has_passphrase:
418
+ return "passphrase"
419
+ raise ValueError(
420
+ "A subgraph bundle must be encrypted: supply a passphrase or the "
421
+ "recipient's public key."
422
+ )
423
+
424
+ def read_subgraph_archive(
425
+ self, path, *, passphrase: Optional[str] = None
426
+ ) -> Dict[str, Any]:
427
+ """Decrypt an encrypted subgraph bundle back into a signed artifact.
428
+
429
+ The envelope says how it was sealed, so the reader never has to guess:
430
+ a passphrase bundle needs the passphrase, a sealed-box bundle needs
431
+ this Brain's own receiving key and no passphrase at all.
432
+ """
433
+ require_brain_network()
434
+ source = Path(path)
435
+ if not source.exists():
436
+ raise FileNotFoundError(f"Subgraph bundle not found: {source}")
437
+ try:
438
+ envelope = json.loads(source.read_text(encoding="utf-8"))
439
+ except json.JSONDecodeError as exc:
440
+ raise ValueError("Subgraph bundle is not valid JSON.") from exc
441
+ if envelope.get("format") != SUBGRAPH_ARCHIVE_FORMAT:
442
+ raise ValueError("Not a .latticebrain subgraph bundle.")
443
+ if envelope.get("encryption") == "recipient_public_key":
444
+ plaintext = self._unseal_bundle(envelope)
445
+ else:
446
+ plaintext = self._decrypt_with_passphrase(envelope, passphrase)
447
+ body = json.loads(plaintext.decode("utf-8"))
448
+ return {
449
+ "header": envelope.get("header") or {},
450
+ **body,
451
+ "signature": envelope.get("signature") or {},
452
+ }
453
+
454
+ def _unseal_bundle(self, envelope: Dict[str, Any]) -> bytes:
455
+ """Open a sealed box with this Brain's receiving key, or say why not."""
456
+ identity = self._recipient_identity()
457
+ if identity is None:
458
+ raise ValueError(
459
+ "This bundle is sealed to a public key, but no receiving key "
460
+ "could be loaded on this machine."
461
+ )
462
+ block = envelope.get("sealed_box")
463
+ if not isinstance(block, dict):
464
+ raise ValueError("Subgraph bundle is missing encryption metadata.")
465
+ return bytes(identity.unseal(block))
466
+
467
+ @staticmethod
468
+ def _decrypt_with_passphrase(
469
+ envelope: Dict[str, Any], passphrase: Optional[str]
470
+ ) -> bytes:
471
+ if not str(passphrase or "").strip():
472
+ raise ValueError("This bundle is passphrase-encrypted; a passphrase is required.")
473
+ try:
474
+ salt = base64.b64decode(envelope["kdf"]["salt"])
475
+ nonce = base64.b64decode(envelope["cipher"]["nonce"])
476
+ ciphertext = base64.b64decode(envelope["payload"])
477
+ except (KeyError, TypeError, ValueError) as exc:
478
+ raise ValueError("Subgraph bundle is missing encryption metadata.") from exc
479
+ try:
480
+ return bytes(
481
+ AESGCM(_derive_key(str(passphrase), salt)).decrypt(nonce, ciphertext, None)
482
+ )
483
+ except InvalidTag as exc:
484
+ raise ValueError(
485
+ "Subgraph decryption failed; the passphrase or the bundle is invalid."
486
+ ) from exc
487
+
488
+ def verify_subgraph(self, artifact: Dict[str, Any]) -> Dict[str, Any]:
489
+ """Signature + payload-digest verdict for a received bundle.
490
+
491
+ Fail-closed and specific: the caller learns *which* check failed, and
492
+ an unsigned bundle is a failure here (unlike a local file import, where
493
+ pre-v4 unsigned artifacts stay importable).
494
+ """
495
+ errors: List[str] = []
496
+ header = artifact.get("header") if isinstance(artifact, dict) else None
497
+ header = header if isinstance(header, dict) else {}
498
+ signature = artifact.get("signature") if isinstance(artifact, dict) else None
499
+ signature = signature if isinstance(signature, dict) else {}
500
+ if header.get("format") != SUBGRAPH_FORMAT:
501
+ errors.append("not a Lattice subgraph bundle")
502
+ incoming_version = int(header.get("format_version") or 0)
503
+ if incoming_version > SUBGRAPH_FORMAT_VERSION:
504
+ errors.append(
505
+ f"bundle format version {incoming_version} is newer than this build "
506
+ f"({SUBGRAPH_FORMAT_VERSION})"
507
+ )
508
+ if not signature.get("signature"):
509
+ errors.append("bundle is unsigned")
510
+ else:
511
+ from ..graph.identity import verify_manifest
512
+
513
+ if not verify_manifest(header, signature):
514
+ errors.append("signature does not match the bundle header")
515
+ expected = header.get("payload_sha256")
516
+ if expected:
517
+ payload = {key: artifact.get(key) or [] for key in _PAYLOAD_KEYS}
518
+ if _canonical_digest(payload) != expected:
519
+ errors.append("bundle contents do not match the signed digest")
520
+ else:
521
+ errors.append("bundle header does not pin its payload digest")
522
+ fingerprint = str(signature.get("fingerprint") or "") or None
523
+ return {
524
+ "ok": not errors,
525
+ "errors": errors,
526
+ "fingerprint": fingerprint,
527
+ "origin": f"device:{fingerprint}" if fingerprint and not errors else None,
528
+ "exported_at": header.get("exported_at"),
529
+ "counts": header.get("counts") or {},
530
+ }
531
+
532
+ def import_subgraph_proposals(
533
+ self,
534
+ artifact: Dict[str, Any],
535
+ *,
536
+ review_sink: Any,
537
+ workspace_id: Optional[str] = None,
538
+ user_email: Optional[str] = None,
539
+ dry_run: bool = False,
540
+ cap: int = SUBGRAPH_PROPOSAL_CAP,
541
+ ) -> Dict[str, Any]:
542
+ """Receive a subgraph as *proposals*, never as a merge.
543
+
544
+ Every node becomes one review item carrying its edges, chunks, and
545
+ provenance, stamped with the sending device's fingerprint and the
546
+ signature verdict. Nothing reaches the graph until a human accepts an
547
+ item through :meth:`accept_subgraph_proposal`.
548
+ """
549
+ require_brain_network()
550
+ self._require()
551
+ verdict = self.verify_subgraph(artifact)
552
+ if not verdict["ok"]:
553
+ raise ValueError(
554
+ "Refusing the bundle: " + "; ".join(verdict["errors"])
555
+ )
556
+ header = dict(artifact.get("header") or {})
557
+ nodes = [n for n in artifact.get("nodes") or [] if n.get("id")]
558
+ edges = list(artifact.get("edges") or [])
559
+ chunks = list(artifact.get("chunks") or [])
560
+ chunk_nodes = {str(n.get("id")): n for n in artifact.get("chunk_nodes") or []}
561
+ provenance = list(artifact.get("provenance") or [])
562
+ cap = max(1, int(cap))
563
+ selected = nodes[:cap]
564
+ summary: Dict[str, Any] = {
565
+ "status": "dry_run" if dry_run else "proposed",
566
+ "origin": verdict["origin"],
567
+ "fingerprint": verdict["fingerprint"],
568
+ "signed": True,
569
+ "signature_verified": True,
570
+ "nodes": len(nodes),
571
+ "edges": len(edges),
572
+ "chunks": len(chunks),
573
+ "proposed": len(selected),
574
+ "skipped": len(nodes) - len(selected),
575
+ "capped": len(nodes) > len(selected),
576
+ "exported_at": header.get("exported_at"),
577
+ "items": [],
578
+ }
579
+ if dry_run:
580
+ return summary
581
+ for node in selected:
582
+ node_id = str(node.get("id"))
583
+ node_chunks = [c for c in chunks if str(c.get("source_node")) == node_id]
584
+ carried = {node_id} | {str(c.get("id")) for c in node_chunks}
585
+ item = review_sink.create(
586
+ title=str(node.get("title") or node_id)[:200],
587
+ summary=_shared_node_summary(node, verdict),
588
+ source=SUBGRAPH_REVIEW_SOURCE,
589
+ kind=SUBGRAPH_REVIEW_KIND,
590
+ payload={
591
+ "kind": SUBGRAPH_REVIEW_KIND,
592
+ "node": node,
593
+ "chunk_nodes": [
594
+ chunk_nodes[str(c.get("id"))]
595
+ for c in node_chunks
596
+ if str(c.get("id")) in chunk_nodes
597
+ ],
598
+ "edges": [
599
+ e for e in edges
600
+ if str(e.get("from_node")) in carried or str(e.get("to_node")) in carried
601
+ ],
602
+ "chunks": node_chunks,
603
+ "provenance": [p for p in provenance if str(p.get("node_id")) == node_id],
604
+ "graph_schema_version": header.get("graph_schema_version"),
605
+ },
606
+ provenance={
607
+ "origin": verdict["origin"],
608
+ "fingerprint": verdict["fingerprint"],
609
+ "public_key": (artifact.get("signature") or {}).get("public_key"),
610
+ "signature_verified": True,
611
+ "exported_at": header.get("exported_at"),
612
+ "source_detail": "brain_network_subgraph",
613
+ "redacted": header.get("redacted") or [],
614
+ },
615
+ user_email=user_email,
616
+ workspace_id=workspace_id,
617
+ )
618
+ summary["items"].append(item.get("id"))
619
+ try:
620
+ self._kg.record_provenance(
621
+ node_id="subgraph-proposal:" + str(header.get("exported_at") or utc_now_iso()),
622
+ source_type="subgraph_share",
623
+ pipeline="kg-portability",
624
+ owner=user_email,
625
+ workspace_id=workspace_id,
626
+ metadata={
627
+ "origin": verdict["origin"],
628
+ "proposed": len(selected),
629
+ "counts": header.get("counts"),
630
+ },
631
+ )
632
+ except Exception: # noqa: BLE001 — the proposals already landed
633
+ quiet()
634
+ return summary
635
+
636
+ def accept_subgraph_proposal(
637
+ self,
638
+ item_id: str,
639
+ *,
640
+ review_sink: Any,
641
+ workspace_id: Optional[str] = None,
642
+ ) -> Dict[str, Any]:
643
+ """Merge one accepted proposal into this Brain and approve the item.
644
+
645
+ Only the node the reviewer looked at is written. An edge whose other
646
+ endpoint is not (yet) in this Brain is *deferred* and reported, because
647
+ writing a dangling relation would invent a connection the receiver
648
+ cannot see.
649
+ """
650
+ require_brain_network()
651
+ self._require()
652
+ item = review_sink.get(item_id, workspace_id=workspace_id)
653
+ payload = dict((item or {}).get("payload") or {})
654
+ if payload.get("kind") != SUBGRAPH_REVIEW_KIND:
655
+ raise ValueError("That review item is not a shared-subgraph proposal.")
656
+ node = dict(payload.get("node") or {})
657
+ node_id = str(node.get("id") or "")
658
+ if not node_id:
659
+ raise ValueError("The proposal carries no node id.")
660
+ status = str((item or {}).get("status") or "pending")
661
+ if status not in _OPEN_REVIEW_STATUSES:
662
+ # Import first, approve second would re-write an already-decided
663
+ # item; refuse before touching the graph instead.
664
+ raise ValueError(f"That proposal is already {status}; nothing was imported.")
665
+ chunk_nodes = [dict(n) for n in payload.get("chunk_nodes") or []]
666
+ if workspace_id:
667
+ node = _scope_node(node, workspace_id)
668
+ chunk_nodes = [_scope_node(n, workspace_id) for n in chunk_nodes]
669
+ # The chunk rows land in the same write, so their nodes count as
670
+ # present even though this Brain has not seen them yet.
671
+ writing = {node_id} | {str(n.get("id")) for n in chunk_nodes}
672
+ kept: List[Dict[str, Any]] = []
673
+ deferred: List[Dict[str, Any]] = []
674
+ for edge in payload.get("edges") or []:
675
+ endpoints = {str(edge.get("from_node")), str(edge.get("to_node"))}
676
+ outside = endpoints - writing
677
+ if all(self._node_present(other) for other in outside):
678
+ kept.append(edge)
679
+ else:
680
+ deferred.append({
681
+ "from": edge.get("from_node"),
682
+ "to": edge.get("to_node"),
683
+ "type": edge.get("type"),
684
+ "reason": "the other node is not in this Brain yet",
685
+ })
686
+ result = self._kg.import_graph_data(
687
+ {
688
+ "header": {"graph_schema_version": payload.get("graph_schema_version")},
689
+ "nodes": [node, *chunk_nodes],
690
+ "edges": kept,
691
+ "chunks": list(payload.get("chunks") or []),
692
+ "knowledge_sources": [],
693
+ "provenance": list(payload.get("provenance") or []),
694
+ },
695
+ mode="merge",
696
+ )
697
+ approved = review_sink.approve(item_id, workspace_id=workspace_id)
698
+ return {
699
+ "status": "accepted",
700
+ "item_id": item_id,
701
+ "node_id": node_id,
702
+ "imported": result,
703
+ "edges_written": len(kept),
704
+ "edges_deferred": deferred,
705
+ "origin": (item.get("provenance") or {}).get("origin"),
706
+ "review_status": approved.get("status"),
707
+ }
708
+
709
+ def _node_present(self, node_id: str) -> bool:
710
+ try:
711
+ self._kg.get_node(node_id)
712
+ except Exception: # noqa: BLE001 — "not found" is the answer, not a failure
713
+ return False
714
+ return True