synabun 2.4.1 → 2.4.3

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 (345) hide show
  1. package/CHANGELOG.md +50 -0
  2. package/README.md +1 -1
  3. package/docs/browser-extension-bridge.md +46 -6
  4. package/lib/data-home-files.js +4 -2
  5. package/lib/first-launch-protection.js +8 -2
  6. package/lib/release-npm-ci.mjs +23 -1
  7. package/lib/update-snapshot.js +11 -4
  8. package/mcp-server/dist/http.d.ts.map +1 -1
  9. package/mcp-server/dist/http.js +25 -2
  10. package/mcp-server/dist/http.js.map +1 -1
  11. package/mcp-server/dist/index.d.ts.map +1 -1
  12. package/mcp-server/dist/index.js +62 -17
  13. package/mcp-server/dist/index.js.map +1 -1
  14. package/mcp-server/dist/services/browser-bench.d.ts +22 -22
  15. package/mcp-server/dist/services/memory-maintenance.d.ts +1 -0
  16. package/mcp-server/dist/services/memory-maintenance.d.ts.map +1 -1
  17. package/mcp-server/dist/services/memory-maintenance.js +34 -45
  18. package/mcp-server/dist/services/memory-maintenance.js.map +1 -1
  19. package/mcp-server/dist/services/memory-migration-copy.d.ts +144 -0
  20. package/mcp-server/dist/services/memory-migration-copy.d.ts.map +1 -0
  21. package/mcp-server/dist/services/memory-migration-copy.js +467 -0
  22. package/mcp-server/dist/services/memory-migration-copy.js.map +1 -0
  23. package/mcp-server/dist/services/memory-migration-worker.d.ts +2 -0
  24. package/mcp-server/dist/services/memory-migration-worker.d.ts.map +1 -0
  25. package/mcp-server/dist/services/memory-migration-worker.js +60 -0
  26. package/mcp-server/dist/services/memory-migration-worker.js.map +1 -0
  27. package/mcp-server/dist/services/memory-retrieval.d.ts +4 -0
  28. package/mcp-server/dist/services/memory-retrieval.d.ts.map +1 -1
  29. package/mcp-server/dist/services/memory-retrieval.js +188 -40
  30. package/mcp-server/dist/services/memory-retrieval.js.map +1 -1
  31. package/mcp-server/dist/services/memory-schema.d.ts +58 -2
  32. package/mcp-server/dist/services/memory-schema.d.ts.map +1 -1
  33. package/mcp-server/dist/services/memory-schema.js +190 -13
  34. package/mcp-server/dist/services/memory-schema.js.map +1 -1
  35. package/mcp-server/dist/services/memory-sessions.d.ts +19 -1
  36. package/mcp-server/dist/services/memory-sessions.d.ts.map +1 -1
  37. package/mcp-server/dist/services/memory-sessions.js +56 -20
  38. package/mcp-server/dist/services/memory-sessions.js.map +1 -1
  39. package/mcp-server/dist/services/memory-verification.d.ts.map +1 -1
  40. package/mcp-server/dist/services/memory-verification.js +8 -5
  41. package/mcp-server/dist/services/memory-verification.js.map +1 -1
  42. package/mcp-server/dist/services/neural-interface.d.ts +5 -0
  43. package/mcp-server/dist/services/neural-interface.d.ts.map +1 -1
  44. package/mcp-server/dist/services/neural-interface.js +19 -2
  45. package/mcp-server/dist/services/neural-interface.js.map +1 -1
  46. package/mcp-server/dist/services/retrieval-reader-worker.d.ts +2 -0
  47. package/mcp-server/dist/services/retrieval-reader-worker.d.ts.map +1 -0
  48. package/mcp-server/dist/services/retrieval-reader-worker.js +76 -0
  49. package/mcp-server/dist/services/retrieval-reader-worker.js.map +1 -0
  50. package/mcp-server/dist/services/retrieval-reader.d.ts +38 -0
  51. package/mcp-server/dist/services/retrieval-reader.d.ts.map +1 -0
  52. package/mcp-server/dist/services/retrieval-reader.js +145 -0
  53. package/mcp-server/dist/services/retrieval-reader.js.map +1 -0
  54. package/mcp-server/dist/services/sqlite-write.d.ts +14 -0
  55. package/mcp-server/dist/services/sqlite-write.d.ts.map +1 -0
  56. package/mcp-server/dist/services/sqlite-write.js +94 -0
  57. package/mcp-server/dist/services/sqlite-write.js.map +1 -0
  58. package/mcp-server/dist/services/sqlite.d.ts +39 -0
  59. package/mcp-server/dist/services/sqlite.d.ts.map +1 -1
  60. package/mcp-server/dist/services/sqlite.js +249 -8
  61. package/mcp-server/dist/services/sqlite.js.map +1 -1
  62. package/mcp-server/dist/services/tool-catalog.d.ts +1 -1
  63. package/mcp-server/dist/services/typesafe-config.d.ts +7 -1
  64. package/mcp-server/dist/services/typesafe-config.d.ts.map +1 -1
  65. package/mcp-server/dist/services/typesafe-config.js +32 -10
  66. package/mcp-server/dist/services/typesafe-config.js.map +1 -1
  67. package/mcp-server/dist/services/typesafe.d.ts.map +1 -1
  68. package/mcp-server/dist/services/typesafe.js +9 -7
  69. package/mcp-server/dist/services/typesafe.js.map +1 -1
  70. package/mcp-server/dist/services/vector-cache.d.ts +32 -0
  71. package/mcp-server/dist/services/vector-cache.d.ts.map +1 -1
  72. package/mcp-server/dist/services/vector-cache.js +161 -8
  73. package/mcp-server/dist/services/vector-cache.js.map +1 -1
  74. package/mcp-server/dist/tools/agent-definition.d.ts +2 -2
  75. package/mcp-server/dist/tools/agents.d.ts +11 -7
  76. package/mcp-server/dist/tools/agents.d.ts.map +1 -1
  77. package/mcp-server/dist/tools/agents.js +27 -9
  78. package/mcp-server/dist/tools/agents.js.map +1 -1
  79. package/mcp-server/dist/tools/browser-advanced.d.ts +1 -1
  80. package/mcp-server/dist/tools/browser-advanced.d.ts.map +1 -1
  81. package/mcp-server/dist/tools/browser-advanced.js +10 -3
  82. package/mcp-server/dist/tools/browser-advanced.js.map +1 -1
  83. package/mcp-server/dist/tools/browser-extension-setup.d.ts +5 -0
  84. package/mcp-server/dist/tools/browser-extension-setup.d.ts.map +1 -0
  85. package/mcp-server/dist/tools/browser-extension-setup.js +29 -0
  86. package/mcp-server/dist/tools/browser-extension-setup.js.map +1 -0
  87. package/mcp-server/dist/tools/browser-interact.d.ts.map +1 -1
  88. package/mcp-server/dist/tools/browser-interact.js +6 -1
  89. package/mcp-server/dist/tools/browser-interact.js.map +1 -1
  90. package/mcp-server/dist/tools/fb-groups.d.ts +2 -2
  91. package/mcp-server/dist/tools/skill-tools.d.ts +4 -4
  92. package/mcp-server/dist/tools/tool-groups.d.ts +1 -1
  93. package/mcp-server/package-lock.json +5 -5
  94. package/mcp-server/package.json +1 -1
  95. package/mcp-server/src/http.ts +20 -2
  96. package/mcp-server/src/index.ts +59 -17
  97. package/mcp-server/src/services/memory-maintenance.ts +31 -28
  98. package/mcp-server/src/services/memory-migration-copy.ts +419 -0
  99. package/mcp-server/src/services/memory-migration-worker.ts +55 -0
  100. package/mcp-server/src/services/memory-retrieval.ts +173 -32
  101. package/mcp-server/src/services/memory-schema.ts +194 -12
  102. package/mcp-server/src/services/memory-sessions.ts +54 -21
  103. package/mcp-server/src/services/memory-verification.ts +7 -4
  104. package/mcp-server/src/services/neural-interface.ts +22 -2
  105. package/mcp-server/src/services/retrieval-reader-worker.ts +67 -0
  106. package/mcp-server/src/services/retrieval-reader.ts +131 -0
  107. package/mcp-server/src/services/sqlite-write.ts +60 -0
  108. package/mcp-server/src/services/sqlite.ts +246 -8
  109. package/mcp-server/src/services/typesafe-config.ts +25 -6
  110. package/mcp-server/src/services/typesafe.ts +9 -7
  111. package/mcp-server/src/services/vector-cache.ts +154 -9
  112. package/mcp-server/src/tools/agents.ts +26 -9
  113. package/mcp-server/src/tools/browser-advanced.ts +10 -3
  114. package/mcp-server/src/tools/browser-extension-setup.ts +36 -0
  115. package/mcp-server/src/tools/browser-interact.ts +5 -1
  116. package/neural-interface/i18n/en.json +313 -2
  117. package/neural-interface/i18n/pt-BR.json +321 -10
  118. package/neural-interface/lib/agents/split.js +32 -4
  119. package/neural-interface/lib/assistant-api.js +52 -8
  120. package/neural-interface/lib/assistant-brains/claude.js +2 -0
  121. package/neural-interface/lib/assistant-brains/opencode.js +121 -7
  122. package/neural-interface/lib/assistant-catalog.js +2 -2
  123. package/neural-interface/lib/assistant-config.js +0 -7
  124. package/neural-interface/lib/assistant-dispatch.js +281 -95
  125. package/neural-interface/lib/assistant-envelope.js +40 -0
  126. package/neural-interface/lib/assistant-persona.js +16 -4
  127. package/neural-interface/lib/assistant-pricing.js +65 -14
  128. package/neural-interface/lib/assistant-router.js +131 -47
  129. package/neural-interface/lib/assistant-run-wait.js +45 -28
  130. package/neural-interface/lib/assistant-runtime.js +133 -42
  131. package/neural-interface/lib/backup-contents.js +158 -0
  132. package/neural-interface/lib/backup-crypto-io.js +330 -0
  133. package/neural-interface/lib/backup-crypto-worker.js +130 -0
  134. package/neural-interface/lib/backup-crypto.js +525 -0
  135. package/neural-interface/lib/backup-download.js +268 -0
  136. package/neural-interface/lib/backup-encryption.js +318 -0
  137. package/neural-interface/lib/backup-groups.js +287 -0
  138. package/neural-interface/lib/backup-restore-session.js +176 -0
  139. package/neural-interface/lib/backup-restore-stage.js +60 -0
  140. package/neural-interface/lib/backup-service.js +788 -233
  141. package/neural-interface/lib/backup-zip-reader.js +30 -18
  142. package/neural-interface/lib/backup-zip-writer.js +34 -10
  143. package/neural-interface/lib/browser-extension-adapter.js +89 -15
  144. package/neural-interface/lib/browser-extension-archive.js +149 -0
  145. package/neural-interface/lib/browser-extension-bridge.js +24 -10
  146. package/neural-interface/lib/browser-extension-folder.js +596 -76
  147. package/neural-interface/lib/browser-extension-package.js +200 -0
  148. package/neural-interface/lib/browser-extension-pin.js +84 -0
  149. package/neural-interface/lib/browser-extension-pin.json +33 -0
  150. package/{browser-extension/protocol.js → neural-interface/lib/browser-extension-protocol.js} +91 -6
  151. package/neural-interface/lib/browser-extension-setup.js +105 -18
  152. package/neural-interface/lib/claude-agent-bridge.js +1 -0
  153. package/neural-interface/lib/claude-session-cleanup.js +5 -1
  154. package/neural-interface/lib/cli-install.js +23 -3
  155. package/neural-interface/lib/cli-update-planner.js +171 -9
  156. package/neural-interface/lib/client-diagnostics.js +42 -0
  157. package/neural-interface/lib/confined-fs.js +7 -2
  158. package/neural-interface/lib/coordination/README.md +8 -2
  159. package/neural-interface/lib/coordination/contract.js +161 -0
  160. package/neural-interface/lib/coordination/database.js +999 -0
  161. package/neural-interface/lib/coordination/operations.js +436 -0
  162. package/neural-interface/lib/coordination/service.js +68 -537
  163. package/neural-interface/lib/coordination/storage-worker.js +101 -0
  164. package/neural-interface/lib/coordination/store.js +219 -1111
  165. package/neural-interface/lib/db.js +70 -32
  166. package/neural-interface/lib/health-count.js +37 -0
  167. package/neural-interface/lib/loop-stall.js +139 -0
  168. package/neural-interface/lib/maritaca/client.js +2 -2
  169. package/neural-interface/lib/maritaca/models.js +12 -17
  170. package/neural-interface/lib/maritaca/opencode.js +4 -2
  171. package/neural-interface/lib/memory-api.js +9 -1
  172. package/neural-interface/lib/memory-session-capture.js +42 -10
  173. package/neural-interface/lib/memory-store-gate.js +313 -0
  174. package/neural-interface/lib/memory-store-migrate.js +65 -0
  175. package/neural-interface/lib/memory-timers.js +7 -7
  176. package/neural-interface/lib/native-loop-providers.js +23 -17
  177. package/neural-interface/lib/native-loop-runtime.js +48 -9
  178. package/neural-interface/lib/opencode-build-preflight.js +18 -1
  179. package/neural-interface/lib/opencode-native-boundary.js +69 -8
  180. package/neural-interface/lib/opencode-provider-view.js +14 -3
  181. package/neural-interface/lib/opencode-shell-read.js +107 -0
  182. package/neural-interface/lib/opencode-stop-failures.js +40 -0
  183. package/neural-interface/lib/opencode-turn-release.js +173 -0
  184. package/neural-interface/lib/opencode-v2-client.js +4 -1
  185. package/neural-interface/lib/opencode-v2-ws-requests.js +65 -1
  186. package/neural-interface/lib/opencode2-client.js +343 -7
  187. package/neural-interface/lib/opencode2-translate.js +161 -4
  188. package/neural-interface/lib/recall-impact.js +122 -0
  189. package/neural-interface/lib/scratch-evidence.js +420 -0
  190. package/neural-interface/lib/scratch-process-guard.js +139 -0
  191. package/neural-interface/lib/scratch-references.js +279 -0
  192. package/neural-interface/lib/scratch-retention-core.js +385 -0
  193. package/neural-interface/lib/scratch-retention-worker.js +37 -0
  194. package/neural-interface/lib/scratch-retention.js +151 -0
  195. package/neural-interface/lib/session-cache-builder.js +31 -43
  196. package/neural-interface/lib/session-cache-worker.js +157 -0
  197. package/neural-interface/lib/session-indexer.js +28 -21
  198. package/neural-interface/lib/session-search-index.js +85 -0
  199. package/neural-interface/lib/skills/creation.js +1 -1
  200. package/neural-interface/lib/sqlite-integrity-worker.js +3 -1
  201. package/neural-interface/lib/style-guide/store.js +43 -3
  202. package/neural-interface/lib/system-restore.js +50 -0
  203. package/neural-interface/lib/teams/api.js +15 -6
  204. package/neural-interface/lib/teams/claims.js +67 -31
  205. package/neural-interface/lib/teams/index.js +7 -7
  206. package/neural-interface/lib/teams/integration.js +40 -40
  207. package/neural-interface/lib/teams/landing.js +6 -6
  208. package/neural-interface/lib/teams/recovery.js +24 -23
  209. package/neural-interface/lib/teams/scheduler.js +194 -95
  210. package/neural-interface/lib/teams/state.js +14 -14
  211. package/neural-interface/lib/teams/worktrees.js +27 -27
  212. package/neural-interface/lib/terminal-token-redaction.js +83 -0
  213. package/neural-interface/lib/whatsapp/bridge.js +54 -7
  214. package/neural-interface/lib/worker-confinement.js +47 -2
  215. package/neural-interface/lib/worker-mcp-channel.js +2 -0
  216. package/neural-interface/lib/worker-resume.js +5 -0
  217. package/neural-interface/lib/worker-stop.js +86 -0
  218. package/neural-interface/package-lock.json +5 -5
  219. package/neural-interface/package.json +1 -1
  220. package/neural-interface/public/extension-setup.html +5 -2
  221. package/neural-interface/public/index.html +233 -24
  222. package/neural-interface/public/onboarding.html +259 -34
  223. package/neural-interface/public/shared/agents/studio/ax-library.js +0 -6
  224. package/neural-interface/public/shared/agents/studio/ax-main.js +14 -7
  225. package/neural-interface/public/shared/agy/agy-options.js +11 -0
  226. package/neural-interface/public/shared/agy/agy-panel.js +67 -20
  227. package/neural-interface/public/shared/agy/agy-styles.js +14 -12
  228. package/neural-interface/public/shared/agy/agy-tabs-logic.js +4 -1
  229. package/neural-interface/public/shared/api.js +1 -1
  230. package/neural-interface/public/shared/assistant/asst-api.js +28 -3
  231. package/neural-interface/public/shared/assistant/asst-brain-picker.js +13 -6
  232. package/neural-interface/public/shared/assistant/asst-control.js +2 -0
  233. package/neural-interface/public/shared/assistant/asst-motion-gate.js +78 -4
  234. package/neural-interface/public/shared/assistant/asst-panel.js +87 -3
  235. package/neural-interface/public/shared/assistant/asst-rack-styles.js +27 -0
  236. package/neural-interface/public/shared/assistant/asst-render.js +243 -44
  237. package/neural-interface/public/shared/assistant/asst-route.js +100 -21
  238. package/neural-interface/public/shared/assistant/asst-routes-editor.js +1 -1
  239. package/neural-interface/public/shared/assistant/asst-shell-logic.js +200 -0
  240. package/neural-interface/public/shared/assistant/asst-shell.js +111 -0
  241. package/neural-interface/public/shared/assistant/asst-sidepanel.js +4 -2
  242. package/neural-interface/public/shared/assistant/asst-state.js +11 -0
  243. package/neural-interface/public/shared/assistant/asst-styles.js +11 -23
  244. package/neural-interface/public/shared/assistant/route-identity.js +2 -1
  245. package/neural-interface/public/shared/cdx/cdx-render.js +9 -0
  246. package/neural-interface/public/shared/cdx/cdx-settings.js +3 -1
  247. package/neural-interface/public/shared/cdx/cdx-styles.js +6 -0
  248. package/neural-interface/public/shared/cdx/cdx-tabs.js +54 -9
  249. package/neural-interface/public/shared/client-diagnostics.js +94 -0
  250. package/neural-interface/public/shared/cp/cp-markdown.js +7 -2
  251. package/neural-interface/public/shared/cp/cp-styles.js +1 -1
  252. package/neural-interface/public/shared/effort-i18n.js +118 -0
  253. package/neural-interface/public/shared/extension-setup/es-page.js +10 -4
  254. package/neural-interface/public/shared/extension-setup/es-view.js +25 -10
  255. package/neural-interface/public/shared/html-shell.js +4 -52
  256. package/neural-interface/public/shared/loading-diagnostic-entry.js +64 -0
  257. package/neural-interface/public/shared/memory-store-wait.js +52 -0
  258. package/neural-interface/public/shared/morelogin-profile-field.js +1 -1
  259. package/neural-interface/public/shared/mtc/mtc-logic.js +2 -1
  260. package/neural-interface/public/shared/mtc/mtc-panel.js +25 -3
  261. package/neural-interface/public/shared/mtc/mtc-styles.js +13 -12
  262. package/neural-interface/public/shared/ocp-v2/ocp-v2-childpanel.js +7 -0
  263. package/neural-interface/public/shared/ocp-v2/ocp-v2-events.js +5 -0
  264. package/neural-interface/public/shared/ocp-v2/ocp-v2-location-logic.js +109 -0
  265. package/neural-interface/public/shared/ocp-v2/ocp-v2-manager.js +1 -0
  266. package/neural-interface/public/shared/ocp-v2/ocp-v2-modelpicker.js +8 -1
  267. package/neural-interface/public/shared/ocp-v2/ocp-v2-panel.js +152 -8
  268. package/neural-interface/public/shared/ocp-v2/ocp-v2-rehydrate.js +7 -1
  269. package/neural-interface/public/shared/ocp-v2/ocp-v2-render.js +53 -4
  270. package/neural-interface/public/shared/ocp-v2/ocp-v2-send.js +52 -6
  271. package/neural-interface/public/shared/ocp-v2/ocp-v2-session-actions.js +22 -2
  272. package/neural-interface/public/shared/ocp-v2/ocp-v2-shell-block.js +165 -0
  273. package/neural-interface/public/shared/ocp-v2/ocp-v2-shell-logic.js +346 -0
  274. package/neural-interface/public/shared/ocp-v2/ocp-v2-shell.js +108 -0
  275. package/neural-interface/public/shared/ocp-v2/ocp-v2-state.js +49 -3
  276. package/neural-interface/public/shared/ocp-v2/ocp-v2-styles.js +67 -93
  277. package/neural-interface/public/shared/ocp-v2/ocp-v2-tools-logic.js +20 -5
  278. package/neural-interface/public/shared/ocp-v2/ocp-v2-tools.js +7 -1
  279. package/neural-interface/public/shared/ocp-v2/ocp-v2-variantpicker.js +17 -6
  280. package/neural-interface/public/shared/ocp-v2/ocp-v2-ws.js +7 -2
  281. package/neural-interface/public/shared/output-format.js +294 -0
  282. package/neural-interface/public/shared/provider-icons.js +6 -0
  283. package/neural-interface/public/shared/schedules-view.js +2 -1
  284. package/neural-interface/public/shared/server-presence.js +77 -0
  285. package/neural-interface/public/shared/settings/settings-backup-contents.js +241 -0
  286. package/neural-interface/public/shared/settings/settings-backup-download.js +298 -0
  287. package/neural-interface/public/shared/settings/settings-backup-encryption-pane.js +335 -0
  288. package/neural-interface/public/shared/settings/settings-backup-encryption.js +545 -0
  289. package/neural-interface/public/shared/settings/settings-browser-extension.js +54 -12
  290. package/neural-interface/public/shared/settings/settings-ia.js +1 -1
  291. package/neural-interface/public/shared/shell-stop-view.js +83 -0
  292. package/neural-interface/public/shared/skills/studio/sx-geometry.js +12 -3
  293. package/neural-interface/public/shared/skills/studio/sx-main.js +14 -7
  294. package/neural-interface/public/shared/studio-attention.js +6 -0
  295. package/neural-interface/public/shared/styles.css +341 -437
  296. package/neural-interface/public/shared/tour/tour-actor.js +14 -3
  297. package/neural-interface/public/shared/transcript-rows.js +28 -3
  298. package/neural-interface/public/shared/tray-auto-close.js +49 -6
  299. package/neural-interface/public/shared/ui-agents.js +1 -2
  300. package/neural-interface/public/shared/ui-automation-studio.js +168 -108
  301. package/neural-interface/public/shared/ui-claude-panel.js +62 -65
  302. package/neural-interface/public/shared/ui-loading.js +124 -17
  303. package/neural-interface/public/shared/ui-native-loop-router.js +52 -0
  304. package/neural-interface/public/shared/ui-navbar.js +2 -1
  305. package/neural-interface/public/shared/ui-output.js +533 -0
  306. package/neural-interface/public/shared/ui-schedules-studio.js +165 -128
  307. package/neural-interface/public/shared/ui-scroll-follow.js +101 -6
  308. package/neural-interface/public/shared/ui-sessions.js +2 -2
  309. package/neural-interface/public/shared/ui-settings-entry.js +18 -0
  310. package/neural-interface/public/shared/ui-settings.js +224 -65
  311. package/neural-interface/public/shared/ui-sidepanel-tray.js +3 -2
  312. package/neural-interface/public/shared/ui-tooltip.js +16 -0
  313. package/neural-interface/public/shared/ui-tutorial.js +5 -6
  314. package/neural-interface/public/shared/ui-worker-end.js +27 -8
  315. package/neural-interface/public/shared/worker-end.js +9 -4
  316. package/neural-interface/public/variant/2d/main.js +5 -0
  317. package/neural-interface/public/variant/3d/app.js +10 -0
  318. package/neural-interface/public/variant/3d/main.js +5 -1
  319. package/neural-interface/scripts/scratch-retention.mjs +20 -0
  320. package/neural-interface/server.js +725 -173
  321. package/npm-shrinkwrap.json +5 -5
  322. package/package.json +1 -2
  323. package/scripts/restore-data-home-from-backup.mjs +175 -8
  324. package/setup.js +18 -4
  325. package/browser-extension/content.js +0 -189
  326. package/browser-extension/engine.js +0 -508
  327. package/browser-extension/icons/icon-128.png +0 -0
  328. package/browser-extension/icons/icon-16.png +0 -0
  329. package/browser-extension/icons/icon-32.png +0 -0
  330. package/browser-extension/icons/icon-48.png +0 -0
  331. package/browser-extension/icons/status-off-16.png +0 -0
  332. package/browser-extension/icons/status-off-32.png +0 -0
  333. package/browser-extension/icons/status-off-48.png +0 -0
  334. package/browser-extension/icons/status-on-16.png +0 -0
  335. package/browser-extension/icons/status-on-32.png +0 -0
  336. package/browser-extension/icons/status-on-48.png +0 -0
  337. package/browser-extension/manifest.json +0 -56
  338. package/browser-extension/popup-strings.js +0 -250
  339. package/browser-extension/popup-view.js +0 -151
  340. package/browser-extension/popup.css +0 -166
  341. package/browser-extension/popup.html +0 -108
  342. package/browser-extension/popup.js +0 -359
  343. package/browser-extension/service-worker.js +0 -275
  344. package/browser-extension/setup-content.js +0 -36
  345. package/browser-extension/tokens.css +0 -326
@@ -1,3 +1,4 @@
1
+ import { callerStopReason, mayEndSuspendedRun, pageStopProvenance, stampStopProvenance } from './lib/worker-stop.js';
1
2
  import { readStoredToolListRecord, toolListRecordForUpdate } from './lib/tool-lists.js';
2
3
  import { externalServerInventory, selectExternalServers, externalCatalogReport, mergeExternalAvailability, EXTERNAL_SERVER_LIMITATIONS, scopeOpenCodeServers, retainExternalRefs, writePrivateMcpConfig, redactMcpValues, mcpSecretValues } from './lib/mcp-external-servers.js';
3
4
  import { openCodeWorkerData } from './lib/opencode-worker-data.js';
@@ -28,6 +29,7 @@ import { createPageSession, PAGE_SECRET_PATHS, PAGE_SECRET_REFRESH_PATH, SERVICE
28
29
  import { normalizeViewUrl } from './public/shared/view-variant.js';
29
30
  import { createPeerIdentity, debugClientPolicy, PEER_VERDICT, peerAuthority } from './lib/peer-identity.js';
30
31
  import { createOwnerAuthority, isAgentCall } from './lib/owner-authority.js';
32
+ import { useDefaultJsonParser, parseClientDiagnostics, createClientDiagnostics } from './lib/client-diagnostics.js';
31
33
  import { collectRelayListenerPorts, localProxyPorts } from './lib/worker-relay-ports.js';
32
34
  import { machineNames } from './lib/machine-names.js';
33
35
  import { draftConfinementSupport } from './lib/skills/draft-confinement.js';
@@ -55,7 +57,7 @@ import { describeLocatorMatches, healLocatorByText, validNthMatch, captureTarget
55
57
  import { getInteractiveHints, collectSemanticContext, buildAssist, describeTargetFacts, verifyHealTarget, createAssistContextStore } from './lib/browser-semantic-context.js';
56
58
  import { createBrowserAssistRouter } from './lib/browser-assist-api.js';
57
59
  import { handleReflect as reflectMemory } from '../mcp-server/dist/tools/reflect.js';
58
- import { startMemoryCapture } from './lib/memory-session-capture.js';
60
+ import { startMemoryCapture, stopMemoryCapture } from './lib/memory-session-capture.js';
59
61
  import { createMemoryApi } from './lib/memory-api.js';
60
62
  import { createMemoryMapService, createMemoryMapApi } from './lib/memory-map-api.js';
61
63
  import { createAiSnapshotStore, settleBrowserPage } from './lib/browser-snapshots.js';
@@ -64,8 +66,9 @@ import { attachConsoleBuffer, readConsoleBuffer, parseConsoleSince } from './lib
64
66
  import { resolveBrowserLanguage, validateBrowserLanguageConfig } from './lib/browser-language.js';
65
67
  import { parseScreenshotOptions, captureScreenshot, screenshotPathRefusal, defaultScreenshotPath, writeScreenshotFile } from './lib/browser-screenshot.js';
66
68
  import { openBackgroundPageStrict, backgroundTabsEnabled, newContextWithId, selectedTabReading } from './lib/browser-background-tab.js';
69
+ import { withMemoryWrite } from '../mcp-server/dist/services/sqlite-write.js';
67
70
  import { memoryRevision } from '../mcp-server/dist/services/memory-maintenance.js';
68
- import { startGatedMemoryMaintenance } from './lib/memory-timers.js';
71
+ import { startGatedMemoryMaintenance, stopGatedMemoryMaintenance } from './lib/memory-timers.js';
69
72
  import { createEventLoopMonitor } from './lib/event-loop-monitor.js';
70
73
  import { createRulesetInstaller } from './lib/rulesets/installer.js';
71
74
  import { registerRulesetRoutes, registerLegacyRulesetRoutes } from './lib/rulesets/api.js';
@@ -112,6 +115,9 @@ function handleProcessFailure(label, failure) {
112
115
  console.warn(`[playwright] Ignoring stale lifecycle error (${label}):`, error.message);
113
116
  return;
114
117
  }
118
+ // A tick or background job that met the memory store while it is being upgraded (lib/memory-store-gate.js): that
119
+ // job is skipped and the server stays up.
120
+ if (isMemoryStoreRefusal(error)) { noteMemoryStoreRefusal(label, error); return; }
115
121
  console.error(`${label}:`, failure);
116
122
  process.exit(1);
117
123
  }
@@ -157,13 +163,17 @@ import * as pluginInstaller from './lib/plugin-installer.js';
157
163
  // loopLog here is the wrapper below browserCaller (it never names a log file after a whole MCP session id).
158
164
  import { loopLog as writeLoopLog, loopLogPath, flushLoopLogs } from './lib/loop-logger.js';
159
165
  import {
166
+ brewNeedsRefresh,
160
167
  buildInstallCommand,
161
168
  buildUpdateCommand,
162
169
  isBrewSource,
170
+ OPENCODE_WINGET_SEARCH_ARGS,
163
171
  parseBrewOutdated,
172
+ parseWingetSearchVersion,
164
173
  quoteCommandPath,
165
174
  resolveBrewToken,
166
175
  resolveLatest,
176
+ upstreamVersionSource,
167
177
  } from './lib/cli-update-planner.js';
168
178
  import { createCliResolver, spawnArgsFor } from './lib/cli-resolver.js';
169
179
  import { osPath } from './lib/os-path.js';
@@ -176,25 +186,36 @@ import { createCliPathManager } from './lib/cli-path.js';
176
186
  import { composeTerminalPath, terminalLaunchCommand, terminalArgument } from './lib/terminal-path.js';
177
187
  import {
178
188
  applyBackupRetention,
189
+ assertBackupGroups,
190
+ backupRoots,
179
191
  createVerifiedBackup,
192
+ sweepCrashedBackupArtifacts,
180
193
  getBackupHealth,
181
194
  listBackupSnapshots,
182
195
  loadBackupConfig as loadBackupConfigFile,
196
+ measureBackupContents,
183
197
  nextBackupDueMs,
184
198
  normalizeBackupConfig,
185
199
  saveBackupConfig as saveBackupConfigFile,
186
200
  } from './lib/backup-service.js';
201
+ import { backupDownloadHandlers, createBackupDownloadService } from './lib/backup-download.js';
202
+ import { backupContentsHandlers, createBackupContentsService } from './lib/backup-contents.js';
203
+ import { readManifestGroups } from './lib/backup-groups.js';
204
+ import { isEncryptedBackupFile } from './lib/backup-crypto.js';
205
+ import { backupEncryptionHandlers, createBackupEncryptionService, createPasswordAttemptLimiter } from './lib/backup-encryption.js';
206
+ import { createRestoreSessions, encryptedRestoreHandlers } from './lib/backup-restore-session.js';
187
207
  import {
188
208
  extractZipEntry,
189
209
  openZipArchive,
190
210
  readBackupManifest,
191
211
  verifyBackupChecksums,
192
212
  } from './lib/backup-zip-reader.js';
193
- import { planRestoreWrites, removeRestoreUpload, saveRestoreUpload } from './lib/system-restore.js';
213
+ import { planRestoreWrites, removeRestoreUpload, restoreFailureCode, restoreFailureFields, restoreWarningCode, saveRestoreUpload } from './lib/system-restore.js';
194
214
  import * as opencodeV2Client from './lib/opencode-v2-client.js';
195
215
  import { OPENCODE_MIN_VERSION, basicAuthHeader, checkPrivateOpencodeServer as checkOpencodeServer, createServeLogRedactor, opencodeInstallCommands, opencodeProblemText, opencodeSupportFor, redactServeOutput, servePasswordReader, serveSpecFor, serveUnsetCommand, withServeEnv } from './lib/opencode-protocol.js';
196
216
  import { SERVE_TOKEN_ENV } from './lib/process-identity.js';
197
217
  import { commandArgs, createServeRecords } from './lib/opencode-serve-records.js';
218
+ import { activeOpencodeSessions, binaryFileKey as opencodeBinaryFileKey, createServeEnds, staleServePlan } from './lib/opencode-turn-release.js';
198
219
  import { opencode2Proxy } from './lib/opencode2-proxy.js';
199
220
  import { macScreenshotDir } from './lib/screenshot-location.js';
200
221
  import { integrationCredentialIds, integrationsWithCredentials } from './lib/opencode2-translate.js';
@@ -208,9 +229,11 @@ import {
208
229
  } from './lib/opencode-config.js';
209
230
  import {
210
231
  handleOpencodeV2Request, opencodeV2WsCapabilities,
211
- buildSessionListQuery, mapSessionListRow, OPENCODE_V2_WS_MUTATION_TYPES, guardOpencodeV2Request,
232
+ buildSessionListQuery, mapSessionListRow, OPENCODE_V2_WS_MUTATION_TYPES, guardOpencodeV2Request, folderIsGone,
212
233
  } from './lib/opencode-v2-ws-requests.js';
234
+ import { createStopFailures } from './lib/opencode-stop-failures.js';
213
235
  import { NativeLoopRuntime, isNativeLoopProfile } from './lib/native-loop-runtime.js';
236
+ import { scheduleScratchRetention } from './lib/scratch-retention.js';
214
237
  import { migrateAutomationContextFiles, normalizeAutomationRecord } from './lib/automation-storage-migration.js';
215
238
  import { createLoopGoalJudge } from './lib/native-loop-goal.js';
216
239
  import { McpToolsRefreshCoordinator } from './lib/mcp-tools-refresh-coordinator.js';
@@ -231,7 +254,7 @@ import { createOpenCodeActivityRelay } from './lib/opencode-worker-activity.js';
231
254
  import { browserServePortDenial, browserSessionLossRule } from './lib/browser-tool-policy.js';
232
255
  import { createNativeServeBoundary, createVerdictFile, nativeContextRevocation, nativeServeCapability, nativeServeReason, nativeServeVersionPolicy, narrowOffenders } from './lib/opencode-native-boundary.js';
233
256
  import { isolatedServeFailure } from './lib/opencode-launch-error.js';
234
- import { reconcilePreflightProfiles, preflightExcludedPorts, runOpencodeBuildPreflight } from './lib/opencode-build-preflight.js';
257
+ import { reconcilePreflightProfiles, preflightExcludedPorts, runOpencodeBuildPreflight, startOpencodeAtBoot } from './lib/opencode-build-preflight.js';
235
258
  import { binaryIdentity as opencodeBinaryIdentity, binaryKey as opencodeBinaryKey } from './lib/opencode-serve-probe.js';
236
259
  // Every OpenCode serve SynaBun starts is probed once it answers (lib/opencode-serve-probe.js: loopback only, every
237
260
  // sensitive /api request and WebSocket upgrade refused without its password, SynaBun's password accepted); what is
@@ -319,7 +342,7 @@ import { registerMaritacaRoutes } from './lib/maritaca/api.js';
319
342
  import { createMaritacaOpencodeSync, maritacaWorkerChannelProvider } from './lib/maritaca/opencode.js';
320
343
  import { createMaritacaOpencodeProxy, maritacaOpencodeProxyBaseUrl } from './lib/maritaca/opencode-proxy.js';
321
344
  import { antigravityHomeDir, antigravityHomesRoot, pruneAntigravityHomes } from './lib/antigravity/home.js';
322
- import { antigravityStores, findUserConversation, parseAntigravityTranscript, readTranscriptText } from './lib/antigravity/transcripts.js';
345
+ import { findUserConversation, parseAntigravityTranscript, readTranscriptText } from './lib/antigravity/transcripts.js';
323
346
  import {
324
347
  buildAgentDisallowedTools,
325
348
  agentAccessFrom,
@@ -460,14 +483,24 @@ import {
460
483
  getMemoriesByCategory, updateMemoriesCategory,
461
484
  getCategories as dbGetCategories, saveCategories as dbSaveCategories,
462
485
  countSessionChunks, searchSessionChunks as dbSearchSessionChunks,
463
- getKvConfig, setKvConfig, EMBEDDING_MODEL,
486
+ getKvConfig, setKvConfig, saveEmbeddingMetadata, EMBEDDING_MODEL,
464
487
  searchSessionFts, listSessionCache, getSessionCacheEntry, clearSessionCacheProvider,
465
488
  memoryVectors, getRecentXEngagements, getXActionBudget, getXEngagementTier, X_ACTION_TYPES,
466
489
  getFbActionBudget, getFbEngagementTier, FB_ACTION_TYPES,
467
490
  } from './lib/db.js';
468
- import {
469
- rebuildClaudeCache, rebuildCodexCache, rebuildOpencodeCache, rebuildAntigravityCache,
470
- } from './lib/session-cache-builder.js';
491
+ import { drainSessionJobs, runSessionJob, setSessionJobStoreGate } from './lib/session-cache-worker.js';
492
+ import { beginActivity, instrumentSqlite, markActivity, startLoopStallMonitor } from './lib/loop-stall.js';
493
+ import { createHealthCount } from './lib/health-count.js';
494
+ import { createRecallImpact } from './lib/recall-impact.js';
495
+ import { installMemoryStoreGate, isMemoryStoreRefusal, noteMemoryStoreRefusal } from './lib/memory-store-gate.js';
496
+
497
+ // Before anything opens the memory store: a migration it needs runs in a child process, never on this thread.
498
+ const memoryStoreGate = installMemoryStoreGate();
499
+ setSessionJobStoreGate(() => (memoryStoreGate.open() ? null : memoryStoreGate.forJobs()));
500
+
501
+ startLoopStallMonitor();
502
+ // A stall line names the slowest synchronous SQLite statement it held (off: SYNABUN_LOOP_STALL_SQL=off).
503
+ instrumentSqlite();
471
504
  import {
472
505
  clearOpenCodeHistory,
473
506
  getOpenCodeHistoryStats,
@@ -569,7 +602,7 @@ const requestGates = createRequestGates({
569
602
  settingsHint: () => ENV_PATH,
570
603
  });
571
604
  app.use(requestGates.host);
572
- app.use(express.json({ limit: '25mb' }));
605
+ app.use(express.json({ limit: '25mb', type: useDefaultJsonParser }));
573
606
 
574
607
  // Clean body-parser error handler: ui-state / whiteboard persist base64 images and can
575
608
  // exceed the JSON limit. Default Express handler dumps a 10-line raw-body stack with no
@@ -651,13 +684,15 @@ _peerIdentity.probe();
651
684
  const _ownerAuthority = createOwnerAuthority({ pageSession: () => _pageSession, isRemote: (req) => requestGates.isRemote(req), peer: _peerIdentity, log: (line) => console.warn(line), automationBrowserAllowed: () => _automationBrowserOwnerAccess.enabled() });
652
685
  app.use(_peerIdentity.middleware({ needs: peerLookupWanted }));
653
686
  app.use(_ownerAuthority.restGate);
687
+ // While the memory store is being upgraded, a route that needed it answers 503 "migrating", never an empty result.
688
+ app.use(memoryStoreGate.requestGuard);
654
689
 
655
690
  import { registerCodexPlanRoutes } from './lib/codex-plan-store.js';
656
691
  import { createOpencodeHiddenModelsRouter, createOpencodeHiddenModelsStore } from './lib/opencode-hidden-models.js';
657
692
  import { createEditorFilesRouter, EDITOR_BACKUP_CAPABILITIES, EDITOR_BACKUP_NAMESPACE } from './lib/editor-files-api.js';
658
693
  import { createEditorGitRouter, EDITOR_GIT_CAPABILITIES } from './lib/editor-git-api.js';
659
694
  import { confinedFolder, createFileExplorerRouter, EXPLORER_CAPABILITIES } from './lib/file-explorer-api.js';
660
- import { folderPickerCommand } from './lib/file-explorer-system.js';
695
+ import { createRevealer, folderPickerCommand } from './lib/file-explorer-system.js';
661
696
  import { createEditorConfigRouter, createEditorConfigStore, createEndpointKeyStore, EDITOR_CONFIG_CAPABILITIES } from './lib/editor-config.js';
662
697
  import {
663
698
  COMPLETION_SYSTEM, EDITOR_COMPLETION_CAPABILITIES, createEditorCompletionRouter, createEditorCompletionService, createUsageStore,
@@ -666,11 +701,12 @@ import { createOpencodeCompletionEngine } from './lib/editor-completion-opencode
666
701
  import { createEndpointCompletionEngine } from './lib/editor-completion-endpoint.js';
667
702
  import { ownerRouteGuard } from './lib/http-guards.js';
668
703
  import { createBridgeStore, createExtensionBridge } from './lib/browser-extension-bridge.js';
669
- import { createExtensionAdapter, EXTENSION_FOLDER } from './lib/browser-extension-adapter.js';
704
+ import { createExtensionAdapter } from './lib/browser-extension-adapter.js';
670
705
  import { detectBrowsers } from './lib/browser-default.js';
671
- import { extensionFolderState, prepareExtensionFolder } from './lib/browser-extension-folder.js';
672
- import { createExtensionSetup, setupError as extensionSetupError } from './lib/browser-extension-setup.js';
673
- import { safeError as extensionSafeError } from '../browser-extension/protocol.js';
706
+ import { extensionFolderState } from './lib/browser-extension-folder.js';
707
+ import { createExtensionPackage } from './lib/browser-extension-package.js';
708
+ import { createExtensionSetup, extensionVersions, setupError as extensionSetupError } from './lib/browser-extension-setup.js';
709
+ import { safeError as extensionSafeError } from './lib/browser-extension-protocol.js';
674
710
  import { setUntrustedFileHeaders } from './lib/untrusted-file-headers.js';
675
711
  import { BUNDLED_LOGO_FILES, UPLOADED_IMAGE_PATH } from './lib/request-gate.js';
676
712
  import { createCloudflaredManager } from './lib/cloudflared/manager.js';
@@ -1089,6 +1125,7 @@ function peerLookupWanted(req) {
1089
1125
  app.use(_pageSession.serviceWorker); // GET /sw.js: a worker that takes itself away, for a browser refused the secret
1090
1126
  app.use(_pageSession.pages);
1091
1127
  app.get('/api/page-session', (req, res) => _pageSession.refresh(req, res)); // PAGE_SECRET_REFRESH_PATH
1128
+ app.post('/api/client-diagnostics', parseClientDiagnostics, createClientDiagnostics({ ownerPage: ownerPageApprovalCall, refuseOwner: refuseNotOwnerPage }));
1092
1129
  // The extension's "Connect your browser" page, opened by the one-button setup in the owner's everyday browser. One of
1093
1130
  // the app's pages (PAGE_SECRET_PATHS): it gets this boot's page secret like any of them, so its reads of the setup's
1094
1131
  // status and its one ticket are the owner's, under the same owner guard; an automation browser and an agent's process
@@ -1722,32 +1759,13 @@ app.get('/api/stats', async (req, res) => {
1722
1759
  }
1723
1760
  });
1724
1761
 
1725
- // GET /api/recall-impact — Memory counts by importance threshold for recall settings UI
1726
- app.get('/api/recall-impact', (req, res) => {
1762
+ // GET /api/recall-impact — Memory counts by importance threshold for recall settings UI.
1763
+ // The two aggregates behind it read every memory and every session chunk whole; they run off this thread, in
1764
+ // slices, and the answer is kept for a minute (lib/recall-impact.js).
1765
+ const recallImpact = createRecallImpact();
1766
+ app.get('/api/recall-impact', async (req, res) => {
1727
1767
  try {
1728
- const d = getDb();
1729
- const rows = d.prepare(`
1730
- SELECT importance, COUNT(*) as cnt, CAST(AVG(LENGTH(content)) AS INTEGER) as avg_len,
1731
- CAST(AVG(CASE WHEN tags IS NOT NULL AND tags != '[]' THEN LENGTH(tags) ELSE 0 END) AS INTEGER) as avg_tags_len,
1732
- CAST(AVG(CASE WHEN related_files IS NOT NULL AND related_files != '[]' THEN LENGTH(related_files) ELSE 0 END) AS INTEGER) as avg_files_len
1733
- FROM memories WHERE trashed_at IS NULL GROUP BY importance ORDER BY importance
1734
- `).all();
1735
- // Session chunk stats for token estimation
1736
- let sessionStats = { count: 0, avg_summary_len: 0, avg_details_len: 0 };
1737
- try {
1738
- const sc = d.prepare(`
1739
- SELECT COUNT(*) as count,
1740
- CAST(AVG(LENGTH(summary)) AS INTEGER) as avg_summary_len,
1741
- CAST(AVG(
1742
- COALESCE(LENGTH(tools_used), 0) +
1743
- COALESCE(LENGTH(files_modified), 0) +
1744
- COALESCE(LENGTH(related_memory_ids), 0)
1745
- ) AS INTEGER) as avg_details_len
1746
- FROM session_chunks
1747
- `).get();
1748
- if (sc) sessionStats = sc;
1749
- } catch { /* session_chunks table may not exist */ }
1750
- res.json({ rows, sessionStats });
1768
+ res.json(await recallImpact.get());
1751
1769
  } catch (err) {
1752
1770
  console.error('GET /api/recall-impact error:', err.message);
1753
1771
  res.status(500).json({ error: err.message });
@@ -2570,6 +2588,10 @@ async function runGracefulShutdown(reason) {
2570
2588
 
2571
2589
  // 1. opencode sidecar — has its own teardown that handles managed PID + ollama.
2572
2590
  try { stopOpencodeServer(); } catch (err) { console.warn(' opencode stop err:', err?.message); }
2591
+ // The serves stopped above interrupt the turns still running on them before their processes end
2592
+ // (lib/opencode-turn-release.js). Waited for here, bounded, so that the exit does not cut that short and leave a
2593
+ // session claimed for OpenCode's own background service to resume.
2594
+ try { await _ocpServeEnds.settled(); } catch (err) { console.warn(' opencode serve end err:', err?.message); }
2573
2595
 
2574
2596
  // 2. Agents in agentRegistry — use platform-native tree kill so descendants die too.
2575
2597
  try {
@@ -2612,7 +2634,8 @@ async function runGracefulShutdown(reason) {
2612
2634
  // The coordination store (agent events, the Assistant's mailbox, the follow-up outbox): closed once the workers
2613
2635
  // are stopped or suspended and what that changed is recorded. Every open wait is answered, the write-ahead log is
2614
2636
  // folded into the file. Signals and the restart/update/shutdown routes all use this teardown.
2615
- try { _assistantCoordination?.close(); } catch (err) { console.warn(' coordination close err:', err?.message); }
2637
+ try { await _assistantDispatcher?.drainFinalizations?.(); } catch (err) { console.warn(' terminal run events:', err?.message); }
2638
+ try { await _assistantCoordination?.close(); } catch (err) { console.warn(' coordination close err:', err?.message); }
2616
2639
  try { closeDb(); } catch {}
2617
2640
  try { closeBlobStore(); } catch {}
2618
2641
 
@@ -3158,6 +3181,9 @@ app.post('/api/system/run-update', async (req, res) => {
3158
3181
  }
3159
3182
  });
3160
3183
 
3184
+ // Session indexing holds its own SQLite connection while a pass runs. A file replacement must wait for it.
3185
+ app.post(['/api/settings/move-db', '/api/settings/move-db/cleanup', '/api/system/restore', '/api/system/restore/apply-staged'], drainSessionJobs);
3186
+
3161
3187
  // POST /api/settings/move-db — Move SQLite database to a new directory
3162
3188
  app.post('/api/settings/move-db', (req, res) => {
3163
3189
  try {
@@ -3269,7 +3295,7 @@ async function runReindex(job) {
3269
3295
  const updateStmt = d.prepare('UPDATE memories SET vector = ? WHERE id = ?');
3270
3296
  for (let i = 0; i < rows.length; i++) {
3271
3297
  try {
3272
- updateStmt.run(encodeVector(vectors[i]), rows[i].id);
3298
+ await withMemoryWrite(d, () => updateStmt.run(encodeVector(vectors[i]), rows[i].id));
3273
3299
  job.completed++;
3274
3300
  } catch {
3275
3301
  job.errors++;
@@ -3297,7 +3323,7 @@ async function runReindex(job) {
3297
3323
  const updateStmt = d.prepare('UPDATE session_chunks SET vector = ? WHERE id = ?');
3298
3324
  for (let i = 0; i < rows.length; i++) {
3299
3325
  try {
3300
- updateStmt.run(encodeVector(vectors[i]), rows[i].id);
3326
+ await withMemoryWrite(d, () => updateStmt.run(encodeVector(vectors[i]), rows[i].id));
3301
3327
  job.chunks++;
3302
3328
  } catch {
3303
3329
  job.errors++;
@@ -3312,8 +3338,7 @@ async function runReindex(job) {
3312
3338
 
3313
3339
  // Update stored model metadata
3314
3340
  try {
3315
- setKvConfig('embedding_model', EMBEDDING_MODEL);
3316
- setKvConfig('embedding_dims', String(EMBEDDING_DIMS));
3341
+ await saveEmbeddingMetadata();
3317
3342
  } catch {}
3318
3343
 
3319
3344
  job.running = false;
@@ -8388,6 +8413,7 @@ let _ocpVersion = null;
8388
8413
  // says why OpenCode cannot be used (shown by the panel, Settings and the tray).
8389
8414
  let _ocpPassword = null;
8390
8415
  let _ocpProblem = null;
8416
+ let _ocpStartRefusal = null; // The MoreLogin check that refused the last start (startOpencodeAtBoot reads it).
8391
8417
  let _ocpHistoryClearInProgress = false;
8392
8418
  let _ocpSessionCacheWarmup = null;
8393
8419
 
@@ -8406,6 +8432,16 @@ const opencodeServeRecords = createServeRecords({
8406
8432
  migrateOpencodeManagedPid();
8407
8433
  let _ocpBootReconcileTried = false;
8408
8434
  let _ocpLastBootAt = 0; // Date.now() when serve process last became ready
8435
+ // The file SynaBun's shared serve was started from (lib/opencode-turn-release.js binaryFileKey), while SynaBun's own
8436
+ // child runs it: an OpenCode update replaces the file on disk and leaves this serve on the old program.
8437
+ let _ocpServeFileKey = null;
8438
+ // The end of the shared serve while its turns are still being released: a new start waits for it, so that it never
8439
+ // finds the serve that is being stopped still answering on the port.
8440
+ let _ocpSharedEnd = null;
8441
+ // How SynaBun ends its serves (lib/opencode-turn-release.js): the turns still running on a serve are interrupted
8442
+ // before its process is stopped. A turn left in flight stays claimed in OpenCode's database, and OpenCode's own
8443
+ // background service (a plain `opencode` in a terminal starts it) resumes every such session at its boot.
8444
+ const _ocpServeEnds = createServeEnds({ log: (line) => console.log(`[opencode] ${line}`) });
8409
8445
 
8410
8446
  // ── Verbose trace logging (opt-in: OCP_VERBOSE=1 to enable) ──
8411
8447
  const OCP_VERBOSE = process.env.OCP_VERBOSE === '1';
@@ -9057,6 +9093,8 @@ async function ensureIsolatedServe(termId, { xdgRoot: requestedXdgRoot = null, c
9057
9093
  });
9058
9094
  entry.proc = proc;
9059
9095
  entry.password = launch.password || null;
9096
+ // The file this serve runs: an update of OpenCode makes it a serve of the old program (retireStaleOpencodeServes).
9097
+ entry.fileKey = opencodeBinaryFileKey(launch.nativeServe?.identity);
9060
9098
  // On record from its spawn: a crash of SynaBun from here on does not leave it running for good.
9061
9099
  const tracked = trackOpencodeServe(proc, { kind: 'isolated', id: termId, port, token, nativeWebSocketSafe: launch.nativeWebSocketSafe, nativeServe: launch.nativeServe });
9062
9100
  // While it boots, its start sees an exit itself (another server on the port is a collision); afterwards
@@ -9174,7 +9212,10 @@ async function ensureIsolatedServe(termId, { xdgRoot: requestedXdgRoot = null, c
9174
9212
  }
9175
9213
  }
9176
9214
 
9177
- function stopIsolatedServe(termId, { preserveBindings = false } = {}) {
9215
+ // `immediate`: the process's exit handler, where nothing can be awaited: the serve's process is ended at once.
9216
+ // Otherwise the turns still running on the serve are interrupted first (lib/opencode-turn-release.js, a bounded
9217
+ // wait), so that none of its sessions stays claimed in OpenCode's database; everything else here is done at once.
9218
+ function stopIsolatedServe(termId, { preserveBindings = false, immediate = false } = {}) {
9178
9219
  const entry = _ocpIsoServes.get(termId);
9179
9220
  if (entry?.xdgRoot) _externalMcpLogValues.delete(entry.xdgRoot);
9180
9221
  if (!entry) return;
@@ -9191,12 +9232,20 @@ function stopIsolatedServe(termId, { preserveBindings = false } = {}) {
9191
9232
  }
9192
9233
  try { entry.unsub?.(); } catch {}
9193
9234
  try { entry.client?.stop(); } catch {}
9194
- killIsolatedServeProcess(entry.proc);
9235
+ const proc = entry.proc;
9236
+ _ocpServeEnds.end({
9237
+ port: entry.ready ? entry.port : null,
9238
+ password: entry.password || null,
9239
+ alive: () => !!proc && proc.exitCode == null && proc.signalCode == null,
9240
+ kill: () => killIsolatedServeProcess(proc),
9241
+ label: `serve ${String(termId).slice(-8)}`,
9242
+ immediate,
9243
+ });
9195
9244
  try { if (!entry.persistentData && entry.xdgRoot && existsSync(entry.xdgRoot)) rmSync(entry.xdgRoot, { recursive: true, force: true }); } catch {}
9196
9245
  }
9197
9246
 
9198
- function stopAllIsolatedServes() {
9199
- for (const termId of [..._ocpIsoServes.keys()]) stopIsolatedServe(termId);
9247
+ function stopAllIsolatedServes({ immediate = false } = {}) {
9248
+ for (const termId of [..._ocpIsoServes.keys()]) stopIsolatedServe(termId, { immediate });
9200
9249
  }
9201
9250
 
9202
9251
  // Resolve the client to run a TURN for a session. Every sidepanel session gets
@@ -9376,7 +9425,62 @@ setInterval(() => {
9376
9425
  }
9377
9426
  }, 60 * 1000).unref?.();
9378
9427
 
9379
- process.once('exit', stopAllIsolatedServes);
9428
+ // Whether an isolated serve is in use right now (the reaper's own rule): a live run or brain keeps it, a turn runs
9429
+ // on it, or it is still starting.
9430
+ function isolatedServeBusy(termId, entry) {
9431
+ if (entry.keepAlive && (_nativeLoopRuntime?.isAlive(termId) || _assistantRuntime?.ownsIsolatedServe?.(termId))) return true;
9432
+ if (entry.starting || !entry.ready) return true;
9433
+ if ([..._ocpSessionServeStarts.values()].some((pending) => pending.termId === termId)) return true;
9434
+ return [...entry.sessions].some((sessionId) => _ocpActiveSessionTurns.has(sessionId));
9435
+ }
9436
+
9437
+ // The file of the OpenCode SynaBun would start now, as a key. null (nothing is decided) when Settings names a
9438
+ // command line (which runs whatever it names), while the file has not answered `--version` yet (an update still
9439
+ // being written; the resolver asks in the background and the next look knows), and for an OpenCode SynaBun does not
9440
+ // drive: a serve that works is never stopped for one that would be refused.
9441
+ function currentOpencodeFileKey() {
9442
+ if (configuredCommandLine('opencode')) return null;
9443
+ const found = cliResolver.launcher('opencode');
9444
+ if (found.state !== 'installed' || !opencodeSupportFor(found.version, { path: found.path }).supported) return null;
9445
+ return opencodeBinaryFileKey(opencodeBinaryIdentity(found.launchPath || found.path || null));
9446
+ }
9447
+
9448
+ // OpenCode was updated while SynaBun runs (its badge, `opencode upgrade` in a terminal, OpenCode's own updater):
9449
+ // the file on disk is the new program, and the serves SynaBun started before still run the old one. The shared
9450
+ // serve is restarted once it runs no turn, and a session's serve that is not in use is stopped (the session's next
9451
+ // message starts one, as after the idle reaper). A serve in use is left for the next look. Looked at after every
9452
+ // check of the CLI versions and once a minute while a serve of SynaBun's runs.
9453
+ let _ocpRetireInFlight = null;
9454
+ function retireStaleOpencodeServes(reason = 'watch') {
9455
+ if (_ocpRetireInFlight) return _ocpRetireInFlight;
9456
+ _ocpRetireInFlight = (async () => {
9457
+ if (_ocpHistoryClearInProgress || (!_ocpProc && _ocpIsoServes.size === 0)) return null;
9458
+ let current = null;
9459
+ try { current = currentOpencodeFileKey(); } catch { current = null; }
9460
+ const plan = staleServePlan({
9461
+ current,
9462
+ shared: { key: _ocpServeFileKey, managed: !!_ocpProc, ready: _ocpReady, starting: _ocpStarting },
9463
+ isolated: [..._ocpIsoServes].map(([termId, entry]) => ({ termId, key: entry.fileKey || null, busy: isolatedServeBusy(termId, entry) })),
9464
+ });
9465
+ for (const termId of plan.isolated) {
9466
+ console.log(`[ocp-iso] OpenCode on disk changed: stopping serve ${String(termId).slice(-8)}, which runs the earlier program (${reason}); its session's next message starts a new one`);
9467
+ stopIsolatedServe(termId);
9468
+ }
9469
+ if (plan.shared === 'restart') {
9470
+ const turns = await activeOpencodeSessions({ port: _ocpPort, password: _ocpPassword });
9471
+ // Asked again after the wait: a stop or a restart meanwhile has already replaced it.
9472
+ if (turns.ok && !turns.ids.length && _ocpProc && _ocpReady && !_ocpStarting && _ocpServeFileKey && _ocpServeFileKey !== current) {
9473
+ console.log(`[opencode] OpenCode on disk changed: restarting SynaBun's shared serve, which runs the earlier program (v${_ocpVersion || '?'}; ${reason})`);
9474
+ try { await takeoverOpencodeServer(); } catch (error) { console.warn(`[opencode] shared serve restart after an OpenCode update failed: ${error?.message || error}`); }
9475
+ }
9476
+ }
9477
+ return plan;
9478
+ })().catch(() => null).finally(() => { _ocpRetireInFlight = null; });
9479
+ return _ocpRetireInFlight;
9480
+ }
9481
+ setInterval(() => { retireStaleOpencodeServes('watch'); }, 60 * 1000).unref?.();
9482
+
9483
+ process.once('exit', () => { stopAllIsolatedServes({ immediate: true }); _ocpServeEnds.killNow(); });
9380
9484
 
9381
9485
  // ── Antigravity side panel (/ws/antigravity) ──
9382
9486
  // One `agy acp` (Google's Antigravity ACP server) per panel socket, one ACP session per tab
@@ -9451,6 +9555,10 @@ function handleOpencodeV2Ws(ws) {
9451
9555
 
9452
9556
  // Track in-flight prompts so a fresh send can abort the previous turn cleanly.
9453
9557
  const sendAborts = new Map(); // sessionID → AbortController
9558
+ // Stops that could not end a command of the turn (lib/opencode-stop-failures.js): from the second one on the panel
9559
+ // offers "Stop anyway" (message:abort with `force`). A new turn starts the count again; an entry goes with its
9560
+ // turn, its session and this socket.
9561
+ const stopFailures = createStopFailures({ activeTurn: (sid) => _ocpActiveSessionTurns.get(sid) });
9454
9562
 
9455
9563
  const send = (data) => {
9456
9564
  if (ws.readyState === 1) {
@@ -9490,6 +9598,7 @@ function handleOpencodeV2Ws(ws) {
9490
9598
  end() {
9491
9599
  if (_ocpActiveSessionTurns.get(sid) === token) _ocpActiveSessionTurns.delete(sid);
9492
9600
  if (sendAborts.get(sid) === ctrl) sendAborts.delete(sid);
9601
+ stopFailures.prune();
9493
9602
  },
9494
9603
  };
9495
9604
  },
@@ -9516,6 +9625,9 @@ function handleOpencodeV2Ws(ws) {
9516
9625
  nativeMutationTypes: OPENCODE_NATIVE_MUTATION_TYPES,
9517
9626
  protectedRunFor: activeNativeOpenCodeRunForSession,
9518
9627
  ownsRun: (run) => opencodeV2ClientOwnsRun(ws, run),
9628
+ // A session or a turn in a folder that no longer exists (a removed worktree) is refused before OpenCode
9629
+ // makes a session that can never run: the panel moves to the project the folder was in.
9630
+ folderGone: folderIsGone,
9519
9631
  });
9520
9632
  if (refused) {
9521
9633
  send({ type: `${type}:result`, id, ...refused });
@@ -9612,6 +9724,7 @@ function handleOpencodeV2Ws(ws) {
9612
9724
  _ocpSessionToServe.delete(msg.sessionId);
9613
9725
  _ocpSessionTools.delete(msg.sessionId);
9614
9726
  _ocpActiveSessionTurns.delete(msg.sessionId);
9727
+ stopFailures.clear(msg.sessionId);
9615
9728
  if (entry && entry.sessions.size === 0) stopIsolatedServe(termId);
9616
9729
  send({ type: 'session:delete:result', id, status: r.status, data: r.data });
9617
9730
  break;
@@ -9714,19 +9827,43 @@ function handleOpencodeV2Ws(ws) {
9714
9827
  _ocpActiveSessionTurns.delete(sid);
9715
9828
  }
9716
9829
  if (sendAborts.get(sid) === ctrl) sendAborts.delete(sid);
9830
+ // A turn that ended (or was replaced by this one) takes its failed Stops along.
9831
+ stopFailures.prune();
9717
9832
  }
9718
9833
  break;
9719
9834
  }
9720
9835
  case 'message:abort': {
9721
9836
  const sid = msg.sessionId;
9722
- const ctrl = sendAborts.get(sid);
9723
- if (ctrl) { try { ctrl.abort(); } catch {} sendAborts.delete(sid); }
9837
+ // `force`: "Stop anyway", offered after a second failed Stop. The turn ends even while a command OpenCode
9838
+ // could not end may still run (its removal goes on in the background, lib/opencode2-client.js).
9839
+ const force = msg.force === true;
9840
+ const bound = boundIsoClient(sid);
9841
+ const endSend = () => {
9842
+ const ctrl = sendAborts.get(sid);
9843
+ if (ctrl) { try { ctrl.abort(); } catch {} sendAborts.delete(sid); }
9844
+ };
9845
+ // A Stop with a command to end can fail, and then the turn goes on: the prompt's wait (`sendAborts`) is
9846
+ // ended only once the stop worked. With none, as always: the wait ends first.
9847
+ const mayFail = !force && bound?.getClient?.()?.stopNeedsKill?.(sid) === true;
9848
+ if (!mayFail) endSend();
9724
9849
  try {
9725
- await boundIsoClient(sid).session.abort({ sessionID: sid });
9850
+ const r = await bound.session.abort({ sessionID: sid, ...(force ? { force: true } : {}) });
9851
+ endSend();
9726
9852
  _ocpActiveSessionTurns.delete(sid);
9727
- send({ type: 'message:abort:result', id, ok: true });
9853
+ stopFailures.clear(sid);
9854
+ const abandoned = Array.isArray(r?.data?.abandoned) ? r.data.abandoned : [];
9855
+ send({ type: 'message:abort:result', id, ok: true, ...(abandoned.length ? { abandoned } : {}) });
9728
9856
  } catch (err) {
9729
- send({ type: 'message:abort:result', id, ok: false, error: err?.message });
9857
+ if (err?.cause?.name === 'ShellStopFailed') {
9858
+ // A command Stop could not end still runs (lib/opencode2-client.js abortSession): the turn goes on,
9859
+ // and the panel says so instead of showing it stopped; from the second failure it offers Stop anyway.
9860
+ const count = stopFailures.fail(sid);
9861
+ const shells = Array.isArray(err?.data?.shells) ? err.data.shells : [];
9862
+ send({ type: 'message:abort:result', id, ok: false, error: err?.message, code: 'SHELL_STOP_FAILED', shells, failures: count, canForce: count >= 2 });
9863
+ } else {
9864
+ endSend();
9865
+ send({ type: 'message:abort:result', id, ok: false, error: err?.message });
9866
+ }
9730
9867
  }
9731
9868
  break;
9732
9869
  }
@@ -9770,6 +9907,7 @@ function handleOpencodeV2Ws(ws) {
9770
9907
  _ocpV2WsClients.delete(ws);
9771
9908
  for (const ctrl of sendAborts.values()) { try { ctrl.abort(); } catch {} }
9772
9909
  sendAborts.clear();
9910
+ stopFailures.clearAll();
9773
9911
  console.log(`[ocp-v2-ws] close conn=${connId} total=${_ocpV2WsClients.size}`);
9774
9912
  });
9775
9913
 
@@ -9903,6 +10041,7 @@ async function ensureOpencodeServer({ allowDuringHistoryClear = false } = {}) {
9903
10041
  return false;
9904
10042
  }
9905
10043
  _ocpStarting = true;
10044
+ if (_ocpSharedEnd) await _ocpSharedEnd;
9906
10045
 
9907
10046
  // 0. Which OpenCode is installed. One SynaBun does not drive (OpenCode 1, an OpenCode 2 older than the
9908
10047
  // minimum) is refused here, with a sentence the panel and Settings show, instead of failing call by call later.
@@ -9913,6 +10052,7 @@ async function ensureOpencodeServer({ allowDuringHistoryClear = false } = {}) {
9913
10052
  return false;
9914
10053
  }
9915
10054
  _ocpProblem = null;
10055
+ _ocpStartRefusal = null;
9916
10056
  // A serve already running is adopted when it answers SynaBun: only to the password SynaBun gave it, and only
9917
10057
  // as a version SynaBun drives (checkOpencodeServer). A serve an earlier SynaBun left running (on this port or any other it used) goes before anything here is
9918
10058
  // adopted, and its port with it.
@@ -9965,6 +10105,7 @@ async function ensureOpencodeServer({ allowDuringHistoryClear = false } = {}) {
9965
10105
  shell: false,
9966
10106
  });
9967
10107
  _ocpProc = proc;
10108
+ _ocpServeFileKey = opencodeBinaryFileKey(launch.nativeServe?.identity);
9968
10109
  // On record from its spawn: a crash of SynaBun from here on does not leave it running for good.
9969
10110
  tracked = trackOpencodeServe(proc, { kind: 'shared', id: 'shared', port: _ocpPort, token, nativeWebSocketSafe: launch.nativeWebSocketSafe, nativeServe: launch.nativeServe });
9970
10111
  const readPassword = servePasswordReader();
@@ -9985,12 +10126,18 @@ async function ensureOpencodeServer({ allowDuringHistoryClear = false } = {}) {
9985
10126
  // its process either way: trackOpencodeServe.)
9986
10127
  if (_ocpProc !== proc) return;
9987
10128
  _ocpProc = null;
10129
+ _ocpServeFileKey = null;
9988
10130
  _ocpReady = false;
9989
10131
  opencodeV2Client.disconnect().catch(() => {});
9990
10132
  broadcastToOpencodeV2Clients({ type: 'server:status', status: 'offline', port: _ocpPort });
9991
10133
  });
9992
10134
  } catch (err) {
9993
10135
  console.error(`[opencode] Failed to spawn: ${err.message}`);
10136
+ // A MoreLogin check that refused this start: the panel says why instead of staying silently offline.
10137
+ if (err?.sharedPreflight) {
10138
+ _ocpStartRefusal = err;
10139
+ reportOpencodeProblem(err.message);
10140
+ }
9994
10141
  return 'not-spawned';
9995
10142
  }
9996
10143
  for (let i = 0; i < 30; i++) {
@@ -10042,10 +10189,14 @@ async function ensureOpencodeServer({ allowDuringHistoryClear = false } = {}) {
10042
10189
  return false;
10043
10190
  }
10044
10191
 
10045
- function stopOpencodeServer({ stopManagedOllama = true } = {}) {
10192
+ // Returns a promise of the end of SynaBun's own child when its turns are released first (a bounded wait,
10193
+ // lib/opencode-turn-release.js), else null: its process was ended at once. `immediate`: the process's exit handler,
10194
+ // where nothing can be awaited.
10195
+ function stopOpencodeServer({ stopManagedOllama = true, immediate = false } = {}) {
10046
10196
  opencodeV2Client.disconnect().catch(() => {});
10047
10197
  const procPid = _ocpProc?.pid || null;
10048
10198
  const isWin = process.platform === 'win32';
10199
+ let ended = null;
10049
10200
 
10050
10201
  // On Windows `process.kill(pid, 'SIGTERM')` is unreliable for non-Node
10051
10202
  // children (cmd.exe shells, opencode native binaries). Use taskkill /T /F
@@ -10062,12 +10213,26 @@ function stopOpencodeServer({ stopManagedOllama = true } = {}) {
10062
10213
  };
10063
10214
 
10064
10215
  if (_ocpProc && !_ocpProc.killed) {
10065
- if (isWin && procPid) {
10066
- winKill(procPid);
10067
- } else {
10068
- try { _ocpProc.kill(); } catch {}
10216
+ const proc = _ocpProc;
10217
+ ended = _ocpServeEnds.end({
10218
+ // Only a serve that answered can be asked for its turns; one that never became healthy has none.
10219
+ port: _ocpReady ? _ocpPort : null,
10220
+ password: _ocpPassword,
10221
+ alive: () => proc.exitCode == null && proc.signalCode == null,
10222
+ kill: () => {
10223
+ if (isWin && procPid) winKill(procPid);
10224
+ else { try { proc.kill(); } catch {} }
10225
+ },
10226
+ label: 'shared serve',
10227
+ immediate,
10228
+ });
10229
+ if (ended) {
10230
+ const ending = ended;
10231
+ _ocpSharedEnd = ending;
10232
+ ending.finally(() => { if (_ocpSharedEnd === ending) _ocpSharedEnd = null; });
10069
10233
  }
10070
10234
  _ocpProc = null;
10235
+ _ocpServeFileKey = null;
10071
10236
  }
10072
10237
  // SynaBun's recorded serves (a process its child started that answers on the port; one of an earlier run whose
10073
10238
  // SynaBun has ended), only while the OS still reports each as that very process: a pid another program has by now,
@@ -10086,6 +10251,7 @@ function stopOpencodeServer({ stopManagedOllama = true } = {}) {
10086
10251
  if (stopManagedOllama) {
10087
10252
  try { stopOllama(); } catch {}
10088
10253
  }
10254
+ return ended;
10089
10255
  }
10090
10256
 
10091
10257
  // Takeover: a fresh shared serve that boots from the updated auth/config files. A serve is stopped only when it
@@ -10098,8 +10264,9 @@ function stopOpencodeServer({ stopManagedOllama = true } = {}) {
10098
10264
  async function takeoverOpencodeServer() {
10099
10265
  if (_ocpHistoryClearInProgress) throw new Error('OpenCode history is being cleared');
10100
10266
  if (_ocpProc) {
10101
- // Already managed — simple restart
10102
- stopOpencodeServer();
10267
+ // Already managed — simple restart. The old serve's end is waited for (its turns are released first): the new
10268
+ // start must never find the old one still answering on the port.
10269
+ await stopOpencodeServer();
10103
10270
  await new Promise(r => setTimeout(r, 1000));
10104
10271
  return ensureOpencodeServer();
10105
10272
  }
@@ -15229,9 +15396,23 @@ app.post('/api/loop/stop', async (req, res) => {
15229
15396
  // No agent header at all: the owner's page, with its page secret (or an invite guest, whom the guest rules decide).
15230
15397
  if (!who.automation && !browserPageOwner(req)) return refuseNotOwnerPage(req, res, 'Loops are stopped from SynaBun\'s own page (its page secret, which the page\'s browser sends by itself), or by a run itself (X-Synabun-Terminal with its terminal token). This request is neither: reload SynaBun\'s page and stop it there.');
15231
15398
  const targetTerminalId = who.automation ? who.id : named;
15399
+ // Accepted legacy/grace pins authorize their existing operation but do not prove identity.
15400
+ const stopProvenance = stampStopProvenance(null, who.automation
15401
+ ? (who.status === 'verified' ? { actor: 'automation', action: 'self_stop', runId: who.id } : { actor: 'unknown', action: 'stop' })
15402
+ : pageStopProvenance(req.body?.action, true), new Date().toISOString());
15403
+ if (!targetTerminalId) stopProvenance.scope = 'all';
15404
+ // 'user' only for a control a person operated; a run stopping itself and an unnamed caller say so.
15405
+ const stopReason = callerStopReason(stopProvenance);
15406
+ // A run suspended for a restart outlives its old process, a closing page and the tray's timer: only a deliberate
15407
+ // stop ends it (lib/worker-stop.js). It keeps its loop file, which is what its resume reads.
15408
+ const staysSuspended = (id) => _nativeLoopRuntime?.isSuspended?.(id) && !mayEndSuspendedRun(stopProvenance);
15409
+ if (targetTerminalId && staysSuspended(targetTerminalId)) {
15410
+ loopLog(targetTerminalId, 'loop:stop-refused', 'A suspended run stays suspended: this caller may not end it', { stopProvenance });
15411
+ return res.status(409).json({ ok: false, code: 'RUN_SUSPENDED', stopped: 0, error: 'This run is suspended for a server restart and resumes by itself. Only a deliberate stop ends it.' });
15412
+ }
15232
15413
  let directlyStopped = false;
15233
15414
  if (targetTerminalId && _nativeLoopRuntime?.isAlive(targetTerminalId)) {
15234
- directlyStopped = await _nativeLoopRuntime.stop(targetTerminalId, 'user');
15415
+ directlyStopped = await _nativeLoopRuntime.stop(targetTerminalId, stopReason, { stopProvenance });
15235
15416
  }
15236
15417
  if (!existsSync(LOOP_DIR)) return res.json({ ok: true, stopped: directlyStopped ? 1 : 0 });
15237
15418
  const files = readdirSync(LOOP_DIR).filter(f => f.endsWith('.json') && f !== '.gitkeep');
@@ -15248,17 +15429,22 @@ app.post('/api/loop/stop', async (req, res) => {
15248
15429
  if (data.active || data.pending) {
15249
15430
  // Per-loop stop: skip loops that don't match the target
15250
15431
  if (targetTerminalId && data.runId !== targetTerminalId && data.terminalSessionId !== targetTerminalId) continue;
15432
+ // "Stop every loop" from a caller that may not end a suspended run passes over it.
15433
+ if (staysSuspended(data.runId || data.terminalSessionId)) continue;
15251
15434
  if (!directlyStopped && (data.runtimeType === 'native' || data.driverType === 'native')) {
15252
- await _nativeLoopRuntime?.stop(data.runId || data.terminalSessionId, 'user');
15435
+ await _nativeLoopRuntime?.stop(data.runId || data.terminalSessionId, stopReason, { stopProvenance });
15253
15436
  }
15254
15437
  if (data.driverType === 'exec' && data.scheduledBy) {
15255
15438
  data.active = false;
15256
15439
  data.pending = false;
15257
15440
  data.completedAt = new Date().toISOString();
15258
- data.stoppedReason = 'user';
15441
+ data.stoppedReason = stopReason;
15442
+ data.stopProvenance = stopProvenance;
15259
15443
  try { writeFileSync(filePath, JSON.stringify(data, null, 2)); } catch {}
15260
- persistExecScheduleOutcome(data, 'stopped', 'user');
15444
+ persistExecScheduleOutcome(data, 'stopped', stopReason);
15261
15445
  }
15446
+ // Classic loop files are removed below; keep the action in their per-run log.
15447
+ loopLog(data.runId || data.terminalSessionId, 'loop:stop', 'Loop stopped', { stopProvenance });
15262
15448
  // Kill PTY session if still alive
15263
15449
  if (data.terminalSessionId && terminalSessions.has(data.terminalSessionId)) {
15264
15450
  const session = terminalSessions.get(data.terminalSessionId);
@@ -16324,7 +16510,8 @@ async function launchScheduledLoop(schedule) {
16324
16510
  if (isXAutomation) {
16325
16511
  try {
16326
16512
  const xAccount = (template.account || (/^cp_/.test(schedule.templateId || '') ? 'Crit_Pix' : '')).trim();
16327
- const { handles, statusIds, blocked, error: ledgerErr } = getRecentXEngagements({ account: xAccount || null, days: 7, limit: 200 });
16513
+ // The ledger's reads scan memories by tag: they run off this thread and are awaited (lib/db.js ledgerRows).
16514
+ const { handles, statusIds, blocked, error: ledgerErr } = await getRecentXEngagements({ account: xAccount || null, days: 7, limit: 200 });
16328
16515
  if (ledgerErr) {
16329
16516
  loopLog(terminalSessionId, 'launch:dedup', 'engagement ledger read failed (continuing)', { err: ledgerErr });
16330
16517
  } else if (handles.length || statusIds.length || blocked.length) {
@@ -16351,8 +16538,8 @@ async function launchScheduledLoop(schedule) {
16351
16538
  const tz = schedule.timezone || 'America/Sao_Paulo';
16352
16539
  const nowLocal = getNowInTimezone(tz);
16353
16540
  const msIntoDay = ((nowLocal.getHours() * 60 + nowLocal.getMinutes()) * 60 + nowLocal.getSeconds()) * 1000 + nowLocal.getMilliseconds();
16354
- const spent = getXActionBudget({ account: xAccount || null, sinceIso: new Date(Date.now() - msIntoDay).toISOString() });
16355
- const { tier, caps, source: tierSource } = getXEngagementTier({ account: xAccount || null });
16541
+ const spent = await getXActionBudget({ account: xAccount || null, sinceIso: new Date(Date.now() - msIntoDay).toISOString() });
16542
+ const { tier, caps, source: tierSource } = await getXEngagementTier({ account: xAccount || null });
16356
16543
  if (spent.error) {
16357
16544
  loopLog(terminalSessionId, 'launch:budget', 'action budget read failed (continuing)', { err: spent.error });
16358
16545
  } else {
@@ -16392,8 +16579,8 @@ async function launchScheduledLoop(schedule) {
16392
16579
  const tz = schedule.timezone || 'America/Sao_Paulo';
16393
16580
  const nowLocal = getNowInTimezone(tz);
16394
16581
  const msIntoDay = ((nowLocal.getHours() * 60 + nowLocal.getMinutes()) * 60 + nowLocal.getSeconds()) * 1000 + nowLocal.getMilliseconds();
16395
- const spent = getFbActionBudget({ sinceIso: new Date(Date.now() - msIntoDay).toISOString() });
16396
- const { tier, caps, source: tierSource } = getFbEngagementTier();
16582
+ const spent = await getFbActionBudget({ sinceIso: new Date(Date.now() - msIntoDay).toISOString() });
16583
+ const { tier, caps, source: tierSource } = await getFbEngagementTier();
16397
16584
  if (spent.error) {
16398
16585
  loopLog(terminalSessionId, 'launch:budget', 'FB action budget read failed (continuing)', { err: spent.error });
16399
16586
  } else {
@@ -16896,6 +17083,7 @@ function reconcileKeepAwake() {
16896
17083
  }
16897
17084
 
16898
17085
  function evaluateSchedules() {
17086
+ markActivity('scheduler:schedules');
16899
17087
  // P5 deterministic health shares the scheduler's tick; disabled until enabled in Skills Studio.
16900
17088
  skillsService?.health.tick().catch((error) => console.error('[skills-health]', error?.code || 'check_failed'));
16901
17089
  _scheduleEvalCount++;
@@ -18833,8 +19021,9 @@ const TOOL_DEFS = [
18833
19021
  // Google's Antigravity CLI has no npm package: a Homebrew cask's newer version is what `brew outdated` says, and
18834
19022
  // the CLI updates itself (`agy update`).
18835
19023
  { key: 'antigravity', cmd: 'agy', versionArg: '--version' },
18836
- // npm's opencode-ai is OpenCode 1: OpenCode 2's newer version is what Homebrew says (a brew install) or what OpenCode
18837
- // itself announces in its own interface.
19024
+ // npm's opencode-ai is OpenCode 1: OpenCode 2's newer version is read where its install channel publishes it
19025
+ // (upstreamVersionSource in lib/cli-update-planner.js: OpenCode's own update API, or the formula of its Homebrew
19026
+ // tap, whose local clone `brew outdated` reads stale).
18838
19027
  { key: 'opencode', cmd: 'opencode', versionArg: '--version' },
18839
19028
  ];
18840
19029
 
@@ -18889,6 +19078,32 @@ async function probeBrewOutdated(env) {
18889
19078
  }
18890
19079
  }
18891
19080
 
19081
+ // Ask WinGet which version of OpenCode it can install (`winget search`, as OpenCode's own updater does: a release
19082
+ // reaches WinGet's repository days after OpenCode publishes it, and some never do). `{ version }`, or null when
19083
+ // WinGet could not be asked or lists no version: the caller fails closed, like the brew probe.
19084
+ async function probeWingetOpencode(env) {
19085
+ try {
19086
+ const { stdout } = await execFileAsync('winget', [...OPENCODE_WINGET_SEARCH_ARGS], {
19087
+ encoding: 'utf-8',
19088
+ timeout: 20000,
19089
+ env,
19090
+ windowsHide: true,
19091
+ maxBuffer: 1024 * 1024,
19092
+ });
19093
+ const version = parseWingetSearchVersion(stdout);
19094
+ return version ? { version } : null;
19095
+ } catch {
19096
+ return null;
19097
+ }
19098
+ }
19099
+
19100
+ // The Git Bash this PC has, for OpenCode's own installer (`opencode upgrade --method curl` on Windows runs it with
19101
+ // Git Bash): the one Claude Code gets (lib/git-bash/). null anywhere else, and where there is none.
19102
+ function opencodeGitBashPath() {
19103
+ if (process.platform !== 'win32') return null;
19104
+ try { return gitBash.resolution()?.path || null; } catch { return null; }
19105
+ }
19106
+
18892
19107
  // Resolve SynaBun's own install roots so we can reject any tool binary that
18893
19108
  // lives inside our bundled node_modules — bulletproof guard for the recurring
18894
19109
  // phantom-version bug (e.g. stale @anthropic-ai/claude-code left over from
@@ -18937,6 +19152,7 @@ function pruneBundledCliTools() {
18937
19152
  }
18938
19153
 
18939
19154
  async function checkToolVersions({ force = false } = {}) {
19155
+ markActivity('cli:versions');
18940
19156
  const generation = ++_toolVersionGeneration;
18941
19157
  // Every CLI exactly as the panels and launchers find it (lib/cli-resolver.js):
18942
19158
  // the path in Settings first, then PATH with the OS PATH read afresh, then the
@@ -18951,6 +19167,10 @@ async function checkToolVersions({ force = false } = {}) {
18951
19167
  const brewOutdated = Object.values(statuses).some((status) => status.state === 'installed' && isBrewSource(status.installSource))
18952
19168
  ? await probeBrewOutdated(cleanEnv)
18953
19169
  : null;
19170
+ // A WinGet install of OpenCode is measured against what WinGet can install (`undefined`: not such an install).
19171
+ const wingetOpencode = process.platform === 'win32' && statuses.opencode?.state === 'installed' && statuses.opencode.installSource === 'winget'
19172
+ ? await probeWingetOpencode(cleanEnv)
19173
+ : undefined;
18954
19174
 
18955
19175
  const checkOneTool = async (tool) => {
18956
19176
  const status = statuses[tool.key];
@@ -18960,6 +19180,12 @@ async function checkToolVersions({ force = false } = {}) {
18960
19180
  // Homebrew routinely trails npm by a few releases, so comparing against it
18961
19181
  // produced a badge that lit up while `brew upgrade` answered "already
18962
19182
  // installed". Reported as upstreamLatest purely for diagnostics.
19183
+ const installSource = status.installSource;
19184
+ const brewToken = isBrewSource(installSource) ? resolveBrewToken(tool.key, status.realPath || status.path) : null;
19185
+ // A tool without an npm package (OpenCode 2) says where its newest version is published for the way it was
19186
+ // installed: its vendor's update API, or the formula of its Homebrew tap (lib/cli-update-planner.js).
19187
+ const published = tool.npm || tool.github ? null : upstreamVersionSource(tool.key, installSource, brewToken);
19188
+
18963
19189
  let upstreamLatest = null;
18964
19190
  try {
18965
19191
  const controller = new AbortController();
@@ -18972,22 +19198,32 @@ async function checkToolVersions({ force = false } = {}) {
18972
19198
  const res = await fetch(`https://api.github.com/repos/${tool.github}/releases/latest`, { signal: controller.signal });
18973
19199
  clearTimeout(timeout);
18974
19200
  if (res.ok) { const d = await res.json(); upstreamLatest = parseVersion(d.tag_name || ''); }
19201
+ } else if (published) {
19202
+ const res = await fetch(published.url, { signal: controller.signal });
19203
+ clearTimeout(timeout);
19204
+ if (res.ok) upstreamLatest = published.read(await res.text());
19205
+ } else {
19206
+ clearTimeout(timeout);
18975
19207
  }
18976
19208
  } catch { /* network error */ }
18977
19209
 
18978
- const installSource = status.installSource;
18979
- const brewToken = isBrewSource(installSource) ? resolveBrewToken(tool.key, status.realPath || status.path) : null;
19210
+ // The tap's formula as published: what Homebrew installs once it is refreshed. `brew outdated` reads the
19211
+ // local clone of a tap, which nothing refreshes between the user's own brew runs.
19212
+ const brewUpstream = published?.channel === 'brew-formula' ? upstreamLatest : null;
18980
19213
  const latest = resolveLatest({
18981
19214
  installSource,
18982
19215
  brewToken,
18983
19216
  brewOutdated,
18984
19217
  npmLatest: upstreamLatest,
19218
+ brewUpstream,
18985
19219
  installed,
19220
+ ...(tool.key === 'opencode' ? { winget: wingetOpencode } : {}),
18986
19221
  });
19222
+ const refreshBrew = brewNeedsRefresh({ installSource, brewToken, brewOutdated, brewUpstream, installed });
18987
19223
  // A self-updater is started by the path found, so the update reaches this
18988
19224
  // very installation even where a terminal's PATH does not name its folder.
18989
19225
  const updateCommand = installed
18990
- ? buildUpdateCommand(tool.key, installSource, { brewToken, binPath: status.path, platform: process.platform })
19226
+ ? buildUpdateCommand(tool.key, installSource, { brewToken, binPath: status.path, platform: process.platform, refreshBrew, installedVersion: installed, gitBash: tool.key === 'opencode' ? opencodeGitBashPath() : null })
18991
19227
  : null;
18992
19228
 
18993
19229
  return [tool.key, {
@@ -19042,6 +19278,9 @@ async function checkToolVersions({ force = false } = {}) {
19042
19278
  // A check started before a newer refresh must never publish its stale answer.
19043
19279
  if (generation !== _toolVersionGeneration) return;
19044
19280
  _toolVersionCache = { checkedAt: new Date().toISOString(), tools: results };
19281
+ // An update that just landed (the badge's own poll asks every 10 s until it has): SynaBun's serves that still run
19282
+ // the earlier program are replaced now, not at the next restart of SynaBun.
19283
+ try { retireStaleOpencodeServes('version check'); } catch { /* the once-a-minute look tries again */ }
19045
19284
 
19046
19285
  const updates = Object.entries(results).filter(([, v]) => v.updateAvailable);
19047
19286
  const broken = Object.entries(results).filter(([, v]) => v.state === 'broken');
@@ -19144,6 +19383,56 @@ app.use('/api/cli/opencode-serves', createOpencodeServeVerifyApi({ boundary: nat
19144
19383
  // FULL SYSTEM BACKUP & RESTORE
19145
19384
  // ═══════════════════════════════════════════
19146
19385
 
19386
+ // ── Download backup into a folder the owner chose (lib/backup-download.js) ──
19387
+ // Settings → Backups. The server builds the verified archive directly in a folder of this computer (remembered in
19388
+ // data/backup-download.json, ~/Downloads until one is chosen) as one job the page starts and then asks about: no
19389
+ // response a browser tab has to hold in memory. One backup at a time, through serializeBackupOperation, like the
19390
+ // scheduled ones. The owner's routes (editorOwnerGuard, as /api/browse-folder, whose dialog picks the folder), and the
19391
+ // three that write are the owner's page's alone, as restore is: they put a copy of everything, the .env included,
19392
+ // where the request says. Reveal takes no path: it shows the last finished backup, or the folder.
19393
+ const backupDownload = createBackupDownloadService({
19394
+ configPath: resolve(DATA_HOME, 'data', 'backup-download.json'),
19395
+ dataHome: DATA_HOME,
19396
+ sourceRoots: () => backupRoots(DATA_HOME, getBackupAdditionalEntries()),
19397
+ serialize: (operation) => serializeBackupOperation(operation),
19398
+ isBusy: () => _backupOperationActive,
19399
+ createBackup: ({ folderPath, onProgress, signal }) => createVerifiedBackup({
19400
+ dataHome: DATA_HOME,
19401
+ databasePath: getDbPath(),
19402
+ folderPath,
19403
+ kind: 'manual',
19404
+ appVersion: JSON.parse(readFileSync(resolve(PACKAGE_ROOT, 'package.json'), 'utf-8')).version || null,
19405
+ additionalEntries: getBackupAdditionalEntries(),
19406
+ groups: backupContents.groups(),
19407
+ onProgress,
19408
+ signal,
19409
+ }),
19410
+ log: (line) => console.log(line),
19411
+ });
19412
+ const backupDownloadRoutes = backupDownloadHandlers(backupDownload, { revealer: createRevealer() });
19413
+ // ── What a backup holds (lib/backup-groups.js, lib/backup-contents.js) ──
19414
+ // Settings → Backups → What to back up. One choice, kept in data/backup-selection.json, for every backup made on
19415
+ // request or on schedule (the pre-update snapshot keeps its own rules). The sizes are measured on a worker thread
19416
+ // and only read here. Reading is the owner's; changing the choice is the owner's page's alone, as choosing the
19417
+ // folder is.
19418
+ const backupContents = createBackupContentsService({
19419
+ configPath: resolve(DATA_HOME, 'data', 'backup-selection.json'),
19420
+ measure: () => measureBackupContents({ dataHome: DATA_HOME, databasePath: getDbPath(), additionalEntries: getBackupAdditionalEntries() }),
19421
+ log: (line) => console.log(line),
19422
+ });
19423
+ const backupContentsRoutes = backupContentsHandlers(backupContents);
19424
+ function backupDownloadOwnerPage(req, res, next) {
19425
+ if (restoreOwnerPageCall(req)) return next();
19426
+ return refuseNotOwnerPage(req, res, 'Choosing where a backup is saved, and saving one there, is done from SynaBun\'s own page (Settings → Backups), never by an agent, a run or another program.');
19427
+ }
19428
+ app.get('/api/system/backup/job', editorOwnerGuard, backupDownloadRoutes.status);
19429
+ app.put('/api/system/backup/destination', editorOwnerGuard, backupDownloadOwnerPage, backupDownloadRoutes.setDestination);
19430
+ app.post('/api/system/backup/job', editorOwnerGuard, backupDownloadOwnerPage, backupDownloadRoutes.start);
19431
+ app.post('/api/system/backup/job/cancel', editorOwnerGuard, backupDownloadOwnerPage, backupDownloadRoutes.cancel);
19432
+ app.post('/api/system/backup/reveal', editorOwnerGuard, backupDownloadOwnerPage, backupDownloadRoutes.reveal);
19433
+ app.get('/api/system/backup/contents', editorOwnerGuard, backupContentsRoutes.status);
19434
+ app.put('/api/system/backup/contents', editorOwnerGuard, backupDownloadOwnerPage, backupContentsRoutes.update);
19435
+
19147
19436
  // GET /api/system/backup — Download full system backup as ZIP
19148
19437
  app.get('/api/system/backup', async (req, res) => {
19149
19438
  try {
@@ -19156,6 +19445,7 @@ app.get('/api/system/backup', async (req, res) => {
19156
19445
  kind: 'manual',
19157
19446
  appVersion: pkg.version || null,
19158
19447
  additionalEntries: getBackupAdditionalEntries(),
19448
+ groups: backupContents.groups(),
19159
19449
  }));
19160
19450
  res.download(backup.path, backup.name, error => {
19161
19451
  try { if (existsSync(backup.path)) unlinkSync(backup.path); } catch {}
@@ -19173,6 +19463,46 @@ app.get('/api/system/backup', async (req, res) => {
19173
19463
  // and a ZIP over 2 GiB cannot be read into a Buffer at all.
19174
19464
  const RESTORE_STAGING_DIR = resolve(DATA_HOME, 'backups', 'restore-staging');
19175
19465
 
19466
+ // ── Password protection of backups (lib/backup-encryption.js, docs/backup-encryption.md) ──
19467
+ // Settings → Backups → Password protection. Off until the owner sets a password; while it is on, every backup this
19468
+ // server or the updater makes is encrypted or fails (lib/backup-service.js asks the data home's key file itself, so
19469
+ // no caller here passes anything). Reading the state is the owner's; turning it on, changing the password and
19470
+ // turning it off are the owner's page's alone, each with the password in its JSON body, never in the address. Wrong
19471
+ // passwords are slowed by one limiter, shared with the restore's unlock below.
19472
+ const backupPasswordAttempts = createPasswordAttemptLimiter();
19473
+ const backupEncryption = createBackupEncryptionService({ dataHome: DATA_HOME, limiter: backupPasswordAttempts, log: (line) => console.log(line) });
19474
+ const backupEncryptionRoutes = backupEncryptionHandlers(backupEncryption);
19475
+ function backupEncryptionOwnerPage(req, res, next) {
19476
+ if (restoreOwnerPageCall(req)) return next();
19477
+ return refuseNotOwnerPage(req, res, 'The backup password is set, changed and removed from SynaBun\'s own page (Settings → Backups), never by an agent, a run or another program.');
19478
+ }
19479
+ app.get('/api/system/backup/encryption', editorOwnerGuard, backupEncryptionRoutes.status);
19480
+ app.post('/api/system/backup/encryption/enable', editorOwnerGuard, backupEncryptionOwnerPage, backupEncryptionRoutes.enable);
19481
+ app.post('/api/system/backup/encryption/change', editorOwnerGuard, backupEncryptionOwnerPage, backupEncryptionRoutes.change);
19482
+ app.post('/api/system/backup/encryption/disable', editorOwnerGuard, backupEncryptionOwnerPage, backupEncryptionRoutes.disable);
19483
+ // The latest backups in the folders SynaBun writes them to, and whether each is encrypted (told by the file's first
19484
+ // bytes, never by its name). Names, dates and sizes only: no path leaves the server and no archive is opened.
19485
+ app.get('/api/system/backup/history', editorOwnerGuard, async (req, res) => {
19486
+ try {
19487
+ const folders = [resolve(DATA_HOME, 'backups', 'updates')];
19488
+ try { folders.push(loadAutoBackupConfig().folderPath); } catch { /* no schedule */ }
19489
+ try { folders.push(backupDownload.destination().folderPath); } catch { /* no folder chosen */ }
19490
+ const listed = [];
19491
+ for (const folder of new Set(folders.filter(Boolean).map(item => resolve(item)))) {
19492
+ try { listed.push(...await listBackupSnapshots(folder)); } catch { /* a drive that is not there */ }
19493
+ }
19494
+ listed.sort((a, b) => b.createdMs - a.createdMs);
19495
+ const backups = [];
19496
+ for (const item of listed.slice(0, 12)) {
19497
+ backups.push({ name: item.name, kind: item.kind, createdAt: item.createdAt, sizeBytes: item.sizeBytes, encrypted: await isEncryptedBackupFile(item.path) });
19498
+ }
19499
+ res.json({ ok: true, backups, total: listed.length });
19500
+ } catch (err) {
19501
+ console.error('GET /api/system/backup/history error:', err.message);
19502
+ res.status(500).json({ ok: false, error: 'The list of backups could not be read.' });
19503
+ }
19504
+ });
19505
+
19176
19506
  // POST /api/system/restore/preview — Read manifest from uploaded ZIP without applying
19177
19507
  /** One sentence for a failed MCP server build (lib/mcp-build.js result), with what the compiler said when it said anything. */
19178
19508
  function mcpBuildFailureMessage(build) {
@@ -19232,6 +19562,22 @@ function markRestoredAutomationRecords(targets) {
19232
19562
  return marked;
19233
19563
  }
19234
19564
 
19565
+ /**
19566
+ * What the page shows before it asks for a restore: when the backup was made, how many files, and which groups it
19567
+ * holds (lib/backup-groups.js). The file list and the checksums stay here: for a full backup they are tens of MB.
19568
+ * The same answer for a plain backup and for an encrypted one after its password opened it.
19569
+ */
19570
+ async function restorePreviewOf(zip) {
19571
+ const found = await readBackupManifest(zip);
19572
+ if (!found) throw Object.assign(new Error('Invalid backup: manifest.json not found'), { status: 400, code: 'RESTORE_MANIFEST_MISSING' });
19573
+ const { files, checksums, inputs, ...head } = found.manifest;
19574
+ return {
19575
+ ok: true,
19576
+ manifest: { ...head, fileCount: Array.isArray(files) ? files.length : 0 },
19577
+ contents: readManifestGroups(found.manifest),
19578
+ };
19579
+ }
19580
+
19235
19581
  app.post('/api/system/restore/preview', async (req, res) => {
19236
19582
  if (!restoreOwnerPageCall(req)) return refuseRestoreCaller(req, res);
19237
19583
  let upload = null;
@@ -19239,17 +19585,20 @@ app.post('/api/system/restore/preview', async (req, res) => {
19239
19585
  try {
19240
19586
  upload = await saveRestoreUpload(req, RESTORE_STAGING_DIR);
19241
19587
  if (upload.sizeBytes === 0) {
19242
- return res.status(400).json({ error: 'No data received' });
19588
+ return res.status(400).json({ error: 'No data received', code: 'RESTORE_EMPTY_UPLOAD' });
19243
19589
  }
19244
- zip = await openZipArchive(upload.path);
19245
- const found = await readBackupManifest(zip);
19246
- if (!found) {
19247
- return res.status(400).json({ error: 'Invalid backup: manifest.json not found' });
19590
+ // An encrypted backup says nothing of what it holds before its password. It stays staged, still encrypted, and
19591
+ // the page sends the password in a JSON body (POST /api/system/restore/unlock, lib/backup-restore-session.js).
19592
+ if (await isEncryptedBackupFile(upload.path)) {
19593
+ const staged = await restoreSessions.keep(upload);
19594
+ upload = null;
19595
+ return res.json({ ok: true, encrypted: true, locked: true, ...staged });
19248
19596
  }
19249
- res.json({ ok: true, manifest: found.manifest });
19597
+ zip = await openZipArchive(upload.path);
19598
+ res.json(await restorePreviewOf(zip));
19250
19599
  } catch (err) {
19251
19600
  console.error('POST /api/system/restore/preview error:', err.message);
19252
- if (!res.headersSent) res.status(500).json({ error: err.message });
19601
+ if (!res.headersSent) res.status(Number(err.status) || 500).json({ error: err.message, code: restoreFailureCode(err) });
19253
19602
  } finally {
19254
19603
  await zip?.close().catch(() => {});
19255
19604
  removeRestoreUpload(upload);
@@ -19265,32 +19614,64 @@ app.post('/api/system/restore', async (req, res) => {
19265
19614
  try {
19266
19615
  upload = await saveRestoreUpload(req, RESTORE_STAGING_DIR);
19267
19616
  if (upload.sizeBytes === 0) {
19268
- return res.status(400).json({ error: 'No backup data received' });
19617
+ return res.status(400).json({ error: 'No backup data received', code: 'RESTORE_EMPTY_UPLOAD' });
19618
+ }
19619
+ // An encrypted backup is restored in steps (preview, unlock, apply-staged): this route has no way to be given
19620
+ // its password, and must not be given one in the address.
19621
+ if (await isEncryptedBackupFile(upload.path)) {
19622
+ return res.status(400).json({ ok: false, code: 'BACKUP_ENCRYPTED', error: 'This backup is encrypted. Restore it from Settings → Memory & backups → Backups → Restore, which asks for its password.' });
19269
19623
  }
19270
-
19271
- const mode = req.query.mode || 'full';
19272
19624
 
19273
19625
  zip = await openZipArchive(upload.path);
19626
+ await applyRestoreArchive(zip, req.query.mode || 'full', res);
19627
+ } catch (err) {
19628
+ console.error('POST /api/system/restore error:', err.message);
19629
+ if (!res.headersSent) res.status(500).json({ error: err.message, ...restoreFailureFields(err, res) });
19630
+ } finally {
19631
+ await zip?.close().catch(() => {});
19632
+ removeRestoreUpload(upload);
19633
+ }
19634
+ });
19274
19635
 
19636
+ /**
19637
+ * The restore itself, from an opened archive: the uploaded ZIP, or the ZIP inside an encrypted backup whose password
19638
+ * opened it (lib/backup-restore-session.js). Verifies before it writes, writes only what the archive holds, and
19639
+ * answers `res`. The caller closes the archive and removes the upload.
19640
+ */
19641
+ async function applyRestoreArchive(zip, mode, res) {
19275
19642
  // Find and validate manifest
19276
19643
  const found = await readBackupManifest(zip);
19277
19644
  if (!found) {
19278
- return res.status(400).json({ error: 'Invalid backup: manifest.json not found' });
19645
+ return res.status(400).json({ error: 'Invalid backup: manifest.json not found', code: 'RESTORE_MANIFEST_MISSING' });
19279
19646
  }
19280
19647
  const { manifest, prefix } = found;
19281
19648
  if (![1, 2, 3].includes(manifest.version)) {
19282
- return res.status(400).json({ error: `Unsupported backup version: ${manifest.version}` });
19649
+ return res.status(400).json({ error: `Unsupported backup version: ${manifest.version}`, code: 'RESTORE_UNSUPPORTED_VERSION' });
19283
19650
  }
19284
19651
 
19285
19652
  // v3 archives are published only after checksum verification. Recheck on
19286
19653
  // restore so a damaged or edited snapshot cannot partially replace state.
19287
19654
  if (manifest.version >= 3) {
19288
- try { await verifyBackupChecksums(zip, { prefix, manifest, label: 'Invalid backup' }); }
19289
- catch (error) { return res.status(400).json({ error: error.message }); }
19655
+ // An archive that records its groups holds exactly those, or it is refused before anything is written.
19656
+ try {
19657
+ assertBackupGroups(zip, manifest, prefix, 'Invalid backup');
19658
+ await verifyBackupChecksums(zip, { prefix, manifest, label: 'Invalid backup' });
19659
+ }
19660
+ catch (error) { return res.status(400).json({ error: error.message, code: restoreFailureCode(error) }); }
19661
+ }
19662
+ // An encrypted backup: every part of the file passes its check before anything is written, the parts no entry
19663
+ // reaches too (a file cut short, added to or reordered fails here).
19664
+ if (zip.encrypted) {
19665
+ try { await zip.source.authenticateRest(); }
19666
+ catch (error) { return res.status(400).json({ error: error.message, code: restoreFailureCode(error) }); }
19290
19667
  }
19668
+ // What this restore brings and what it leaves as it is: only files the archive holds are written, nothing is
19669
+ // deleted, so the groups a backup does not contain keep whatever is here now.
19670
+ const contents = readManifestGroups(manifest);
19291
19671
 
19292
19672
  const entryAt = rel => zip.getEntry(`${prefix}/${rel}`);
19293
- const results = { files: [], snapshots: [], errors: [] };
19673
+ // `errorCodes`: one stable code per sentence of `errors`, read when the answer is written.
19674
+ const results = { files: [], snapshots: [], errors: [], get errorCodes() { return this.errors.map((sentence) => restoreWarningCode(sentence)); } };
19294
19675
 
19295
19676
  // Restore config files
19296
19677
  if (mode === 'full' || mode === 'config-only') {
@@ -19307,9 +19688,12 @@ app.post('/api/system/restore', async (req, res) => {
19307
19688
  claudeSettings: home ? join(home, '.claude', 'settings.json') : null,
19308
19689
  });
19309
19690
  if (unsafe.length) {
19310
- return res.status(400).json({ error: `Invalid backup: unsafe path ${unsafe[0]}` });
19691
+ return res.status(400).json({ error: `Invalid backup: unsafe path ${unsafe[0]}`, code: 'RESTORE_UNSAFE_PATH' });
19311
19692
  }
19312
19693
 
19694
+ // From here on a failure may leave some files replaced, and its answer says so (restoreFailureFields).
19695
+ (res.locals ||= {}).restoreWriting = true;
19696
+
19313
19697
  // .env
19314
19698
  const envEntry = entryAt('env.bak');
19315
19699
  if (envEntry) {
@@ -19358,6 +19742,7 @@ app.post('/api/system/restore', async (req, res) => {
19358
19742
  if (mode === 'full' || mode === 'snapshots-only') {
19359
19743
  const dbEntry = entryAt('database/memory.db');
19360
19744
  if (dbEntry) {
19745
+ (res.locals ||= {}).restoreWriting = true;
19361
19746
  try {
19362
19747
  // Close existing database connection before replacing
19363
19748
  closeDb();
@@ -19384,6 +19769,20 @@ app.post('/api/system/restore', async (req, res) => {
19384
19769
  }
19385
19770
  }
19386
19771
 
19772
+ // What the archive held, by group, goes with the answer; the sizes next to Settings → Backups → What to back
19773
+ // up were measured before this restore.
19774
+ results.contents = contents;
19775
+ backupContents.invalidate();
19776
+ // Backup encryption is this installation's own (its key file is in no archive and no restore writes it). Where
19777
+ // there is none and this backup was encrypted, its key is kept, so the backups made from here on are encrypted
19778
+ // as the restored one was, with the password that just opened it: a restore on a new computer never ends in
19779
+ // scheduled backups written in plain.
19780
+ if (zip.encrypted) {
19781
+ results.encrypted = true;
19782
+ try { if (backupEncryption.adopt(zip.source.recipientForAdoption())) results.encryptionKept = true; }
19783
+ catch (err) { results.errors.push(`Backup encryption could not be kept: ${err.message}. Turn it on in Settings → Backups.`); }
19784
+ }
19785
+
19387
19786
  // Post-restore: ensure MCP server is built (critical for fresh installs + restore). Built means dist/index.js
19388
19787
  // and every module it imports (lib/mcp-dist.js), stamped with this version and source (lib/mcp-build.js): the
19389
19788
  // builder compiles into a temp folder and swaps it in only on success, so a failure keeps whatever dist there was.
@@ -19408,14 +19807,23 @@ app.post('/api/system/restore', async (req, res) => {
19408
19807
  res.json({ ok: true, message: 'Backup restored successfully', results, ...(results.restart ? { restart: true, bootId: SERVER_BOOT_ID } : {}) });
19409
19808
  // The new build loads only in a new server: the same restart as Apps → Restart Server, once the answer is out.
19410
19809
  if (results.restart) setTimeout(() => { try { requestServerRestart(); } catch (err) { console.error('[restore] restart after the MCP build failed:', err?.message); } }, 500);
19411
- } catch (err) {
19412
- console.error('POST /api/system/restore error:', err.message);
19413
- if (!res.headersSent) res.status(500).json({ error: err.message });
19414
- } finally {
19415
- await zip?.close().catch(() => {});
19416
- removeRestoreUpload(upload);
19417
- }
19418
- });
19810
+ }
19811
+
19812
+ // ── An encrypted backup: upload once, then the password, then the restore (lib/backup-restore-session.js) ──
19813
+ // The preview route above keeps an encrypted upload instead of answering with its contents. These three are the
19814
+ // rest: unlock ({ uploadId, password }: the same preview a plain backup gets, or 401 WRONG_PASSWORD with nothing
19815
+ // changed), apply-staged ({ uploadId, mode }: applyRestoreArchive over the decrypting reader) and discard. The
19816
+ // owner's page's alone, as restore is. The password is in the JSON body of unlock only; what stays afterwards is
19817
+ // that one file's keys, in memory, until the restore, a discard or 30 minutes. A right password clears the count of
19818
+ // wrong ones only for this installation's own key: anybody can upload a file whose password they know.
19819
+ const restoreSessions = createRestoreSessions({ limiter: backupPasswordAttempts, currentKeyId: () => backupEncryption.status().keyId || null });
19820
+ const encryptedRestoreRoutes = encryptedRestoreHandlers({ sessions: restoreSessions, preview: restorePreviewOf, apply: applyRestoreArchive });
19821
+ function restoreOwnerPageOnly(req, res, next) {
19822
+ return restoreOwnerPageCall(req) ? next() : refuseRestoreCaller(req, res);
19823
+ }
19824
+ app.post('/api/system/restore/unlock', editorOwnerGuard, restoreOwnerPageOnly, encryptedRestoreRoutes.unlock);
19825
+ app.post('/api/system/restore/apply-staged', editorOwnerGuard, restoreOwnerPageOnly, encryptedRestoreRoutes.apply);
19826
+ app.post('/api/system/restore/discard', editorOwnerGuard, restoreOwnerPageOnly, encryptedRestoreRoutes.discard);
19419
19827
 
19420
19828
  // ═══════════════════════════════════════════
19421
19829
  // AUTO-BACKUP SYSTEM
@@ -19473,8 +19881,8 @@ function getBackupAdditionalEntries() {
19473
19881
  return entries;
19474
19882
  }
19475
19883
 
19476
- function backupConfigResponse(cfg = loadAutoBackupConfig()) {
19477
- const snapshots = cfg.folderPath ? listBackupSnapshots(cfg.folderPath) : [];
19884
+ async function backupConfigResponse(cfg = loadAutoBackupConfig()) {
19885
+ const snapshots = cfg.folderPath ? await listBackupSnapshots(cfg.folderPath) : [];
19478
19886
  const health = getBackupHealth(cfg, { snapshots });
19479
19887
  if (_backupOperationActive || _autoBackupPromise) {
19480
19888
  health.status = 'running';
@@ -19504,15 +19912,15 @@ async function runAutoBackup({ force = false, kind = 'scheduled', folderPath = n
19504
19912
  try {
19505
19913
  const pkg = JSON.parse(readFileSync(resolve(PACKAGE_ROOT, 'package.json'), 'utf-8'));
19506
19914
  let preRetention = null;
19507
- const backup = await serializeBackupOperation(async () => {
19915
+ const { backup, retention } = await serializeBackupOperation(async () => {
19508
19916
  if (kind === 'scheduled') {
19509
- preRetention = applyBackupRetention({
19917
+ preRetention = await applyBackupRetention({
19510
19918
  folderPath: destination,
19511
19919
  retention: cfg.retention,
19512
19920
  incomingBytes: cfg.lastBackupSize,
19513
19921
  });
19514
19922
  }
19515
- return createVerifiedBackup({
19923
+ const backup = await createVerifiedBackup({
19516
19924
  dataHome: DATA_HOME,
19517
19925
  databasePath: getDbPath(),
19518
19926
  folderPath: destination,
@@ -19520,9 +19928,13 @@ async function runAutoBackup({ force = false, kind = 'scheduled', folderPath = n
19520
19928
  appVersion: pkg.version || null,
19521
19929
  additionalEntries: getBackupAdditionalEntries(),
19522
19930
  expectedArchiveBytes: cfg.lastBackupSize,
19931
+ // The same choice as a manual backup (Settings → Backups → What to back up).
19932
+ groups: backupContents.groups(),
19523
19933
  });
19934
+ // Keep both async sweeps in the backup queue so another operation cannot publish between them.
19935
+ const retention = await applyBackupRetention({ folderPath: destination, retention: cfg.retention });
19936
+ return { backup, retention };
19524
19937
  });
19525
- const retention = applyBackupRetention({ folderPath: destination, retention: cfg.retention });
19526
19938
  cfg.lastVerifiedBackup = backup.createdAt;
19527
19939
  cfg.lastBackup = backup.createdAt; // backward compatibility
19528
19940
  cfg.lastBackupPath = backup.path;
@@ -19553,6 +19965,7 @@ function startAutoBackupScheduler() {
19553
19965
  const nextDue = nextBackupDueMs(cfg, { lastAttemptMs: _autoBackupLastAttemptMs });
19554
19966
  const delay = Math.max(0, Math.min(2_147_000_000, nextDue - Date.now()));
19555
19967
  _autoBackupTimer = setTimeout(async () => {
19968
+ if (typeof markActivity === 'function') markActivity('scheduler:backup');
19556
19969
  try { await runAutoBackup(); }
19557
19970
  catch (error) { console.error(`[auto-backup] Scheduler failed safely: ${error.message}`); }
19558
19971
  finally { startAutoBackupScheduler(); }
@@ -19562,7 +19975,7 @@ function startAutoBackupScheduler() {
19562
19975
 
19563
19976
  function stopAutoBackupScheduler() {
19564
19977
  if (_autoBackupTimer) {
19565
- clearInterval(_autoBackupTimer);
19978
+ clearTimeout(_autoBackupTimer);
19566
19979
  _autoBackupTimer = null;
19567
19980
  }
19568
19981
  }
@@ -19570,13 +19983,27 @@ function stopAutoBackupScheduler() {
19570
19983
  // Boot: start scheduler if enabled
19571
19984
  startAutoBackupScheduler();
19572
19985
 
19986
+ // Boot: what a backup or a restore that never finished left behind (a crash, a kill, a power cut). The partial
19987
+ // archives and the staged copies of a process that is gone, in every folder a backup works in, and whatever is in
19988
+ // the two folders that only ever hold this server's own working files (restore uploads, the browser download's
19989
+ // staging). The staged copies of an encrypted backup are plaintext: they do not wait for the next backup to be
19990
+ // removed. On a worker thread: a backup folder can be a drive that answers slowly.
19991
+ setTimeout(() => {
19992
+ let folders = [];
19993
+ try { folders = [loadAutoBackupConfig().folderPath, backupDownload.destination().folderPath]; } catch { /* the data home's own folders are swept all the same */ }
19994
+ sweepCrashedBackupArtifacts({ dataHome: DATA_HOME, folders, scratchFolders: [RESTORE_STAGING_DIR, resolve(DATA_HOME, 'backups', 'manual-staging')] }).then((removed) => {
19995
+ for (const [folder, names] of Object.entries(removed || {})) console.log(`[backup] Removed ${names.length} leftover working file(s) of an unfinished backup or restore in ${folder}`);
19996
+ }, (error) => console.warn(`[backup] Leftovers of unfinished backups could not be swept: ${error?.message || error}`));
19997
+ }, 1500).unref?.();
19998
+
19573
19999
  // GET /api/system/auto-backup — Get auto-backup config
19574
- app.get('/api/system/auto-backup', (req, res) => {
19575
- res.json(backupConfigResponse());
20000
+ app.get('/api/system/auto-backup', async (req, res) => {
20001
+ try { res.json(await backupConfigResponse()); }
20002
+ catch (err) { res.status(500).json({ error: err.message }); }
19576
20003
  });
19577
20004
 
19578
20005
  // PUT /api/system/auto-backup — Update auto-backup config
19579
- app.put('/api/system/auto-backup', (req, res) => {
20006
+ app.put('/api/system/auto-backup', async (req, res) => {
19580
20007
  try {
19581
20008
  const current = loadAutoBackupConfig();
19582
20009
  const { enabled, intervalMinutes, folderPath, retention } = req.body;
@@ -19595,7 +20022,7 @@ app.put('/api/system/auto-backup', (req, res) => {
19595
20022
  stopAutoBackupScheduler();
19596
20023
  }
19597
20024
 
19598
- res.json({ ok: true, config: backupConfigResponse(current) });
20025
+ res.json({ ok: true, config: await backupConfigResponse(current) });
19599
20026
  } catch (err) {
19600
20027
  res.status(500).json({ error: err.message });
19601
20028
  }
@@ -19607,18 +20034,18 @@ app.post('/api/system/auto-backup/trigger', async (req, res) => {
19607
20034
  const cfg = loadAutoBackupConfig();
19608
20035
  if (!cfg.folderPath) return res.status(400).json({ error: 'No backup folder configured' });
19609
20036
  const result = await runAutoBackup({ force: true });
19610
- if (result?.error) return res.status(500).json({ error: result.error, ...backupConfigResponse() });
19611
- res.json(backupConfigResponse());
20037
+ if (result?.error) return res.status(500).json({ error: result.error, ...await backupConfigResponse() });
20038
+ res.json(await backupConfigResponse());
19612
20039
  } catch (err) {
19613
20040
  res.status(500).json({ error: err.message });
19614
20041
  }
19615
20042
  });
19616
20043
 
19617
20044
  // GET /api/system/backups — verified/runtime backup history for Settings.
19618
- app.get('/api/system/backups', (req, res) => {
20045
+ app.get('/api/system/backups', async (req, res) => {
19619
20046
  try {
19620
20047
  const cfg = loadAutoBackupConfig();
19621
- const snapshots = cfg.folderPath ? listBackupSnapshots(cfg.folderPath) : [];
20048
+ const snapshots = cfg.folderPath ? await listBackupSnapshots(cfg.folderPath) : [];
19622
20049
  res.json({ ok: true, snapshots, health: getBackupHealth(cfg, { snapshots }), retention: cfg.retention });
19623
20050
  } catch (err) {
19624
20051
  res.status(500).json({ error: err.message });
@@ -22601,8 +23028,7 @@ async function getSessionEntriesForRequest(projDir, { forceRefresh = false } = {
22601
23028
  let _codexSessionCatalogRefresh = null;
22602
23029
  function getCodexSessionCatalogRefresh() {
22603
23030
  if (!_codexSessionCatalogRefresh) {
22604
- _codexSessionCatalogRefresh = memoCache(() => rebuildCodexCache({
22605
- background: true,
23031
+ _codexSessionCatalogRefresh = memoCache(() => runSessionJob('codex', {
22606
23032
  accounts: loadCodexAccounts().accounts,
22607
23033
  projects: loadHookProjects(),
22608
23034
  }), { ttlMs: 15000 });
@@ -23029,15 +23455,16 @@ function antigravityHomeFor(kind, id) { return antigravityHomeDir(antigravityHom
23029
23455
  // included, into memory capture (lib/memory-session-capture.js). A pass at start, one after a panel turn ends (that
23030
23456
  // conversation only, a moment later so agy has written its last step), one every five minutes, and a fresh one
23031
23457
  // before Resume or Skills Studio searches them (at most every 15 s).
23032
- function antigravitySessionStores({ userOnly = false } = {}) {
23033
- return antigravityStores({ homesRoot: userOnly ? null : antigravityHomesRoot(DATA_HOME) });
23034
- }
23035
23458
  let _antigravityCacheAt = 0;
23459
+ let _antigravityPass = null;
23036
23460
  function refreshAntigravityCatalog({ force = false } = {}) {
23461
+ if (_antigravityPass) return _antigravityPass;
23037
23462
  if (!force && Date.now() - _antigravityCacheAt < 15_000) return null;
23038
- _antigravityCacheAt = Date.now();
23039
- try { return rebuildAntigravityCache({ stores: antigravitySessionStores() }); }
23040
- catch (err) { console.warn(' Session cache (antigravity) error:', err.message); return null; }
23463
+ _antigravityPass = runSessionJob('antigravity', { homesRoot: antigravityHomesRoot(DATA_HOME) })
23464
+ .then(result => { _antigravityCacheAt = Date.now(); return result; })
23465
+ .catch(err => { console.warn(' Session cache (antigravity) error:', err.message); return null; })
23466
+ .finally(() => { _antigravityPass = null; });
23467
+ return _antigravityPass;
23041
23468
  }
23042
23469
  const _antigravityRefreshTimers = new Map();
23043
23470
  function refreshAntigravitySession(sessionId) {
@@ -23045,8 +23472,9 @@ function refreshAntigravitySession(sessionId) {
23045
23472
  clearTimeout(_antigravityRefreshTimers.get(sessionId));
23046
23473
  _antigravityRefreshTimers.set(sessionId, setTimeout(() => {
23047
23474
  _antigravityRefreshTimers.delete(sessionId);
23048
- try { rebuildAntigravityCache({ stores: antigravitySessionStores({ userOnly: true }), only: sessionId }); }
23049
- catch (err) { console.warn(' Session cache (antigravity) error:', err.message); }
23475
+ markActivity('session-cache:antigravity-turn');
23476
+ runSessionJob('antigravity', { only: sessionId })
23477
+ .catch(err => console.warn(' Session cache (antigravity) error:', err.message));
23050
23478
  }, 1500));
23051
23479
  _antigravityRefreshTimers.get(sessionId).unref?.();
23052
23480
  }
@@ -23103,7 +23531,7 @@ app.get('/api/session-search', async (req, res) => {
23103
23531
  }
23104
23532
 
23105
23533
  // Antigravity's index follows its transcripts (refreshAntigravityCatalog: at most every 15 s).
23106
- if (provider === 'antigravity') refreshAntigravityCatalog();
23534
+ if (provider === 'antigravity') await refreshAntigravityCatalog();
23107
23535
 
23108
23536
  // 1. FTS5 substring hits
23109
23537
  const ftsRows = searchSessionFts(q, { provider, project: projectFilter, limit: limit * 2 });
@@ -24558,8 +24986,7 @@ skillsService = createSkillsService({
24558
24986
  operationsOptions: { notify: (item) => {
24559
24987
  const session = _assistantRuntime?.listSessions?.().find((s) => s.status !== 'ended');
24560
24988
  if (!session) return false;
24561
- _assistantRuntime.routerMailbox(session.id, item);
24562
- return true;
24989
+ return _assistantRuntime.routerMailbox(session.id, item);
24563
24990
  } },
24564
24991
  });
24565
24992
  registerSkillsV2Routes(app, {
@@ -24936,7 +25363,7 @@ async function skillSourceSessions({ provider, project = null, q = '', limit = 4
24936
25363
  } else if (provider === 'antigravity') {
24937
25364
  // The user's own Antigravity conversations (the panel's and a terminal agy's), as Resume's index keeps them,
24938
25365
  // titled as Antigravity titles them (refreshAntigravityCatalog).
24939
- refreshAntigravityCatalog();
25366
+ await refreshAntigravityCatalog();
24940
25367
  for (const entry of listSessionCache('antigravity', { limit: 100000 })) {
24941
25368
  if (entry.deleted || !entry.project_path) continue;
24942
25369
  const dir = resolve(entry.project_path);
@@ -26862,13 +27289,17 @@ app.delete('/api/skills-studio/import/stage/:stagingId', (req, res) => {
26862
27289
  });
26863
27290
 
26864
27291
  // GET /api/health — Check if SQLite database is accessible
27292
+ // The page asks this every 3 s to tell a running server from a stopped one (public/shared/server-presence.js), so
27293
+ // it must answer whatever else the database is doing: the count is read at most once per HEALTH_COUNT_TTL_MS, never
27294
+ // per request. On 2026-11-21 each probe ran its own synchronous COUNT(*) behind statements that took seconds while a
27295
+ // backup kept the disk busy, two probes in a row timed out, and a live server was shown as offline.
27296
+ const healthMemoryCount = createHealthCount({ read: () => { getDb(); return countMemories(); }, store: memoryStoreGate });
26865
27297
  app.get('/api/health', (req, res) => {
26866
27298
  try {
26867
- // getDb() auto-creates the directory, file, and schema if missing
26868
- getDb();
26869
- const count = countMemories();
27299
+ // getDb() auto-creates the directory, file, and schema if missing (inside the count's read)
27300
+ const count = healthMemoryCount();
26870
27301
  res.json({
26871
- ok: true, storage: 'sqlite', memories: count, projectDir: PACKAGE_ROOT, install: INSTALL_KIND, startLauncher: getStartLauncherState(), entry: START_ENTRY,
27302
+ ok: true, storage: 'sqlite', memories: count, ...healthMemoryCount.storeState?.(), projectDir: PACKAGE_ROOT, install: INSTALL_KIND, startLauncher: getStartLauncherState(), entry: START_ENTRY,
26872
27303
  version: SERVER_VERSION, dataHomeId: DATA_HOME_ID, installEntry: INSTALL_ENTRY,
26873
27304
  // Which server this is, and whether it is on its way out for a restart: a
26874
27305
  // page showing the restart tells this one from the one that replaces it.
@@ -28121,11 +28552,14 @@ try {
28121
28552
  const { createMcpRoutes, ensureInit: mcpEnsureInit } = await import(mcpPath);
28122
28553
 
28123
28554
  // Eagerly init: DB, categories, embedding model — runs in background, doesn't block server start
28124
- mcpEnsureInit().then(() => {
28555
+ const warmMcp = () => mcpEnsureInit().then(() => {
28125
28556
  console.log(' MCP HTTP: DB + embeddings warm');
28126
28557
  }).catch(err => {
28558
+ if (isMemoryStoreRefusal(err)) return; // warmed below, once the store is back
28127
28559
  console.error(' MCP HTTP eager init failed:', err.message);
28128
28560
  });
28561
+ warmMcp();
28562
+ memoryStoreGate.subscribe((state) => { if (state === 'ready' || state === 'deferred') warmMcp(); });
28129
28563
 
28130
28564
  // A request that names a run (X-Synabun-Terminal) without that run's terminal token is not that run here either
28131
28565
  // (lib/terminal-tokens.js): the MCP server routes it as its own MCP session, so it never shares the run's identity
@@ -28137,6 +28571,13 @@ try {
28137
28571
  // /mcp mount directly" (mcpSessionProofEligible, finding 5); the MCP's own loopback check stays in front of it.
28138
28572
  const mcpRouter = createMcpRoutes({ terminalAuth, sessionProof: { eligible: (req) => mcpSessionProofEligible(req), issue: (sid) => _terminalTokens.issueSession(sid), revoke: (sid) => { endMcpSessionProof(sid); } } });
28139
28573
 
28574
+ // The in-process MCP runs its tools on this thread (an Assistant brain's recall among them): name it for the stall log.
28575
+ // Answers nothing. No mount path of its own: a '/mcp' mount here would be mirrored by the route-table tests.
28576
+ app.use(function markMcpActivity(req, res, next) {
28577
+ if (req.path === '/mcp' || req.path.startsWith('/mcp/')) { const end = beginActivity('mcp:request'); res.once('close', end); }
28578
+ next();
28579
+ });
28580
+
28140
28581
  // Keyed path: /mcp/<key> — validates key, then forwards to MCP router
28141
28582
  app.use('/mcp/:key', (req, res, next) => {
28142
28583
  if (req.params.key !== activeMcpKey) {
@@ -29108,6 +29549,7 @@ function persistNativeScheduleOutcome(run, runningInfo = null) {
29108
29549
 
29109
29550
  const schedule = schedules[index];
29110
29551
  schedule.lastRunResult = nativeScheduleResult(run);
29552
+ schedule.lastStopProvenance = run.stopProvenance || null;
29111
29553
  schedule.updatedAt = new Date().toISOString();
29112
29554
  saveSchedules(schedules);
29113
29555
  broadcastSync({ type: 'schedule:updated', schedule });
@@ -29131,6 +29573,7 @@ function persistExecScheduleOutcome(loopState, status, reason = '') {
29131
29573
  const index = schedules.findIndex((schedule) => schedule.id === loopState.scheduledBy);
29132
29574
  if (index === -1) return;
29133
29575
  const schedule = schedules[index];
29576
+ schedule.lastStopProvenance = loopState.stopProvenance || null;
29134
29577
  schedule.lastRunResult = status === 'completed'
29135
29578
  ? 'completed'
29136
29579
  : status === 'stopped'
@@ -29872,6 +30315,7 @@ function noteMoreLoginContextClose(session, sessionId, context = session?.contex
29872
30315
  // Asked before a card's pick is approved: a held run that would refuse it keeps the card open.
29873
30316
  checkHeld: (runId, target, role) => _assistantDispatcher?.heldRouteRefusal?.(runId, target, role) || null,
29874
30317
  declineHeld: (runId, reason) => _assistantDispatcher?.declineRoute?.(runId, { reason }),
30318
+ activeRouteRuns: (sessionId, routeId) => _assistantDispatcher?.activeRouteRuns(sessionId, routeId),
29875
30319
  },
29876
30320
  log: (tag, message) => assistantLog(tag, message),
29877
30321
  clarifier: assistantClarifier,
@@ -29946,6 +30390,7 @@ function noteMoreLoginContextClose(session, sessionId, context = session?.contex
29946
30390
  // The one instance of this server (never a second createCoordinationService in this file): a stop that is not
29947
30391
  // a signal (Restart Server, /api/server/shutdown, an update) closes it at the end of runGracefulShutdown.
29948
30392
  _assistantCoordination = assistantCoordination;
30393
+ await assistantCoordination.ready;
29949
30394
  if (assistantCoordination.degraded) console.warn(`[assistant] coordination store unavailable (${assistantCoordination.degraded.message}): agent events are kept in memory until the next start`);
29950
30395
  }
29951
30396
  // ══ end Agents P2 ══════════════════════════════════════════════════════════════════════════════════════════
@@ -30105,6 +30550,7 @@ function noteMoreLoginContextClose(session, sessionId, context = session?.contex
30105
30550
  .then((m) => m.setTeamContextResolver((runId) => !!teamScheduler.member(runId)))
30106
30551
  .catch((err) => console.warn('[assistant] team tool unavailable (mcp-server needs a build):', err?.message || err));
30107
30552
  // After a restart: the library's own recovery, then every team under way is taken up again. Never awaited here.
30553
+ markActivity('startup:team-recovery');
30108
30554
  teamScheduler.recover().catch((err) => console.warn('[assistant] team recovery failed:', err?.message || err))
30109
30555
  .finally(() => broadcastSync({ type: 'assistant:team-changed', event: 'recovered' }));
30110
30556
  _assistantTeamScheduler = teamScheduler;
@@ -30117,6 +30563,7 @@ function noteMoreLoginContextClose(session, sessionId, context = session?.contex
30117
30563
  // then repair saved routes whose effort their model does not run (idempotent;
30118
30564
  // a provider whose list is not available yet is retried a few times).
30119
30565
  const repairRouteEfforts = async (attempt = 0) => {
30566
+ markActivity('startup:route-efforts');
30120
30567
  const { repairPreferenceEfforts } = await import('./lib/effort-levels.js');
30121
30568
  const cat = await assistantCatalog.full({ force: attempt > 0 });
30122
30569
  const { fixes, unverified } = repairPreferenceEfforts(assistantConfigStore.routing().preferences, cat);
@@ -30347,25 +30794,24 @@ function cleanupClaudeLoopMcpConfig(terminalSessionId) {
30347
30794
  * Each opencode-<sid> dir carries a ~61 MB node_modules; the per-loop cleanup
30348
30795
  * runs on graceful stop and PTY exit, but a server crash/restart (or a PTY that
30349
30796
  * never fired its exit) leaves dirs stranded forever. At boot no loop is live,
30350
- * so anything older than the cutoff is safe to remove. Mirrors the mtime-cutoff
30351
- * rmSync pattern used by cleanupOldUpdaterStages().
30797
+ * so anything older than the cutoff is safe to remove. Removal runs off the main thread even for an entire dependency tree.
30352
30798
  */
30353
- function cleanupStaleLoopConfigs(maxAgeMs = 6 * 60 * 60 * 1000) {
30799
+ async function cleanupStaleLoopConfigs(maxAgeMs = 6 * 60 * 60 * 1000) {
30354
30800
  const dir = resolve(DATA_HOME, 'data', 'loop-configs');
30355
30801
  let removedDirs = 0, removedFiles = 0;
30356
30802
  try {
30357
30803
  if (!existsSync(dir)) return { removedDirs, removedFiles };
30358
30804
  const cutoff = Date.now() - maxAgeMs;
30359
- for (const name of readdirSync(dir)) {
30805
+ for (const name of await fsp.readdir(dir)) {
30360
30806
  const isOpencodeDir = name.startsWith('opencode-');
30361
30807
  const isClaudeCfg = name.startsWith('claude-mcp-') && name.endsWith('.json');
30362
30808
  if (!isOpencodeDir && !isClaudeCfg) continue;
30363
30809
  const full = resolve(dir, name);
30364
30810
  try {
30365
- const st = statSync(full);
30811
+ const st = await fsp.stat(full);
30366
30812
  if (st.mtimeMs >= cutoff) continue;
30367
- if (st.isDirectory()) { rmSync(full, { recursive: true, force: true }); removedDirs++; }
30368
- else { unlinkSync(full); removedFiles++; }
30813
+ if (st.isDirectory()) { await fsp.rm(full, { recursive: true, force: true }); removedDirs++; }
30814
+ else { await fsp.unlink(full); removedFiles++; }
30369
30815
  } catch { /* skip unreadable/racing entries */ }
30370
30816
  }
30371
30817
  if (removedDirs || removedFiles) {
@@ -30951,6 +31397,7 @@ function scanForLeaks() {
30951
31397
 
30952
31398
  let _lastLeakHash = '';
30953
31399
  setInterval(() => {
31400
+ markActivity('timer:session-leaks');
30954
31401
  syncRegistryFromTerminals();
30955
31402
  const leaks = scanForLeaks();
30956
31403
  // Strip ageMs AND description (which embeds age as "Xm old") to prevent
@@ -31012,6 +31459,7 @@ function scanLoopInventory() {
31012
31459
 
31013
31460
  let _lastLoopHash = '';
31014
31461
  setInterval(() => {
31462
+ markActivity('timer:loop-inventory');
31015
31463
  const inventory = scanLoopInventory();
31016
31464
  // Hash on stable fields only (drop minute counters that tick every poll)
31017
31465
  const hash = JSON.stringify({
@@ -32804,18 +33252,45 @@ const extensionBridge = createExtensionBridge({
32804
33252
  log: record => console.log('[extension-bridge]', JSON.stringify(record)),
32805
33253
  onInventory: state => extensionAdapter.sync(state),
32806
33254
  });
33255
+ // Page JavaScript in the owner's everyday browser (browser_evaluate through the extension) is held to what the
33256
+ // Playwright evaluate route holds a loop's tab to, so an extension session is no way around either: the X publish gate
33257
+ // (xGateBypassRefusal: no scripted click on a publish / like / repost / follow control) and the spacing of social
33258
+ // writes (`pace` in the body, socialWritePacer). The same functions with the same scoping: a loop-owned tab only.
33259
+ // One paired browser is one signed-in account, whatever the session object is called: one queue per platform.
33260
+ const extensionEvaluateGate = {
33261
+ refusal: ({ session, req, tabId, script }) => xGateBypassRefusal(session, req, { page: session.tabs.get(tabId)?.page, tabId }, 'evaluate', script),
33262
+ async run({ session, req, execute }) {
33263
+ const pace = socialPaceRequest(req?.body);
33264
+ if (!pace || !isLoopPaced(session, req)) return { result: await execute() };
33265
+ const outcome = await socialWritePacer.run(`${pace.platform}:extension`, {
33266
+ platform: pace.platform, maxWaitMs: socialPaceWaitBudget(req, pace.maxWaitMs), signal: req,
33267
+ }, execute);
33268
+ const gap = SOCIAL_WRITE_GAPS[pace.platform];
33269
+ if (outcome.status === 'paced') return { paced: { pending: true, retryAfterMs: outcome.retryAfterMs, waitedMs: outcome.waitedMs, gapMinMs: gap.minMs, gapMaxMs: gap.maxMs } };
33270
+ return { result: outcome.result, paced: { pending: false, waitedMs: outcome.waitedMs, gapMinMs: gap.minMs, gapMaxMs: gap.maxMs } };
33271
+ },
33272
+ };
32807
33273
  const extensionAdapter = createExtensionAdapter({
32808
33274
  bridge: extensionBridge, sessions: browserSessions, uploadRoot: extensionUploadRoot, dataHome: DATA_HOME,
32809
- caller: browserCaller, ownerPage: browserOwnerPageOnly,
33275
+ caller: browserCaller, ownerPage: browserOwnerPageOnly, evaluateGate: extensionEvaluateGate,
32810
33276
  selected: req => loadBrowserConfig().connectMode === 'extension' && !runMoreLoginPin(browserCaller(req).id),
32811
33277
  });
32812
- // The extension folder the owner loads (DATA_HOME/browser-extension/unpacked): refreshed at start when the bundled
32813
- // extension changed and is not older (lib/browser-extension-folder.js). The browser then needs the extension's Reload,
32814
- // which Settings and the setup page say (`reloadNeeded`). Never fatal: a folder that cannot be written is prepared
32815
- // again by the one-button setup, which says so.
32816
- const prepareOwnerExtensionFolder = () => prepareExtensionFolder({ source: EXTENSION_FOLDER, home: DATA_HOME, appPort: Number(PORT) || 3344 });
32817
- try { const prepared = prepareOwnerExtensionFolder(); if (prepared.changed) console.log(`[extension-bridge] extension folder ${prepared.previousVersion ? `refreshed ${prepared.previousVersion} → ${prepared.version}` : `prepared (${prepared.version})`}; reload the extension in the browser`); }
32818
- catch (error) { console.warn(`[extension-bridge] extension folder not prepared (${error?.code || 'error'})`); }
33278
+ // The extension folder the owner loads (DATA_HOME/browser-extension/unpacked). Its files are the one package this
33279
+ // release pins (lib/browser-extension-pin.js), downloaded from synabun.ai and verified (lib/browser-extension-package.js):
33280
+ // nothing of the extension is inside the app, and nothing here needs it or the network to start. At start only the
33281
+ // folder's own setup content script is brought to this server's port (no network). A folder older than the pin is
33282
+ // refreshed after listen, in the background (the old one stays on any failure); a folder that is not there is
33283
+ // downloaded only when the owner starts "Connect your browser". The browser then needs the extension's Reload, which
33284
+ // Settings and the setup page say (`reloadNeeded`). Never fatal.
33285
+ const extensionPackage = createExtensionPackage({
33286
+ home: DATA_HOME, appPort: () => Number(PORT) || 3344,
33287
+ log: record => console.log('[extension-bridge]', JSON.stringify(record)),
33288
+ });
33289
+ // Under the data home's lock: a replacement a stopped process left is finished or taken back, its leftovers removed, the
33290
+ // pinned extension's setup script set to this port from its own verified files, and a changed folder repaired from the
33291
+ // verified package the data home keeps (no network; otherwise the background refresh below downloads it).
33292
+ try { const prepared = extensionPackage.retarget(); if (prepared.changed) console.log(`[extension-bridge] extension folder ${prepared.reason === 'repair' ? 'repaired from the verified package' : "set to this server's port"} (${prepared.version}); reload the extension in the browser`); else if (prepared.state === 'other') console.warn('[extension-bridge] the extension folder is not the pinned extension; it is downloaded again after start-up'); }
33293
+ catch (error) { console.warn(`[extension-bridge] extension folder not checked (${error?.code || 'error'}${error?.code === 'EXTENSION_FOLDER_UNSAFE' && error.reason ? `: ${error.reason}` : ''})`); }
32819
33294
  // The one-button setup (Settings → Browser → "Connect your browser"; docs/browser-extension-bridge.md → One-button
32820
33295
  // setup). Programs are started with execFile/spawn and argument arrays, never a shell; reads time out.
32821
33296
  const extensionSetup = createExtensionSetup({
@@ -32826,13 +33301,15 @@ const extensionSetup = createExtensionSetup({
32826
33301
  exists: path => { try { return existsSync(path); } catch { return false; } },
32827
33302
  list: dir => { try { return readdirSync(dir); } catch { return []; } },
32828
33303
  }),
32829
- prepare: () => prepareOwnerExtensionFolder(),
33304
+ prepare: ({ signal } = {}) => extensionPackage.ensure({ reason: 'setup', signal }),
33305
+ packageStatus: () => extensionPackage.status(),
33306
+ confirmReload: () => extensionPackage.confirmReload(),
32830
33307
  exec: (cmd, args) => new Promise((resolveExec, rejectExec) => {
32831
33308
  const child = spawn(cmd, args, { detached: true, stdio: 'ignore', windowsHide: true, shell: false });
32832
33309
  child.once('error', rejectExec); child.once('spawn', () => { child.unref(); resolveExec(); });
32833
33310
  }),
32834
33311
  appOrigin: () => `http://127.0.0.1:${Number(PORT) || 3344}`,
32835
- folderVersion: () => extensionFolderState(DATA_HOME).version,
33312
+ folderVersion: () => { const state = extensionFolderState(DATA_HOME); return state.present ? state.version : null; },
32836
33313
  });
32837
33314
  {
32838
33315
  const restored = extensionBridge.restore();
@@ -37096,9 +37573,12 @@ app.use('/api/browser/extension', extensionOwnerGuard, (req, res, next) => {
37096
37573
  });
37097
37574
  app.get('/api/browser/extension', (_req, res) => {
37098
37575
  const folderState = extensionFolderState(DATA_HOME), status = extensionBridge.status();
37099
- // `folder`: the folder the owner loads (the prepared copy; the bundled one only when none could be prepared).
37100
- res.json({ ...status, folder: folderState.prepared ? folderState.folder : EXTENSION_FOLDER, bundledFolder: EXTENSION_FOLDER, uploadFolder: extensionUploadRoot,
37101
- folderVersion: folderState.version, reloadNeeded: !!(status.connected && folderState.version && status.extensionVersion !== folderState.version),
37576
+ // `folder`: the folder the owner loads, once it is there (null until "Connect your browser" downloaded the extension).
37577
+ // `package`: the pinned package and its download (pinnedVersion, needs, phase, received, total, code).
37578
+ const pkg = extensionPackage.status();
37579
+ res.json({ ...status, folder: folderState.present ? folderState.folder : null, uploadFolder: extensionUploadRoot,
37580
+ folderVersion: folderState.present ? folderState.version : null, pinnedVersion: pkg.pinnedVersion, package: pkg,
37581
+ ...extensionVersions({ connected: status.connected, extensionVersion: status.extensionVersion, folderVersion: folderState.present ? folderState.version : null, pinnedVersion: pkg.pinnedVersion, reloadPending: pkg.reloadPending === true, reloadReason: pkg.reloadReason ?? null }),
37102
37582
  setup: extensionSetup.status().state });
37103
37583
  });
37104
37584
  // The one-button setup. Owner only: these sit under the guard above (ownerRouteGuard, the page secret, no automation
@@ -37111,6 +37591,20 @@ app.post('/api/browser/extension/setup/ticket', (_req, res) => { res.setHeader('
37111
37591
  app.post('/api/browser/extension/setup/cancel', (_req, res) => sendSetup(res, () => extensionSetup.cancel()));
37112
37592
  app.post('/api/browser/extension/setup/reveal', (_req, res) => sendSetup(res, () => extensionSetup.reveal()));
37113
37593
  app.post('/api/browser/extension/setup/reopen', (_req, res) => sendSetup(res, () => extensionSetup.reopen()));
37594
+ // The setup page saw the extension's content script on this port: the Reload a port change asked for is done. A
37595
+ // repair's Reload is not (the copy the browser still runs answers the page just the same): see reload/confirm.
37596
+ app.post('/api/browser/extension/setup/seen', (_req, res) => sendSetup(res, () => extensionSetup.seen()));
37597
+ // The owner's click in Settings ("I reloaded the extension"): the one way a repair's Reload is cleared. Behind the
37598
+ // guard above like `seen` (ownerRouteGuard with its own Origin required, this boot's page secret, no agent or guest),
37599
+ // and also refused here for a request from an extension's own origin, one the browser does not mark same-origin, or
37600
+ // one without the app's X-SynaBun-UI header. The body must say so (`reloaded: true`): nothing the page loads or polls
37601
+ // sends it.
37602
+ app.post('/api/browser/extension/reload/confirm', (req, res) => {
37603
+ const origin = String(req.headers.origin || ''), site = req.headers['sec-fetch-site'];
37604
+ if (/^[a-z-]*extension:/i.test(origin) || (site !== undefined && site !== 'same-origin') || req.headers['x-synabun-ui'] !== '1') return res.status(403).json({ code: 'OWNER_ROUTE', error: 'Only the owner\'s SynaBun Settings can confirm the Reload.' });
37605
+ if (req.body?.reloaded !== true) return res.status(400).json({ code: 'INVALID_MESSAGE', error: 'Send { "reloaded": true } once the extension was reloaded in the browser.' });
37606
+ return sendSetup(res, () => ({ cleared: extensionPackage.confirmRepairReload(), ...extensionSetup.status() }));
37607
+ });
37114
37608
  app.post('/api/browser/extension/:action', async (req, res) => {
37115
37609
  try {
37116
37610
  const action = req.params.action;
@@ -37122,6 +37616,8 @@ app.post('/api/browser/extension/:action', async (req, res) => {
37122
37616
  else if (action === 'revoke-site') await extensionBridge.revokeSite(req.body?.site);
37123
37617
  // The owner's mode: full control (any site and tab of the paired browser) or only what the owner shares.
37124
37618
  else if (action === 'mode') await extensionBridge.setMode(req.body?.fullControl);
37619
+ // The owner's retry of an update that did not download (Settings): only for a folder that is already there.
37620
+ else if (action === 'update') { if (extensionPackage.needs() === 'update') extensionPackage.ensure({ reason: 'update' }).catch(() => {}); }
37125
37621
  else return res.status(400).json({ code: 'INVALID_MESSAGE', error: 'Unknown extension action.' });
37126
37622
  return res.json({ ok: true, ...extensionBridge.status() });
37127
37623
  } catch (error) { return res.status(400).json(extensionSafeError(error)); }
@@ -39219,9 +39715,16 @@ app.post('/api/browser/sessions/:id/upload', async (req, res) => {
39219
39715
  }
39220
39716
  markBrowserActionStarted(req);
39221
39717
  await target.setInputFiles(filePaths, { timeout: browserActionTimeout(req, 10000) });
39718
+ // Native pickers supply the MIME. The handler may consume or remove the input synchronously.
39719
+ const files = await target.evaluateAll(elements => {
39720
+ if (elements.length !== 1) return [];
39721
+ const el = elements[0], input = el.localName === 'label' ? el.control : el;
39722
+ if (!input?.matches('input[type=file]')) return [];
39723
+ return Array.from(input.files, ({ name, type, size }) => ({ name, type, size }));
39724
+ }).catch(() => []);
39222
39725
  if (!browserV2Enabled()) await cancellableBrowserDelay(500, req);
39223
39726
  const state = await getBrowserActionState(session, routed, compact);
39224
- res.json({ ok: true, url: state.url, title: state.title });
39727
+ res.json({ ok: true, url: state.url, title: state.title, files });
39225
39728
  } catch (err) {
39226
39729
  res.status(500).json({ error: err.message });
39227
39730
  }
@@ -39502,8 +40005,10 @@ function runLaunchStep(name) {
39502
40005
  const task = LAUNCH_TASKS[name];
39503
40006
  if (!task) return Promise.resolve();
39504
40007
  return _launchQueue(async () => {
40008
+ const endActivity = beginActivity(`launch:${name}`);
39505
40009
  const started = Date.now();
39506
40010
  try { await task(); } catch (error) { console.warn(`[launch-cache] ${name}: ${error?.message || error}`); }
40011
+ finally { endActivity(); }
39507
40012
  const took = Date.now() - started;
39508
40013
  if (took > 2000) console.log(`[launch-cache] ${name} warmed in ${(took / 1000).toFixed(1)} s`);
39509
40014
  await new Promise((done) => { const timer = setTimeout(done, LAUNCH_STEP_GAP_MS); timer.unref?.(); });
@@ -39530,6 +40035,10 @@ function startLaunchWarmup() {
39530
40035
  reloadConfig();
39531
40036
 
39532
40037
  const httpServer = app.listen(PORT, async () => {
40038
+ markActivity('startup:listen');
40039
+ scheduleScratchRetention(DATA_HOME, () => ({
40040
+ dispatcher: _assistantDispatcher, runtime: _nativeLoopRuntime, scheduled: _runningScheduledLoops, closing: _shutdownInProgress,
40041
+ }));
39533
40042
  // Before anything else: the sessions that saved a MoreLogin profile choice (POST /api/morelogin/use) must prove
39534
40043
  // who they are again before that choice is used (retireSavedProfileChoiceOwners).
39535
40044
  try { retireSavedProfileChoiceOwners(); } catch (err) { console.warn(`[morelogin] the owners of the saved profile choices were not retired: ${err.message}`); }
@@ -39547,8 +40056,7 @@ const httpServer = app.listen(PORT, async () => {
39547
40056
 
39548
40057
  // Write embedding model metadata so mismatch can be detected later
39549
40058
  try {
39550
- setKvConfig('embedding_model', EMBEDDING_MODEL);
39551
- setKvConfig('embedding_dims', String(EMBEDDING_DIMS));
40059
+ await saveEmbeddingMetadata();
39552
40060
  } catch {}
39553
40061
 
39554
40062
  // Keep the Start Server launcher (synabun://) pointing at this install even
@@ -39583,20 +40091,32 @@ const httpServer = app.listen(PORT, async () => {
39583
40091
 
39584
40092
  // Gated: an idle tick reads one kv row + one index probe instead of the
39585
40093
  // ~9-query maintenanceStatus() and a BEGIN IMMEDIATE (see lib/memory-timers.js).
39586
- startGatedMemoryMaintenance();
39587
40094
  // The TypeSafe judge backfill runs only here: one runner per store, never in
39588
40095
  // the stdio MCP servers. It is inert until the Judgments tab starts it.
39589
- startJudgeBackfill();
39590
- startMemoryCapture();
40096
+ // None of the three ticks while the memory store is being upgraded.
40097
+ const startMemoryTimers = () => { startGatedMemoryMaintenance(); startJudgeBackfill(); startMemoryCapture(); };
40098
+ const stopMemoryTimers = () => { stopGatedMemoryMaintenance(); try { stopJudgeBackfill(); } catch {} stopMemoryCapture(); };
40099
+ if (memoryStoreGate.open()) startMemoryTimers();
40100
+ memoryStoreGate.subscribe((state) => { if (state === 'ready' || state === 'deferred') startMemoryTimers(); else stopMemoryTimers(); });
39591
40101
 
39592
40102
  // Warm the embedding model + vector caches in the background so the first
39593
40103
  // recall/search doesn't pay the 2-5s Transformers.js model load or the
39594
40104
  // initial vector-matrix build.
39595
40105
  setTimeout(() => {
40106
+ markActivity('startup:embeddings');
39596
40107
  warmupEmbeddings()
39597
40108
  .then(() => console.log(' Embeddings: model warmed up'))
39598
40109
  .catch((err) => console.warn(' Embeddings warmup failed:', err.message));
39599
- try { memoryVectors.size(); } catch { /* cache builds lazily on failure */ }
40110
+ // Memory vectors, then the passage vectors every hybrid recall reads, both in slices (warmRetrievalCaches).
40111
+ // Session-chunk vectors load on the first recall that searches sessions, in slices as well (VectorCache.ready).
40112
+ const warmMemoryCaches = () => {
40113
+ markActivity('startup:memory-vectors');
40114
+ import('../mcp-server/dist/services/memory-retrieval.js')
40115
+ .then(({ warmRetrievalCaches }) => (warmRetrievalCaches ? warmRetrievalCaches() : memoryVectors.warm()))
40116
+ .catch(err => { if (!isMemoryStoreRefusal(err)) console.warn(' Vector cache warmup failed:', err.message); });
40117
+ };
40118
+ if (memoryStoreGate.open()) warmMemoryCaches();
40119
+ memoryStoreGate.subscribe((state) => { if (state === 'ready' || state === 'deferred') warmMemoryCaches(); });
39600
40120
  }, 500);
39601
40121
 
39602
40122
  // Local profiles still running from before this start (their Chrome outlives the server, as a MoreLogin profile
@@ -39604,6 +40124,7 @@ const httpServer = app.listen(PORT, async () => {
39604
40124
  // was taken meanwhile, that profile's pages fail (never a direct connection); its next start starts it again.
39605
40125
  setTimeout(async () => {
39606
40126
  try {
40127
+ markActivity('startup:local-profiles');
39607
40128
  const adopted = await moreLogin.adoptLocalProfiles();
39608
40129
  if (!adopted.length) return;
39609
40130
  const stuck = adopted.filter((p) => p.relay === 'restart-needed');
@@ -39615,6 +40136,7 @@ const httpServer = app.listen(PORT, async () => {
39615
40136
  // Activation is an explicit user choice in the MoreLogin tab (Default AI browser).
39616
40137
  setTimeout(async () => {
39617
40138
  try {
40139
+ markActivity('startup:morelogin-detection');
39618
40140
  const mlBootCfg = loadBrowserConfig();
39619
40141
  const cfg = mlBootCfg;
39620
40142
  const port = moreLogin.getMoreLoginPort(cfg);
@@ -39628,27 +40150,45 @@ const httpServer = app.listen(PORT, async () => {
39628
40150
  // Reclaim orphaned per-loop config dirs left by crashed/killed loops. At boot
39629
40151
  // no loop is live, so this is the safe choke point to drop multi-GB of stale
39630
40152
  // opencode-<sid> node_modules that never got their per-loop cleanup.
39631
- setTimeout(() => { try { cleanupStaleLoopConfigs(); } catch {} }, 1500);
40153
+ setTimeout(() => {
40154
+ markActivity('startup:loop-config-cleanup');
40155
+ void cleanupStaleLoopConfigs();
40156
+ }, 1500);
39632
40157
 
39633
40158
  // OpenCode serves an earlier SynaBun left running (it crashed, or was killed): found by their records alone and
39634
40159
  // stopped only when they are provably its own and nothing uses them (lib/opencode-serve-records.js). An
39635
40160
  // OpenCode start that comes earlier makes the same look first (and this one then finds nothing left).
39636
- setTimeout(() => { sweepLeftoverOpencodeServes(); }, 1000);
40161
+ setTimeout(() => {
40162
+ markActivity('startup:opencode-sweep');
40163
+ sweepLeftoverOpencodeServes();
40164
+ }, 1000);
39637
40165
  // The cloudflared a crashed server left running (lib/cloudflared/tunnel.js): at once, its old address points here.
39638
40166
  sweepLeftoverTunnels();
39639
40167
 
39640
40168
  // Compare the installed Claude CLI with the release the Agent SDK was built
39641
40169
  // against, once, so an older installation is named in the log before the
39642
40170
  // first session runs on it (checkClaudeCliSkew in lib/claude-model-catalog.js).
39643
- setTimeout(() => { checkClaudeCliSkew(getClaudeBin()).catch(() => {}); }, 1000);
40171
+ setTimeout(() => {
40172
+ markActivity('startup:claude-cli-skew');
40173
+ checkClaudeCliSkew(getClaudeBin()).catch(() => {});
40174
+ }, 1000);
39644
40175
 
39645
40176
  // The lists windows, menus and Settings wait for, read once in the background (see LAUNCH_TASKS above).
39646
40177
  startLaunchWarmup();
39647
40178
 
40179
+ // The owner's extension folder, when it holds an older extension than this release pins: the pinned package is
40180
+ // fetched and verified in the background (lib/browser-extension-package.js). Nothing is downloaded for somebody who
40181
+ // never set the extension up, and a failure keeps the folder that is there.
40182
+ setTimeout(() => {
40183
+ try { markActivity('startup:extension-package'); extensionPackage.refreshInBackground(); }
40184
+ catch (error) { console.warn(`[extension-bridge] extension update not started (${error?.code || 'error'})`); }
40185
+ }, 4000).unref?.();
40186
+
39648
40187
  // Windows: the Git Bash every Claude Code gets (lib/git-bash/). Looked for now (the settings of the user's own
39649
40188
  // claude follow it); a PC with none, and an app that carries none, gets SynaBun's copy, fetched in the background.
39650
40189
  setTimeout(() => {
39651
40190
  try {
40191
+ markActivity('startup:git-bash');
39652
40192
  gitBash.refresh();
39653
40193
  if (gitBash.status().state === 'missing') gitBash.ensure({ reason: 'first run' });
39654
40194
  // What an earlier run left in the data home (a stopped attempt's work folder, an older version), off the event loop.
@@ -39657,35 +40197,42 @@ const httpServer = app.listen(PORT, async () => {
39657
40197
  }, 2500);
39658
40198
 
39659
40199
  // Warm the session_cache + session_fts tables so the hybrid search has data
39660
- // on first keystroke. The large history scans yield between sessions, and
40200
+ // on first keystroke. A worker indexes Claude, Codex and OpenCode, and
39661
40201
  // a Codex catalog request shares the same refresh with this startup pass.
39662
40202
  setTimeout(async () => {
39663
40203
  const passes = [
39664
40204
  async () => {
39665
40205
  try {
39666
- const claude = await rebuildClaudeCache({ background: true });
40206
+ markActivity('session-cache:claude');
40207
+ const claude = await runSessionJob('claude');
39667
40208
  if (claude.updated > 0) console.log(` Session cache (claude): indexed ${claude.updated}/${claude.sessions}`);
39668
40209
  } catch (err) { console.warn(' Session cache (claude) error:', err.message); }
39669
40210
  },
39670
40211
  async () => {
39671
40212
  try {
40213
+ markActivity('session-cache:codex');
39672
40214
  const codex = await refreshCodexSessionCatalog();
39673
40215
  if (codex.updated > 0) console.log(` Session cache (codex): indexed ${codex.updated}/${codex.sessions}`);
39674
40216
  } catch (err) { console.warn(' Session cache (codex) error:', err.message); }
39675
40217
  },
39676
40218
  async () => {
39677
40219
  try {
39678
- _ocpSessionCacheWarmup = rebuildOpencodeCache({ getOpencodeDb, background: true });
40220
+ markActivity('session-cache:opencode');
40221
+ _ocpSessionCacheWarmup = runSessionJob('opencode', { path: getOpencodeDbPath() });
39679
40222
  const oc = await _ocpSessionCacheWarmup;
39680
40223
  if (oc.updated > 0) console.log(` Session cache (opencode): indexed ${oc.updated}/${oc.sessions}`);
39681
40224
  } catch (err) { console.warn(' Session cache (opencode) error:', err.message); }
39682
40225
  finally { _ocpSessionCacheWarmup = null; }
39683
40226
  },
39684
- () => {
39685
- const agy = refreshAntigravityCatalog({ force: true });
40227
+ async () => {
40228
+ markActivity('session-cache:antigravity');
40229
+ const agy = await refreshAntigravityCatalog({ force: true });
39686
40230
  if (agy?.updated > 0) console.log(` Session cache (antigravity): indexed ${agy.updated}/${agy.sessions}`);
39687
40231
  // Runs and brains end on their own: their conversations are picked up by this pass, every five minutes.
39688
- setInterval(() => refreshAntigravityCatalog({ force: true }), 5 * 60 * 1000).unref?.();
40232
+ setInterval(() => {
40233
+ markActivity('session-cache:antigravity');
40234
+ refreshAntigravityCatalog({ force: true });
40235
+ }, 5 * 60 * 1000).unref?.();
39689
40236
  },
39690
40237
  ];
39691
40238
  for (const pass of passes) {
@@ -39711,6 +40258,7 @@ const httpServer = app.listen(PORT, async () => {
39711
40258
  // already self-healing via addHookToSettings; this catches damage from
39712
40259
  // previous versions of the install flow.
39713
40260
  try {
40261
+ markActivity('startup:hooks');
39714
40262
  const dedupStats = dedupeAllSettingsHooks();
39715
40263
  if (dedupStats.removed > 0 || dedupStats.repaired > 0 || dedupStats.matchers > 0) {
39716
40264
  const bits = [];
@@ -39743,6 +40291,7 @@ const httpServer = app.listen(PORT, async () => {
39743
40291
  // wait is for the rules lock another SynaBun process on this data home may
39744
40292
  // hold (2 s at most: then the installer logs one line and this boot skips it).
39745
40293
  try {
40294
+ markActivity('startup:rules');
39746
40295
  const rules = rulesetInstaller.reconcile();
39747
40296
  if (rules.updated.length) console.log(` Rules: updated to ${rules.notice?.to || 'the current version'} for ${rules.updated.join(', ')}`);
39748
40297
  if (rules.optedOut.length) console.log(` Rules: no longer managed for ${rules.optedOut.join(', ')} (the installed copy was removed)`);
@@ -39842,7 +40391,8 @@ const httpServer = app.listen(PORT, async () => {
39842
40391
  // OpenCode panel, Settings) see providers/models immediately without the
39843
40392
  // user having to click Start each time.
39844
40393
  try {
39845
- const ready = await ensureOpencodeServer();
40394
+ markActivity('startup:opencode-serve');
40395
+ const ready = await startOpencodeAtBoot(() => ensureOpencodeServer(), () => _ocpStartRefusal);
39846
40396
  if (ready) console.log(` OpenCode: auto-started on :${_ocpPort}`);
39847
40397
  else console.log(' OpenCode: auto-start skipped (binary missing or failed to launch)');
39848
40398
  } catch (err) {
@@ -40556,6 +41106,7 @@ const SERVER_START_TIME = Date.now();
40556
41106
  const RESUME_GRACE_PERIOD_MS = 120_000; // 2 min — don't delete snapshot before client can check
40557
41107
 
40558
41108
  function saveSessionSnapshot() {
41109
+ markActivity('timer:session-snapshot');
40559
41110
  const sessions = [];
40560
41111
  const seen = new Set(); // dedup — avoid resuming same Claude session twice
40561
41112
 
@@ -40634,7 +41185,8 @@ process.on('exit', () => {
40634
41185
  try { _whatsapp?.killNow(); } catch {}
40635
41186
  try { tunnel.killNow(); } catch {}
40636
41187
  try { gitBash.cancel(); } catch {}
40637
- try { stopOpencodeServer(); } catch {}
41188
+ try { stopOpencodeServer({ immediate: true }); } catch {}
41189
+ try { _ocpServeEnds.killNow(); } catch {}
40638
41190
  try { editorCompletionServe.stop('exit'); } catch {}
40639
41191
  try { _claudeBridge?.shutdownAllBridges?.(); } catch {}
40640
41192
  try { antigravityPanel.closeAll(); } catch {}