ltcai 11.5.2 → 11.6.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 (439) hide show
  1. package/README.md +91 -148
  2. package/bin/ltcai.js +234 -24
  3. package/docs/CHANGELOG.md +75 -0
  4. package/docs/COMMUNITY_AND_PLUGINS.md +1 -1
  5. package/docs/DEVELOPMENT.md +8 -6
  6. package/docs/ENTERPRISE.md +2 -1
  7. package/docs/MULTI_AGENT_RUNTIME.md +12 -5
  8. package/docs/ONBOARDING.md +1 -1
  9. package/docs/OPERATIONS.md +6 -3
  10. package/docs/REALTIME_COLLABORATION.md +1 -1
  11. package/docs/TRUST_MODEL.md +1 -1
  12. package/docs/WHY_LATTICE.md +1 -1
  13. package/docs/WORKFLOW_DESIGNER.md +3 -2
  14. package/docs/kg-schema.md +1 -1
  15. package/docs/v11.6.0_ONE_DOOR_PLAN.md +170 -0
  16. package/lattice_brain/__init__.py +42 -79
  17. package/lattice_brain/graph/__init__.py +9 -24
  18. package/lattice_brain/graph/_kg_common/__init__.py +13 -24
  19. package/lattice_brain/ingestion/__init__.py +19 -58
  20. package/lattice_brain/ingestion/pipeline.py +20 -398
  21. package/lattice_brain/multimodal/__init__.py +7 -18
  22. package/lattice_brain/multimodal/images.py +6 -264
  23. package/lattice_brain/multimodal/video.py +8 -247
  24. package/lattice_brain/runtime/__init__.py +8 -79
  25. package/lattice_brain/runtime/hooks.py +22 -584
  26. package/latticeai/__init__.py +1 -1
  27. package/latticeai/api/agent_worker_seam.py +7 -80
  28. package/latticeai/api/health.py +6 -20
  29. package/latticeai/api/local_files.py +16 -613
  30. package/latticeai/api/models.py +12 -87
  31. package/latticeai/api/search.py +17 -255
  32. package/latticeai/api/tools.py +69 -750
  33. package/latticeai/api/voice_capture.py +8 -70
  34. package/latticeai/api/worker_compute.py +842 -0
  35. package/latticeai/api/worker_seams.py +216 -0
  36. package/latticeai/app_factory.py +23 -232
  37. package/latticeai/cli/entrypoint.py +36 -249
  38. package/latticeai/core/agent_permission.py +16 -91
  39. package/latticeai/core/messages.py +89 -531
  40. package/latticeai/runtime/access_runtime.py +0 -14
  41. package/latticeai/runtime/bootstrap.py +10 -21
  42. package/latticeai/runtime/brain_runtime.py +35 -43
  43. package/latticeai/runtime/build_phases/__init__.py +21 -37
  44. package/latticeai/runtime/build_phases/features.py +99 -389
  45. package/latticeai/runtime/build_phases/foundation.py +82 -392
  46. package/latticeai/runtime/build_phases/web.py +91 -408
  47. package/latticeai/runtime/build_phases/worker_profile.py +244 -0
  48. package/latticeai/runtime/lifespan_runtime.py +7 -16
  49. package/latticeai/runtime/platform_services_runtime.py +1 -15
  50. package/latticeai/runtime/runtime_context.py +13 -130
  51. package/latticeai/runtime/security_runtime.py +10 -103
  52. package/latticeai/services/architecture_readiness.py +82 -43
  53. package/latticeai/services/model_runtime/__init__.py +2 -11
  54. package/latticeai/services/model_runtime/service.py +4 -28
  55. package/latticeai/services/p_reinforce.py +10 -261
  56. package/latticeai/services/product_readiness.py +31 -38
  57. package/latticeai/services/search_service.py +37 -795
  58. package/latticeai/services/tool_dispatch.py +30 -386
  59. package/latticeai/services/voice_capture.py +13 -107
  60. package/latticeai/tools/__init__.py +22 -49
  61. package/latticeai/tools/commands.py +0 -163
  62. package/latticeai/tools/computer.py +0 -39
  63. package/latticeai/tools/documents.py +1 -134
  64. package/latticeai/tools/filesystem.py +1 -247
  65. package/latticeai/tools/knowledge.py +1 -52
  66. package/latticeai/tools/local_files.py +0 -20
  67. package/latticeai/worker_app.py +75 -0
  68. package/package.json +2 -3
  69. package/requirements.txt +0 -5
  70. package/scripts/agent_eval.py +16 -28
  71. package/scripts/brain_quality_eval.py +20 -183
  72. package/scripts/bump_version.py +5 -5
  73. package/scripts/check_current_release_docs.mjs +7 -4
  74. package/scripts/check_openapi_drift.mjs +10 -0
  75. package/scripts/check_server_i18n.mjs +2 -18
  76. package/scripts/compose_openapi.py +377 -0
  77. package/scripts/export_openapi.py +32 -4
  78. package/scripts/gen_messages_catalog_fixture.py +302 -0
  79. package/scripts/gen_openapi_fragments.py +365 -0
  80. package/scripts/gen_redact_fixture.py +196 -0
  81. package/scripts/gen_worker_allowlist_fixture.py +115 -0
  82. package/scripts/generate_agent_parity_fixtures.py +33 -14
  83. package/scripts/openapi_route_families.json +2161 -0
  84. package/scripts/release_screen_claims.json +21 -0
  85. package/scripts/run_integration_tests.mjs +134 -29
  86. package/scripts/run_sidecar_e2e.mjs +104 -11
  87. package/scripts/wheel_smoke.py +32 -22
  88. package/src-tauri/Cargo.lock +375 -9
  89. package/src-tauri/Cargo.toml +1 -1
  90. package/src-tauri/src/backend.rs +151 -45
  91. package/src-tauri/src/main.rs +18 -18
  92. package/src-tauri/src/topology.rs +58 -88
  93. package/src-tauri/tauri.conf.json +1 -2
  94. package/static/app/asset-manifest.json +41 -41
  95. package/static/app/assets/{Act-DcQizkl1.js → Act-CToZnOHz.js} +1 -1
  96. package/static/app/assets/{AdminConsole-cf4npybT.js → AdminConsole-D5kbrBu8.js} +1 -1
  97. package/static/app/assets/{Brain-3VCSHFcn.js → Brain-C6zCdv4S.js} +1 -1
  98. package/static/app/assets/{BrainHome-Qm8eaztx.js → BrainHome-D4n3EDUt.js} +1 -1
  99. package/static/app/assets/{BrainSignals-DS9BtKOW.js → BrainSignals-CzeZ-vQ9.js} +1 -1
  100. package/static/app/assets/{Capture-DiQ219jW.js → Capture-DPcyTczq.js} +1 -1
  101. package/static/app/assets/{Chronicle-BGvuAchH.js → Chronicle-D3Nx-oWS.js} +1 -1
  102. package/static/app/assets/{CommandPalette-Bqhm0Urn.js → CommandPalette-DPPvpp28.js} +1 -1
  103. package/static/app/assets/{Library-BV6NnF0a.js → Library-Co2qTu3I.js} +1 -1
  104. package/static/app/assets/{LivingBrain-GzenJchP.js → LivingBrain-Bsmzwy8_.js} +1 -1
  105. package/static/app/assets/{ProductFlow-DEP6-vML.js → ProductFlow-CBLdmesT.js} +1 -1
  106. package/static/app/assets/{ReviewCard-CNZ7XjWG.js → ReviewCard-CfR6DLs7.js} +1 -1
  107. package/static/app/assets/{System-CieofHQa.js → System-Ce-P2YL6.js} +1 -1
  108. package/static/app/assets/arrow-left-DD5jFGHV.js +1 -0
  109. package/static/app/assets/{bot-B_K1Tdmw.js → bot-C5-XIww2.js} +1 -1
  110. package/static/app/assets/{brain-DWyaV1L1.js → brain-CFRJUvdX.js} +1 -1
  111. package/static/app/assets/{button-aTn4s84A.js → button-DI1KcQP-.js} +1 -1
  112. package/static/app/assets/circle-check-CY20XMCh.js +1 -0
  113. package/static/app/assets/{circle-pause-xKgeGXkT.js → circle-pause-C8HHyood.js} +1 -1
  114. package/static/app/assets/{circle-play-DkT6tYPX.js → circle-play-Cufc235E.js} +1 -1
  115. package/static/app/assets/{cpu-85xYObUC.js → cpu-DW2_JVsv.js} +1 -1
  116. package/static/app/assets/{download-B5Fm7YXo.js → download-gbdKTBb8.js} +1 -1
  117. package/static/app/assets/{folder-open-kk2Xa52u.js → folder-open-C9ydyX33.js} +1 -1
  118. package/static/app/assets/{hard-drive-DkA3zBW_.js → hard-drive-BxNMzBM3.js} +1 -1
  119. package/static/app/assets/index-BovSWRmQ.css +2 -0
  120. package/static/app/assets/{index-BMPdTmlY.js → index-q9XyDY7A.js} +3 -3
  121. package/static/app/assets/{input-B0nRf2jO.js → input-GLD94Y_K.js} +1 -1
  122. package/static/app/assets/{link-2-Dwb4gnTc.js → link-2-B4Y0gz1S.js} +1 -1
  123. package/static/app/assets/{permissionCopy-CQDUBrOZ.js → permissionCopy-CxrV0fvU.js} +1 -1
  124. package/static/app/assets/{primitives-SNp0LRJz.js → primitives-2ANdAsu2.js} +1 -1
  125. package/static/app/assets/search-DTxtjQ07.js +1 -0
  126. package/static/app/assets/{share-2-BsrxFglO.js → share-2-DxArfiuI.js} +1 -1
  127. package/static/app/assets/{shield-alert-5BStfp2_.js → shield-alert-CgftuFFs.js} +1 -1
  128. package/static/app/assets/{textarea-Cg8IUA-k.js → textarea-BHVBAoCr.js} +1 -1
  129. package/static/app/assets/{useFocusTrap-CYKvE46M.js → useFocusTrap-Dzq2j_OG.js} +1 -1
  130. package/static/app/assets/{useMutation-CSn9t1op.js → useMutation-BcqfMLNq.js} +1 -1
  131. package/static/app/assets/{useQuery-CY2OI2uy.js → useQuery-DBzLKCOv.js} +1 -1
  132. package/static/app/assets/{utils-Ddol2RWD.js → utils-B-Aah1bO.js} +1 -1
  133. package/static/app/assets/{workspace-BqDwOz_p.js → workspace-B6fFhoko.js} +1 -1
  134. package/static/app/index.html +4 -4
  135. package/static/sw.js +1 -1
  136. package/lattice_brain/archive.py +0 -522
  137. package/lattice_brain/context.py +0 -325
  138. package/lattice_brain/conversations.py +0 -382
  139. package/lattice_brain/core.py +0 -82
  140. package/lattice_brain/graph/_kg_contract.py +0 -249
  141. package/lattice_brain/graph/curator.py +0 -676
  142. package/lattice_brain/graph/discovery.py +0 -595
  143. package/lattice_brain/graph/discovery_index/__init__.py +0 -35
  144. package/lattice_brain/graph/discovery_index/cleanup.py +0 -182
  145. package/lattice_brain/graph/discovery_index/extract.py +0 -137
  146. package/lattice_brain/graph/discovery_index/scan.py +0 -411
  147. package/lattice_brain/graph/discovery_index/upsert.py +0 -495
  148. package/lattice_brain/graph/documents.py +0 -380
  149. package/lattice_brain/graph/fusion.py +0 -395
  150. package/lattice_brain/graph/identity.py +0 -175
  151. package/lattice_brain/graph/image_vectors.py +0 -230
  152. package/lattice_brain/graph/ingest.py +0 -829
  153. package/lattice_brain/graph/network.py +0 -205
  154. package/lattice_brain/graph/proactive.py +0 -724
  155. package/lattice_brain/graph/projection/__init__.py +0 -42
  156. package/lattice_brain/graph/projection/curation.py +0 -500
  157. package/lattice_brain/graph/projection/v2_schema.py +0 -518
  158. package/lattice_brain/graph/provenance.py +0 -524
  159. package/lattice_brain/graph/rerank.py +0 -163
  160. package/lattice_brain/graph/retrieval/__init__.py +0 -54
  161. package/lattice_brain/graph/retrieval/context.py +0 -197
  162. package/lattice_brain/graph/retrieval/graph_view.py +0 -319
  163. package/lattice_brain/graph/retrieval/hybrid.py +0 -488
  164. package/lattice_brain/graph/retrieval/maintenance.py +0 -121
  165. package/lattice_brain/graph/retrieval/signals.py +0 -95
  166. package/lattice_brain/graph/retrieval_docgen.py +0 -253
  167. package/lattice_brain/graph/retrieval_policy.py +0 -180
  168. package/lattice_brain/graph/retrieval_reads.py +0 -769
  169. package/lattice_brain/graph/retrieval_vector/__init__.py +0 -42
  170. package/lattice_brain/graph/retrieval_vector/fingerprint.py +0 -97
  171. package/lattice_brain/graph/retrieval_vector/indexing.py +0 -347
  172. package/lattice_brain/graph/retrieval_vector/search.py +0 -560
  173. package/lattice_brain/graph/retrieval_vector/status.py +0 -374
  174. package/lattice_brain/graph/schema.py +0 -792
  175. package/lattice_brain/graph/store.py +0 -268
  176. package/lattice_brain/graph/vector_index/__init__.py +0 -85
  177. package/lattice_brain/graph/vector_index/base.py +0 -167
  178. package/lattice_brain/graph/vector_index/brute_force.py +0 -110
  179. package/lattice_brain/graph/vector_index/hnsw.py +0 -290
  180. package/lattice_brain/graph/vector_index/jobs.py +0 -287
  181. package/lattice_brain/graph/vector_index/quantized.py +0 -148
  182. package/lattice_brain/graph/vector_index/selector.py +0 -161
  183. package/lattice_brain/graph/write_master.py +0 -308
  184. package/lattice_brain/ingestion/_contract.py +0 -90
  185. package/lattice_brain/ingestion/folder_scan.py +0 -57
  186. package/lattice_brain/ingestion/folders.py +0 -258
  187. package/lattice_brain/ingestion/jobs_api.py +0 -107
  188. package/lattice_brain/ingestion/routing.py +0 -295
  189. package/lattice_brain/ingestion_jobs.py +0 -380
  190. package/lattice_brain/memory.py +0 -75
  191. package/lattice_brain/portability/__init__.py +0 -90
  192. package/lattice_brain/portability/_contract.py +0 -42
  193. package/lattice_brain/portability/backups.py +0 -338
  194. package/lattice_brain/portability/bundles.py +0 -136
  195. package/lattice_brain/portability/constants.py +0 -93
  196. package/lattice_brain/portability/fsops.py +0 -138
  197. package/lattice_brain/portability/service.py +0 -41
  198. package/lattice_brain/portability/sharing.py +0 -710
  199. package/lattice_brain/quality.py +0 -543
  200. package/lattice_brain/retrieval_benchmark_fixtures.py +0 -92
  201. package/lattice_brain/runtime/agent_runtime.py +0 -859
  202. package/lattice_brain/runtime/contracts.py +0 -460
  203. package/lattice_brain/runtime/multi_agent.py +0 -942
  204. package/lattice_brain/runtime/statuses.py +0 -10
  205. package/lattice_brain/sealed_box.py +0 -240
  206. package/lattice_brain/self_model.py +0 -675
  207. package/lattice_brain/sensitivity.py +0 -94
  208. package/lattice_brain/storage/__init__.py +0 -22
  209. package/lattice_brain/storage/base.py +0 -100
  210. package/lattice_brain/storage/docker.py +0 -105
  211. package/lattice_brain/storage/factory.py +0 -31
  212. package/lattice_brain/storage/migration.py +0 -191
  213. package/lattice_brain/storage/postgres.py +0 -123
  214. package/lattice_brain/storage/sqlite.py +0 -143
  215. package/lattice_brain/synthesis.py +0 -824
  216. package/lattice_brain/workflow.py +0 -497
  217. package/latticeai/api/admin.py +0 -471
  218. package/latticeai/api/agent_registry.py +0 -105
  219. package/latticeai/api/agents.py +0 -228
  220. package/latticeai/api/auth.py +0 -383
  221. package/latticeai/api/automation_intelligence.py +0 -401
  222. package/latticeai/api/brain_intelligence.py +0 -199
  223. package/latticeai/api/browser.py +0 -493
  224. package/latticeai/api/change_proposals.py +0 -89
  225. package/latticeai/api/chat.py +0 -572
  226. package/latticeai/api/chat_agent_http.py +0 -892
  227. package/latticeai/api/chat_contracts.py +0 -73
  228. package/latticeai/api/chat_documents.py +0 -276
  229. package/latticeai/api/chat_helpers.py +0 -460
  230. package/latticeai/api/chat_history.py +0 -101
  231. package/latticeai/api/chat_hybrid.py +0 -113
  232. package/latticeai/api/chat_intents.py +0 -646
  233. package/latticeai/api/chat_stream.py +0 -216
  234. package/latticeai/api/chronicle.py +0 -63
  235. package/latticeai/api/command_center.py +0 -51
  236. package/latticeai/api/computer_use.py +0 -474
  237. package/latticeai/api/evidence_actions.py +0 -48
  238. package/latticeai/api/features.py +0 -70
  239. package/latticeai/api/funnel_metrics.py +0 -31
  240. package/latticeai/api/garden.py +0 -34
  241. package/latticeai/api/hooks.py +0 -165
  242. package/latticeai/api/index_jobs.py +0 -145
  243. package/latticeai/api/invitations.py +0 -100
  244. package/latticeai/api/knowledge_graph.py +0 -536
  245. package/latticeai/api/marketplace.py +0 -105
  246. package/latticeai/api/mcp.py +0 -482
  247. package/latticeai/api/memory.py +0 -270
  248. package/latticeai/api/network.py +0 -81
  249. package/latticeai/api/network_boundary.py +0 -225
  250. package/latticeai/api/permission_mode.py +0 -61
  251. package/latticeai/api/permissions.py +0 -436
  252. package/latticeai/api/plugins.py +0 -126
  253. package/latticeai/api/portability.py +0 -391
  254. package/latticeai/api/project_sessions.py +0 -114
  255. package/latticeai/api/realtime.py +0 -118
  256. package/latticeai/api/review_queue.py +0 -364
  257. package/latticeai/api/security_dashboard.py +0 -604
  258. package/latticeai/api/setup.py +0 -319
  259. package/latticeai/api/static_routes.py +0 -354
  260. package/latticeai/api/ui_redirects.py +0 -26
  261. package/latticeai/api/workflow_designer.py +0 -394
  262. package/latticeai/api/workspace.py +0 -856
  263. package/latticeai/api/workspace_scope.py +0 -125
  264. package/latticeai/core/agent/__init__.py +0 -93
  265. package/latticeai/core/agent/_contract.py +0 -79
  266. package/latticeai/core/agent/context.py +0 -57
  267. package/latticeai/core/agent/deps.py +0 -125
  268. package/latticeai/core/agent/execution.py +0 -622
  269. package/latticeai/core/agent/planning.py +0 -145
  270. package/latticeai/core/agent/recovery.py +0 -157
  271. package/latticeai/core/agent/runtime.py +0 -210
  272. package/latticeai/core/agent/verification.py +0 -231
  273. package/latticeai/core/agent_eval.py +0 -739
  274. package/latticeai/core/agent_helpers.py +0 -493
  275. package/latticeai/core/agent_profiles.py +0 -110
  276. package/latticeai/core/agent_prompts.py +0 -171
  277. package/latticeai/core/agent_registry.py +0 -232
  278. package/latticeai/core/agent_state.py +0 -41
  279. package/latticeai/core/agent_trace.py +0 -104
  280. package/latticeai/core/artifact_ledger.py +0 -109
  281. package/latticeai/core/audit.py +0 -260
  282. package/latticeai/core/builtin_hooks.py +0 -105
  283. package/latticeai/core/context_builder.py +0 -394
  284. package/latticeai/core/document_generator.py +0 -103
  285. package/latticeai/core/enterprise.py +0 -154
  286. package/latticeai/core/enterprise_admin.py +0 -158
  287. package/latticeai/core/file_generation/__init__.py +0 -115
  288. package/latticeai/core/file_generation/bundles.py +0 -76
  289. package/latticeai/core/file_generation/extraction.py +0 -154
  290. package/latticeai/core/file_generation/inference.py +0 -235
  291. package/latticeai/core/file_generation/orchestration.py +0 -152
  292. package/latticeai/core/file_generation/prompting.py +0 -117
  293. package/latticeai/core/file_generation/repair.py +0 -114
  294. package/latticeai/core/file_generation/sanitize.py +0 -61
  295. package/latticeai/core/file_generation/validation.py +0 -201
  296. package/latticeai/core/invitations.py +0 -132
  297. package/latticeai/core/legacy_compatibility.py +0 -243
  298. package/latticeai/core/logging_safety.py +0 -46
  299. package/latticeai/core/marketplace.py +0 -293
  300. package/latticeai/core/mcp_catalog.py +0 -452
  301. package/latticeai/core/mcp_registry.py +0 -506
  302. package/latticeai/core/network_boundary.py +0 -168
  303. package/latticeai/core/oidc.py +0 -208
  304. package/latticeai/core/plugins.py +0 -432
  305. package/latticeai/core/product_hardening.py +0 -218
  306. package/latticeai/core/project_sessions.py +0 -337
  307. package/latticeai/core/realtime.py +0 -238
  308. package/latticeai/core/run_explain.py +0 -426
  309. package/latticeai/core/run_store.py +0 -252
  310. package/latticeai/core/timezones.py +0 -80
  311. package/latticeai/core/workspace_computer_memory.py +0 -84
  312. package/latticeai/core/workspace_graph_trace.py +0 -155
  313. package/latticeai/core/workspace_indexing.py +0 -102
  314. package/latticeai/core/workspace_memory.py +0 -77
  315. package/latticeai/core/workspace_onboarding.py +0 -104
  316. package/latticeai/core/workspace_os.py +0 -978
  317. package/latticeai/core/workspace_os_constants.py +0 -126
  318. package/latticeai/core/workspace_os_state.py +0 -180
  319. package/latticeai/core/workspace_os_utils.py +0 -103
  320. package/latticeai/core/workspace_permissions.py +0 -101
  321. package/latticeai/core/workspace_plugins.py +0 -97
  322. package/latticeai/core/workspace_relationships.py +0 -99
  323. package/latticeai/core/workspace_reorganization.py +0 -335
  324. package/latticeai/core/workspace_review_items.py +0 -112
  325. package/latticeai/core/workspace_runs.py +0 -726
  326. package/latticeai/core/workspace_skills.py +0 -109
  327. package/latticeai/core/workspace_snapshots.py +0 -198
  328. package/latticeai/core/workspace_timeline.py +0 -110
  329. package/latticeai/integrations/__init__.py +0 -0
  330. package/latticeai/integrations/telegram_bot/__init__.py +0 -123
  331. package/latticeai/integrations/telegram_bot/__main__.py +0 -17
  332. package/latticeai/integrations/telegram_bot/config.py +0 -86
  333. package/latticeai/integrations/telegram_bot/dispatch.py +0 -311
  334. package/latticeai/integrations/telegram_bot/flows.py +0 -478
  335. package/latticeai/integrations/telegram_bot/helpers.py +0 -322
  336. package/latticeai/integrations/telegram_bot/screens.py +0 -394
  337. package/latticeai/runtime/audit_runtime.py +0 -76
  338. package/latticeai/runtime/automation_runtime.py +0 -81
  339. package/latticeai/runtime/chat_wiring.py +0 -141
  340. package/latticeai/runtime/context_runtime.py +0 -66
  341. package/latticeai/runtime/feature_toggle_wiring.py +0 -157
  342. package/latticeai/runtime/history_runtime.py +0 -163
  343. package/latticeai/runtime/history_writer.py +0 -138
  344. package/latticeai/runtime/hooks_runtime.py +0 -77
  345. package/latticeai/runtime/model_wiring.py +0 -68
  346. package/latticeai/runtime/namespace_runtime.py +0 -163
  347. package/latticeai/runtime/network_boundary_wiring.py +0 -117
  348. package/latticeai/runtime/network_config_runtime.py +0 -56
  349. package/latticeai/runtime/permission_mode_wiring.py +0 -112
  350. package/latticeai/runtime/persistence_runtime.py +0 -159
  351. package/latticeai/runtime/platform_runtime_wiring.py +0 -89
  352. package/latticeai/runtime/review_wiring.py +0 -42
  353. package/latticeai/runtime/router_registration.py +0 -693
  354. package/latticeai/runtime/service_singletons.py +0 -55
  355. package/latticeai/runtime/sso_config_runtime.py +0 -128
  356. package/latticeai/runtime/user_key_runtime.py +0 -106
  357. package/latticeai/runtime/web_runtime.py +0 -92
  358. package/latticeai/server_app.py +0 -51
  359. package/latticeai/services/app_context.py +0 -130
  360. package/latticeai/services/automation_execution.py +0 -266
  361. package/latticeai/services/automation_intelligence.py +0 -614
  362. package/latticeai/services/brain_automation.py +0 -191
  363. package/latticeai/services/brain_intelligence/__init__.py +0 -58
  364. package/latticeai/services/brain_intelligence/_contract.py +0 -71
  365. package/latticeai/services/brain_intelligence/consistency.py +0 -193
  366. package/latticeai/services/brain_intelligence/constants.py +0 -47
  367. package/latticeai/services/brain_intelligence/digest.py +0 -258
  368. package/latticeai/services/brain_intelligence/health.py +0 -331
  369. package/latticeai/services/brain_intelligence/proposals.py +0 -259
  370. package/latticeai/services/brain_intelligence/sampling.py +0 -84
  371. package/latticeai/services/brain_intelligence/service.py +0 -48
  372. package/latticeai/services/change_proposals.py +0 -471
  373. package/latticeai/services/chat_service.py +0 -243
  374. package/latticeai/services/chronicle.py +0 -555
  375. package/latticeai/services/cloud_egress_audit.py +0 -85
  376. package/latticeai/services/cloud_extraction.py +0 -129
  377. package/latticeai/services/cloud_streaming.py +0 -268
  378. package/latticeai/services/cloud_token_guard.py +0 -84
  379. package/latticeai/services/command_center.py +0 -548
  380. package/latticeai/services/evidence_actions.py +0 -258
  381. package/latticeai/services/feature_toggles.py +0 -502
  382. package/latticeai/services/folder_watch.py +0 -520
  383. package/latticeai/services/funnel_metrics.py +0 -307
  384. package/latticeai/services/hybrid_chat.py +0 -316
  385. package/latticeai/services/hybrid_context.py +0 -228
  386. package/latticeai/services/hybrid_policy.py +0 -129
  387. package/latticeai/services/interop_bridges.py +0 -978
  388. package/latticeai/services/local_knowledge.py +0 -465
  389. package/latticeai/services/memory_service/__init__.py +0 -52
  390. package/latticeai/services/memory_service/_contract.py +0 -100
  391. package/latticeai/services/memory_service/brief.py +0 -431
  392. package/latticeai/services/memory_service/constants.py +0 -57
  393. package/latticeai/services/memory_service/maintenance.py +0 -138
  394. package/latticeai/services/memory_service/manager.py +0 -186
  395. package/latticeai/services/memory_service/proof.py +0 -136
  396. package/latticeai/services/memory_service/recall.py +0 -225
  397. package/latticeai/services/memory_service/service.py +0 -48
  398. package/latticeai/services/memory_service/stores.py +0 -110
  399. package/latticeai/services/mode_store.py +0 -132
  400. package/latticeai/services/model_recommendation.py +0 -224
  401. package/latticeai/services/model_runtime/cloud.py +0 -87
  402. package/latticeai/services/network_boundary_service.py +0 -117
  403. package/latticeai/services/obsidian_bridge.py +0 -609
  404. package/latticeai/services/openai_compatible_adapter.py +0 -101
  405. package/latticeai/services/permission_mode_service.py +0 -122
  406. package/latticeai/services/platform_runtime.py +0 -366
  407. package/latticeai/services/review_queue.py +0 -380
  408. package/latticeai/services/router_context.py +0 -59
  409. package/latticeai/services/run_executor.py +0 -387
  410. package/latticeai/services/self_model_service.py +0 -171
  411. package/latticeai/services/setup_detection.py +0 -147
  412. package/latticeai/services/triggers.py +0 -378
  413. package/latticeai/services/upload_service.py +0 -172
  414. package/latticeai/services/workspace_service.py +0 -165
  415. package/latticeai/setup/__init__.py +0 -25
  416. package/latticeai/setup/auto_setup.py +0 -846
  417. package/latticeai/setup/demo_corpus.py +0 -98
  418. package/latticeai/setup/wizard/__init__.py +0 -126
  419. package/latticeai/setup/wizard/catalog.py +0 -175
  420. package/latticeai/setup/wizard/detect.py +0 -302
  421. package/latticeai/setup/wizard/install.py +0 -348
  422. package/latticeai/setup/wizard/paths.py +0 -165
  423. package/latticeai/setup/wizard/plans.py +0 -74
  424. package/latticeai/setup/wizard/recommend.py +0 -320
  425. package/scripts/bench_agent_smoke.py +0 -409
  426. package/scripts/bench_models.py +0 -540
  427. package/scripts/bench_vector_index.py +0 -295
  428. package/scripts/funnel_soft_gate.py +0 -192
  429. package/scripts/generate_agent_loop_fixtures.py +0 -994
  430. package/scripts/generate_rust_parity_fixtures.py +0 -908
  431. package/scripts/migrate_brain_storage.py +0 -57
  432. package/scripts/parity_fixture_corpus_context.py +0 -162
  433. package/scripts/parity_fixture_corpus_docgen.py +0 -341
  434. package/scripts/profile_kg.py +0 -355
  435. package/server.py +0 -30
  436. package/static/app/assets/arrow-left-kfsrk0mv.js +0 -1
  437. package/static/app/assets/circle-check-qqLug9nU.js +0 -1
  438. package/static/app/assets/index-DxmOfNRi.css +0 -2
  439. package/static/app/assets/search-BcHqkjoy.js +0 -1
@@ -1,307 +0,0 @@
1
- """UX funnel metrics — lightweight runtime counters (backlog #16, review §4.3).
2
-
3
- Tracks the product's core value funnel with honest, local-only counters:
4
-
5
- * ``file_requests`` — chat requests recognized as file intents;
6
- * ``real_file_delivered`` — file intents that produced actual artifacts;
7
- * ``code_only_responses`` — file intents that finished with only a
8
- code/prose answer (the failure mode the >95% real-file goal watches);
9
- * ``agent_runs`` — completed chat agent runs (rate denominator);
10
- * ``needs_review_runs`` — agent runs that ended in ``NEEDS_REVIEW``;
11
- * ``ingest_completions`` — successful ingestion pipeline completions;
12
- * ``recall_successes`` — chat turns whose context was grounded in at
13
- least one Brain node;
14
- * ``approval_pauses`` — agent/workflow runs paused for human approval;
15
- * ``approval_resumes`` — paused runs a human explicitly resumed
16
- (approved), the ``approval_resume_rate`` numerator.
17
-
18
- TTFV ("time to first value") derives from two first-occurrence timestamps:
19
- the first successful ingest and the first grounded recall/answer.
20
-
21
- Design constraints (deliberate):
22
-
23
- * **Cheap.** One JSON file under the data dir, atomic replace on write, a
24
- single ``threading.Lock`` — no background threads, no new dependencies.
25
- * **Never breaks the product.** Every public method swallows I/O errors;
26
- metrics are advisory observability, not a gate.
27
- """
28
-
29
- from __future__ import annotations
30
-
31
- import json
32
- import logging
33
- import os
34
- import tempfile
35
- import threading
36
- from datetime import datetime, timezone
37
- from pathlib import Path
38
- from typing import Any, Dict, Optional
39
-
40
- from latticeai.core.quiet import quiet
41
-
42
- LOGGER = logging.getLogger(__name__)
43
-
44
- COUNTER_NAMES = (
45
- "file_requests",
46
- "real_file_delivered",
47
- "code_only_responses",
48
- "agent_runs",
49
- "needs_review_runs",
50
- "ingest_completions",
51
- "recall_successes",
52
- "approval_pauses",
53
- "approval_resumes",
54
- )
55
-
56
- _FIRST_NAMES = ("first_ingest_at", "first_value_at")
57
-
58
-
59
- def _utc_now_iso() -> str:
60
- return datetime.now(timezone.utc).isoformat(timespec="seconds")
61
-
62
-
63
- def _parse_iso(value: Any) -> Optional[datetime]:
64
- if not value:
65
- return None
66
- try:
67
- parsed = datetime.fromisoformat(str(value).replace("Z", "+00:00"))
68
- except ValueError:
69
- return None
70
- if parsed.tzinfo is None:
71
- parsed = parsed.replace(tzinfo=timezone.utc)
72
- return parsed
73
-
74
-
75
- def _rate(numerator: int, denominator: int) -> Optional[float]:
76
- """Honest rate: ``None`` (not 0.0) when there is no denominator yet."""
77
- if denominator <= 0:
78
- return None
79
- return round(numerator / denominator, 4)
80
-
81
-
82
- class FunnelMetricsService:
83
- """Thread-safe, JSON-persisted funnel counters."""
84
-
85
- def __init__(self, path: Any) -> None:
86
- self._path = Path(path)
87
- self._lock = threading.Lock()
88
- self._state: Dict[str, Any] = self._load()
89
-
90
- # ── persistence ──────────────────────────────────────────────────────
91
-
92
- def _load(self) -> Dict[str, Any]:
93
- state: Dict[str, Any] = {name: 0 for name in COUNTER_NAMES}
94
- for name in _FIRST_NAMES:
95
- state[name] = None
96
- try:
97
- raw = json.loads(self._path.read_text(encoding="utf-8"))
98
- except FileNotFoundError:
99
- return state
100
- except Exception as exc: # noqa: BLE001 — corrupt metrics never break startup
101
- LOGGER.warning("funnel metrics load failed (%s); starting fresh", exc)
102
- return state
103
- if isinstance(raw, dict):
104
- for name in COUNTER_NAMES:
105
- try:
106
- state[name] = max(0, int(raw.get(name) or 0))
107
- except (TypeError, ValueError):
108
- state[name] = 0
109
- for name in _FIRST_NAMES:
110
- value = raw.get(name)
111
- state[name] = str(value) if value else None
112
- return state
113
-
114
- def _save_locked(self) -> None:
115
- try:
116
- self._path.parent.mkdir(parents=True, exist_ok=True)
117
- fd, tmp_name = tempfile.mkstemp(
118
- prefix=self._path.name, dir=str(self._path.parent)
119
- )
120
- try:
121
- with os.fdopen(fd, "w", encoding="utf-8") as handle:
122
- json.dump(self._state, handle, ensure_ascii=False, indent=2)
123
- os.replace(tmp_name, self._path)
124
- finally:
125
- if os.path.exists(tmp_name):
126
- try:
127
- os.unlink(tmp_name)
128
- except OSError:
129
- quiet()
130
- except Exception as exc: # noqa: BLE001 — metrics persistence is best-effort
131
- LOGGER.warning("funnel metrics save failed: %s", exc)
132
-
133
- # ── mutation ─────────────────────────────────────────────────────────
134
-
135
- def increment(self, name: str, by: int = 1) -> None:
136
- """Increment a known counter; unknown names are ignored (logged)."""
137
- if name not in COUNTER_NAMES:
138
- LOGGER.warning("funnel metrics: unknown counter %r ignored", name)
139
- return
140
- try:
141
- step = int(by)
142
- except (TypeError, ValueError):
143
- step = 1
144
- if step <= 0:
145
- return
146
- with self._lock:
147
- self._state[name] = int(self._state.get(name) or 0) + step
148
- self._save_locked()
149
-
150
- def _mark_first_locked(self, name: str) -> None:
151
- if not self._state.get(name):
152
- self._state[name] = _utc_now_iso()
153
-
154
- def record_ingest(self, *, duplicate: bool = False) -> None:
155
- """A successful ingestion completed; the first one starts the TTFV clock."""
156
- with self._lock:
157
- self._state["ingest_completions"] = (
158
- int(self._state.get("ingest_completions") or 0) + 1
159
- )
160
- self._mark_first_locked("first_ingest_at")
161
- self._save_locked()
162
-
163
- def record_recall_success(self) -> None:
164
- """A chat answer was grounded in the Brain; the first one ends TTFV."""
165
- with self._lock:
166
- self._state["recall_successes"] = (
167
- int(self._state.get("recall_successes") or 0) + 1
168
- )
169
- # First value only counts after knowledge actually entered the Brain.
170
- if self._state.get("first_ingest_at"):
171
- self._mark_first_locked("first_value_at")
172
- self._save_locked()
173
-
174
- # ── reads ────────────────────────────────────────────────────────────
175
-
176
- def ttfv_seconds(self) -> Optional[float]:
177
- with self._lock:
178
- first_ingest = _parse_iso(self._state.get("first_ingest_at"))
179
- first_value = _parse_iso(self._state.get("first_value_at"))
180
- if first_ingest is None or first_value is None:
181
- return None
182
- delta = (first_value - first_ingest).total_seconds()
183
- return round(delta, 1) if delta >= 0 else None
184
-
185
- def snapshot(self) -> Dict[str, Any]:
186
- """Counters + derived rates + actionable alerts for the admin surface."""
187
- with self._lock:
188
- counters = {name: int(self._state.get(name) or 0) for name in COUNTER_NAMES}
189
- firsts = {name: self._state.get(name) for name in _FIRST_NAMES}
190
- rates = {
191
- "real_file_rate": _rate(
192
- counters["real_file_delivered"], counters["file_requests"]
193
- ),
194
- "code_only_rate": _rate(
195
- counters["code_only_responses"], counters["file_requests"]
196
- ),
197
- "needs_review_rate": _rate(
198
- counters["needs_review_runs"], counters["agent_runs"]
199
- ),
200
- "approval_resume_rate": _rate(
201
- counters["approval_resumes"], counters["approval_pauses"]
202
- ),
203
- }
204
- return {
205
- "counters": counters,
206
- "firsts": firsts,
207
- "rates": rates,
208
- "alerts": funnel_alerts(counters, rates),
209
- "ttfv_seconds": self.ttfv_seconds(),
210
- "generated_at": _utc_now_iso(),
211
- }
212
-
213
-
214
- # ── alerts (review 2026-07-27 P2 #10) ────────────────────────────────────────
215
- # The funnel already measured the right things; nothing turned a bad number
216
- # into a decision, so a regression was only visible to whoever opened the
217
- # admin page. These thresholds convert rates into named, actionable signals.
218
- #
219
- # Minimum samples per rule exist so a single unlucky run never raises an
220
- # alarm — an alert with n=1 is noise, and noisy alerts get ignored.
221
-
222
- REAL_FILE_RATE_FLOOR = 0.95
223
- CODE_ONLY_RATE_CEILING = 0.05
224
- NEEDS_REVIEW_RATE_CEILING = 0.25
225
- APPROVAL_RESUME_RATE_FLOOR = 0.5
226
- MIN_SAMPLES = 10
227
-
228
-
229
- def _alert(
230
- key: str, severity: str, ko: str, en: str, **detail: Any
231
- ) -> Dict[str, Any]:
232
- return {"key": key, "severity": severity, "ko": ko, "en": en, **detail}
233
-
234
-
235
- def funnel_alerts(
236
- counters: Dict[str, int], rates: Dict[str, Optional[float]]
237
- ) -> list:
238
- """Turn funnel rates into named signals a person can act on.
239
-
240
- Pure function of the snapshot — no I/O, no clock — so the thresholds are
241
- testable and the same numbers always produce the same alerts. Rules stay
242
- silent below :data:`MIN_SAMPLES`: an alert nobody can trust is worse than
243
- no alert.
244
- """
245
- alerts: list = []
246
- file_requests = int(counters.get("file_requests") or 0)
247
- agent_runs = int(counters.get("agent_runs") or 0)
248
- approval_pauses = int(counters.get("approval_pauses") or 0)
249
-
250
- real_file_rate = rates.get("real_file_rate")
251
- if file_requests >= MIN_SAMPLES and real_file_rate is not None:
252
- if real_file_rate < REAL_FILE_RATE_FLOOR:
253
- alerts.append(_alert(
254
- "real_file_rate_low", "warning",
255
- f"파일 요청 중 실제 파일이 나온 비율이 {real_file_rate:.0%}입니다 "
256
- f"(목표 {REAL_FILE_RATE_FLOOR:.0%}). 파일 생성 파이프라인을 확인하세요.",
257
- f"Only {real_file_rate:.0%} of file requests produced a real file "
258
- f"(target {REAL_FILE_RATE_FLOOR:.0%}). Check the file-generation pipeline.",
259
- value=real_file_rate, threshold=REAL_FILE_RATE_FLOOR, samples=file_requests,
260
- ))
261
-
262
- code_only_rate = rates.get("code_only_rate")
263
- if file_requests >= MIN_SAMPLES and code_only_rate is not None:
264
- if code_only_rate > CODE_ONLY_RATE_CEILING:
265
- alerts.append(_alert(
266
- "code_only_rate_high", "warning",
267
- f"파일을 요청했는데 코드/설명만 돌아온 비율이 {code_only_rate:.0%}입니다.",
268
- f"{code_only_rate:.0%} of file requests came back as code or prose only.",
269
- value=code_only_rate, threshold=CODE_ONLY_RATE_CEILING, samples=file_requests,
270
- ))
271
-
272
- needs_review_rate = rates.get("needs_review_rate")
273
- if agent_runs >= MIN_SAMPLES and needs_review_rate is not None:
274
- if needs_review_rate > NEEDS_REVIEW_RATE_CEILING:
275
- alerts.append(_alert(
276
- "needs_review_rate_high", "warning",
277
- f"에이전트 실행의 {needs_review_rate:.0%}가 '검토 필요'로 끝났습니다. "
278
- "더 큰 모델을 쓰거나 요청을 작게 나누세요.",
279
- f"{needs_review_rate:.0%} of agent runs ended as NEEDS_REVIEW. "
280
- "Use a larger model or split requests into smaller steps.",
281
- value=needs_review_rate, threshold=NEEDS_REVIEW_RATE_CEILING, samples=agent_runs,
282
- ))
283
-
284
- resume_rate = rates.get("approval_resume_rate")
285
- if approval_pauses >= MIN_SAMPLES and resume_rate is not None:
286
- if resume_rate < APPROVAL_RESUME_RATE_FLOOR:
287
- alerts.append(_alert(
288
- "approval_resume_rate_low", "info",
289
- f"승인 대기 중 실제로 이어서 실행된 비율이 {resume_rate:.0%}입니다. "
290
- "승인 카드가 잘 보이는지 확인하세요.",
291
- f"Only {resume_rate:.0%} of paused runs were resumed. "
292
- "Check that the approval card is actually reaching users.",
293
- value=resume_rate, threshold=APPROVAL_RESUME_RATE_FLOOR, samples=approval_pauses,
294
- ))
295
-
296
- if int(counters.get("ingest_completions") or 0) > 0 and not counters.get("recall_successes"):
297
- alerts.append(_alert(
298
- "no_grounded_recall", "warning",
299
- "자료는 들어왔지만 근거 있는 회상이 아직 한 번도 없었습니다. 검색/인덱싱을 확인하세요.",
300
- "Content was ingested but no answer has ever been grounded in it yet — "
301
- "check retrieval and indexing.",
302
- samples=int(counters.get("ingest_completions") or 0),
303
- ))
304
- return alerts
305
-
306
-
307
- __all__ = ["FunnelMetricsService", "COUNTER_NAMES", "funnel_alerts"]
@@ -1,316 +0,0 @@
1
- """Hybrid chat turn: minimal KG context → cloud stream → local KG expansion.
2
-
3
- Phase 1–2 entry point used by the chat path when NetworkBoundaryMode is
4
- CLOUD_ALLOWED. Local-only sessions never enter this module's cloud path.
5
-
6
- Both turn functions take the Review Center sink and the hybrid policy's
7
- ``auto_commit`` decision as arguments rather than reaching for them: the
8
- caller that knows *whose* turn this is is the only one that can resolve a
9
- per-user policy, and a service that reads a process singleton cannot be
10
- tested against both branches. Defaults are the safe ones — no sink, no
11
- auto-commit — so a headless caller stages nothing rather than writing.
12
- """
13
-
14
- from __future__ import annotations
15
-
16
- import logging
17
- from typing import Any, AsyncIterator, Dict, Optional
18
-
19
- from latticeai.core.network_boundary import (
20
- NetworkBoundaryMode,
21
- normalize_network_mode,
22
- )
23
- from latticeai.core.sse import sse_frame
24
- from latticeai.services.cloud_egress_audit import record_cloud_egress
25
- from latticeai.services.cloud_extraction import plan_kg_expansion_rich
26
- from latticeai.services.cloud_streaming import (
27
- CloudResponseIngestor,
28
- CloudStreamingBridge,
29
- CloudTurnResult,
30
- )
31
- from latticeai.services.cloud_token_guard import budget_for
32
- from latticeai.services.hybrid_context import MinimalContext, build_minimal_context
33
- from latticeai.services.openai_compatible_adapter import OpenAICompatibleAdapter
34
-
35
- logger = logging.getLogger(__name__)
36
-
37
-
38
- def _sse(data: Dict[str, Any]) -> str:
39
- return sse_frame(None, data)
40
-
41
-
42
- def _scope_key(user_email: Optional[str], workspace_id: Optional[str]) -> str:
43
- return f"{user_email or 'anon'}|{workspace_id or 'global'}"
44
-
45
-
46
- def _ingest_cloud_expansion(
47
- result: CloudTurnResult,
48
- *,
49
- knowledge_graph: Any,
50
- review_queue: Any,
51
- auto_commit: bool,
52
- user_email: Optional[str],
53
- workspace_id: Optional[str],
54
- ) -> Dict[str, Any]:
55
- """Stage what the cloud answer taught the Brain (v11.2.0 wiring).
56
-
57
- ``plan_kg_expansion_rich`` builds every plan with ``auto_commit=False``
58
- because extraction has no idea what the user consented to; the policy dial
59
- does, and this is where the two meet. With the sink bound the plan lands in
60
- the Review Center as a ``change_proposal``, which is what makes
61
- cloud-derived memory growth a thing the user approves rather than a thing
62
- that happens to them.
63
- """
64
- plan = plan_kg_expansion_rich(result)
65
- plan.auto_commit = bool(auto_commit)
66
- ingestor = CloudResponseIngestor(
67
- store=knowledge_graph,
68
- review_queue=review_queue,
69
- user_email=user_email,
70
- workspace_id=workspace_id,
71
- )
72
- return ingestor.ingest(plan)
73
-
74
-
75
- async def run_hybrid_cloud_turn(
76
- *,
77
- user_message: str,
78
- knowledge_graph: Any,
79
- mode: NetworkBoundaryMode | str,
80
- workspace_id: Optional[str] = None,
81
- user_email: Optional[str] = None,
82
- model: Optional[str] = None,
83
- top_k: int = 6,
84
- adapter: Optional[Any] = None,
85
- review_queue: Any = None,
86
- auto_commit: bool = False,
87
- ) -> CloudTurnResult:
88
- """Non-streaming helper: full answer + expansion plan."""
89
- mode = normalize_network_mode(mode)
90
- if mode != NetworkBoundaryMode.CLOUD_ALLOWED:
91
- raise PermissionError(
92
- f"hybrid cloud turn refused under NetworkBoundaryMode={mode.value!r}"
93
- )
94
-
95
- minimal = build_minimal_context(
96
- user_message,
97
- store=knowledge_graph,
98
- mode=mode,
99
- top_k=top_k,
100
- allowed_workspaces={workspace_id} if workspace_id else None,
101
- )
102
- budget = budget_for(_scope_key(user_email, workspace_id))
103
- refusal = budget.check_turn(minimal.token_estimate)
104
- if refusal:
105
- record_cloud_egress(
106
- node_ids=minimal.node_ids, token_estimate=minimal.token_estimate,
107
- mode=mode.value, provider="(refused)", model=model,
108
- user_email=user_email, workspace_id=workspace_id,
109
- outcome="refused_token_guard", detail=refusal,
110
- )
111
- raise PermissionError(f"cloud token guard: {refusal}")
112
-
113
- chosen_adapter = adapter or OpenAICompatibleAdapter()
114
- record_cloud_egress(
115
- node_ids=minimal.node_ids, token_estimate=minimal.token_estimate,
116
- mode=mode.value, provider=getattr(chosen_adapter, "name", type(chosen_adapter).__name__),
117
- model=model, user_email=user_email, workspace_id=workspace_id,
118
- )
119
- bridge = CloudStreamingBridge(adapter=chosen_adapter)
120
- result = await bridge.run_turn(
121
- user_message=user_message,
122
- minimal=minimal,
123
- mode=mode,
124
- model=model,
125
- )
126
- ingest_status = _ingest_cloud_expansion(
127
- result,
128
- knowledge_graph=knowledge_graph,
129
- review_queue=review_queue,
130
- auto_commit=auto_commit,
131
- user_email=user_email,
132
- workspace_id=workspace_id,
133
- )
134
- used = minimal.token_estimate + max(1, len(result.answer_text) // 4)
135
- budget.record(used)
136
- result.usage = {
137
- **(result.usage or {}),
138
- "minimal_nodes": len(minimal.node_ids),
139
- "token_estimate": minimal.token_estimate,
140
- "context_quality": minimal.quality,
141
- "kg_expansion": ingest_status,
142
- "token_budget": budget.snapshot(),
143
- }
144
- return result
145
-
146
-
147
- async def stream_hybrid_cloud_turn(
148
- *,
149
- user_message: str,
150
- knowledge_graph: Any,
151
- mode: NetworkBoundaryMode | str,
152
- workspace_id: Optional[str] = None,
153
- user_email: Optional[str] = None,
154
- model: Optional[str] = None,
155
- top_k: int = 6,
156
- adapter: Optional[Any] = None,
157
- chat_service: Any = None,
158
- history_meta: Optional[Dict[str, Any]] = None,
159
- history_user: Optional[Dict[str, Any]] = None,
160
- notify: Any = None,
161
- source: Optional[str] = None,
162
- review_queue: Any = None,
163
- auto_commit: bool = False,
164
- ) -> AsyncIterator[str]:
165
- """SSE generator for a hybrid cloud turn (Phase 2 chat path).
166
-
167
- Events:
168
- * ``hybrid_context`` — which local nodes were selected
169
- * ``token`` / classic ``chunk`` — streamed text
170
- * ``hybrid_done`` — final answer + KG expansion status
171
- * ``error`` — honest failure
172
- """
173
- mode = normalize_network_mode(mode)
174
- if mode != NetworkBoundaryMode.CLOUD_ALLOWED:
175
- yield _sse(
176
- {
177
- "type": "error",
178
- "detail": f"NetworkBoundaryMode is {mode.value!r}; cloud path disabled",
179
- }
180
- )
181
- yield "data: [DONE]\n\n"
182
- return
183
-
184
- minimal = build_minimal_context(
185
- user_message,
186
- store=knowledge_graph,
187
- mode=mode,
188
- top_k=top_k,
189
- allowed_workspaces={workspace_id} if workspace_id else None,
190
- )
191
- budget = budget_for(_scope_key(user_email, workspace_id))
192
- refusal = budget.check_turn(minimal.token_estimate)
193
- if refusal:
194
- # A refusal is auditable too: "nothing left the machine, and here is why".
195
- record_cloud_egress(
196
- node_ids=minimal.node_ids, token_estimate=minimal.token_estimate,
197
- mode=mode.value, provider="(refused)", model=model,
198
- user_email=user_email, workspace_id=workspace_id,
199
- outcome="refused_token_guard", detail=refusal,
200
- )
201
- yield _sse({"type": "error", "detail": f"cloud token guard: {refusal}"})
202
- yield "data: [DONE]\n\n"
203
- return
204
-
205
- yield _sse(
206
- {
207
- "type": "hybrid_context",
208
- "node_ids": minimal.node_ids,
209
- "keywords": minimal.keywords,
210
- "token_estimate": minimal.token_estimate,
211
- "quality": minimal.quality,
212
- "titles": [str(n.get("title") or n.get("id") or "") for n in minimal.nodes],
213
- "token_budget": budget.snapshot(),
214
- }
215
- )
216
-
217
- chosen_adapter = adapter or OpenAICompatibleAdapter()
218
- bridge = CloudStreamingBridge(adapter=chosen_adapter)
219
-
220
- # Recorded before the call, not after: if the provider hangs or the process
221
- # dies mid-stream, the record of what was about to leave must already exist.
222
- record_cloud_egress(
223
- node_ids=minimal.node_ids, token_estimate=minimal.token_estimate,
224
- mode=mode.value, provider=getattr(chosen_adapter, "name", type(chosen_adapter).__name__),
225
- model=model, user_email=user_email, workspace_id=workspace_id,
226
- )
227
-
228
- try:
229
- chunks: list[str] = []
230
- if chosen_adapter is not None and hasattr(chosen_adapter, "stream"):
231
- system = (
232
- "You are assisting a user whose private Knowledge Graph lives on their machine. "
233
- "Use only the provided context. If the context is insufficient, say so honestly."
234
- )
235
- async for piece in chosen_adapter.stream(
236
- system=system,
237
- user=user_message,
238
- context=minimal.compact_text,
239
- model=model,
240
- ):
241
- chunks.append(piece)
242
- # dual shape: hybrid token + classic chunk for existing clients
243
- yield _sse({"type": "token", "text": piece, "chunk": piece, "model": model})
244
- answer = "".join(chunks)
245
- result = CloudTurnResult(
246
- user_message=user_message,
247
- answer_text=answer,
248
- sent_node_ids=list(minimal.node_ids),
249
- provider=getattr(chosen_adapter, "provider_name", "cloud"),
250
- model=str(model or getattr(chosen_adapter, "default_model", "")),
251
- )
252
- else:
253
- result = await bridge.run_turn(
254
- user_message=user_message,
255
- minimal=minimal,
256
- mode=mode,
257
- model=model,
258
- )
259
- yield _sse(
260
- {
261
- "type": "token",
262
- "text": result.answer_text,
263
- "chunk": result.answer_text,
264
- "model": model,
265
- }
266
- )
267
-
268
- ingest_status = _ingest_cloud_expansion(
269
- result,
270
- knowledge_graph=knowledge_graph,
271
- review_queue=review_queue,
272
- auto_commit=auto_commit,
273
- user_email=user_email,
274
- workspace_id=workspace_id,
275
- )
276
- used = minimal.token_estimate + max(1, len(result.answer_text) // 4)
277
- budget.record(used)
278
-
279
- if chat_service is not None:
280
- try:
281
- await chat_service.persist_entry(
282
- "assistant",
283
- result.answer_text,
284
- history_meta=history_meta or {},
285
- history_user=history_user or {},
286
- )
287
- if notify is not None:
288
- notify("assistant", result.answer_text, source)
289
- except Exception as exc: # noqa: BLE001
290
- logger.warning("hybrid chat persistence failed: %s", exc)
291
-
292
- yield _sse(
293
- {
294
- "type": "hybrid_done",
295
- "chunk": "",
296
- "answer": result.answer_text,
297
- "sent_node_ids": result.sent_node_ids,
298
- "provider": result.provider,
299
- "model": result.model,
300
- "kg_expansion": ingest_status,
301
- "token_estimate": minimal.token_estimate,
302
- "token_budget": budget.snapshot(),
303
- }
304
- )
305
- yield "data: [DONE]\n\n"
306
- except Exception as exc: # noqa: BLE001 — surface honest error to client
307
- logger.warning("hybrid cloud turn failed: %s", exc)
308
- yield _sse({"type": "error", "detail": str(exc), "error": str(exc)})
309
- yield "data: [DONE]\n\n"
310
-
311
-
312
- __all__ = [
313
- "run_hybrid_cloud_turn",
314
- "stream_hybrid_cloud_turn",
315
- "MinimalContext",
316
- ]