ltcai 11.5.2 → 11.7.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 (443) hide show
  1. package/README.md +93 -148
  2. package/bin/ltcai.js +234 -24
  3. package/docs/CHANGELOG.md +119 -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 +54 -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-BPcVAbOL.js} +1 -1
  96. package/static/app/assets/AdminConsole-Bw1ATQL0.js +1 -0
  97. package/static/app/assets/{Brain-3VCSHFcn.js → Brain-CT92Kos0.js} +2 -2
  98. package/static/app/assets/{BrainHome-Qm8eaztx.js → BrainHome-CFBkt1K_.js} +1 -1
  99. package/static/app/assets/{BrainSignals-DS9BtKOW.js → BrainSignals-ReLWF2H8.js} +1 -1
  100. package/static/app/assets/Capture-BsTokYkk.js +1 -0
  101. package/static/app/assets/{Chronicle-BGvuAchH.js → Chronicle-B6f0T9id.js} +1 -1
  102. package/static/app/assets/{CommandPalette-Bqhm0Urn.js → CommandPalette-CuvjTv1u.js} +1 -1
  103. package/static/app/assets/{Library-BV6NnF0a.js → Library-BGJbG9Hd.js} +1 -1
  104. package/static/app/assets/{LivingBrain-GzenJchP.js → LivingBrain-DGYK_Jsa.js} +1 -1
  105. package/static/app/assets/{ProductFlow-DEP6-vML.js → ProductFlow-DXBC6brE.js} +1 -1
  106. package/static/app/assets/{ReviewCard-CNZ7XjWG.js → ReviewCard-HXRle3qq.js} +2 -2
  107. package/static/app/assets/System-CMHSO9qM.js +1 -0
  108. package/static/app/assets/arrow-left-BfmkskWx.js +1 -0
  109. package/static/app/assets/{bot-B_K1Tdmw.js → bot-Cn8bWRuq.js} +1 -1
  110. package/static/app/assets/{brain-DWyaV1L1.js → brain-CQJberbE.js} +1 -1
  111. package/static/app/assets/{button-aTn4s84A.js → button-Ct9f2_oT.js} +1 -1
  112. package/static/app/assets/circle-check-DruOxB-4.js +1 -0
  113. package/static/app/assets/{circle-pause-xKgeGXkT.js → circle-pause-CmzC_apg.js} +1 -1
  114. package/static/app/assets/{circle-play-DkT6tYPX.js → circle-play-D8mW2aQ7.js} +1 -1
  115. package/static/app/assets/{cpu-85xYObUC.js → cpu-DZcdd0PZ.js} +1 -1
  116. package/static/app/assets/{download-B5Fm7YXo.js → download-bv1KEPGQ.js} +1 -1
  117. package/static/app/assets/{folder-open-kk2Xa52u.js → folder-open-d-Pip5gr.js} +1 -1
  118. package/static/app/assets/{hard-drive-DkA3zBW_.js → hard-drive-D20iavUb.js} +1 -1
  119. package/static/app/assets/index-D9x-kSNy.css +2 -0
  120. package/static/app/assets/{index-BMPdTmlY.js → index-Do83hDzJ.js} +3 -3
  121. package/static/app/assets/{input-B0nRf2jO.js → input-BLXVNmj1.js} +1 -1
  122. package/static/app/assets/{link-2-Dwb4gnTc.js → link-2-BPJOFlAy.js} +1 -1
  123. package/static/app/assets/{permissionCopy-CQDUBrOZ.js → permissionCopy-ChdJd493.js} +1 -1
  124. package/static/app/assets/primitives-Cv5tbZBY.js +1 -0
  125. package/static/app/assets/search-CT9aho2j.js +1 -0
  126. package/static/app/assets/{share-2-BsrxFglO.js → share-2-YNX_NtMU.js} +1 -1
  127. package/static/app/assets/{shield-alert-5BStfp2_.js → shield-alert-DuQ3zrVL.js} +1 -1
  128. package/static/app/assets/{textarea-Cg8IUA-k.js → textarea-DqwLnli4.js} +1 -1
  129. package/static/app/assets/{useFocusTrap-CYKvE46M.js → useFocusTrap-ZVI98jaW.js} +1 -1
  130. package/static/app/assets/{useMutation-CSn9t1op.js → useMutation-CVC4qv_D.js} +1 -1
  131. package/static/app/assets/{useQuery-CY2OI2uy.js → useQuery-C7BeG4HU.js} +1 -1
  132. package/static/app/assets/{utils-Ddol2RWD.js → utils-CiFtIdZq.js} +1 -1
  133. package/static/app/assets/{workspace-BqDwOz_p.js → workspace-DQz9vIId.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/AdminConsole-cf4npybT.js +0 -1
  437. package/static/app/assets/Capture-DiQ219jW.js +0 -1
  438. package/static/app/assets/System-CieofHQa.js +0 -1
  439. package/static/app/assets/arrow-left-kfsrk0mv.js +0 -1
  440. package/static/app/assets/circle-check-qqLug9nU.js +0 -1
  441. package/static/app/assets/index-DxmOfNRi.css +0 -2
  442. package/static/app/assets/primitives-SNp0LRJz.js +0 -1
  443. package/static/app/assets/search-BcHqkjoy.js +0 -1
@@ -1,238 +0,0 @@
1
- """Realtime Collaboration — an in-process pub/sub bus, presence registry, and
2
- activity feed delivered over Server-Sent Events.
3
-
4
- SSE is chosen deliberately: the codebase already streams model output over SSE
5
- (``latticeai.services.model_runtime.sse_event``), it needs no extra dependency,
6
- and it works through the existing single-port local-first deployment. The bus is
7
- in-process (one server, local-first) and fans events out to subscriber queues.
8
-
9
- Integration shape: the Workspace OS store exposes a single ``event_sink`` hook
10
- that fires on every ``record_timeline_event``. Wiring ``RealtimeBus.publish`` as
11
- that sink makes *all* workspace / graph / agent / workflow activity flow into
12
- the realtime feed automatically — no per-call instrumentation, no duplicated
13
- event system.
14
-
15
- Guarantees:
16
-
17
- * **Single-user local mode keeps working.** Publishing with zero subscribers is
18
- a no-op; the feed ring buffer is still maintained so a late subscriber can
19
- catch up.
20
- * **Workspace isolation preserved.** Every event carries ``workspace_id``; a
21
- subscriber only receives events whose workspace is in its allowed scope set
22
- (``None`` scope = personal/local view sees unscoped + personal events).
23
- * **Backpressure-safe.** Per-subscriber queues are bounded; on overflow the
24
- oldest event is dropped rather than blocking the publisher.
25
- """
26
-
27
- from __future__ import annotations
28
-
29
- import asyncio
30
- import json
31
- import threading
32
- from typing import Any, AsyncIterator, Callable, Dict, List, Optional, Set
33
-
34
- from lattice_brain.runtime.contracts import realtime_event_contract
35
- from latticeai.core.quiet import quiet
36
-
37
- from .timeutil import now_iso as _now
38
-
39
- REALTIME_VERSION = "2.2.0"
40
- _FEED_LIMIT = 200
41
- _QUEUE_MAX = 100
42
-
43
-
44
- def sse_format(event: Dict[str, Any]) -> str:
45
- """Encode an event as an SSE ``data:`` frame."""
46
- return f"data: {json.dumps(event, ensure_ascii=False, default=str)}\n\n"
47
-
48
-
49
- class _Subscriber:
50
- __slots__ = ("id", "queue", "workspace_scope", "user", "joined_at", "loop")
51
-
52
- def __init__(self, sub_id: str, workspace_scope: Optional[Set[str]], user: Optional[str]):
53
- self.id = sub_id
54
- self.queue: "asyncio.Queue[Dict[str, Any]]" = asyncio.Queue(maxsize=_QUEUE_MAX)
55
- self.workspace_scope = workspace_scope
56
- self.user = user
57
- self.joined_at = _now()
58
- try:
59
- self.loop: Optional[asyncio.AbstractEventLoop] = asyncio.get_running_loop()
60
- except RuntimeError:
61
- self.loop = None
62
-
63
- def accepts(self, workspace_id: Optional[str]) -> bool:
64
- # Only the explicit no-auth/local ``None`` scope sees unscoped events.
65
- # Any concrete set, including the authenticated fail-closed empty set,
66
- # requires an exact workspace match.
67
- if self.workspace_scope is None:
68
- return True
69
- return workspace_id in self.workspace_scope
70
-
71
-
72
- class RealtimeBus:
73
- """In-process event bus with presence and a recent-activity ring buffer."""
74
-
75
- def __init__(self) -> None:
76
- self._subscribers: Dict[str, _Subscriber] = {}
77
- self._feed: List[Dict[str, Any]] = []
78
- self._presence: Dict[str, Dict[str, Any]] = {}
79
- self._seq = 0
80
- self._lock = threading.RLock()
81
-
82
- # ── publishing ────────────────────────────────────────────────────────
83
-
84
- def publish(self, event: Dict[str, Any]) -> Dict[str, Any]:
85
- """Publish an event to matching subscribers + the activity feed.
86
-
87
- Safe to call from sync code (e.g. the store's timeline hook). Never
88
- raises and never blocks the caller.
89
- """
90
- with self._lock:
91
- self._seq += 1
92
- enriched = {
93
- "seq": self._seq,
94
- "received_at": _now(),
95
- "area": event.get("area", "workspace"),
96
- "event_type": event.get("event_type", "event"),
97
- "workspace_id": event.get("workspace_id"),
98
- "payload": event.get("payload", {}),
99
- **{k: v for k, v in event.items() if k not in {"area", "event_type", "workspace_id", "payload"}},
100
- }
101
- enriched["contract"] = realtime_event_contract(enriched)
102
- self._feed.append(enriched)
103
- if len(self._feed) > _FEED_LIMIT:
104
- self._feed = self._feed[-_FEED_LIMIT:]
105
-
106
- workspace_id = enriched.get("workspace_id")
107
- subscribers = [sub for sub in self._subscribers.values() if sub.accepts(workspace_id)]
108
- for sub in subscribers:
109
- if sub.loop is not None and sub.loop.is_running():
110
- sub.loop.call_soon_threadsafe(self._enqueue, sub, enriched)
111
- else:
112
- self._enqueue(sub, enriched)
113
- return enriched
114
-
115
- @staticmethod
116
- def _enqueue(sub: _Subscriber, event: Dict[str, Any]) -> None:
117
- try:
118
- sub.queue.put_nowait(event)
119
- except asyncio.QueueFull:
120
- try:
121
- sub.queue.get_nowait() # drop oldest
122
- sub.queue.put_nowait(event)
123
- except Exception:
124
- quiet()
125
-
126
- # The store calls ``event_sink(event)`` positionally; expose a stable alias.
127
- def __call__(self, event: Dict[str, Any]) -> Dict[str, Any]:
128
- return self.publish(event)
129
-
130
- # ── subscription ──────────────────────────────────────────────────────
131
-
132
- def add_subscriber(self, sub_id: str, *, workspace_scope: Optional[Set[str]] = None, user: Optional[str] = None) -> _Subscriber:
133
- sub = _Subscriber(sub_id, workspace_scope, user)
134
- with self._lock:
135
- self._subscribers[sub_id] = sub
136
- return sub
137
-
138
- def remove_subscriber(self, sub_id: str) -> None:
139
- with self._lock:
140
- self._subscribers.pop(sub_id, None)
141
-
142
- async def stream(
143
- self,
144
- sub: _Subscriber,
145
- *,
146
- heartbeat: float = 15.0,
147
- refresh_authorization: Optional[Callable[[_Subscriber], bool]] = None,
148
- ) -> AsyncIterator[str]:
149
- """Yield SSE frames for a subscriber until the client disconnects.
150
-
151
- Emits a periodic heartbeat comment so proxies keep the connection open
152
- and single-user local mode never looks "stuck" with no events.
153
- """
154
- # Replay a small tail so a fresh subscriber has immediate context.
155
- if refresh_authorization is not None and not refresh_authorization(sub):
156
- self.remove_subscriber(sub.id)
157
- return
158
- for event in self.recent(limit=10, workspace_scope=sub.workspace_scope):
159
- if refresh_authorization is not None and not refresh_authorization(sub):
160
- self.remove_subscriber(sub.id)
161
- return
162
- if sub.accepts(event.get("workspace_id")):
163
- yield sse_format(event)
164
- try:
165
- while True:
166
- try:
167
- event = await asyncio.wait_for(sub.queue.get(), timeout=heartbeat)
168
- if refresh_authorization is not None and not refresh_authorization(sub):
169
- break
170
- # The event may have been queued under an older membership
171
- # snapshot. Recheck it against the refreshed scope before
172
- # any bytes leave the process.
173
- if sub.accepts(event.get("workspace_id")):
174
- yield sse_format(event)
175
- except asyncio.TimeoutError:
176
- if refresh_authorization is not None and not refresh_authorization(sub):
177
- break
178
- yield ": heartbeat\n\n"
179
- finally:
180
- self.remove_subscriber(sub.id)
181
-
182
- # ── feed + presence ─────────────────────────────────────────────────────
183
-
184
- def recent(self, *, limit: int = 50, workspace_scope: Optional[Set[str]] = None) -> List[Dict[str, Any]]:
185
- with self._lock:
186
- events = list(self._feed)
187
- if workspace_scope is not None:
188
- events = [e for e in events if e.get("workspace_id") in workspace_scope]
189
- return list(reversed(events[-max(1, min(limit, _FEED_LIMIT)):]))
190
-
191
- def join(self, client_id: str, *, user: Optional[str], workspace_id: Optional[str]) -> Dict[str, Any]:
192
- record = {
193
- "client_id": client_id,
194
- "user": user,
195
- "workspace_id": workspace_id,
196
- "joined_at": _now(),
197
- "last_seen": _now(),
198
- }
199
- with self._lock:
200
- existing = self._presence.get(client_id)
201
- if existing is not None and existing.get("user") != user:
202
- raise PermissionError("Presence client belongs to another user.")
203
- self._presence[client_id] = record
204
- self.publish({"area": "presence", "event_type": "join", "workspace_id": workspace_id, "payload": {"user": user, "client_id": client_id}})
205
- return record
206
-
207
- def heartbeat(self, client_id: str) -> Optional[Dict[str, Any]]:
208
- with self._lock:
209
- record = self._presence.get(client_id)
210
- if record:
211
- record["last_seen"] = _now()
212
- return record
213
-
214
- def leave(self, client_id: str, *, user: Optional[str] = None) -> None:
215
- with self._lock:
216
- record = self._presence.get(client_id)
217
- if record is not None and user is not None and record.get("user") != user:
218
- raise PermissionError("Presence client belongs to another user.")
219
- record = self._presence.pop(client_id, None)
220
- if record:
221
- self.publish({"area": "presence", "event_type": "leave", "workspace_id": record.get("workspace_id"), "payload": {"client_id": client_id}})
222
-
223
- def presence(self, *, workspace_scope: Optional[Set[str]] = None) -> List[Dict[str, Any]]:
224
- with self._lock:
225
- records = list(self._presence.values())
226
- if workspace_scope is not None:
227
- records = [r for r in records if r.get("workspace_id") in workspace_scope]
228
- return records
229
-
230
- def stats(self) -> Dict[str, Any]:
231
- with self._lock:
232
- return {
233
- "version": REALTIME_VERSION,
234
- "subscribers": len(self._subscribers),
235
- "presence": len(self._presence),
236
- "feed_size": len(self._feed),
237
- "transport": "sse",
238
- }
@@ -1,426 +0,0 @@
1
- """Plain-language explanation of an agent run's outcome (v9.9.6).
2
-
3
- The loop already records *what* happened — :class:`~latticeai.core.agent_trace.LoopTrace`
4
- counters, the transcript, the terminal state. What it never produced was a
5
- sentence a person can read: why a run ended as ``NEEDS_REVIEW`` rather than
6
- ``DONE``, or how much the model struggled with the tool-call format before it
7
- got there. Weak local models (Gemma-class) routinely need three format
8
- repairs and one correction hint to finish a task that a large model does in
9
- one pass; the counters showed that, the UI did not.
10
-
11
- This module turns the machine-readable signals into one honest, deterministic
12
- summary::
13
-
14
- {"code": "no_evidence",
15
- "headline": {"ko": "...", "en": "..."},
16
- "details": [{"ko": "...", "en": "..."}],
17
- "model_strain": {"level": "moderate", "parse_errors": 2, ...}}
18
-
19
- Rules the rest of the system relies on:
20
-
21
- * **Deterministic.** No model call, no clock, no I/O — the same run always
22
- explains the same way, so tests and the eval harness can assert on it.
23
- * **Honest.** It never upgrades an outcome. A ``NEEDS_REVIEW`` explanation
24
- says the result was not verified; it never reads as a soft success.
25
- * **Advisory.** Building an explanation must never fail a run — callers get a
26
- minimal payload rather than an exception.
27
- """
28
-
29
- from __future__ import annotations
30
-
31
- from typing import Any, Dict, List, Mapping, Optional, Sequence
32
-
33
- from latticeai.core.messages import bilingual as _bilingual
34
-
35
- __all__ = ["explain_run", "STRAIN_LEVELS"]
36
-
37
-
38
- STRAIN_LEVELS = ("none", "light", "moderate", "heavy")
39
-
40
- # Repair names produced by ``extract_action_details`` / the artifact pipeline,
41
- # grouped so the explanation says what the model got wrong, not which internal
42
- # tolerance fired.
43
- _REPAIR_GROUPS: Dict[str, tuple] = {
44
- "format": ("fence", "slice", "think_strip", "trailing_comma", "python_literal"),
45
- "plan": (
46
- "plan_not_object",
47
- "goal_defaulted",
48
- "steps_filtered",
49
- "estimated_steps_invalid",
50
- "manifest_steps",
51
- "manifest_rewrite",
52
- "heuristic_file_step",
53
- ),
54
- "artifact": ("artifact_sanitize", "artifact_repair"),
55
- }
56
-
57
-
58
-
59
- #: Historical module-local name for the shared phrase-pair helper.
60
- _phrase = _bilingual
61
-
62
-
63
- def _int(value: Any) -> int:
64
- try:
65
- return max(0, int(value))
66
- except (TypeError, ValueError):
67
- return 0
68
-
69
-
70
- def _steps(transcript: Any) -> List[Mapping[str, Any]]:
71
- if not isinstance(transcript, Sequence) or isinstance(transcript, (str, bytes)):
72
- return []
73
- return [step for step in transcript if isinstance(step, Mapping)]
74
-
75
-
76
- def _last_verdict(steps: Sequence[Mapping[str, Any]]) -> Optional[Mapping[str, Any]]:
77
- for step in reversed(steps):
78
- if step.get("state") == "VERIFYING":
79
- return step
80
- return None
81
-
82
-
83
- def _repaired_artifacts(steps: Sequence[Mapping[str, Any]]) -> List[str]:
84
- """Paths whose content the artifact pipeline had to repair into a scaffold."""
85
- paths: List[str] = []
86
- for step in steps:
87
- meta = step.get("content_sanitize")
88
- if not isinstance(meta, Mapping) or not meta.get("repaired"):
89
- continue
90
- raw_result = step.get("result")
91
- raw_args = step.get("args")
92
- result: Mapping[str, Any] = raw_result if isinstance(raw_result, Mapping) else {}
93
- args: Mapping[str, Any] = raw_args if isinstance(raw_args, Mapping) else {}
94
- path = result.get("path") or args.get("path")
95
- if path and str(path) not in paths:
96
- paths.append(str(path))
97
- return paths
98
-
99
-
100
- def _blocked_actions(steps: Sequence[Mapping[str, Any]]) -> List[str]:
101
- blocked: List[str] = []
102
- for step in steps:
103
- error = str(step.get("error") or "")
104
- if error.startswith("BLOCKED:") and step.get("action"):
105
- name = str(step["action"])
106
- if name not in blocked:
107
- blocked.append(name)
108
- return blocked
109
-
110
-
111
- def _proposed_count(steps: Sequence[Mapping[str, Any]]) -> int:
112
- return sum(
113
- 1
114
- for step in steps
115
- if isinstance(step.get("result"), Mapping) and step["result"].get("proposed")
116
- )
117
-
118
-
119
- def _repair_totals(loop: Mapping[str, Any]) -> Dict[str, int]:
120
- repairs = loop.get("repairs")
121
- repairs = repairs if isinstance(repairs, Mapping) else {}
122
- totals = {group: 0 for group in _REPAIR_GROUPS}
123
- totals["other"] = 0
124
- for name, count in repairs.items():
125
- amount = _int(count)
126
- for group, members in _REPAIR_GROUPS.items():
127
- if name in members:
128
- totals[group] += amount
129
- break
130
- else:
131
- totals["other"] += amount
132
- return totals
133
-
134
-
135
- def _strain_level(score: int) -> str:
136
- if score <= 0:
137
- return "none"
138
- if score <= 2:
139
- return "light"
140
- if score <= 5:
141
- return "moderate"
142
- return "heavy"
143
-
144
-
145
- def _missing_files(steps: Sequence[Mapping[str, Any]]) -> List[str]:
146
- """Requested files the run never wrote (from the coverage check)."""
147
- for step in reversed(steps):
148
- coverage = step.get("requirement_coverage")
149
- if isinstance(coverage, Mapping):
150
- missing = coverage.get("missing_files")
151
- if isinstance(missing, Sequence) and not isinstance(missing, (str, bytes)):
152
- return [str(path) for path in missing if path]
153
- return []
154
-
155
-
156
- def _outcome(state: str, steps: Sequence[Mapping[str, Any]]) -> str:
157
- """Terminal-state reason code — the *why*, not just the state name."""
158
- verdict_step = _last_verdict(steps)
159
- if state == "DONE":
160
- return "done"
161
- if state == "NEEDS_REVIEW":
162
- if _missing_files(steps):
163
- return "missing_files"
164
- if verdict_step is None:
165
- return "needs_review"
166
- if verdict_step.get("verdict") == "UNAVAILABLE":
167
- return "verifier_unavailable"
168
- if verdict_step.get("verdict") == "PASS" and not verdict_step.get("evidence"):
169
- return "no_evidence"
170
- if verdict_step.get("next_state") == "DONE":
171
- return "inconsistent_verdict"
172
- return "needs_review"
173
- if state == "FAILED":
174
- if any(step.get("state") == "ROLLBACK" for step in steps):
175
- return "rolled_back"
176
- for step in steps:
177
- if step.get("state") == "WAITING_APPROVAL" and (
178
- step.get("decision") == "blocked_pending_approval"
179
- ):
180
- return "approval_required"
181
- if verdict_step is not None and verdict_step.get("next_state") == "EXECUTING":
182
- return "retry_budget"
183
- return "failed"
184
- return "unknown"
185
-
186
-
187
- _HEADLINES: Dict[str, Dict[str, str]] = {
188
- "done": _phrase(
189
- "요청한 작업을 끝냈고 검증도 통과했습니다.",
190
- "The task finished and passed verification.",
191
- ),
192
- "verifier_unavailable": _phrase(
193
- "작업은 실행됐지만 검증 모델의 답을 읽지 못해 '완료'로 처리하지 않았습니다.",
194
- "The work ran, but the reviewing model's answer could not be read, so it was not marked complete.",
195
- ),
196
- "no_evidence": _phrase(
197
- "검증자는 통과라고 했지만 실제로 실행된 기록이 없어 '완료'로 처리하지 않았습니다.",
198
- "The reviewer said PASS but there is no record of anything actually running, so it was not marked complete.",
199
- ),
200
- "inconsistent_verdict": _phrase(
201
- "검증 결과가 앞뒤가 맞지 않아 '완료'로 처리하지 않았습니다.",
202
- "The verification verdict contradicted itself, so it was not marked complete.",
203
- ),
204
- "missing_files": _phrase(
205
- "요청한 파일 중 일부가 만들어지지 않아 '완료'로 처리하지 않았습니다.",
206
- "Some requested files were never written, so it was not marked complete.",
207
- ),
208
- "needs_review": _phrase(
209
- "작업은 끝났지만 완료를 확인하지 못했습니다. 결과를 직접 확인해 주세요.",
210
- "The run ended but completion could not be confirmed — please check the result yourself.",
211
- ),
212
- "rolled_back": _phrase(
213
- "실행이 실패해서 바꾼 파일을 되돌렸습니다.",
214
- "Execution failed, so the changed files were rolled back.",
215
- ),
216
- "approval_required": _phrase(
217
- "승인이 필요한 도구가 있어 실행을 시작하지 못했습니다.",
218
- "The run never started because it needed approval for a gated tool.",
219
- ),
220
- "retry_budget": _phrase(
221
- "검증자가 계속 다시 하라고 해서 재시도 한도까지 갔고, 끝내 완료하지 못했습니다.",
222
- "The reviewer kept asking for another attempt until the retry budget ran out.",
223
- ),
224
- "failed": _phrase(
225
- "작업을 끝내지 못했습니다.",
226
- "The task did not complete.",
227
- ),
228
- "unknown": _phrase(
229
- "실행 상태를 확인하지 못했습니다.",
230
- "The run state could not be determined.",
231
- ),
232
- }
233
-
234
-
235
- _STRAIN_PHRASES: Dict[str, Dict[str, str]] = {
236
- "light": _phrase(
237
- "이 모델은 형식을 살짝 헷갈려 했지만 자동으로 정리했습니다.",
238
- "The model slipped on the reply format once or twice; it was cleaned up automatically.",
239
- ),
240
- "moderate": _phrase(
241
- "이 모델은 형식을 자주 틀려서 자동 보정이 여러 번 필요했습니다. 더 큰 모델을 쓰면 결과가 안정적입니다.",
242
- "The model needed several automatic format repairs. A larger model would be steadier.",
243
- ),
244
- "heavy": _phrase(
245
- "이 모델에게는 이 작업이 버거웠습니다 — 형식 오류와 보정이 많았습니다. 더 큰 모델로 다시 시도하는 것을 권합니다.",
246
- "This task strained the model — many format errors and repairs. Consider retrying with a larger model.",
247
- ),
248
- }
249
-
250
-
251
- def explain_run(
252
- *,
253
- state: Any,
254
- loop: Optional[Mapping[str, Any]] = None,
255
- transcript: Any = None,
256
- max_retry: Optional[int] = None,
257
- ) -> Dict[str, Any]:
258
- """Explain one finished agent run in plain language.
259
-
260
- ``state`` is the terminal :class:`~latticeai.core.agent.AgentState` value
261
- (or its ``.value`` string), ``loop`` a :meth:`LoopTrace.summary` payload,
262
- ``transcript`` the run transcript. Every argument is optional-tolerant:
263
- a partial run still produces a usable payload rather than raising.
264
- """
265
- state_name = str(getattr(state, "value", state) or "").upper()
266
- loop = loop if isinstance(loop, Mapping) else {}
267
- steps = _steps(transcript)
268
-
269
- code = _outcome(state_name, steps)
270
- parse_errors = _int(loop.get("parse_errors"))
271
- parse_recovered = _int(loop.get("parse_recovered"))
272
- corrections = _int(loop.get("corrections"))
273
- retries = _int(loop.get("retries"))
274
- repair_totals = _repair_totals(loop)
275
- repair_sum = sum(repair_totals.values())
276
-
277
- strain_score = parse_errors * 2 + corrections + retries + repair_totals["format"]
278
- strain: Dict[str, Any] = {
279
- "level": _strain_level(strain_score),
280
- "score": strain_score,
281
- "parse_errors": parse_errors,
282
- "parse_recovered": parse_recovered,
283
- "corrections": corrections,
284
- "retries": retries,
285
- "repairs": repair_totals,
286
- "repair_total": repair_sum,
287
- }
288
-
289
- details: List[Dict[str, str]] = []
290
- if parse_errors:
291
- details.append(_phrase(
292
- f"모델이 정해진 형식을 {parse_errors}번 벗어났고, 그중 {parse_recovered}번은 자동으로 복구했습니다.",
293
- f"The model broke the required reply format {parse_errors} time(s); "
294
- f"{parse_recovered} of those were recovered automatically.",
295
- ))
296
- if repair_totals["format"]:
297
- details.append(_phrase(
298
- f"모델 응답을 {repair_totals['format']}번 자동으로 다듬어 읽었습니다 (코드블록·따옴표 정리 등).",
299
- f"The model's reply needed {repair_totals['format']} automatic clean-up(s) "
300
- "(code fences, quoting, stray text).",
301
- ))
302
- if repair_totals["plan"]:
303
- details.append(_phrase(
304
- f"계획이 비어 있거나 요청한 파일을 빠뜨려서 {repair_totals['plan']}번 자동으로 보완했습니다.",
305
- f"The plan was empty or missed requested files and was repaired {repair_totals['plan']} time(s).",
306
- ))
307
- repaired_paths = _repaired_artifacts(steps)
308
- if repaired_paths:
309
- details.append(_phrase(
310
- "다음 파일은 모델 출력이 온전하지 않아 기본 뼈대로 대신 저장했습니다 — 내용을 꼭 확인하세요: "
311
- + ", ".join(repaired_paths[:4]),
312
- "These files were saved as a generated scaffold because the model output was "
313
- "not usable — check them: " + ", ".join(repaired_paths[:4]),
314
- ))
315
- if retries:
316
- details.append(_phrase(
317
- f"검증자가 {retries}번 다시 하라고 요청했습니다.",
318
- f"The reviewer asked for another attempt {retries} time(s).",
319
- ))
320
- proposed = _proposed_count(steps)
321
- if proposed:
322
- details.append(_phrase(
323
- f"기존 내용을 바꾸는 작업 {proposed}건은 바로 적용하지 않고 변경 제안으로 저장했습니다. 검토함에서 승인하면 적용됩니다.",
324
- f"{proposed} change(s) to existing content were staged as review proposals "
325
- "instead of applied — approve them in the review center.",
326
- ))
327
- blocked = _blocked_actions(steps)
328
- if blocked:
329
- details.append(_phrase(
330
- "다음 도구는 정책상 막혀서 실행하지 않았습니다: " + ", ".join(blocked[:4]),
331
- "These tools were blocked by policy and did not run: " + ", ".join(blocked[:4]),
332
- ))
333
- if code == "retry_budget" and max_retry:
334
- details.append(_phrase(
335
- f"재시도 한도({max_retry}회)에 도달했습니다.",
336
- f"The retry budget ({max_retry}) was exhausted.",
337
- ))
338
- missing_files = _missing_files(steps)
339
- if missing_files:
340
- details.append(_phrase(
341
- "만들어지지 않은 파일: " + ", ".join(missing_files[:4]),
342
- "Files that were never written: " + ", ".join(missing_files[:4]),
343
- ))
344
- strain_phrase = _STRAIN_PHRASES.get(str(strain["level"]))
345
- if strain_phrase is not None:
346
- details.append(dict(strain_phrase))
347
-
348
- return {
349
- "code": code,
350
- "state": state_name,
351
- "ok": code == "done",
352
- "headline": dict(_HEADLINES.get(code, _HEADLINES["unknown"])),
353
- "details": details,
354
- "model_strain": strain,
355
- # Failure-learning surface (review 루프 §3): a structured "what to do
356
- # differently", carried into the next plan by the project session
357
- # instead of being lost with the run.
358
- "next_step": _next_step(
359
- code, missing_files=missing_files, blocked=blocked, strain=strain
360
- ),
361
- }
362
-
363
-
364
- _NEXT_STEPS: Dict[str, Dict[str, str]] = {
365
- "verifier_unavailable": _phrase(
366
- "검증 모델을 더 큰 모델로 바꾸거나, 결과를 직접 확인한 뒤 다시 실행하세요.",
367
- "Switch the reviewing model to a larger one, or check the result yourself and re-run.",
368
- ),
369
- "no_evidence": _phrase(
370
- "요청을 더 구체적으로 (무엇을 어디에 만들지) 적어 다시 실행하세요.",
371
- "Re-run with a more concrete request — what to build and where.",
372
- ),
373
- "inconsistent_verdict": _phrase(
374
- "결과를 확인한 뒤, 남은 부분만 다시 요청하세요.",
375
- "Check the result, then re-request only what is still missing.",
376
- ),
377
- "approval_required": _phrase(
378
- "승인 흐름으로 다시 실행하거나, 승인이 필요 없는 범위로 요청을 줄이세요.",
379
- "Re-run through the approval flow, or narrow the request to steps that need no approval.",
380
- ),
381
- "rolled_back": _phrase(
382
- "실패 원인을 확인한 뒤, 더 작은 단위로 나눠 다시 요청하세요.",
383
- "Check what failed, then re-request in smaller steps.",
384
- ),
385
- "retry_budget": _phrase(
386
- "요청을 더 작은 단계로 나누거나 더 큰 모델로 다시 시도하세요.",
387
- "Split the request into smaller steps, or retry with a larger model.",
388
- ),
389
- }
390
-
391
-
392
- def _next_step(
393
- code: str,
394
- *,
395
- missing_files: Sequence[str],
396
- blocked: Sequence[str],
397
- strain: Mapping[str, Any],
398
- ) -> Optional[Dict[str, str]]:
399
- """One concrete "do this next", or None when the run needs nothing.
400
-
401
- Specific evidence beats a generic template: a named missing file or a
402
- blocked tool says more than "try again".
403
- """
404
- if code == "done" and str(strain.get("level")) in ("none", "light"):
405
- return None
406
- if missing_files:
407
- names = ", ".join(list(missing_files)[:4])
408
- return _phrase(
409
- f"다음 파일만 다시 만들어 달라고 요청하세요: {names}",
410
- f"Ask again for just these files: {names}",
411
- )
412
- if blocked:
413
- names = ", ".join(list(blocked)[:3])
414
- return _phrase(
415
- f"막힌 도구({names}) 없이 할 수 있는 범위로 요청을 바꾸거나, 승인 후 다시 실행하세요.",
416
- f"Rephrase the request to avoid the blocked tools ({names}), or approve them and re-run.",
417
- )
418
- specific = _NEXT_STEPS.get(code)
419
- if specific is not None:
420
- return dict(specific)
421
- if str(strain.get("level")) == "heavy":
422
- return _phrase(
423
- "더 큰 모델로 다시 시도하면 성공률이 올라갑니다.",
424
- "Retrying with a larger model will raise the success rate.",
425
- )
426
- return None