synabun 2.4.0 → 2.4.2

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 (319) hide show
  1. package/CHANGELOG.md +47 -0
  2. package/README.md +1 -1
  3. package/browser-extension/content.js +73 -11
  4. package/browser-extension/engine.js +196 -15
  5. package/browser-extension/manifest.json +4 -2
  6. package/browser-extension/popup-strings.js +10 -4
  7. package/browser-extension/popup-view.js +1 -1
  8. package/browser-extension/popup.css +1 -0
  9. package/browser-extension/popup.html +4 -1
  10. package/browser-extension/popup.js +22 -10
  11. package/browser-extension/protocol.js +102 -11
  12. package/browser-extension/service-worker.js +20 -4
  13. package/browser-extension/tokens.css +1 -1
  14. package/docs/browser-extension-bridge.md +25 -5
  15. package/lib/data-home-files.js +47 -0
  16. package/lib/data-home-migration.js +34 -58
  17. package/lib/first-launch-protection.js +8 -2
  18. package/lib/update-snapshot.js +11 -4
  19. package/mcp-server/dist/http.d.ts.map +1 -1
  20. package/mcp-server/dist/http.js +25 -2
  21. package/mcp-server/dist/http.js.map +1 -1
  22. package/mcp-server/dist/index.d.ts.map +1 -1
  23. package/mcp-server/dist/index.js +62 -17
  24. package/mcp-server/dist/index.js.map +1 -1
  25. package/mcp-server/dist/services/browser-bench.d.ts +22 -22
  26. package/mcp-server/dist/services/memory-maintenance.d.ts +1 -0
  27. package/mcp-server/dist/services/memory-maintenance.d.ts.map +1 -1
  28. package/mcp-server/dist/services/memory-maintenance.js +34 -45
  29. package/mcp-server/dist/services/memory-maintenance.js.map +1 -1
  30. package/mcp-server/dist/services/memory-migration-copy.d.ts +144 -0
  31. package/mcp-server/dist/services/memory-migration-copy.d.ts.map +1 -0
  32. package/mcp-server/dist/services/memory-migration-copy.js +467 -0
  33. package/mcp-server/dist/services/memory-migration-copy.js.map +1 -0
  34. package/mcp-server/dist/services/memory-migration-worker.d.ts +2 -0
  35. package/mcp-server/dist/services/memory-migration-worker.d.ts.map +1 -0
  36. package/mcp-server/dist/services/memory-migration-worker.js +60 -0
  37. package/mcp-server/dist/services/memory-migration-worker.js.map +1 -0
  38. package/mcp-server/dist/services/memory-retrieval.d.ts +4 -0
  39. package/mcp-server/dist/services/memory-retrieval.d.ts.map +1 -1
  40. package/mcp-server/dist/services/memory-retrieval.js +188 -40
  41. package/mcp-server/dist/services/memory-retrieval.js.map +1 -1
  42. package/mcp-server/dist/services/memory-schema.d.ts +58 -2
  43. package/mcp-server/dist/services/memory-schema.d.ts.map +1 -1
  44. package/mcp-server/dist/services/memory-schema.js +190 -13
  45. package/mcp-server/dist/services/memory-schema.js.map +1 -1
  46. package/mcp-server/dist/services/memory-sessions.d.ts +19 -1
  47. package/mcp-server/dist/services/memory-sessions.d.ts.map +1 -1
  48. package/mcp-server/dist/services/memory-sessions.js +56 -20
  49. package/mcp-server/dist/services/memory-sessions.js.map +1 -1
  50. package/mcp-server/dist/services/memory-verification.d.ts.map +1 -1
  51. package/mcp-server/dist/services/memory-verification.js +8 -5
  52. package/mcp-server/dist/services/memory-verification.js.map +1 -1
  53. package/mcp-server/dist/services/neural-interface.d.ts +6 -0
  54. package/mcp-server/dist/services/neural-interface.d.ts.map +1 -1
  55. package/mcp-server/dist/services/neural-interface.js +19 -2
  56. package/mcp-server/dist/services/neural-interface.js.map +1 -1
  57. package/mcp-server/dist/services/retrieval-reader-worker.d.ts +2 -0
  58. package/mcp-server/dist/services/retrieval-reader-worker.d.ts.map +1 -0
  59. package/mcp-server/dist/services/retrieval-reader-worker.js +76 -0
  60. package/mcp-server/dist/services/retrieval-reader-worker.js.map +1 -0
  61. package/mcp-server/dist/services/retrieval-reader.d.ts +38 -0
  62. package/mcp-server/dist/services/retrieval-reader.d.ts.map +1 -0
  63. package/mcp-server/dist/services/retrieval-reader.js +145 -0
  64. package/mcp-server/dist/services/retrieval-reader.js.map +1 -0
  65. package/mcp-server/dist/services/sqlite-write.d.ts +14 -0
  66. package/mcp-server/dist/services/sqlite-write.d.ts.map +1 -0
  67. package/mcp-server/dist/services/sqlite-write.js +94 -0
  68. package/mcp-server/dist/services/sqlite-write.js.map +1 -0
  69. package/mcp-server/dist/services/sqlite.d.ts +39 -0
  70. package/mcp-server/dist/services/sqlite.d.ts.map +1 -1
  71. package/mcp-server/dist/services/sqlite.js +249 -8
  72. package/mcp-server/dist/services/sqlite.js.map +1 -1
  73. package/mcp-server/dist/services/tool-catalog.d.ts +1 -1
  74. package/mcp-server/dist/services/typesafe-config.d.ts +7 -1
  75. package/mcp-server/dist/services/typesafe-config.d.ts.map +1 -1
  76. package/mcp-server/dist/services/typesafe-config.js +32 -10
  77. package/mcp-server/dist/services/typesafe-config.js.map +1 -1
  78. package/mcp-server/dist/services/typesafe.d.ts.map +1 -1
  79. package/mcp-server/dist/services/typesafe.js +9 -7
  80. package/mcp-server/dist/services/typesafe.js.map +1 -1
  81. package/mcp-server/dist/services/vector-cache.d.ts +32 -0
  82. package/mcp-server/dist/services/vector-cache.d.ts.map +1 -1
  83. package/mcp-server/dist/services/vector-cache.js +161 -8
  84. package/mcp-server/dist/services/vector-cache.js.map +1 -1
  85. package/mcp-server/dist/tools/agent-definition.d.ts +2 -2
  86. package/mcp-server/dist/tools/agents.d.ts +13 -8
  87. package/mcp-server/dist/tools/agents.d.ts.map +1 -1
  88. package/mcp-server/dist/tools/agents.js +35 -15
  89. package/mcp-server/dist/tools/agents.js.map +1 -1
  90. package/mcp-server/dist/tools/browser-advanced.d.ts +1 -1
  91. package/mcp-server/dist/tools/browser-advanced.d.ts.map +1 -1
  92. package/mcp-server/dist/tools/browser-advanced.js +10 -3
  93. package/mcp-server/dist/tools/browser-advanced.js.map +1 -1
  94. package/mcp-server/dist/tools/browser-extension-setup.d.ts +5 -0
  95. package/mcp-server/dist/tools/browser-extension-setup.d.ts.map +1 -0
  96. package/mcp-server/dist/tools/browser-extension-setup.js +23 -0
  97. package/mcp-server/dist/tools/browser-extension-setup.js.map +1 -0
  98. package/mcp-server/dist/tools/browser-interact.d.ts.map +1 -1
  99. package/mcp-server/dist/tools/browser-interact.js +6 -1
  100. package/mcp-server/dist/tools/browser-interact.js.map +1 -1
  101. package/mcp-server/dist/tools/fb-groups.d.ts +2 -2
  102. package/mcp-server/dist/tools/skill-tools.d.ts +4 -4
  103. package/mcp-server/dist/tools/tool-groups.d.ts +1 -1
  104. package/mcp-server/package-lock.json +2 -2
  105. package/mcp-server/package.json +1 -1
  106. package/mcp-server/src/http.ts +20 -2
  107. package/mcp-server/src/index.ts +59 -17
  108. package/mcp-server/src/services/memory-maintenance.ts +31 -28
  109. package/mcp-server/src/services/memory-migration-copy.ts +419 -0
  110. package/mcp-server/src/services/memory-migration-worker.ts +55 -0
  111. package/mcp-server/src/services/memory-retrieval.ts +173 -32
  112. package/mcp-server/src/services/memory-schema.ts +194 -12
  113. package/mcp-server/src/services/memory-sessions.ts +54 -21
  114. package/mcp-server/src/services/memory-verification.ts +7 -4
  115. package/mcp-server/src/services/neural-interface.ts +23 -2
  116. package/mcp-server/src/services/retrieval-reader-worker.ts +67 -0
  117. package/mcp-server/src/services/retrieval-reader.ts +131 -0
  118. package/mcp-server/src/services/sqlite-write.ts +60 -0
  119. package/mcp-server/src/services/sqlite.ts +246 -8
  120. package/mcp-server/src/services/typesafe-config.ts +25 -6
  121. package/mcp-server/src/services/typesafe.ts +9 -7
  122. package/mcp-server/src/services/vector-cache.ts +154 -9
  123. package/mcp-server/src/tools/agents.ts +33 -14
  124. package/mcp-server/src/tools/browser-advanced.ts +10 -3
  125. package/mcp-server/src/tools/browser-extension-setup.ts +30 -0
  126. package/mcp-server/src/tools/browser-interact.ts +5 -1
  127. package/neural-interface/i18n/en.json +266 -2
  128. package/neural-interface/i18n/pt-BR.json +267 -3
  129. package/neural-interface/lib/agents/builtins.json +207 -0
  130. package/neural-interface/lib/agents/registry.js +60 -15
  131. package/neural-interface/lib/agents/resolve.js +69 -10
  132. package/neural-interface/lib/agents/split.js +32 -4
  133. package/neural-interface/lib/assistant-api.js +19 -8
  134. package/neural-interface/lib/assistant-brains/claude.js +2 -0
  135. package/neural-interface/lib/assistant-brains/opencode.js +60 -11
  136. package/neural-interface/lib/assistant-catalog.js +2 -2
  137. package/neural-interface/lib/assistant-config.js +0 -7
  138. package/neural-interface/lib/assistant-dispatch.js +384 -119
  139. package/neural-interface/lib/assistant-persona.js +17 -5
  140. package/neural-interface/lib/assistant-pricing.js +65 -14
  141. package/neural-interface/lib/assistant-router.js +181 -54
  142. package/neural-interface/lib/assistant-run-wait.js +45 -28
  143. package/neural-interface/lib/assistant-runtime.js +48 -34
  144. package/neural-interface/lib/backup-contents.js +158 -0
  145. package/neural-interface/lib/backup-crypto-io.js +330 -0
  146. package/neural-interface/lib/backup-crypto-worker.js +130 -0
  147. package/neural-interface/lib/backup-crypto.js +525 -0
  148. package/neural-interface/lib/backup-download.js +268 -0
  149. package/neural-interface/lib/backup-encryption.js +318 -0
  150. package/neural-interface/lib/backup-groups.js +287 -0
  151. package/neural-interface/lib/backup-restore-session.js +176 -0
  152. package/neural-interface/lib/backup-restore-stage.js +60 -0
  153. package/neural-interface/lib/backup-service.js +836 -322
  154. package/neural-interface/lib/backup-zip-reader.js +30 -18
  155. package/neural-interface/lib/backup-zip-writer.js +34 -10
  156. package/neural-interface/lib/browser-extension-adapter.js +109 -24
  157. package/neural-interface/lib/browser-extension-bridge.js +42 -8
  158. package/neural-interface/lib/claude-agent-bridge.js +1 -0
  159. package/neural-interface/lib/claude-session-cleanup.js +5 -1
  160. package/neural-interface/lib/cli-update-planner.js +105 -6
  161. package/neural-interface/lib/client-diagnostics.js +42 -0
  162. package/neural-interface/lib/confined-fs.js +7 -2
  163. package/neural-interface/lib/coordination/README.md +8 -2
  164. package/neural-interface/lib/coordination/contract.js +161 -0
  165. package/neural-interface/lib/coordination/database.js +999 -0
  166. package/neural-interface/lib/coordination/operations.js +436 -0
  167. package/neural-interface/lib/coordination/service.js +68 -537
  168. package/neural-interface/lib/coordination/storage-worker.js +101 -0
  169. package/neural-interface/lib/coordination/store.js +219 -1111
  170. package/neural-interface/lib/db.js +70 -32
  171. package/neural-interface/lib/health-count.js +37 -0
  172. package/neural-interface/lib/loop-stall.js +139 -0
  173. package/neural-interface/lib/maritaca/client.js +2 -2
  174. package/neural-interface/lib/maritaca/models.js +12 -17
  175. package/neural-interface/lib/maritaca/opencode.js +4 -2
  176. package/neural-interface/lib/memory-api.js +9 -1
  177. package/neural-interface/lib/memory-session-capture.js +42 -10
  178. package/neural-interface/lib/memory-store-gate.js +313 -0
  179. package/neural-interface/lib/memory-store-migrate.js +65 -0
  180. package/neural-interface/lib/memory-timers.js +7 -7
  181. package/neural-interface/lib/native-loop-providers.js +13 -16
  182. package/neural-interface/lib/native-loop-runtime.js +34 -14
  183. package/neural-interface/lib/opencode-build-preflight.js +30 -8
  184. package/neural-interface/lib/opencode-native-boundary.js +69 -8
  185. package/neural-interface/lib/opencode-provider-view.js +14 -3
  186. package/neural-interface/lib/opencode-v2-ws-requests.js +31 -1
  187. package/neural-interface/lib/opencode2-client.js +2 -1
  188. package/neural-interface/lib/peer-identity.js +13 -8
  189. package/neural-interface/lib/recall-impact.js +122 -0
  190. package/neural-interface/lib/scratch-evidence.js +420 -0
  191. package/neural-interface/lib/scratch-process-guard.js +139 -0
  192. package/neural-interface/lib/scratch-references.js +279 -0
  193. package/neural-interface/lib/scratch-retention-core.js +385 -0
  194. package/neural-interface/lib/scratch-retention-worker.js +37 -0
  195. package/neural-interface/lib/scratch-retention.js +151 -0
  196. package/neural-interface/lib/session-cache-builder.js +70 -44
  197. package/neural-interface/lib/session-cache-worker.js +157 -0
  198. package/neural-interface/lib/session-indexer.js +28 -21
  199. package/neural-interface/lib/session-search-index.js +85 -0
  200. package/neural-interface/lib/skills/creation.js +1 -1
  201. package/neural-interface/lib/sqlite-integrity-worker.js +3 -1
  202. package/neural-interface/lib/style-guide/store.js +43 -3
  203. package/neural-interface/lib/system-restore.js +50 -0
  204. package/neural-interface/lib/teams/api.js +15 -6
  205. package/neural-interface/lib/teams/claims.js +67 -31
  206. package/neural-interface/lib/teams/index.js +7 -7
  207. package/neural-interface/lib/teams/integration.js +40 -40
  208. package/neural-interface/lib/teams/landing.js +6 -6
  209. package/neural-interface/lib/teams/recovery.js +24 -23
  210. package/neural-interface/lib/teams/scheduler.js +196 -97
  211. package/neural-interface/lib/teams/schema.js +1 -1
  212. package/neural-interface/lib/teams/state.js +14 -14
  213. package/neural-interface/lib/teams/worktrees.js +27 -27
  214. package/neural-interface/lib/whatsapp/bridge.js +2 -1
  215. package/neural-interface/lib/worker-confinement.js +47 -2
  216. package/neural-interface/lib/worker-mcp-channel.js +2 -0
  217. package/neural-interface/lib/worker-resume.js +5 -0
  218. package/neural-interface/lib/worker-stop.js +86 -0
  219. package/neural-interface/package-lock.json +2 -2
  220. package/neural-interface/package.json +1 -1
  221. package/neural-interface/public/index.html +260 -0
  222. package/neural-interface/public/offline.html +4 -3
  223. package/neural-interface/public/onboarding.html +259 -34
  224. package/neural-interface/public/shared/agents/studio/ax-agent-view.js +2 -2
  225. package/neural-interface/public/shared/agents/studio/ax-editor-view.js +1 -1
  226. package/neural-interface/public/shared/agents/studio/ax-library.js +0 -6
  227. package/neural-interface/public/shared/agents/studio/ax-main.js +14 -7
  228. package/neural-interface/public/shared/agents/studio/ax-ui.js +2 -2
  229. package/neural-interface/public/shared/agy/agy-options.js +11 -0
  230. package/neural-interface/public/shared/agy/agy-panel.js +29 -10
  231. package/neural-interface/public/shared/agy/agy-styles.js +14 -12
  232. package/neural-interface/public/shared/agy/agy-tabs-logic.js +4 -1
  233. package/neural-interface/public/shared/api.js +3 -2
  234. package/neural-interface/public/shared/assistant/asst-api.js +3 -3
  235. package/neural-interface/public/shared/assistant/asst-brain-picker.js +13 -6
  236. package/neural-interface/public/shared/assistant/asst-control.js +2 -0
  237. package/neural-interface/public/shared/assistant/asst-motion-gate.js +78 -4
  238. package/neural-interface/public/shared/assistant/asst-panel.js +18 -2
  239. package/neural-interface/public/shared/assistant/asst-rack-styles.js +4 -0
  240. package/neural-interface/public/shared/assistant/asst-render.js +106 -38
  241. package/neural-interface/public/shared/assistant/asst-route.js +102 -21
  242. package/neural-interface/public/shared/assistant/asst-routes-editor.js +1 -1
  243. package/neural-interface/public/shared/assistant/asst-sidepanel.js +4 -2
  244. package/neural-interface/public/shared/assistant/asst-state.js +11 -0
  245. package/neural-interface/public/shared/assistant/asst-styles.js +10 -23
  246. package/neural-interface/public/shared/assistant/route-identity.js +2 -1
  247. package/neural-interface/public/shared/cc-dropdown.js +21 -15
  248. package/neural-interface/public/shared/cdx/cdx-render.js +9 -0
  249. package/neural-interface/public/shared/cdx/cdx-settings.js +3 -1
  250. package/neural-interface/public/shared/cdx/cdx-styles.js +6 -0
  251. package/neural-interface/public/shared/cdx/cdx-tabs.js +29 -9
  252. package/neural-interface/public/shared/client-diagnostics.js +94 -0
  253. package/neural-interface/public/shared/cp/cp-markdown.js +7 -2
  254. package/neural-interface/public/shared/cp/cp-styles.js +1 -1
  255. package/neural-interface/public/shared/effort-i18n.js +118 -0
  256. package/neural-interface/public/shared/html-shell.js +4 -51
  257. package/neural-interface/public/shared/loading-diagnostic-entry.js +64 -0
  258. package/neural-interface/public/shared/memory-store-wait.js +52 -0
  259. package/neural-interface/public/shared/morelogin-profile-field.js +1 -1
  260. package/neural-interface/public/shared/mtc/mtc-logic.js +2 -1
  261. package/neural-interface/public/shared/mtc/mtc-panel.js +8 -1
  262. package/neural-interface/public/shared/mtc/mtc-styles.js +13 -12
  263. package/neural-interface/public/shared/ocp-v2/ocp-v2-childpanel.js +7 -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-modelpicker.js +8 -1
  266. package/neural-interface/public/shared/ocp-v2/ocp-v2-panel.js +118 -6
  267. package/neural-interface/public/shared/ocp-v2/ocp-v2-render.js +27 -3
  268. package/neural-interface/public/shared/ocp-v2/ocp-v2-send.js +13 -0
  269. package/neural-interface/public/shared/ocp-v2/ocp-v2-session-actions.js +2 -1
  270. package/neural-interface/public/shared/ocp-v2/ocp-v2-styles.js +27 -93
  271. package/neural-interface/public/shared/ocp-v2/ocp-v2-variantpicker.js +17 -6
  272. package/neural-interface/public/shared/output-format.js +294 -0
  273. package/neural-interface/public/shared/owner-authority-view.js +4 -10
  274. package/neural-interface/public/shared/page-session.js +1 -1
  275. package/neural-interface/public/shared/provider-icons.js +6 -0
  276. package/neural-interface/public/shared/schedules-view.js +2 -1
  277. package/neural-interface/public/shared/server-presence.js +77 -0
  278. package/neural-interface/public/shared/settings/settings-ai-browser.js +5 -5
  279. package/neural-interface/public/shared/settings/settings-backup-contents.js +241 -0
  280. package/neural-interface/public/shared/settings/settings-backup-download.js +298 -0
  281. package/neural-interface/public/shared/settings/settings-backup-encryption-pane.js +335 -0
  282. package/neural-interface/public/shared/settings/settings-backup-encryption.js +545 -0
  283. package/neural-interface/public/shared/settings/settings-ia.js +1 -1
  284. package/neural-interface/public/shared/skills/studio/sx-geometry.js +12 -3
  285. package/neural-interface/public/shared/skills/studio/sx-main.js +14 -7
  286. package/neural-interface/public/shared/start-bridge.js +2 -2
  287. package/neural-interface/public/shared/studio-attention.js +6 -0
  288. package/neural-interface/public/shared/styles.css +354 -438
  289. package/neural-interface/public/shared/transcript-rows.js +28 -3
  290. package/neural-interface/public/shared/tray-auto-close.js +18 -5
  291. package/neural-interface/public/shared/ui-agents.js +1 -2
  292. package/neural-interface/public/shared/ui-automation-studio.js +168 -108
  293. package/neural-interface/public/shared/ui-claude-panel.js +42 -65
  294. package/neural-interface/public/shared/ui-loading.js +185 -25
  295. package/neural-interface/public/shared/ui-native-loop-router.js +59 -20
  296. package/neural-interface/public/shared/ui-navbar.js +2 -1
  297. package/neural-interface/public/shared/ui-output.js +533 -0
  298. package/neural-interface/public/shared/ui-owner-authority.js +48 -25
  299. package/neural-interface/public/shared/ui-schedules-studio.js +165 -128
  300. package/neural-interface/public/shared/ui-scroll-follow.js +97 -6
  301. package/neural-interface/public/shared/ui-sessions.js +2 -2
  302. package/neural-interface/public/shared/ui-settings-entry.js +18 -0
  303. package/neural-interface/public/shared/ui-settings.js +234 -67
  304. package/neural-interface/public/shared/ui-sidepanel-tray.js +3 -2
  305. package/neural-interface/public/shared/ui-sync.js +1 -0
  306. package/neural-interface/public/shared/ui-tooltip.js +16 -0
  307. package/neural-interface/public/shared/ui-tutorial.js +5 -6
  308. package/neural-interface/public/shared/ui-worker-end.js +27 -8
  309. package/neural-interface/public/shared/worker-end.js +9 -4
  310. package/neural-interface/public/sw.js +4 -3
  311. package/neural-interface/public/variant/2d/main.js +5 -0
  312. package/neural-interface/public/variant/3d/app.js +10 -0
  313. package/neural-interface/public/variant/3d/main.js +17 -4
  314. package/neural-interface/scripts/scratch-retention.mjs +20 -0
  315. package/neural-interface/server.js +507 -160
  316. package/npm-shrinkwrap.json +2 -2
  317. package/package.json +2 -1
  318. package/scripts/restore-data-home-from-backup.mjs +175 -8
  319. package/setup.js +18 -4
@@ -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,6 +163,7 @@ 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,
@@ -164,6 +171,7 @@ import {
164
171
  quoteCommandPath,
165
172
  resolveBrewToken,
166
173
  resolveLatest,
174
+ upstreamVersionSource,
167
175
  } from './lib/cli-update-planner.js';
168
176
  import { createCliResolver, spawnArgsFor } from './lib/cli-resolver.js';
169
177
  import { osPath } from './lib/os-path.js';
@@ -176,21 +184,31 @@ import { createCliPathManager } from './lib/cli-path.js';
176
184
  import { composeTerminalPath, terminalLaunchCommand, terminalArgument } from './lib/terminal-path.js';
177
185
  import {
178
186
  applyBackupRetention,
187
+ assertBackupGroups,
188
+ backupRoots,
179
189
  createVerifiedBackup,
190
+ sweepCrashedBackupArtifacts,
180
191
  getBackupHealth,
181
192
  listBackupSnapshots,
182
193
  loadBackupConfig as loadBackupConfigFile,
194
+ measureBackupContents,
183
195
  nextBackupDueMs,
184
196
  normalizeBackupConfig,
185
197
  saveBackupConfig as saveBackupConfigFile,
186
198
  } from './lib/backup-service.js';
199
+ import { backupDownloadHandlers, createBackupDownloadService } from './lib/backup-download.js';
200
+ import { backupContentsHandlers, createBackupContentsService } from './lib/backup-contents.js';
201
+ import { readManifestGroups } from './lib/backup-groups.js';
202
+ import { isEncryptedBackupFile } from './lib/backup-crypto.js';
203
+ import { backupEncryptionHandlers, createBackupEncryptionService, createPasswordAttemptLimiter } from './lib/backup-encryption.js';
204
+ import { createRestoreSessions, encryptedRestoreHandlers } from './lib/backup-restore-session.js';
187
205
  import {
188
206
  extractZipEntry,
189
207
  openZipArchive,
190
208
  readBackupManifest,
191
209
  verifyBackupChecksums,
192
210
  } from './lib/backup-zip-reader.js';
193
- import { planRestoreWrites, removeRestoreUpload, saveRestoreUpload } from './lib/system-restore.js';
211
+ import { planRestoreWrites, removeRestoreUpload, restoreFailureCode, restoreFailureFields, restoreWarningCode, saveRestoreUpload } from './lib/system-restore.js';
194
212
  import * as opencodeV2Client from './lib/opencode-v2-client.js';
195
213
  import { OPENCODE_MIN_VERSION, basicAuthHeader, checkPrivateOpencodeServer as checkOpencodeServer, createServeLogRedactor, opencodeInstallCommands, opencodeProblemText, opencodeSupportFor, redactServeOutput, servePasswordReader, serveSpecFor, serveUnsetCommand, withServeEnv } from './lib/opencode-protocol.js';
196
214
  import { SERVE_TOKEN_ENV } from './lib/process-identity.js';
@@ -208,9 +226,10 @@ import {
208
226
  } from './lib/opencode-config.js';
209
227
  import {
210
228
  handleOpencodeV2Request, opencodeV2WsCapabilities,
211
- buildSessionListQuery, mapSessionListRow, OPENCODE_V2_WS_MUTATION_TYPES, guardOpencodeV2Request,
229
+ buildSessionListQuery, mapSessionListRow, OPENCODE_V2_WS_MUTATION_TYPES, guardOpencodeV2Request, folderIsGone,
212
230
  } from './lib/opencode-v2-ws-requests.js';
213
231
  import { NativeLoopRuntime, isNativeLoopProfile } from './lib/native-loop-runtime.js';
232
+ import { scheduleScratchRetention } from './lib/scratch-retention.js';
214
233
  import { migrateAutomationContextFiles, normalizeAutomationRecord } from './lib/automation-storage-migration.js';
215
234
  import { createLoopGoalJudge } from './lib/native-loop-goal.js';
216
235
  import { McpToolsRefreshCoordinator } from './lib/mcp-tools-refresh-coordinator.js';
@@ -231,7 +250,7 @@ import { createOpenCodeActivityRelay } from './lib/opencode-worker-activity.js';
231
250
  import { browserServePortDenial, browserSessionLossRule } from './lib/browser-tool-policy.js';
232
251
  import { createNativeServeBoundary, createVerdictFile, nativeContextRevocation, nativeServeCapability, nativeServeReason, nativeServeVersionPolicy, narrowOffenders } from './lib/opencode-native-boundary.js';
233
252
  import { isolatedServeFailure } from './lib/opencode-launch-error.js';
234
- import { reconcilePreflightProfiles, preflightExcludedPorts, runOpencodeBuildPreflight } from './lib/opencode-build-preflight.js';
253
+ import { reconcilePreflightProfiles, preflightExcludedPorts, runOpencodeBuildPreflight, startOpencodeAtBoot } from './lib/opencode-build-preflight.js';
235
254
  import { binaryIdentity as opencodeBinaryIdentity, binaryKey as opencodeBinaryKey } from './lib/opencode-serve-probe.js';
236
255
  // Every OpenCode serve SynaBun starts is probed once it answers (lib/opencode-serve-probe.js: loopback only, every
237
256
  // sensitive /api request and WebSocket upgrade refused without its password, SynaBun's password accepted); what is
@@ -243,8 +262,10 @@ const nativeServeBoundary = createNativeServeBoundary({
243
262
  const cfg = loadBrowserConfig();
244
263
  const profiles = new Map(normalizeAgentProfiles(cfg).map(p => [p.envId, p]));
245
264
  const defaultId = moreLoginDefaultEnvId(cfg);
246
- if (defaultId) profiles.set(String(defaultId), { envId: String(defaultId) });
247
- for (const envId of nativePreflightProfiles) profiles.set(envId, { envId });
265
+ if (defaultId && !profiles.has(String(defaultId))) profiles.set(String(defaultId), { envId: String(defaultId) });
266
+ for (const envId of nativePreflightProfiles) {
267
+ if (!profiles.has(envId)) profiles.set(envId, { envId });
268
+ }
248
269
  const remote = [...profiles.values()].filter(p => !moreLogin.isLocalProfileId(p.envId));
249
270
  const liveProfiles = remote.length ? await reconcilePreflightProfiles(remote,
250
271
  () => moreLogin.listCompleteProfiles({ savedCfg: cfg, firstPageTimeout: 5000 }),
@@ -317,7 +338,7 @@ import { registerMaritacaRoutes } from './lib/maritaca/api.js';
317
338
  import { createMaritacaOpencodeSync, maritacaWorkerChannelProvider } from './lib/maritaca/opencode.js';
318
339
  import { createMaritacaOpencodeProxy, maritacaOpencodeProxyBaseUrl } from './lib/maritaca/opencode-proxy.js';
319
340
  import { antigravityHomeDir, antigravityHomesRoot, pruneAntigravityHomes } from './lib/antigravity/home.js';
320
- import { antigravityStores, findUserConversation, parseAntigravityTranscript, readTranscriptText } from './lib/antigravity/transcripts.js';
341
+ import { findUserConversation, parseAntigravityTranscript, readTranscriptText } from './lib/antigravity/transcripts.js';
321
342
  import {
322
343
  buildAgentDisallowedTools,
323
344
  agentAccessFrom,
@@ -458,14 +479,24 @@ import {
458
479
  getMemoriesByCategory, updateMemoriesCategory,
459
480
  getCategories as dbGetCategories, saveCategories as dbSaveCategories,
460
481
  countSessionChunks, searchSessionChunks as dbSearchSessionChunks,
461
- getKvConfig, setKvConfig, EMBEDDING_MODEL,
482
+ getKvConfig, setKvConfig, saveEmbeddingMetadata, EMBEDDING_MODEL,
462
483
  searchSessionFts, listSessionCache, getSessionCacheEntry, clearSessionCacheProvider,
463
484
  memoryVectors, getRecentXEngagements, getXActionBudget, getXEngagementTier, X_ACTION_TYPES,
464
485
  getFbActionBudget, getFbEngagementTier, FB_ACTION_TYPES,
465
486
  } from './lib/db.js';
466
- import {
467
- rebuildClaudeCache, rebuildCodexCache, rebuildOpencodeCache, rebuildAntigravityCache,
468
- } from './lib/session-cache-builder.js';
487
+ import { drainSessionJobs, runSessionJob, setSessionJobStoreGate } from './lib/session-cache-worker.js';
488
+ import { beginActivity, instrumentSqlite, markActivity, startLoopStallMonitor } from './lib/loop-stall.js';
489
+ import { createHealthCount } from './lib/health-count.js';
490
+ import { createRecallImpact } from './lib/recall-impact.js';
491
+ import { installMemoryStoreGate, isMemoryStoreRefusal, noteMemoryStoreRefusal } from './lib/memory-store-gate.js';
492
+
493
+ // Before anything opens the memory store: a migration it needs runs in a child process, never on this thread.
494
+ const memoryStoreGate = installMemoryStoreGate();
495
+ setSessionJobStoreGate(() => (memoryStoreGate.open() ? null : memoryStoreGate.forJobs()));
496
+
497
+ startLoopStallMonitor();
498
+ // A stall line names the slowest synchronous SQLite statement it held (off: SYNABUN_LOOP_STALL_SQL=off).
499
+ instrumentSqlite();
469
500
  import {
470
501
  clearOpenCodeHistory,
471
502
  getOpenCodeHistoryStats,
@@ -567,7 +598,7 @@ const requestGates = createRequestGates({
567
598
  settingsHint: () => ENV_PATH,
568
599
  });
569
600
  app.use(requestGates.host);
570
- app.use(express.json({ limit: '25mb' }));
601
+ app.use(express.json({ limit: '25mb', type: useDefaultJsonParser }));
571
602
 
572
603
  // Clean body-parser error handler: ui-state / whiteboard persist base64 images and can
573
604
  // exceed the JSON limit. Default Express handler dumps a 10-line raw-body stack with no
@@ -649,13 +680,15 @@ _peerIdentity.probe();
649
680
  const _ownerAuthority = createOwnerAuthority({ pageSession: () => _pageSession, isRemote: (req) => requestGates.isRemote(req), peer: _peerIdentity, log: (line) => console.warn(line), automationBrowserAllowed: () => _automationBrowserOwnerAccess.enabled() });
650
681
  app.use(_peerIdentity.middleware({ needs: peerLookupWanted }));
651
682
  app.use(_ownerAuthority.restGate);
683
+ // While the memory store is being upgraded, a route that needed it answers 503 "migrating", never an empty result.
684
+ app.use(memoryStoreGate.requestGuard);
652
685
 
653
686
  import { registerCodexPlanRoutes } from './lib/codex-plan-store.js';
654
687
  import { createOpencodeHiddenModelsRouter, createOpencodeHiddenModelsStore } from './lib/opencode-hidden-models.js';
655
688
  import { createEditorFilesRouter, EDITOR_BACKUP_CAPABILITIES, EDITOR_BACKUP_NAMESPACE } from './lib/editor-files-api.js';
656
689
  import { createEditorGitRouter, EDITOR_GIT_CAPABILITIES } from './lib/editor-git-api.js';
657
690
  import { confinedFolder, createFileExplorerRouter, EXPLORER_CAPABILITIES } from './lib/file-explorer-api.js';
658
- import { folderPickerCommand } from './lib/file-explorer-system.js';
691
+ import { createRevealer, folderPickerCommand } from './lib/file-explorer-system.js';
659
692
  import { createEditorConfigRouter, createEditorConfigStore, createEndpointKeyStore, EDITOR_CONFIG_CAPABILITIES } from './lib/editor-config.js';
660
693
  import {
661
694
  COMPLETION_SYSTEM, EDITOR_COMPLETION_CAPABILITIES, createEditorCompletionRouter, createEditorCompletionService, createUsageStore,
@@ -1087,6 +1120,7 @@ function peerLookupWanted(req) {
1087
1120
  app.use(_pageSession.serviceWorker); // GET /sw.js: a worker that takes itself away, for a browser refused the secret
1088
1121
  app.use(_pageSession.pages);
1089
1122
  app.get('/api/page-session', (req, res) => _pageSession.refresh(req, res)); // PAGE_SECRET_REFRESH_PATH
1123
+ app.post('/api/client-diagnostics', parseClientDiagnostics, createClientDiagnostics({ ownerPage: ownerPageApprovalCall, refuseOwner: refuseNotOwnerPage }));
1090
1124
  // The extension's "Connect your browser" page, opened by the one-button setup in the owner's everyday browser. One of
1091
1125
  // 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
1092
1126
  // status and its one ticket are the owner's, under the same owner guard; an automation browser and an agent's process
@@ -1720,32 +1754,13 @@ app.get('/api/stats', async (req, res) => {
1720
1754
  }
1721
1755
  });
1722
1756
 
1723
- // GET /api/recall-impact — Memory counts by importance threshold for recall settings UI
1724
- app.get('/api/recall-impact', (req, res) => {
1757
+ // GET /api/recall-impact — Memory counts by importance threshold for recall settings UI.
1758
+ // The two aggregates behind it read every memory and every session chunk whole; they run off this thread, in
1759
+ // slices, and the answer is kept for a minute (lib/recall-impact.js).
1760
+ const recallImpact = createRecallImpact();
1761
+ app.get('/api/recall-impact', async (req, res) => {
1725
1762
  try {
1726
- const d = getDb();
1727
- const rows = d.prepare(`
1728
- SELECT importance, COUNT(*) as cnt, CAST(AVG(LENGTH(content)) AS INTEGER) as avg_len,
1729
- CAST(AVG(CASE WHEN tags IS NOT NULL AND tags != '[]' THEN LENGTH(tags) ELSE 0 END) AS INTEGER) as avg_tags_len,
1730
- 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
1731
- FROM memories WHERE trashed_at IS NULL GROUP BY importance ORDER BY importance
1732
- `).all();
1733
- // Session chunk stats for token estimation
1734
- let sessionStats = { count: 0, avg_summary_len: 0, avg_details_len: 0 };
1735
- try {
1736
- const sc = d.prepare(`
1737
- SELECT COUNT(*) as count,
1738
- CAST(AVG(LENGTH(summary)) AS INTEGER) as avg_summary_len,
1739
- CAST(AVG(
1740
- COALESCE(LENGTH(tools_used), 0) +
1741
- COALESCE(LENGTH(files_modified), 0) +
1742
- COALESCE(LENGTH(related_memory_ids), 0)
1743
- ) AS INTEGER) as avg_details_len
1744
- FROM session_chunks
1745
- `).get();
1746
- if (sc) sessionStats = sc;
1747
- } catch { /* session_chunks table may not exist */ }
1748
- res.json({ rows, sessionStats });
1763
+ res.json(await recallImpact.get());
1749
1764
  } catch (err) {
1750
1765
  console.error('GET /api/recall-impact error:', err.message);
1751
1766
  res.status(500).json({ error: err.message });
@@ -2610,7 +2625,8 @@ async function runGracefulShutdown(reason) {
2610
2625
  // The coordination store (agent events, the Assistant's mailbox, the follow-up outbox): closed once the workers
2611
2626
  // are stopped or suspended and what that changed is recorded. Every open wait is answered, the write-ahead log is
2612
2627
  // folded into the file. Signals and the restart/update/shutdown routes all use this teardown.
2613
- try { _assistantCoordination?.close(); } catch (err) { console.warn(' coordination close err:', err?.message); }
2628
+ try { await _assistantDispatcher?.drainFinalizations?.(); } catch (err) { console.warn(' terminal run events:', err?.message); }
2629
+ try { await _assistantCoordination?.close(); } catch (err) { console.warn(' coordination close err:', err?.message); }
2614
2630
  try { closeDb(); } catch {}
2615
2631
  try { closeBlobStore(); } catch {}
2616
2632
 
@@ -3156,6 +3172,9 @@ app.post('/api/system/run-update', async (req, res) => {
3156
3172
  }
3157
3173
  });
3158
3174
 
3175
+ // Session indexing holds its own SQLite connection while a pass runs. A file replacement must wait for it.
3176
+ app.post(['/api/settings/move-db', '/api/settings/move-db/cleanup', '/api/system/restore', '/api/system/restore/apply-staged'], drainSessionJobs);
3177
+
3159
3178
  // POST /api/settings/move-db — Move SQLite database to a new directory
3160
3179
  app.post('/api/settings/move-db', (req, res) => {
3161
3180
  try {
@@ -3267,7 +3286,7 @@ async function runReindex(job) {
3267
3286
  const updateStmt = d.prepare('UPDATE memories SET vector = ? WHERE id = ?');
3268
3287
  for (let i = 0; i < rows.length; i++) {
3269
3288
  try {
3270
- updateStmt.run(encodeVector(vectors[i]), rows[i].id);
3289
+ await withMemoryWrite(d, () => updateStmt.run(encodeVector(vectors[i]), rows[i].id));
3271
3290
  job.completed++;
3272
3291
  } catch {
3273
3292
  job.errors++;
@@ -3295,7 +3314,7 @@ async function runReindex(job) {
3295
3314
  const updateStmt = d.prepare('UPDATE session_chunks SET vector = ? WHERE id = ?');
3296
3315
  for (let i = 0; i < rows.length; i++) {
3297
3316
  try {
3298
- updateStmt.run(encodeVector(vectors[i]), rows[i].id);
3317
+ await withMemoryWrite(d, () => updateStmt.run(encodeVector(vectors[i]), rows[i].id));
3299
3318
  job.chunks++;
3300
3319
  } catch {
3301
3320
  job.errors++;
@@ -3310,8 +3329,7 @@ async function runReindex(job) {
3310
3329
 
3311
3330
  // Update stored model metadata
3312
3331
  try {
3313
- setKvConfig('embedding_model', EMBEDDING_MODEL);
3314
- setKvConfig('embedding_dims', String(EMBEDDING_DIMS));
3332
+ await saveEmbeddingMetadata();
3315
3333
  } catch {}
3316
3334
 
3317
3335
  job.running = false;
@@ -8386,7 +8404,9 @@ let _ocpVersion = null;
8386
8404
  // says why OpenCode cannot be used (shown by the panel, Settings and the tray).
8387
8405
  let _ocpPassword = null;
8388
8406
  let _ocpProblem = null;
8407
+ let _ocpStartRefusal = null; // The MoreLogin check that refused the last start (startOpencodeAtBoot reads it).
8389
8408
  let _ocpHistoryClearInProgress = false;
8409
+ let _ocpSessionCacheWarmup = null;
8390
8410
 
8391
8411
  // ── OpenCode V2 (clean-slate sidepanel) — client set & bridge ──
8392
8412
  const _ocpV2WsClients = new Set(); // all connected /ws/opencode-v2 clients
@@ -9513,6 +9533,9 @@ function handleOpencodeV2Ws(ws) {
9513
9533
  nativeMutationTypes: OPENCODE_NATIVE_MUTATION_TYPES,
9514
9534
  protectedRunFor: activeNativeOpenCodeRunForSession,
9515
9535
  ownsRun: (run) => opencodeV2ClientOwnsRun(ws, run),
9536
+ // A session or a turn in a folder that no longer exists (a removed worktree) is refused before OpenCode
9537
+ // makes a session that can never run: the panel moves to the project the folder was in.
9538
+ folderGone: folderIsGone,
9516
9539
  });
9517
9540
  if (refused) {
9518
9541
  send({ type: `${type}:result`, id, ...refused });
@@ -9910,6 +9933,7 @@ async function ensureOpencodeServer({ allowDuringHistoryClear = false } = {}) {
9910
9933
  return false;
9911
9934
  }
9912
9935
  _ocpProblem = null;
9936
+ _ocpStartRefusal = null;
9913
9937
  // A serve already running is adopted when it answers SynaBun: only to the password SynaBun gave it, and only
9914
9938
  // 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
9915
9939
  // adopted, and its port with it.
@@ -9988,6 +10012,11 @@ async function ensureOpencodeServer({ allowDuringHistoryClear = false } = {}) {
9988
10012
  });
9989
10013
  } catch (err) {
9990
10014
  console.error(`[opencode] Failed to spawn: ${err.message}`);
10015
+ // A MoreLogin check that refused this start: the panel says why instead of staying silently offline.
10016
+ if (err?.sharedPreflight) {
10017
+ _ocpStartRefusal = err;
10018
+ reportOpencodeProblem(err.message);
10019
+ }
9991
10020
  return 'not-spawned';
9992
10021
  }
9993
10022
  for (let i = 0; i < 30; i++) {
@@ -10495,6 +10524,9 @@ app.delete('/api/opencode/history', async (req, res) => {
10495
10524
  try { result.databaseBytesAfter = getOpenCodeHistoryStats({ dbPath, dataRoot: dirname(dbPath) }).databaseBytes; } catch { result.databaseBytesAfter = before.databaseBytes; }
10496
10525
 
10497
10526
  try {
10527
+ // A startup scan may still hold session rows it read before deletion.
10528
+ // Finish that pass before clearing the index so none can be put back.
10529
+ if (_ocpSessionCacheWarmup) await _ocpSessionCacheWarmup.catch(() => {});
10498
10530
  result.resumeCache = clearSessionCacheProvider('opencode');
10499
10531
  } catch (error) {
10500
10532
  result.warnings.push(`OpenCode Resume cache could not be cleared: ${error.message}`);
@@ -15223,9 +15255,23 @@ app.post('/api/loop/stop', async (req, res) => {
15223
15255
  // No agent header at all: the owner's page, with its page secret (or an invite guest, whom the guest rules decide).
15224
15256
  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.');
15225
15257
  const targetTerminalId = who.automation ? who.id : named;
15258
+ // Accepted legacy/grace pins authorize their existing operation but do not prove identity.
15259
+ const stopProvenance = stampStopProvenance(null, who.automation
15260
+ ? (who.status === 'verified' ? { actor: 'automation', action: 'self_stop', runId: who.id } : { actor: 'unknown', action: 'stop' })
15261
+ : pageStopProvenance(req.body?.action, true), new Date().toISOString());
15262
+ if (!targetTerminalId) stopProvenance.scope = 'all';
15263
+ // 'user' only for a control a person operated; a run stopping itself and an unnamed caller say so.
15264
+ const stopReason = callerStopReason(stopProvenance);
15265
+ // A run suspended for a restart outlives its old process, a closing page and the tray's timer: only a deliberate
15266
+ // stop ends it (lib/worker-stop.js). It keeps its loop file, which is what its resume reads.
15267
+ const staysSuspended = (id) => _nativeLoopRuntime?.isSuspended?.(id) && !mayEndSuspendedRun(stopProvenance);
15268
+ if (targetTerminalId && staysSuspended(targetTerminalId)) {
15269
+ loopLog(targetTerminalId, 'loop:stop-refused', 'A suspended run stays suspended: this caller may not end it', { stopProvenance });
15270
+ 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.' });
15271
+ }
15226
15272
  let directlyStopped = false;
15227
15273
  if (targetTerminalId && _nativeLoopRuntime?.isAlive(targetTerminalId)) {
15228
- directlyStopped = await _nativeLoopRuntime.stop(targetTerminalId, 'user');
15274
+ directlyStopped = await _nativeLoopRuntime.stop(targetTerminalId, stopReason, { stopProvenance });
15229
15275
  }
15230
15276
  if (!existsSync(LOOP_DIR)) return res.json({ ok: true, stopped: directlyStopped ? 1 : 0 });
15231
15277
  const files = readdirSync(LOOP_DIR).filter(f => f.endsWith('.json') && f !== '.gitkeep');
@@ -15242,17 +15288,22 @@ app.post('/api/loop/stop', async (req, res) => {
15242
15288
  if (data.active || data.pending) {
15243
15289
  // Per-loop stop: skip loops that don't match the target
15244
15290
  if (targetTerminalId && data.runId !== targetTerminalId && data.terminalSessionId !== targetTerminalId) continue;
15291
+ // "Stop every loop" from a caller that may not end a suspended run passes over it.
15292
+ if (staysSuspended(data.runId || data.terminalSessionId)) continue;
15245
15293
  if (!directlyStopped && (data.runtimeType === 'native' || data.driverType === 'native')) {
15246
- await _nativeLoopRuntime?.stop(data.runId || data.terminalSessionId, 'user');
15294
+ await _nativeLoopRuntime?.stop(data.runId || data.terminalSessionId, stopReason, { stopProvenance });
15247
15295
  }
15248
15296
  if (data.driverType === 'exec' && data.scheduledBy) {
15249
15297
  data.active = false;
15250
15298
  data.pending = false;
15251
15299
  data.completedAt = new Date().toISOString();
15252
- data.stoppedReason = 'user';
15300
+ data.stoppedReason = stopReason;
15301
+ data.stopProvenance = stopProvenance;
15253
15302
  try { writeFileSync(filePath, JSON.stringify(data, null, 2)); } catch {}
15254
- persistExecScheduleOutcome(data, 'stopped', 'user');
15303
+ persistExecScheduleOutcome(data, 'stopped', stopReason);
15255
15304
  }
15305
+ // Classic loop files are removed below; keep the action in their per-run log.
15306
+ loopLog(data.runId || data.terminalSessionId, 'loop:stop', 'Loop stopped', { stopProvenance });
15256
15307
  // Kill PTY session if still alive
15257
15308
  if (data.terminalSessionId && terminalSessions.has(data.terminalSessionId)) {
15258
15309
  const session = terminalSessions.get(data.terminalSessionId);
@@ -16318,7 +16369,8 @@ async function launchScheduledLoop(schedule) {
16318
16369
  if (isXAutomation) {
16319
16370
  try {
16320
16371
  const xAccount = (template.account || (/^cp_/.test(schedule.templateId || '') ? 'Crit_Pix' : '')).trim();
16321
- const { handles, statusIds, blocked, error: ledgerErr } = getRecentXEngagements({ account: xAccount || null, days: 7, limit: 200 });
16372
+ // The ledger's reads scan memories by tag: they run off this thread and are awaited (lib/db.js ledgerRows).
16373
+ const { handles, statusIds, blocked, error: ledgerErr } = await getRecentXEngagements({ account: xAccount || null, days: 7, limit: 200 });
16322
16374
  if (ledgerErr) {
16323
16375
  loopLog(terminalSessionId, 'launch:dedup', 'engagement ledger read failed (continuing)', { err: ledgerErr });
16324
16376
  } else if (handles.length || statusIds.length || blocked.length) {
@@ -16345,8 +16397,8 @@ async function launchScheduledLoop(schedule) {
16345
16397
  const tz = schedule.timezone || 'America/Sao_Paulo';
16346
16398
  const nowLocal = getNowInTimezone(tz);
16347
16399
  const msIntoDay = ((nowLocal.getHours() * 60 + nowLocal.getMinutes()) * 60 + nowLocal.getSeconds()) * 1000 + nowLocal.getMilliseconds();
16348
- const spent = getXActionBudget({ account: xAccount || null, sinceIso: new Date(Date.now() - msIntoDay).toISOString() });
16349
- const { tier, caps, source: tierSource } = getXEngagementTier({ account: xAccount || null });
16400
+ const spent = await getXActionBudget({ account: xAccount || null, sinceIso: new Date(Date.now() - msIntoDay).toISOString() });
16401
+ const { tier, caps, source: tierSource } = await getXEngagementTier({ account: xAccount || null });
16350
16402
  if (spent.error) {
16351
16403
  loopLog(terminalSessionId, 'launch:budget', 'action budget read failed (continuing)', { err: spent.error });
16352
16404
  } else {
@@ -16386,8 +16438,8 @@ async function launchScheduledLoop(schedule) {
16386
16438
  const tz = schedule.timezone || 'America/Sao_Paulo';
16387
16439
  const nowLocal = getNowInTimezone(tz);
16388
16440
  const msIntoDay = ((nowLocal.getHours() * 60 + nowLocal.getMinutes()) * 60 + nowLocal.getSeconds()) * 1000 + nowLocal.getMilliseconds();
16389
- const spent = getFbActionBudget({ sinceIso: new Date(Date.now() - msIntoDay).toISOString() });
16390
- const { tier, caps, source: tierSource } = getFbEngagementTier();
16441
+ const spent = await getFbActionBudget({ sinceIso: new Date(Date.now() - msIntoDay).toISOString() });
16442
+ const { tier, caps, source: tierSource } = await getFbEngagementTier();
16391
16443
  if (spent.error) {
16392
16444
  loopLog(terminalSessionId, 'launch:budget', 'FB action budget read failed (continuing)', { err: spent.error });
16393
16445
  } else {
@@ -16890,6 +16942,7 @@ function reconcileKeepAwake() {
16890
16942
  }
16891
16943
 
16892
16944
  function evaluateSchedules() {
16945
+ markActivity('scheduler:schedules');
16893
16946
  // P5 deterministic health shares the scheduler's tick; disabled until enabled in Skills Studio.
16894
16947
  skillsService?.health.tick().catch((error) => console.error('[skills-health]', error?.code || 'check_failed'));
16895
16948
  _scheduleEvalCount++;
@@ -18827,8 +18880,9 @@ const TOOL_DEFS = [
18827
18880
  // Google's Antigravity CLI has no npm package: a Homebrew cask's newer version is what `brew outdated` says, and
18828
18881
  // the CLI updates itself (`agy update`).
18829
18882
  { key: 'antigravity', cmd: 'agy', versionArg: '--version' },
18830
- // npm's opencode-ai is OpenCode 1: OpenCode 2's newer version is what Homebrew says (a brew install) or what OpenCode
18831
- // itself announces in its own interface.
18883
+ // npm's opencode-ai is OpenCode 1: OpenCode 2's newer version is read where its install channel publishes it
18884
+ // (upstreamVersionSource in lib/cli-update-planner.js: OpenCode's own update API, or the formula of its Homebrew
18885
+ // tap, whose local clone `brew outdated` reads stale).
18832
18886
  { key: 'opencode', cmd: 'opencode', versionArg: '--version' },
18833
18887
  ];
18834
18888
 
@@ -18931,6 +18985,7 @@ function pruneBundledCliTools() {
18931
18985
  }
18932
18986
 
18933
18987
  async function checkToolVersions({ force = false } = {}) {
18988
+ markActivity('cli:versions');
18934
18989
  const generation = ++_toolVersionGeneration;
18935
18990
  // Every CLI exactly as the panels and launchers find it (lib/cli-resolver.js):
18936
18991
  // the path in Settings first, then PATH with the OS PATH read afresh, then the
@@ -18954,6 +19009,12 @@ async function checkToolVersions({ force = false } = {}) {
18954
19009
  // Homebrew routinely trails npm by a few releases, so comparing against it
18955
19010
  // produced a badge that lit up while `brew upgrade` answered "already
18956
19011
  // installed". Reported as upstreamLatest purely for diagnostics.
19012
+ const installSource = status.installSource;
19013
+ const brewToken = isBrewSource(installSource) ? resolveBrewToken(tool.key, status.realPath || status.path) : null;
19014
+ // A tool without an npm package (OpenCode 2) says where its newest version is published for the way it was
19015
+ // installed: its vendor's update API, or the formula of its Homebrew tap (lib/cli-update-planner.js).
19016
+ const published = tool.npm || tool.github ? null : upstreamVersionSource(tool.key, installSource, brewToken);
19017
+
18957
19018
  let upstreamLatest = null;
18958
19019
  try {
18959
19020
  const controller = new AbortController();
@@ -18966,22 +19027,31 @@ async function checkToolVersions({ force = false } = {}) {
18966
19027
  const res = await fetch(`https://api.github.com/repos/${tool.github}/releases/latest`, { signal: controller.signal });
18967
19028
  clearTimeout(timeout);
18968
19029
  if (res.ok) { const d = await res.json(); upstreamLatest = parseVersion(d.tag_name || ''); }
19030
+ } else if (published) {
19031
+ const res = await fetch(published.url, { signal: controller.signal });
19032
+ clearTimeout(timeout);
19033
+ if (res.ok) upstreamLatest = published.read(await res.text());
19034
+ } else {
19035
+ clearTimeout(timeout);
18969
19036
  }
18970
19037
  } catch { /* network error */ }
18971
19038
 
18972
- const installSource = status.installSource;
18973
- const brewToken = isBrewSource(installSource) ? resolveBrewToken(tool.key, status.realPath || status.path) : null;
19039
+ // The tap's formula as published: what Homebrew installs once it is refreshed. `brew outdated` reads the
19040
+ // local clone of a tap, which nothing refreshes between the user's own brew runs.
19041
+ const brewUpstream = published?.channel === 'brew-formula' ? upstreamLatest : null;
18974
19042
  const latest = resolveLatest({
18975
19043
  installSource,
18976
19044
  brewToken,
18977
19045
  brewOutdated,
18978
19046
  npmLatest: upstreamLatest,
19047
+ brewUpstream,
18979
19048
  installed,
18980
19049
  });
19050
+ const refreshBrew = brewNeedsRefresh({ installSource, brewToken, brewOutdated, brewUpstream, installed });
18981
19051
  // A self-updater is started by the path found, so the update reaches this
18982
19052
  // very installation even where a terminal's PATH does not name its folder.
18983
19053
  const updateCommand = installed
18984
- ? buildUpdateCommand(tool.key, installSource, { brewToken, binPath: status.path, platform: process.platform })
19054
+ ? buildUpdateCommand(tool.key, installSource, { brewToken, binPath: status.path, platform: process.platform, refreshBrew })
18985
19055
  : null;
18986
19056
 
18987
19057
  return [tool.key, {
@@ -19138,6 +19208,56 @@ app.use('/api/cli/opencode-serves', createOpencodeServeVerifyApi({ boundary: nat
19138
19208
  // FULL SYSTEM BACKUP & RESTORE
19139
19209
  // ═══════════════════════════════════════════
19140
19210
 
19211
+ // ── Download backup into a folder the owner chose (lib/backup-download.js) ──
19212
+ // Settings → Backups. The server builds the verified archive directly in a folder of this computer (remembered in
19213
+ // data/backup-download.json, ~/Downloads until one is chosen) as one job the page starts and then asks about: no
19214
+ // response a browser tab has to hold in memory. One backup at a time, through serializeBackupOperation, like the
19215
+ // scheduled ones. The owner's routes (editorOwnerGuard, as /api/browse-folder, whose dialog picks the folder), and the
19216
+ // three that write are the owner's page's alone, as restore is: they put a copy of everything, the .env included,
19217
+ // where the request says. Reveal takes no path: it shows the last finished backup, or the folder.
19218
+ const backupDownload = createBackupDownloadService({
19219
+ configPath: resolve(DATA_HOME, 'data', 'backup-download.json'),
19220
+ dataHome: DATA_HOME,
19221
+ sourceRoots: () => backupRoots(DATA_HOME, getBackupAdditionalEntries()),
19222
+ serialize: (operation) => serializeBackupOperation(operation),
19223
+ isBusy: () => _backupOperationActive,
19224
+ createBackup: ({ folderPath, onProgress, signal }) => createVerifiedBackup({
19225
+ dataHome: DATA_HOME,
19226
+ databasePath: getDbPath(),
19227
+ folderPath,
19228
+ kind: 'manual',
19229
+ appVersion: JSON.parse(readFileSync(resolve(PACKAGE_ROOT, 'package.json'), 'utf-8')).version || null,
19230
+ additionalEntries: getBackupAdditionalEntries(),
19231
+ groups: backupContents.groups(),
19232
+ onProgress,
19233
+ signal,
19234
+ }),
19235
+ log: (line) => console.log(line),
19236
+ });
19237
+ const backupDownloadRoutes = backupDownloadHandlers(backupDownload, { revealer: createRevealer() });
19238
+ // ── What a backup holds (lib/backup-groups.js, lib/backup-contents.js) ──
19239
+ // Settings → Backups → What to back up. One choice, kept in data/backup-selection.json, for every backup made on
19240
+ // request or on schedule (the pre-update snapshot keeps its own rules). The sizes are measured on a worker thread
19241
+ // and only read here. Reading is the owner's; changing the choice is the owner's page's alone, as choosing the
19242
+ // folder is.
19243
+ const backupContents = createBackupContentsService({
19244
+ configPath: resolve(DATA_HOME, 'data', 'backup-selection.json'),
19245
+ measure: () => measureBackupContents({ dataHome: DATA_HOME, databasePath: getDbPath(), additionalEntries: getBackupAdditionalEntries() }),
19246
+ log: (line) => console.log(line),
19247
+ });
19248
+ const backupContentsRoutes = backupContentsHandlers(backupContents);
19249
+ function backupDownloadOwnerPage(req, res, next) {
19250
+ if (restoreOwnerPageCall(req)) return next();
19251
+ 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.');
19252
+ }
19253
+ app.get('/api/system/backup/job', editorOwnerGuard, backupDownloadRoutes.status);
19254
+ app.put('/api/system/backup/destination', editorOwnerGuard, backupDownloadOwnerPage, backupDownloadRoutes.setDestination);
19255
+ app.post('/api/system/backup/job', editorOwnerGuard, backupDownloadOwnerPage, backupDownloadRoutes.start);
19256
+ app.post('/api/system/backup/job/cancel', editorOwnerGuard, backupDownloadOwnerPage, backupDownloadRoutes.cancel);
19257
+ app.post('/api/system/backup/reveal', editorOwnerGuard, backupDownloadOwnerPage, backupDownloadRoutes.reveal);
19258
+ app.get('/api/system/backup/contents', editorOwnerGuard, backupContentsRoutes.status);
19259
+ app.put('/api/system/backup/contents', editorOwnerGuard, backupDownloadOwnerPage, backupContentsRoutes.update);
19260
+
19141
19261
  // GET /api/system/backup — Download full system backup as ZIP
19142
19262
  app.get('/api/system/backup', async (req, res) => {
19143
19263
  try {
@@ -19150,6 +19270,7 @@ app.get('/api/system/backup', async (req, res) => {
19150
19270
  kind: 'manual',
19151
19271
  appVersion: pkg.version || null,
19152
19272
  additionalEntries: getBackupAdditionalEntries(),
19273
+ groups: backupContents.groups(),
19153
19274
  }));
19154
19275
  res.download(backup.path, backup.name, error => {
19155
19276
  try { if (existsSync(backup.path)) unlinkSync(backup.path); } catch {}
@@ -19167,6 +19288,46 @@ app.get('/api/system/backup', async (req, res) => {
19167
19288
  // and a ZIP over 2 GiB cannot be read into a Buffer at all.
19168
19289
  const RESTORE_STAGING_DIR = resolve(DATA_HOME, 'backups', 'restore-staging');
19169
19290
 
19291
+ // ── Password protection of backups (lib/backup-encryption.js, docs/backup-encryption.md) ──
19292
+ // Settings → Backups → Password protection. Off until the owner sets a password; while it is on, every backup this
19293
+ // server or the updater makes is encrypted or fails (lib/backup-service.js asks the data home's key file itself, so
19294
+ // no caller here passes anything). Reading the state is the owner's; turning it on, changing the password and
19295
+ // turning it off are the owner's page's alone, each with the password in its JSON body, never in the address. Wrong
19296
+ // passwords are slowed by one limiter, shared with the restore's unlock below.
19297
+ const backupPasswordAttempts = createPasswordAttemptLimiter();
19298
+ const backupEncryption = createBackupEncryptionService({ dataHome: DATA_HOME, limiter: backupPasswordAttempts, log: (line) => console.log(line) });
19299
+ const backupEncryptionRoutes = backupEncryptionHandlers(backupEncryption);
19300
+ function backupEncryptionOwnerPage(req, res, next) {
19301
+ if (restoreOwnerPageCall(req)) return next();
19302
+ 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.');
19303
+ }
19304
+ app.get('/api/system/backup/encryption', editorOwnerGuard, backupEncryptionRoutes.status);
19305
+ app.post('/api/system/backup/encryption/enable', editorOwnerGuard, backupEncryptionOwnerPage, backupEncryptionRoutes.enable);
19306
+ app.post('/api/system/backup/encryption/change', editorOwnerGuard, backupEncryptionOwnerPage, backupEncryptionRoutes.change);
19307
+ app.post('/api/system/backup/encryption/disable', editorOwnerGuard, backupEncryptionOwnerPage, backupEncryptionRoutes.disable);
19308
+ // The latest backups in the folders SynaBun writes them to, and whether each is encrypted (told by the file's first
19309
+ // bytes, never by its name). Names, dates and sizes only: no path leaves the server and no archive is opened.
19310
+ app.get('/api/system/backup/history', editorOwnerGuard, async (req, res) => {
19311
+ try {
19312
+ const folders = [resolve(DATA_HOME, 'backups', 'updates')];
19313
+ try { folders.push(loadAutoBackupConfig().folderPath); } catch { /* no schedule */ }
19314
+ try { folders.push(backupDownload.destination().folderPath); } catch { /* no folder chosen */ }
19315
+ const listed = [];
19316
+ for (const folder of new Set(folders.filter(Boolean).map(item => resolve(item)))) {
19317
+ try { listed.push(...await listBackupSnapshots(folder)); } catch { /* a drive that is not there */ }
19318
+ }
19319
+ listed.sort((a, b) => b.createdMs - a.createdMs);
19320
+ const backups = [];
19321
+ for (const item of listed.slice(0, 12)) {
19322
+ backups.push({ name: item.name, kind: item.kind, createdAt: item.createdAt, sizeBytes: item.sizeBytes, encrypted: await isEncryptedBackupFile(item.path) });
19323
+ }
19324
+ res.json({ ok: true, backups, total: listed.length });
19325
+ } catch (err) {
19326
+ console.error('GET /api/system/backup/history error:', err.message);
19327
+ res.status(500).json({ ok: false, error: 'The list of backups could not be read.' });
19328
+ }
19329
+ });
19330
+
19170
19331
  // POST /api/system/restore/preview — Read manifest from uploaded ZIP without applying
19171
19332
  /** One sentence for a failed MCP server build (lib/mcp-build.js result), with what the compiler said when it said anything. */
19172
19333
  function mcpBuildFailureMessage(build) {
@@ -19226,6 +19387,22 @@ function markRestoredAutomationRecords(targets) {
19226
19387
  return marked;
19227
19388
  }
19228
19389
 
19390
+ /**
19391
+ * What the page shows before it asks for a restore: when the backup was made, how many files, and which groups it
19392
+ * holds (lib/backup-groups.js). The file list and the checksums stay here: for a full backup they are tens of MB.
19393
+ * The same answer for a plain backup and for an encrypted one after its password opened it.
19394
+ */
19395
+ async function restorePreviewOf(zip) {
19396
+ const found = await readBackupManifest(zip);
19397
+ if (!found) throw Object.assign(new Error('Invalid backup: manifest.json not found'), { status: 400, code: 'RESTORE_MANIFEST_MISSING' });
19398
+ const { files, checksums, inputs, ...head } = found.manifest;
19399
+ return {
19400
+ ok: true,
19401
+ manifest: { ...head, fileCount: Array.isArray(files) ? files.length : 0 },
19402
+ contents: readManifestGroups(found.manifest),
19403
+ };
19404
+ }
19405
+
19229
19406
  app.post('/api/system/restore/preview', async (req, res) => {
19230
19407
  if (!restoreOwnerPageCall(req)) return refuseRestoreCaller(req, res);
19231
19408
  let upload = null;
@@ -19233,17 +19410,20 @@ app.post('/api/system/restore/preview', async (req, res) => {
19233
19410
  try {
19234
19411
  upload = await saveRestoreUpload(req, RESTORE_STAGING_DIR);
19235
19412
  if (upload.sizeBytes === 0) {
19236
- return res.status(400).json({ error: 'No data received' });
19413
+ return res.status(400).json({ error: 'No data received', code: 'RESTORE_EMPTY_UPLOAD' });
19237
19414
  }
19238
- zip = await openZipArchive(upload.path);
19239
- const found = await readBackupManifest(zip);
19240
- if (!found) {
19241
- return res.status(400).json({ error: 'Invalid backup: manifest.json not found' });
19415
+ // An encrypted backup says nothing of what it holds before its password. It stays staged, still encrypted, and
19416
+ // the page sends the password in a JSON body (POST /api/system/restore/unlock, lib/backup-restore-session.js).
19417
+ if (await isEncryptedBackupFile(upload.path)) {
19418
+ const staged = await restoreSessions.keep(upload);
19419
+ upload = null;
19420
+ return res.json({ ok: true, encrypted: true, locked: true, ...staged });
19242
19421
  }
19243
- res.json({ ok: true, manifest: found.manifest });
19422
+ zip = await openZipArchive(upload.path);
19423
+ res.json(await restorePreviewOf(zip));
19244
19424
  } catch (err) {
19245
19425
  console.error('POST /api/system/restore/preview error:', err.message);
19246
- if (!res.headersSent) res.status(500).json({ error: err.message });
19426
+ if (!res.headersSent) res.status(Number(err.status) || 500).json({ error: err.message, code: restoreFailureCode(err) });
19247
19427
  } finally {
19248
19428
  await zip?.close().catch(() => {});
19249
19429
  removeRestoreUpload(upload);
@@ -19259,32 +19439,64 @@ app.post('/api/system/restore', async (req, res) => {
19259
19439
  try {
19260
19440
  upload = await saveRestoreUpload(req, RESTORE_STAGING_DIR);
19261
19441
  if (upload.sizeBytes === 0) {
19262
- return res.status(400).json({ error: 'No backup data received' });
19442
+ return res.status(400).json({ error: 'No backup data received', code: 'RESTORE_EMPTY_UPLOAD' });
19443
+ }
19444
+ // An encrypted backup is restored in steps (preview, unlock, apply-staged): this route has no way to be given
19445
+ // its password, and must not be given one in the address.
19446
+ if (await isEncryptedBackupFile(upload.path)) {
19447
+ 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.' });
19263
19448
  }
19264
-
19265
- const mode = req.query.mode || 'full';
19266
19449
 
19267
19450
  zip = await openZipArchive(upload.path);
19451
+ await applyRestoreArchive(zip, req.query.mode || 'full', res);
19452
+ } catch (err) {
19453
+ console.error('POST /api/system/restore error:', err.message);
19454
+ if (!res.headersSent) res.status(500).json({ error: err.message, ...restoreFailureFields(err, res) });
19455
+ } finally {
19456
+ await zip?.close().catch(() => {});
19457
+ removeRestoreUpload(upload);
19458
+ }
19459
+ });
19268
19460
 
19461
+ /**
19462
+ * The restore itself, from an opened archive: the uploaded ZIP, or the ZIP inside an encrypted backup whose password
19463
+ * opened it (lib/backup-restore-session.js). Verifies before it writes, writes only what the archive holds, and
19464
+ * answers `res`. The caller closes the archive and removes the upload.
19465
+ */
19466
+ async function applyRestoreArchive(zip, mode, res) {
19269
19467
  // Find and validate manifest
19270
19468
  const found = await readBackupManifest(zip);
19271
19469
  if (!found) {
19272
- return res.status(400).json({ error: 'Invalid backup: manifest.json not found' });
19470
+ return res.status(400).json({ error: 'Invalid backup: manifest.json not found', code: 'RESTORE_MANIFEST_MISSING' });
19273
19471
  }
19274
19472
  const { manifest, prefix } = found;
19275
19473
  if (![1, 2, 3].includes(manifest.version)) {
19276
- return res.status(400).json({ error: `Unsupported backup version: ${manifest.version}` });
19474
+ return res.status(400).json({ error: `Unsupported backup version: ${manifest.version}`, code: 'RESTORE_UNSUPPORTED_VERSION' });
19277
19475
  }
19278
19476
 
19279
19477
  // v3 archives are published only after checksum verification. Recheck on
19280
19478
  // restore so a damaged or edited snapshot cannot partially replace state.
19281
19479
  if (manifest.version >= 3) {
19282
- try { await verifyBackupChecksums(zip, { prefix, manifest, label: 'Invalid backup' }); }
19283
- catch (error) { return res.status(400).json({ error: error.message }); }
19480
+ // An archive that records its groups holds exactly those, or it is refused before anything is written.
19481
+ try {
19482
+ assertBackupGroups(zip, manifest, prefix, 'Invalid backup');
19483
+ await verifyBackupChecksums(zip, { prefix, manifest, label: 'Invalid backup' });
19484
+ }
19485
+ catch (error) { return res.status(400).json({ error: error.message, code: restoreFailureCode(error) }); }
19486
+ }
19487
+ // An encrypted backup: every part of the file passes its check before anything is written, the parts no entry
19488
+ // reaches too (a file cut short, added to or reordered fails here).
19489
+ if (zip.encrypted) {
19490
+ try { await zip.source.authenticateRest(); }
19491
+ catch (error) { return res.status(400).json({ error: error.message, code: restoreFailureCode(error) }); }
19284
19492
  }
19493
+ // What this restore brings and what it leaves as it is: only files the archive holds are written, nothing is
19494
+ // deleted, so the groups a backup does not contain keep whatever is here now.
19495
+ const contents = readManifestGroups(manifest);
19285
19496
 
19286
19497
  const entryAt = rel => zip.getEntry(`${prefix}/${rel}`);
19287
- const results = { files: [], snapshots: [], errors: [] };
19498
+ // `errorCodes`: one stable code per sentence of `errors`, read when the answer is written.
19499
+ const results = { files: [], snapshots: [], errors: [], get errorCodes() { return this.errors.map((sentence) => restoreWarningCode(sentence)); } };
19288
19500
 
19289
19501
  // Restore config files
19290
19502
  if (mode === 'full' || mode === 'config-only') {
@@ -19301,9 +19513,12 @@ app.post('/api/system/restore', async (req, res) => {
19301
19513
  claudeSettings: home ? join(home, '.claude', 'settings.json') : null,
19302
19514
  });
19303
19515
  if (unsafe.length) {
19304
- return res.status(400).json({ error: `Invalid backup: unsafe path ${unsafe[0]}` });
19516
+ return res.status(400).json({ error: `Invalid backup: unsafe path ${unsafe[0]}`, code: 'RESTORE_UNSAFE_PATH' });
19305
19517
  }
19306
19518
 
19519
+ // From here on a failure may leave some files replaced, and its answer says so (restoreFailureFields).
19520
+ (res.locals ||= {}).restoreWriting = true;
19521
+
19307
19522
  // .env
19308
19523
  const envEntry = entryAt('env.bak');
19309
19524
  if (envEntry) {
@@ -19352,6 +19567,7 @@ app.post('/api/system/restore', async (req, res) => {
19352
19567
  if (mode === 'full' || mode === 'snapshots-only') {
19353
19568
  const dbEntry = entryAt('database/memory.db');
19354
19569
  if (dbEntry) {
19570
+ (res.locals ||= {}).restoreWriting = true;
19355
19571
  try {
19356
19572
  // Close existing database connection before replacing
19357
19573
  closeDb();
@@ -19378,6 +19594,20 @@ app.post('/api/system/restore', async (req, res) => {
19378
19594
  }
19379
19595
  }
19380
19596
 
19597
+ // What the archive held, by group, goes with the answer; the sizes next to Settings → Backups → What to back
19598
+ // up were measured before this restore.
19599
+ results.contents = contents;
19600
+ backupContents.invalidate();
19601
+ // Backup encryption is this installation's own (its key file is in no archive and no restore writes it). Where
19602
+ // there is none and this backup was encrypted, its key is kept, so the backups made from here on are encrypted
19603
+ // as the restored one was, with the password that just opened it: a restore on a new computer never ends in
19604
+ // scheduled backups written in plain.
19605
+ if (zip.encrypted) {
19606
+ results.encrypted = true;
19607
+ try { if (backupEncryption.adopt(zip.source.recipientForAdoption())) results.encryptionKept = true; }
19608
+ catch (err) { results.errors.push(`Backup encryption could not be kept: ${err.message}. Turn it on in Settings → Backups.`); }
19609
+ }
19610
+
19381
19611
  // Post-restore: ensure MCP server is built (critical for fresh installs + restore). Built means dist/index.js
19382
19612
  // and every module it imports (lib/mcp-dist.js), stamped with this version and source (lib/mcp-build.js): the
19383
19613
  // builder compiles into a temp folder and swaps it in only on success, so a failure keeps whatever dist there was.
@@ -19402,14 +19632,23 @@ app.post('/api/system/restore', async (req, res) => {
19402
19632
  res.json({ ok: true, message: 'Backup restored successfully', results, ...(results.restart ? { restart: true, bootId: SERVER_BOOT_ID } : {}) });
19403
19633
  // The new build loads only in a new server: the same restart as Apps → Restart Server, once the answer is out.
19404
19634
  if (results.restart) setTimeout(() => { try { requestServerRestart(); } catch (err) { console.error('[restore] restart after the MCP build failed:', err?.message); } }, 500);
19405
- } catch (err) {
19406
- console.error('POST /api/system/restore error:', err.message);
19407
- if (!res.headersSent) res.status(500).json({ error: err.message });
19408
- } finally {
19409
- await zip?.close().catch(() => {});
19410
- removeRestoreUpload(upload);
19411
- }
19412
- });
19635
+ }
19636
+
19637
+ // ── An encrypted backup: upload once, then the password, then the restore (lib/backup-restore-session.js) ──
19638
+ // The preview route above keeps an encrypted upload instead of answering with its contents. These three are the
19639
+ // rest: unlock ({ uploadId, password }: the same preview a plain backup gets, or 401 WRONG_PASSWORD with nothing
19640
+ // changed), apply-staged ({ uploadId, mode }: applyRestoreArchive over the decrypting reader) and discard. The
19641
+ // owner's page's alone, as restore is. The password is in the JSON body of unlock only; what stays afterwards is
19642
+ // that one file's keys, in memory, until the restore, a discard or 30 minutes. A right password clears the count of
19643
+ // wrong ones only for this installation's own key: anybody can upload a file whose password they know.
19644
+ const restoreSessions = createRestoreSessions({ limiter: backupPasswordAttempts, currentKeyId: () => backupEncryption.status().keyId || null });
19645
+ const encryptedRestoreRoutes = encryptedRestoreHandlers({ sessions: restoreSessions, preview: restorePreviewOf, apply: applyRestoreArchive });
19646
+ function restoreOwnerPageOnly(req, res, next) {
19647
+ return restoreOwnerPageCall(req) ? next() : refuseRestoreCaller(req, res);
19648
+ }
19649
+ app.post('/api/system/restore/unlock', editorOwnerGuard, restoreOwnerPageOnly, encryptedRestoreRoutes.unlock);
19650
+ app.post('/api/system/restore/apply-staged', editorOwnerGuard, restoreOwnerPageOnly, encryptedRestoreRoutes.apply);
19651
+ app.post('/api/system/restore/discard', editorOwnerGuard, restoreOwnerPageOnly, encryptedRestoreRoutes.discard);
19413
19652
 
19414
19653
  // ═══════════════════════════════════════════
19415
19654
  // AUTO-BACKUP SYSTEM
@@ -19467,8 +19706,8 @@ function getBackupAdditionalEntries() {
19467
19706
  return entries;
19468
19707
  }
19469
19708
 
19470
- function backupConfigResponse(cfg = loadAutoBackupConfig()) {
19471
- const snapshots = cfg.folderPath ? listBackupSnapshots(cfg.folderPath) : [];
19709
+ async function backupConfigResponse(cfg = loadAutoBackupConfig()) {
19710
+ const snapshots = cfg.folderPath ? await listBackupSnapshots(cfg.folderPath) : [];
19472
19711
  const health = getBackupHealth(cfg, { snapshots });
19473
19712
  if (_backupOperationActive || _autoBackupPromise) {
19474
19713
  health.status = 'running';
@@ -19498,15 +19737,15 @@ async function runAutoBackup({ force = false, kind = 'scheduled', folderPath = n
19498
19737
  try {
19499
19738
  const pkg = JSON.parse(readFileSync(resolve(PACKAGE_ROOT, 'package.json'), 'utf-8'));
19500
19739
  let preRetention = null;
19501
- const backup = await serializeBackupOperation(async () => {
19740
+ const { backup, retention } = await serializeBackupOperation(async () => {
19502
19741
  if (kind === 'scheduled') {
19503
- preRetention = applyBackupRetention({
19742
+ preRetention = await applyBackupRetention({
19504
19743
  folderPath: destination,
19505
19744
  retention: cfg.retention,
19506
19745
  incomingBytes: cfg.lastBackupSize,
19507
19746
  });
19508
19747
  }
19509
- return createVerifiedBackup({
19748
+ const backup = await createVerifiedBackup({
19510
19749
  dataHome: DATA_HOME,
19511
19750
  databasePath: getDbPath(),
19512
19751
  folderPath: destination,
@@ -19514,9 +19753,13 @@ async function runAutoBackup({ force = false, kind = 'scheduled', folderPath = n
19514
19753
  appVersion: pkg.version || null,
19515
19754
  additionalEntries: getBackupAdditionalEntries(),
19516
19755
  expectedArchiveBytes: cfg.lastBackupSize,
19756
+ // The same choice as a manual backup (Settings → Backups → What to back up).
19757
+ groups: backupContents.groups(),
19517
19758
  });
19759
+ // Keep both async sweeps in the backup queue so another operation cannot publish between them.
19760
+ const retention = await applyBackupRetention({ folderPath: destination, retention: cfg.retention });
19761
+ return { backup, retention };
19518
19762
  });
19519
- const retention = applyBackupRetention({ folderPath: destination, retention: cfg.retention });
19520
19763
  cfg.lastVerifiedBackup = backup.createdAt;
19521
19764
  cfg.lastBackup = backup.createdAt; // backward compatibility
19522
19765
  cfg.lastBackupPath = backup.path;
@@ -19547,6 +19790,7 @@ function startAutoBackupScheduler() {
19547
19790
  const nextDue = nextBackupDueMs(cfg, { lastAttemptMs: _autoBackupLastAttemptMs });
19548
19791
  const delay = Math.max(0, Math.min(2_147_000_000, nextDue - Date.now()));
19549
19792
  _autoBackupTimer = setTimeout(async () => {
19793
+ if (typeof markActivity === 'function') markActivity('scheduler:backup');
19550
19794
  try { await runAutoBackup(); }
19551
19795
  catch (error) { console.error(`[auto-backup] Scheduler failed safely: ${error.message}`); }
19552
19796
  finally { startAutoBackupScheduler(); }
@@ -19556,7 +19800,7 @@ function startAutoBackupScheduler() {
19556
19800
 
19557
19801
  function stopAutoBackupScheduler() {
19558
19802
  if (_autoBackupTimer) {
19559
- clearInterval(_autoBackupTimer);
19803
+ clearTimeout(_autoBackupTimer);
19560
19804
  _autoBackupTimer = null;
19561
19805
  }
19562
19806
  }
@@ -19564,13 +19808,27 @@ function stopAutoBackupScheduler() {
19564
19808
  // Boot: start scheduler if enabled
19565
19809
  startAutoBackupScheduler();
19566
19810
 
19811
+ // Boot: what a backup or a restore that never finished left behind (a crash, a kill, a power cut). The partial
19812
+ // archives and the staged copies of a process that is gone, in every folder a backup works in, and whatever is in
19813
+ // the two folders that only ever hold this server's own working files (restore uploads, the browser download's
19814
+ // staging). The staged copies of an encrypted backup are plaintext: they do not wait for the next backup to be
19815
+ // removed. On a worker thread: a backup folder can be a drive that answers slowly.
19816
+ setTimeout(() => {
19817
+ let folders = [];
19818
+ try { folders = [loadAutoBackupConfig().folderPath, backupDownload.destination().folderPath]; } catch { /* the data home's own folders are swept all the same */ }
19819
+ sweepCrashedBackupArtifacts({ dataHome: DATA_HOME, folders, scratchFolders: [RESTORE_STAGING_DIR, resolve(DATA_HOME, 'backups', 'manual-staging')] }).then((removed) => {
19820
+ 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}`);
19821
+ }, (error) => console.warn(`[backup] Leftovers of unfinished backups could not be swept: ${error?.message || error}`));
19822
+ }, 1500).unref?.();
19823
+
19567
19824
  // GET /api/system/auto-backup — Get auto-backup config
19568
- app.get('/api/system/auto-backup', (req, res) => {
19569
- res.json(backupConfigResponse());
19825
+ app.get('/api/system/auto-backup', async (req, res) => {
19826
+ try { res.json(await backupConfigResponse()); }
19827
+ catch (err) { res.status(500).json({ error: err.message }); }
19570
19828
  });
19571
19829
 
19572
19830
  // PUT /api/system/auto-backup — Update auto-backup config
19573
- app.put('/api/system/auto-backup', (req, res) => {
19831
+ app.put('/api/system/auto-backup', async (req, res) => {
19574
19832
  try {
19575
19833
  const current = loadAutoBackupConfig();
19576
19834
  const { enabled, intervalMinutes, folderPath, retention } = req.body;
@@ -19589,7 +19847,7 @@ app.put('/api/system/auto-backup', (req, res) => {
19589
19847
  stopAutoBackupScheduler();
19590
19848
  }
19591
19849
 
19592
- res.json({ ok: true, config: backupConfigResponse(current) });
19850
+ res.json({ ok: true, config: await backupConfigResponse(current) });
19593
19851
  } catch (err) {
19594
19852
  res.status(500).json({ error: err.message });
19595
19853
  }
@@ -19601,18 +19859,18 @@ app.post('/api/system/auto-backup/trigger', async (req, res) => {
19601
19859
  const cfg = loadAutoBackupConfig();
19602
19860
  if (!cfg.folderPath) return res.status(400).json({ error: 'No backup folder configured' });
19603
19861
  const result = await runAutoBackup({ force: true });
19604
- if (result?.error) return res.status(500).json({ error: result.error, ...backupConfigResponse() });
19605
- res.json(backupConfigResponse());
19862
+ if (result?.error) return res.status(500).json({ error: result.error, ...await backupConfigResponse() });
19863
+ res.json(await backupConfigResponse());
19606
19864
  } catch (err) {
19607
19865
  res.status(500).json({ error: err.message });
19608
19866
  }
19609
19867
  });
19610
19868
 
19611
19869
  // GET /api/system/backups — verified/runtime backup history for Settings.
19612
- app.get('/api/system/backups', (req, res) => {
19870
+ app.get('/api/system/backups', async (req, res) => {
19613
19871
  try {
19614
19872
  const cfg = loadAutoBackupConfig();
19615
- const snapshots = cfg.folderPath ? listBackupSnapshots(cfg.folderPath) : [];
19873
+ const snapshots = cfg.folderPath ? await listBackupSnapshots(cfg.folderPath) : [];
19616
19874
  res.json({ ok: true, snapshots, health: getBackupHealth(cfg, { snapshots }), retention: cfg.retention });
19617
19875
  } catch (err) {
19618
19876
  res.status(500).json({ error: err.message });
@@ -22595,7 +22853,7 @@ async function getSessionEntriesForRequest(projDir, { forceRefresh = false } = {
22595
22853
  let _codexSessionCatalogRefresh = null;
22596
22854
  function getCodexSessionCatalogRefresh() {
22597
22855
  if (!_codexSessionCatalogRefresh) {
22598
- _codexSessionCatalogRefresh = memoCache(() => rebuildCodexCache({
22856
+ _codexSessionCatalogRefresh = memoCache(() => runSessionJob('codex', {
22599
22857
  accounts: loadCodexAccounts().accounts,
22600
22858
  projects: loadHookProjects(),
22601
22859
  }), { ttlMs: 15000 });
@@ -23022,15 +23280,16 @@ function antigravityHomeFor(kind, id) { return antigravityHomeDir(antigravityHom
23022
23280
  // included, into memory capture (lib/memory-session-capture.js). A pass at start, one after a panel turn ends (that
23023
23281
  // conversation only, a moment later so agy has written its last step), one every five minutes, and a fresh one
23024
23282
  // before Resume or Skills Studio searches them (at most every 15 s).
23025
- function antigravitySessionStores({ userOnly = false } = {}) {
23026
- return antigravityStores({ homesRoot: userOnly ? null : antigravityHomesRoot(DATA_HOME) });
23027
- }
23028
23283
  let _antigravityCacheAt = 0;
23284
+ let _antigravityPass = null;
23029
23285
  function refreshAntigravityCatalog({ force = false } = {}) {
23286
+ if (_antigravityPass) return _antigravityPass;
23030
23287
  if (!force && Date.now() - _antigravityCacheAt < 15_000) return null;
23031
- _antigravityCacheAt = Date.now();
23032
- try { return rebuildAntigravityCache({ stores: antigravitySessionStores() }); }
23033
- catch (err) { console.warn(' Session cache (antigravity) error:', err.message); return null; }
23288
+ _antigravityPass = runSessionJob('antigravity', { homesRoot: antigravityHomesRoot(DATA_HOME) })
23289
+ .then(result => { _antigravityCacheAt = Date.now(); return result; })
23290
+ .catch(err => { console.warn(' Session cache (antigravity) error:', err.message); return null; })
23291
+ .finally(() => { _antigravityPass = null; });
23292
+ return _antigravityPass;
23034
23293
  }
23035
23294
  const _antigravityRefreshTimers = new Map();
23036
23295
  function refreshAntigravitySession(sessionId) {
@@ -23038,8 +23297,9 @@ function refreshAntigravitySession(sessionId) {
23038
23297
  clearTimeout(_antigravityRefreshTimers.get(sessionId));
23039
23298
  _antigravityRefreshTimers.set(sessionId, setTimeout(() => {
23040
23299
  _antigravityRefreshTimers.delete(sessionId);
23041
- try { rebuildAntigravityCache({ stores: antigravitySessionStores({ userOnly: true }), only: sessionId }); }
23042
- catch (err) { console.warn(' Session cache (antigravity) error:', err.message); }
23300
+ markActivity('session-cache:antigravity-turn');
23301
+ runSessionJob('antigravity', { only: sessionId })
23302
+ .catch(err => console.warn(' Session cache (antigravity) error:', err.message));
23043
23303
  }, 1500));
23044
23304
  _antigravityRefreshTimers.get(sessionId).unref?.();
23045
23305
  }
@@ -23096,7 +23356,7 @@ app.get('/api/session-search', async (req, res) => {
23096
23356
  }
23097
23357
 
23098
23358
  // Antigravity's index follows its transcripts (refreshAntigravityCatalog: at most every 15 s).
23099
- if (provider === 'antigravity') refreshAntigravityCatalog();
23359
+ if (provider === 'antigravity') await refreshAntigravityCatalog();
23100
23360
 
23101
23361
  // 1. FTS5 substring hits
23102
23362
  const ftsRows = searchSessionFts(q, { provider, project: projectFilter, limit: limit * 2 });
@@ -24551,8 +24811,7 @@ skillsService = createSkillsService({
24551
24811
  operationsOptions: { notify: (item) => {
24552
24812
  const session = _assistantRuntime?.listSessions?.().find((s) => s.status !== 'ended');
24553
24813
  if (!session) return false;
24554
- _assistantRuntime.routerMailbox(session.id, item);
24555
- return true;
24814
+ return _assistantRuntime.routerMailbox(session.id, item);
24556
24815
  } },
24557
24816
  });
24558
24817
  registerSkillsV2Routes(app, {
@@ -24640,11 +24899,12 @@ registerSkillEvalRoutes(app, {
24640
24899
  // and the routes of Agents Studio under /api/agents-studio/v1 (lib/agents-studio-api.js: approving, deleting and test
24641
24900
  // runs are the owner's page only, as the Skills Service's installs are). The older /api/agents routes above (isolated
24642
24901
  // agent processes) are another thing and stay as they are.
24643
- import { createAgentRegistry } from './lib/agents/registry.js';
24902
+ import { createAgentRegistry, loadBuiltinAgents } from './lib/agents/registry.js';
24644
24903
  import { createAgentResolver, setAgentResolver } from './lib/agents/resolve.js';
24645
24904
  import { registerStudioAttention } from './lib/studio-attention.js';
24646
24905
  import { registerAgentsStudioRoutes } from './lib/agents-studio-api.js';
24647
24906
  const agentDefinitions = createAgentRegistry({
24907
+ builtins: loadBuiltinAgents(),
24648
24908
  dir: resolve(DATA_HOME, 'data', 'agents'),
24649
24909
  // Every page of the owner hears of a change; invite guests do not (broadcastSync keeps `assistant:` to the owner).
24650
24910
  emit: (event) => { try { broadcastSync({ type: 'assistant:agents-changed', event }); } catch { /* no page is listening */ } },
@@ -24928,7 +25188,7 @@ async function skillSourceSessions({ provider, project = null, q = '', limit = 4
24928
25188
  } else if (provider === 'antigravity') {
24929
25189
  // The user's own Antigravity conversations (the panel's and a terminal agy's), as Resume's index keeps them,
24930
25190
  // titled as Antigravity titles them (refreshAntigravityCatalog).
24931
- refreshAntigravityCatalog();
25191
+ await refreshAntigravityCatalog();
24932
25192
  for (const entry of listSessionCache('antigravity', { limit: 100000 })) {
24933
25193
  if (entry.deleted || !entry.project_path) continue;
24934
25194
  const dir = resolve(entry.project_path);
@@ -26854,19 +27114,23 @@ app.delete('/api/skills-studio/import/stage/:stagingId', (req, res) => {
26854
27114
  });
26855
27115
 
26856
27116
  // GET /api/health — Check if SQLite database is accessible
27117
+ // The page asks this every 3 s to tell a running server from a stopped one (public/shared/server-presence.js), so
27118
+ // it must answer whatever else the database is doing: the count is read at most once per HEALTH_COUNT_TTL_MS, never
27119
+ // per request. On 2026-11-21 each probe ran its own synchronous COUNT(*) behind statements that took seconds while a
27120
+ // backup kept the disk busy, two probes in a row timed out, and a live server was shown as offline.
27121
+ const healthMemoryCount = createHealthCount({ read: () => { getDb(); return countMemories(); }, store: memoryStoreGate });
26857
27122
  app.get('/api/health', (req, res) => {
26858
27123
  try {
26859
- // getDb() auto-creates the directory, file, and schema if missing
26860
- getDb();
26861
- const count = countMemories();
27124
+ // getDb() auto-creates the directory, file, and schema if missing (inside the count's read)
27125
+ const count = healthMemoryCount();
26862
27126
  res.json({
26863
- ok: true, storage: 'sqlite', memories: count, projectDir: PACKAGE_ROOT, install: INSTALL_KIND, startLauncher: getStartLauncherState(), entry: START_ENTRY,
27127
+ ok: true, storage: 'sqlite', memories: count, ...healthMemoryCount.storeState?.(), projectDir: PACKAGE_ROOT, install: INSTALL_KIND, startLauncher: getStartLauncherState(), entry: START_ENTRY,
26864
27128
  version: SERVER_VERSION, dataHomeId: DATA_HOME_ID, installEntry: INSTALL_ENTRY,
26865
27129
  // Which server this is, and whether it is on its way out for a restart: a
26866
27130
  // page showing the restart tells this one from the one that replaces it.
26867
27131
  bootId: SERVER_BOOT_ID,
26868
27132
  ...(_restartRequestedAt && !_stopOverridesRestart ? { restarting: true } : {}),
26869
- // Whether the owner's authority can be checked (lib/peer-identity.js): ok / degraded (macOS, the lookup fails:
27133
+ // Whether the owner's authority can be checked (lib/peer-identity.js): pending at boot / ok / degraded (macOS, the lookup fails:
26870
27134
  // the owner's actions answer 503 until it works) / unsupported (no lookup on this platform) / off
26871
27135
  // (SYNABUN_PEER_IDENTITY=off). The page's banner reads it (public/shared/ui-owner-authority.js).
26872
27136
  ownerAuthority: _peerIdentity.authorityState(),
@@ -28113,11 +28377,14 @@ try {
28113
28377
  const { createMcpRoutes, ensureInit: mcpEnsureInit } = await import(mcpPath);
28114
28378
 
28115
28379
  // Eagerly init: DB, categories, embedding model — runs in background, doesn't block server start
28116
- mcpEnsureInit().then(() => {
28380
+ const warmMcp = () => mcpEnsureInit().then(() => {
28117
28381
  console.log(' MCP HTTP: DB + embeddings warm');
28118
28382
  }).catch(err => {
28383
+ if (isMemoryStoreRefusal(err)) return; // warmed below, once the store is back
28119
28384
  console.error(' MCP HTTP eager init failed:', err.message);
28120
28385
  });
28386
+ warmMcp();
28387
+ memoryStoreGate.subscribe((state) => { if (state === 'ready' || state === 'deferred') warmMcp(); });
28121
28388
 
28122
28389
  // A request that names a run (X-Synabun-Terminal) without that run's terminal token is not that run here either
28123
28390
  // (lib/terminal-tokens.js): the MCP server routes it as its own MCP session, so it never shares the run's identity
@@ -28129,6 +28396,13 @@ try {
28129
28396
  // /mcp mount directly" (mcpSessionProofEligible, finding 5); the MCP's own loopback check stays in front of it.
28130
28397
  const mcpRouter = createMcpRoutes({ terminalAuth, sessionProof: { eligible: (req) => mcpSessionProofEligible(req), issue: (sid) => _terminalTokens.issueSession(sid), revoke: (sid) => { endMcpSessionProof(sid); } } });
28131
28398
 
28399
+ // The in-process MCP runs its tools on this thread (an Assistant brain's recall among them): name it for the stall log.
28400
+ // Answers nothing. No mount path of its own: a '/mcp' mount here would be mirrored by the route-table tests.
28401
+ app.use(function markMcpActivity(req, res, next) {
28402
+ if (req.path === '/mcp' || req.path.startsWith('/mcp/')) { const end = beginActivity('mcp:request'); res.once('close', end); }
28403
+ next();
28404
+ });
28405
+
28132
28406
  // Keyed path: /mcp/<key> — validates key, then forwards to MCP router
28133
28407
  app.use('/mcp/:key', (req, res, next) => {
28134
28408
  if (req.params.key !== activeMcpKey) {
@@ -29100,6 +29374,7 @@ function persistNativeScheduleOutcome(run, runningInfo = null) {
29100
29374
 
29101
29375
  const schedule = schedules[index];
29102
29376
  schedule.lastRunResult = nativeScheduleResult(run);
29377
+ schedule.lastStopProvenance = run.stopProvenance || null;
29103
29378
  schedule.updatedAt = new Date().toISOString();
29104
29379
  saveSchedules(schedules);
29105
29380
  broadcastSync({ type: 'schedule:updated', schedule });
@@ -29123,6 +29398,7 @@ function persistExecScheduleOutcome(loopState, status, reason = '') {
29123
29398
  const index = schedules.findIndex((schedule) => schedule.id === loopState.scheduledBy);
29124
29399
  if (index === -1) return;
29125
29400
  const schedule = schedules[index];
29401
+ schedule.lastStopProvenance = loopState.stopProvenance || null;
29126
29402
  schedule.lastRunResult = status === 'completed'
29127
29403
  ? 'completed'
29128
29404
  : status === 'stopped'
@@ -29842,6 +30118,7 @@ function noteMoreLoginContextClose(session, sessionId, context = session?.contex
29842
30118
  // DeepSeek-Harness-style routing: the brain proposes, the router enforces the
29843
30119
  // session's route mode. Sinks reach the runtime/dispatcher lazily.
29844
30120
  const assistantRouter = createAssistantRouter({
30121
+ agents: agentDefinitionResolver,
29845
30122
  accountUsage,
29846
30123
  budget: assistantBudget,
29847
30124
  catalog: assistantCatalog,
@@ -29861,8 +30138,9 @@ function noteMoreLoginContextClose(session, sessionId, context = session?.contex
29861
30138
  computerApproved: (sessionId, payload) => _assistantRuntime?.routerComputerApproved?.(sessionId, payload),
29862
30139
  startHeld: (runId, target, meta) => _assistantDispatcher?.resolveRoute?.(runId, { target, ...meta }),
29863
30140
  // Asked before a card's pick is approved: a held run that would refuse it keeps the card open.
29864
- checkHeld: (runId, target) => _assistantDispatcher?.heldRouteRefusal?.(runId, target) || null,
30141
+ checkHeld: (runId, target, role) => _assistantDispatcher?.heldRouteRefusal?.(runId, target, role) || null,
29865
30142
  declineHeld: (runId, reason) => _assistantDispatcher?.declineRoute?.(runId, { reason }),
30143
+ activeRouteRuns: (sessionId, routeId) => _assistantDispatcher?.activeRouteRuns(sessionId, routeId),
29866
30144
  },
29867
30145
  log: (tag, message) => assistantLog(tag, message),
29868
30146
  clarifier: assistantClarifier,
@@ -29937,6 +30215,7 @@ function noteMoreLoginContextClose(session, sessionId, context = session?.contex
29937
30215
  // The one instance of this server (never a second createCoordinationService in this file): a stop that is not
29938
30216
  // a signal (Restart Server, /api/server/shutdown, an update) closes it at the end of runGracefulShutdown.
29939
30217
  _assistantCoordination = assistantCoordination;
30218
+ await assistantCoordination.ready;
29940
30219
  if (assistantCoordination.degraded) console.warn(`[assistant] coordination store unavailable (${assistantCoordination.degraded.message}): agent events are kept in memory until the next start`);
29941
30220
  }
29942
30221
  // ══ end Agents P2 ══════════════════════════════════════════════════════════════════════════════════════════
@@ -30096,6 +30375,7 @@ function noteMoreLoginContextClose(session, sessionId, context = session?.contex
30096
30375
  .then((m) => m.setTeamContextResolver((runId) => !!teamScheduler.member(runId)))
30097
30376
  .catch((err) => console.warn('[assistant] team tool unavailable (mcp-server needs a build):', err?.message || err));
30098
30377
  // After a restart: the library's own recovery, then every team under way is taken up again. Never awaited here.
30378
+ markActivity('startup:team-recovery');
30099
30379
  teamScheduler.recover().catch((err) => console.warn('[assistant] team recovery failed:', err?.message || err))
30100
30380
  .finally(() => broadcastSync({ type: 'assistant:team-changed', event: 'recovered' }));
30101
30381
  _assistantTeamScheduler = teamScheduler;
@@ -30108,6 +30388,7 @@ function noteMoreLoginContextClose(session, sessionId, context = session?.contex
30108
30388
  // then repair saved routes whose effort their model does not run (idempotent;
30109
30389
  // a provider whose list is not available yet is retried a few times).
30110
30390
  const repairRouteEfforts = async (attempt = 0) => {
30391
+ markActivity('startup:route-efforts');
30111
30392
  const { repairPreferenceEfforts } = await import('./lib/effort-levels.js');
30112
30393
  const cat = await assistantCatalog.full({ force: attempt > 0 });
30113
30394
  const { fixes, unverified } = repairPreferenceEfforts(assistantConfigStore.routing().preferences, cat);
@@ -30338,25 +30619,24 @@ function cleanupClaudeLoopMcpConfig(terminalSessionId) {
30338
30619
  * Each opencode-<sid> dir carries a ~61 MB node_modules; the per-loop cleanup
30339
30620
  * runs on graceful stop and PTY exit, but a server crash/restart (or a PTY that
30340
30621
  * never fired its exit) leaves dirs stranded forever. At boot no loop is live,
30341
- * so anything older than the cutoff is safe to remove. Mirrors the mtime-cutoff
30342
- * rmSync pattern used by cleanupOldUpdaterStages().
30622
+ * so anything older than the cutoff is safe to remove. Removal runs off the main thread even for an entire dependency tree.
30343
30623
  */
30344
- function cleanupStaleLoopConfigs(maxAgeMs = 6 * 60 * 60 * 1000) {
30624
+ async function cleanupStaleLoopConfigs(maxAgeMs = 6 * 60 * 60 * 1000) {
30345
30625
  const dir = resolve(DATA_HOME, 'data', 'loop-configs');
30346
30626
  let removedDirs = 0, removedFiles = 0;
30347
30627
  try {
30348
30628
  if (!existsSync(dir)) return { removedDirs, removedFiles };
30349
30629
  const cutoff = Date.now() - maxAgeMs;
30350
- for (const name of readdirSync(dir)) {
30630
+ for (const name of await fsp.readdir(dir)) {
30351
30631
  const isOpencodeDir = name.startsWith('opencode-');
30352
30632
  const isClaudeCfg = name.startsWith('claude-mcp-') && name.endsWith('.json');
30353
30633
  if (!isOpencodeDir && !isClaudeCfg) continue;
30354
30634
  const full = resolve(dir, name);
30355
30635
  try {
30356
- const st = statSync(full);
30636
+ const st = await fsp.stat(full);
30357
30637
  if (st.mtimeMs >= cutoff) continue;
30358
- if (st.isDirectory()) { rmSync(full, { recursive: true, force: true }); removedDirs++; }
30359
- else { unlinkSync(full); removedFiles++; }
30638
+ if (st.isDirectory()) { await fsp.rm(full, { recursive: true, force: true }); removedDirs++; }
30639
+ else { await fsp.unlink(full); removedFiles++; }
30360
30640
  } catch { /* skip unreadable/racing entries */ }
30361
30641
  }
30362
30642
  if (removedDirs || removedFiles) {
@@ -30942,6 +31222,7 @@ function scanForLeaks() {
30942
31222
 
30943
31223
  let _lastLeakHash = '';
30944
31224
  setInterval(() => {
31225
+ markActivity('timer:session-leaks');
30945
31226
  syncRegistryFromTerminals();
30946
31227
  const leaks = scanForLeaks();
30947
31228
  // Strip ageMs AND description (which embeds age as "Xm old") to prevent
@@ -31003,6 +31284,7 @@ function scanLoopInventory() {
31003
31284
 
31004
31285
  let _lastLoopHash = '';
31005
31286
  setInterval(() => {
31287
+ markActivity('timer:loop-inventory');
31006
31288
  const inventory = scanLoopInventory();
31007
31289
  // Hash on stable fields only (drop minute counters that tick every poll)
31008
31290
  const hash = JSON.stringify({
@@ -32795,9 +33077,27 @@ const extensionBridge = createExtensionBridge({
32795
33077
  log: record => console.log('[extension-bridge]', JSON.stringify(record)),
32796
33078
  onInventory: state => extensionAdapter.sync(state),
32797
33079
  });
33080
+ // Page JavaScript in the owner's everyday browser (browser_evaluate through the extension) is held to what the
33081
+ // Playwright evaluate route holds a loop's tab to, so an extension session is no way around either: the X publish gate
33082
+ // (xGateBypassRefusal: no scripted click on a publish / like / repost / follow control) and the spacing of social
33083
+ // writes (`pace` in the body, socialWritePacer). The same functions with the same scoping: a loop-owned tab only.
33084
+ // One paired browser is one signed-in account, whatever the session object is called: one queue per platform.
33085
+ const extensionEvaluateGate = {
33086
+ refusal: ({ session, req, tabId, script }) => xGateBypassRefusal(session, req, { page: session.tabs.get(tabId)?.page, tabId }, 'evaluate', script),
33087
+ async run({ session, req, execute }) {
33088
+ const pace = socialPaceRequest(req?.body);
33089
+ if (!pace || !isLoopPaced(session, req)) return { result: await execute() };
33090
+ const outcome = await socialWritePacer.run(`${pace.platform}:extension`, {
33091
+ platform: pace.platform, maxWaitMs: socialPaceWaitBudget(req, pace.maxWaitMs), signal: req,
33092
+ }, execute);
33093
+ const gap = SOCIAL_WRITE_GAPS[pace.platform];
33094
+ if (outcome.status === 'paced') return { paced: { pending: true, retryAfterMs: outcome.retryAfterMs, waitedMs: outcome.waitedMs, gapMinMs: gap.minMs, gapMaxMs: gap.maxMs } };
33095
+ return { result: outcome.result, paced: { pending: false, waitedMs: outcome.waitedMs, gapMinMs: gap.minMs, gapMaxMs: gap.maxMs } };
33096
+ },
33097
+ };
32798
33098
  const extensionAdapter = createExtensionAdapter({
32799
33099
  bridge: extensionBridge, sessions: browserSessions, uploadRoot: extensionUploadRoot, dataHome: DATA_HOME,
32800
- caller: browserCaller, ownerPage: browserOwnerPageOnly,
33100
+ caller: browserCaller, ownerPage: browserOwnerPageOnly, evaluateGate: extensionEvaluateGate,
32801
33101
  selected: req => loadBrowserConfig().connectMode === 'extension' && !runMoreLoginPin(browserCaller(req).id),
32802
33102
  });
32803
33103
  // The extension folder the owner loads (DATA_HOME/browser-extension/unpacked): refreshed at start when the bundled
@@ -33418,6 +33718,7 @@ async function acquireSharedBrowserTab({ requestedBrowserSessionId = null, owner
33418
33718
  }
33419
33719
 
33420
33720
  if (!browserSessionId) {
33721
+ if (createError?.sharedPreflight) return createError;
33421
33722
  // The run's own profile (its pin, else the MoreLogin default) failed to start or connect in this run: from now on
33422
33723
  // it may not move to another profile (POST /api/morelogin/use answers 409 PROFILE_FAILED_NO_SWITCH) until that
33423
33724
  // profile connects again for it (below), the owner moves it, or it ends (lib/morelogin-profile-failures.js).
@@ -34941,6 +35242,10 @@ async function protectNativeServeContext(ctx, { deadline = Infinity, signal = nu
34941
35242
  // the serves it names (narrowed: never a token or a whole record).
34942
35243
  function browserStartFailure(err) {
34943
35244
  const out = { error: err?.message || String(err) };
35245
+ if (err?.sharedPreflight) {
35246
+ return { error: `Shared OpenCode build verification blocked browser acquisition. ${out.error}`,
35247
+ sharedPreflight: true, code: err.code, offenders: err.offenders.map(({ envId, reason }) => ({ envId, reason })) };
35248
+ }
34944
35249
  if (err?.code === 'NATIVE_SERVE_UNVERIFIED') { out.code = err.code; out.offenders = narrowOffenders(err.offenders); }
34945
35250
  if (err?.code === 'MORELOGIN_NOT_CHROMIUM' || err?.code === 'MORELOGIN_NOT_DEVTOOLS') out.code = err.code;
34946
35251
  // MoreLogin refused the start (a plan limit, …): the user has to act, a retry or another run hits the same answer.
@@ -39205,9 +39510,16 @@ app.post('/api/browser/sessions/:id/upload', async (req, res) => {
39205
39510
  }
39206
39511
  markBrowserActionStarted(req);
39207
39512
  await target.setInputFiles(filePaths, { timeout: browserActionTimeout(req, 10000) });
39513
+ // Native pickers supply the MIME. The handler may consume or remove the input synchronously.
39514
+ const files = await target.evaluateAll(elements => {
39515
+ if (elements.length !== 1) return [];
39516
+ const el = elements[0], input = el.localName === 'label' ? el.control : el;
39517
+ if (!input?.matches('input[type=file]')) return [];
39518
+ return Array.from(input.files, ({ name, type, size }) => ({ name, type, size }));
39519
+ }).catch(() => []);
39208
39520
  if (!browserV2Enabled()) await cancellableBrowserDelay(500, req);
39209
39521
  const state = await getBrowserActionState(session, routed, compact);
39210
- res.json({ ok: true, url: state.url, title: state.title });
39522
+ res.json({ ok: true, url: state.url, title: state.title, files });
39211
39523
  } catch (err) {
39212
39524
  res.status(500).json({ error: err.message });
39213
39525
  }
@@ -39488,8 +39800,10 @@ function runLaunchStep(name) {
39488
39800
  const task = LAUNCH_TASKS[name];
39489
39801
  if (!task) return Promise.resolve();
39490
39802
  return _launchQueue(async () => {
39803
+ const endActivity = beginActivity(`launch:${name}`);
39491
39804
  const started = Date.now();
39492
39805
  try { await task(); } catch (error) { console.warn(`[launch-cache] ${name}: ${error?.message || error}`); }
39806
+ finally { endActivity(); }
39493
39807
  const took = Date.now() - started;
39494
39808
  if (took > 2000) console.log(`[launch-cache] ${name} warmed in ${(took / 1000).toFixed(1)} s`);
39495
39809
  await new Promise((done) => { const timer = setTimeout(done, LAUNCH_STEP_GAP_MS); timer.unref?.(); });
@@ -39516,6 +39830,10 @@ function startLaunchWarmup() {
39516
39830
  reloadConfig();
39517
39831
 
39518
39832
  const httpServer = app.listen(PORT, async () => {
39833
+ markActivity('startup:listen');
39834
+ scheduleScratchRetention(DATA_HOME, () => ({
39835
+ dispatcher: _assistantDispatcher, runtime: _nativeLoopRuntime, scheduled: _runningScheduledLoops, closing: _shutdownInProgress,
39836
+ }));
39519
39837
  // Before anything else: the sessions that saved a MoreLogin profile choice (POST /api/morelogin/use) must prove
39520
39838
  // who they are again before that choice is used (retireSavedProfileChoiceOwners).
39521
39839
  try { retireSavedProfileChoiceOwners(); } catch (err) { console.warn(`[morelogin] the owners of the saved profile choices were not retired: ${err.message}`); }
@@ -39533,8 +39851,7 @@ const httpServer = app.listen(PORT, async () => {
39533
39851
 
39534
39852
  // Write embedding model metadata so mismatch can be detected later
39535
39853
  try {
39536
- setKvConfig('embedding_model', EMBEDDING_MODEL);
39537
- setKvConfig('embedding_dims', String(EMBEDDING_DIMS));
39854
+ await saveEmbeddingMetadata();
39538
39855
  } catch {}
39539
39856
 
39540
39857
  // Keep the Start Server launcher (synabun://) pointing at this install even
@@ -39569,20 +39886,32 @@ const httpServer = app.listen(PORT, async () => {
39569
39886
 
39570
39887
  // Gated: an idle tick reads one kv row + one index probe instead of the
39571
39888
  // ~9-query maintenanceStatus() and a BEGIN IMMEDIATE (see lib/memory-timers.js).
39572
- startGatedMemoryMaintenance();
39573
39889
  // The TypeSafe judge backfill runs only here: one runner per store, never in
39574
39890
  // the stdio MCP servers. It is inert until the Judgments tab starts it.
39575
- startJudgeBackfill();
39576
- startMemoryCapture();
39891
+ // None of the three ticks while the memory store is being upgraded.
39892
+ const startMemoryTimers = () => { startGatedMemoryMaintenance(); startJudgeBackfill(); startMemoryCapture(); };
39893
+ const stopMemoryTimers = () => { stopGatedMemoryMaintenance(); try { stopJudgeBackfill(); } catch {} stopMemoryCapture(); };
39894
+ if (memoryStoreGate.open()) startMemoryTimers();
39895
+ memoryStoreGate.subscribe((state) => { if (state === 'ready' || state === 'deferred') startMemoryTimers(); else stopMemoryTimers(); });
39577
39896
 
39578
39897
  // Warm the embedding model + vector caches in the background so the first
39579
39898
  // recall/search doesn't pay the 2-5s Transformers.js model load or the
39580
39899
  // initial vector-matrix build.
39581
39900
  setTimeout(() => {
39901
+ markActivity('startup:embeddings');
39582
39902
  warmupEmbeddings()
39583
39903
  .then(() => console.log(' Embeddings: model warmed up'))
39584
39904
  .catch((err) => console.warn(' Embeddings warmup failed:', err.message));
39585
- try { memoryVectors.size(); } catch { /* cache builds lazily on failure */ }
39905
+ // Memory vectors, then the passage vectors every hybrid recall reads, both in slices (warmRetrievalCaches).
39906
+ // Session-chunk vectors load on the first recall that searches sessions, in slices as well (VectorCache.ready).
39907
+ const warmMemoryCaches = () => {
39908
+ markActivity('startup:memory-vectors');
39909
+ import('../mcp-server/dist/services/memory-retrieval.js')
39910
+ .then(({ warmRetrievalCaches }) => (warmRetrievalCaches ? warmRetrievalCaches() : memoryVectors.warm()))
39911
+ .catch(err => { if (!isMemoryStoreRefusal(err)) console.warn(' Vector cache warmup failed:', err.message); });
39912
+ };
39913
+ if (memoryStoreGate.open()) warmMemoryCaches();
39914
+ memoryStoreGate.subscribe((state) => { if (state === 'ready' || state === 'deferred') warmMemoryCaches(); });
39586
39915
  }, 500);
39587
39916
 
39588
39917
  // Local profiles still running from before this start (their Chrome outlives the server, as a MoreLogin profile
@@ -39590,6 +39919,7 @@ const httpServer = app.listen(PORT, async () => {
39590
39919
  // was taken meanwhile, that profile's pages fail (never a direct connection); its next start starts it again.
39591
39920
  setTimeout(async () => {
39592
39921
  try {
39922
+ markActivity('startup:local-profiles');
39593
39923
  const adopted = await moreLogin.adoptLocalProfiles();
39594
39924
  if (!adopted.length) return;
39595
39925
  const stuck = adopted.filter((p) => p.relay === 'restart-needed');
@@ -39601,6 +39931,7 @@ const httpServer = app.listen(PORT, async () => {
39601
39931
  // Activation is an explicit user choice in the MoreLogin tab (Default AI browser).
39602
39932
  setTimeout(async () => {
39603
39933
  try {
39934
+ markActivity('startup:morelogin-detection');
39604
39935
  const mlBootCfg = loadBrowserConfig();
39605
39936
  const cfg = mlBootCfg;
39606
39937
  const port = moreLogin.getMoreLoginPort(cfg);
@@ -39614,19 +39945,28 @@ const httpServer = app.listen(PORT, async () => {
39614
39945
  // Reclaim orphaned per-loop config dirs left by crashed/killed loops. At boot
39615
39946
  // no loop is live, so this is the safe choke point to drop multi-GB of stale
39616
39947
  // opencode-<sid> node_modules that never got their per-loop cleanup.
39617
- setTimeout(() => { try { cleanupStaleLoopConfigs(); } catch {} }, 1500);
39948
+ setTimeout(() => {
39949
+ markActivity('startup:loop-config-cleanup');
39950
+ void cleanupStaleLoopConfigs();
39951
+ }, 1500);
39618
39952
 
39619
39953
  // OpenCode serves an earlier SynaBun left running (it crashed, or was killed): found by their records alone and
39620
39954
  // stopped only when they are provably its own and nothing uses them (lib/opencode-serve-records.js). An
39621
39955
  // OpenCode start that comes earlier makes the same look first (and this one then finds nothing left).
39622
- setTimeout(() => { sweepLeftoverOpencodeServes(); }, 1000);
39956
+ setTimeout(() => {
39957
+ markActivity('startup:opencode-sweep');
39958
+ sweepLeftoverOpencodeServes();
39959
+ }, 1000);
39623
39960
  // The cloudflared a crashed server left running (lib/cloudflared/tunnel.js): at once, its old address points here.
39624
39961
  sweepLeftoverTunnels();
39625
39962
 
39626
39963
  // Compare the installed Claude CLI with the release the Agent SDK was built
39627
39964
  // against, once, so an older installation is named in the log before the
39628
39965
  // first session runs on it (checkClaudeCliSkew in lib/claude-model-catalog.js).
39629
- setTimeout(() => { checkClaudeCliSkew(getClaudeBin()).catch(() => {}); }, 1000);
39966
+ setTimeout(() => {
39967
+ markActivity('startup:claude-cli-skew');
39968
+ checkClaudeCliSkew(getClaudeBin()).catch(() => {});
39969
+ }, 1000);
39630
39970
 
39631
39971
  // The lists windows, menus and Settings wait for, read once in the background (see LAUNCH_TASKS above).
39632
39972
  startLaunchWarmup();
@@ -39635,6 +39975,7 @@ const httpServer = app.listen(PORT, async () => {
39635
39975
  // claude follow it); a PC with none, and an app that carries none, gets SynaBun's copy, fetched in the background.
39636
39976
  setTimeout(() => {
39637
39977
  try {
39978
+ markActivity('startup:git-bash');
39638
39979
  gitBash.refresh();
39639
39980
  if (gitBash.status().state === 'missing') gitBash.ensure({ reason: 'first run' });
39640
39981
  // What an earlier run left in the data home (a stopped attempt's work folder, an older version), off the event loop.
@@ -39643,46 +39984,48 @@ const httpServer = app.listen(PORT, async () => {
39643
39984
  }, 2500);
39644
39985
 
39645
39986
  // Warm the session_cache + session_fts tables so the hybrid search has data
39646
- // on first keystroke. Each pass is synchronous and holds the main thread, so
39647
- // they run one per tick (requests are answered in between), and each only
39648
- // re-reads sessions that changed since the last start.
39649
- setTimeout(() => {
39987
+ // on first keystroke. A worker indexes Claude, Codex and OpenCode, and
39988
+ // a Codex catalog request shares the same refresh with this startup pass.
39989
+ setTimeout(async () => {
39650
39990
  const passes = [
39651
- () => {
39991
+ async () => {
39652
39992
  try {
39653
- const claude = rebuildClaudeCache();
39993
+ markActivity('session-cache:claude');
39994
+ const claude = await runSessionJob('claude');
39654
39995
  if (claude.updated > 0) console.log(` Session cache (claude): indexed ${claude.updated}/${claude.sessions}`);
39655
39996
  } catch (err) { console.warn(' Session cache (claude) error:', err.message); }
39656
39997
  },
39657
- () => {
39998
+ async () => {
39658
39999
  try {
39659
- const codex = rebuildCodexCache({
39660
- accounts: loadCodexAccounts().accounts,
39661
- projects: loadHookProjects(),
39662
- });
40000
+ markActivity('session-cache:codex');
40001
+ const codex = await refreshCodexSessionCatalog();
39663
40002
  if (codex.updated > 0) console.log(` Session cache (codex): indexed ${codex.updated}/${codex.sessions}`);
39664
40003
  } catch (err) { console.warn(' Session cache (codex) error:', err.message); }
39665
40004
  },
39666
- () => {
40005
+ async () => {
39667
40006
  try {
39668
- const oc = rebuildOpencodeCache({ getOpencodeDb });
40007
+ markActivity('session-cache:opencode');
40008
+ _ocpSessionCacheWarmup = runSessionJob('opencode', { path: getOpencodeDbPath() });
40009
+ const oc = await _ocpSessionCacheWarmup;
39669
40010
  if (oc.updated > 0) console.log(` Session cache (opencode): indexed ${oc.updated}/${oc.sessions}`);
39670
40011
  } catch (err) { console.warn(' Session cache (opencode) error:', err.message); }
40012
+ finally { _ocpSessionCacheWarmup = null; }
39671
40013
  },
39672
- () => {
39673
- const agy = refreshAntigravityCatalog({ force: true });
40014
+ async () => {
40015
+ markActivity('session-cache:antigravity');
40016
+ const agy = await refreshAntigravityCatalog({ force: true });
39674
40017
  if (agy?.updated > 0) console.log(` Session cache (antigravity): indexed ${agy.updated}/${agy.sessions}`);
39675
40018
  // Runs and brains end on their own: their conversations are picked up by this pass, every five minutes.
39676
- setInterval(() => refreshAntigravityCatalog({ force: true }), 5 * 60 * 1000).unref?.();
40019
+ setInterval(() => {
40020
+ markActivity('session-cache:antigravity');
40021
+ refreshAntigravityCatalog({ force: true });
40022
+ }, 5 * 60 * 1000).unref?.();
39677
40023
  },
39678
40024
  ];
39679
- const next = () => {
39680
- const pass = passes.shift();
39681
- if (!pass) return;
39682
- pass();
39683
- setImmediate(next);
39684
- };
39685
- next();
40025
+ for (const pass of passes) {
40026
+ await new Promise(resolve => setImmediate(resolve));
40027
+ await pass();
40028
+ }
39686
40029
  }, 2000);
39687
40030
 
39688
40031
  // Auto-sync OpenClaw bridge if enabled
@@ -39702,6 +40045,7 @@ const httpServer = app.listen(PORT, async () => {
39702
40045
  // already self-healing via addHookToSettings; this catches damage from
39703
40046
  // previous versions of the install flow.
39704
40047
  try {
40048
+ markActivity('startup:hooks');
39705
40049
  const dedupStats = dedupeAllSettingsHooks();
39706
40050
  if (dedupStats.removed > 0 || dedupStats.repaired > 0 || dedupStats.matchers > 0) {
39707
40051
  const bits = [];
@@ -39734,6 +40078,7 @@ const httpServer = app.listen(PORT, async () => {
39734
40078
  // wait is for the rules lock another SynaBun process on this data home may
39735
40079
  // hold (2 s at most: then the installer logs one line and this boot skips it).
39736
40080
  try {
40081
+ markActivity('startup:rules');
39737
40082
  const rules = rulesetInstaller.reconcile();
39738
40083
  if (rules.updated.length) console.log(` Rules: updated to ${rules.notice?.to || 'the current version'} for ${rules.updated.join(', ')}`);
39739
40084
  if (rules.optedOut.length) console.log(` Rules: no longer managed for ${rules.optedOut.join(', ')} (the installed copy was removed)`);
@@ -39833,7 +40178,8 @@ const httpServer = app.listen(PORT, async () => {
39833
40178
  // OpenCode panel, Settings) see providers/models immediately without the
39834
40179
  // user having to click Start each time.
39835
40180
  try {
39836
- const ready = await ensureOpencodeServer();
40181
+ markActivity('startup:opencode-serve');
40182
+ const ready = await startOpencodeAtBoot(() => ensureOpencodeServer(), () => _ocpStartRefusal);
39837
40183
  if (ready) console.log(` OpenCode: auto-started on :${_ocpPort}`);
39838
40184
  else console.log(' OpenCode: auto-start skipped (binary missing or failed to launch)');
39839
40185
  } catch (err) {
@@ -40547,6 +40893,7 @@ const SERVER_START_TIME = Date.now();
40547
40893
  const RESUME_GRACE_PERIOD_MS = 120_000; // 2 min — don't delete snapshot before client can check
40548
40894
 
40549
40895
  function saveSessionSnapshot() {
40896
+ markActivity('timer:session-snapshot');
40550
40897
  const sessions = [];
40551
40898
  const seen = new Set(); // dedup — avoid resuming same Claude session twice
40552
40899