synabun 2.4.1 → 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 (295) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/README.md +1 -1
  3. package/browser-extension/content.js +56 -14
  4. package/browser-extension/engine.js +158 -8
  5. package/browser-extension/manifest.json +3 -1
  6. package/browser-extension/protocol.js +91 -6
  7. package/browser-extension/service-worker.js +13 -5
  8. package/browser-extension/tokens.css +1 -1
  9. package/docs/browser-extension-bridge.md +24 -4
  10. package/lib/data-home-files.js +4 -2
  11. package/lib/first-launch-protection.js +8 -2
  12. package/lib/update-snapshot.js +11 -4
  13. package/mcp-server/dist/http.d.ts.map +1 -1
  14. package/mcp-server/dist/http.js +25 -2
  15. package/mcp-server/dist/http.js.map +1 -1
  16. package/mcp-server/dist/index.d.ts.map +1 -1
  17. package/mcp-server/dist/index.js +62 -17
  18. package/mcp-server/dist/index.js.map +1 -1
  19. package/mcp-server/dist/services/browser-bench.d.ts +22 -22
  20. package/mcp-server/dist/services/memory-maintenance.d.ts +1 -0
  21. package/mcp-server/dist/services/memory-maintenance.d.ts.map +1 -1
  22. package/mcp-server/dist/services/memory-maintenance.js +34 -45
  23. package/mcp-server/dist/services/memory-maintenance.js.map +1 -1
  24. package/mcp-server/dist/services/memory-migration-copy.d.ts +144 -0
  25. package/mcp-server/dist/services/memory-migration-copy.d.ts.map +1 -0
  26. package/mcp-server/dist/services/memory-migration-copy.js +467 -0
  27. package/mcp-server/dist/services/memory-migration-copy.js.map +1 -0
  28. package/mcp-server/dist/services/memory-migration-worker.d.ts +2 -0
  29. package/mcp-server/dist/services/memory-migration-worker.d.ts.map +1 -0
  30. package/mcp-server/dist/services/memory-migration-worker.js +60 -0
  31. package/mcp-server/dist/services/memory-migration-worker.js.map +1 -0
  32. package/mcp-server/dist/services/memory-retrieval.d.ts +4 -0
  33. package/mcp-server/dist/services/memory-retrieval.d.ts.map +1 -1
  34. package/mcp-server/dist/services/memory-retrieval.js +188 -40
  35. package/mcp-server/dist/services/memory-retrieval.js.map +1 -1
  36. package/mcp-server/dist/services/memory-schema.d.ts +58 -2
  37. package/mcp-server/dist/services/memory-schema.d.ts.map +1 -1
  38. package/mcp-server/dist/services/memory-schema.js +190 -13
  39. package/mcp-server/dist/services/memory-schema.js.map +1 -1
  40. package/mcp-server/dist/services/memory-sessions.d.ts +19 -1
  41. package/mcp-server/dist/services/memory-sessions.d.ts.map +1 -1
  42. package/mcp-server/dist/services/memory-sessions.js +56 -20
  43. package/mcp-server/dist/services/memory-sessions.js.map +1 -1
  44. package/mcp-server/dist/services/memory-verification.d.ts.map +1 -1
  45. package/mcp-server/dist/services/memory-verification.js +8 -5
  46. package/mcp-server/dist/services/memory-verification.js.map +1 -1
  47. package/mcp-server/dist/services/neural-interface.d.ts +5 -0
  48. package/mcp-server/dist/services/neural-interface.d.ts.map +1 -1
  49. package/mcp-server/dist/services/neural-interface.js +19 -2
  50. package/mcp-server/dist/services/neural-interface.js.map +1 -1
  51. package/mcp-server/dist/services/retrieval-reader-worker.d.ts +2 -0
  52. package/mcp-server/dist/services/retrieval-reader-worker.d.ts.map +1 -0
  53. package/mcp-server/dist/services/retrieval-reader-worker.js +76 -0
  54. package/mcp-server/dist/services/retrieval-reader-worker.js.map +1 -0
  55. package/mcp-server/dist/services/retrieval-reader.d.ts +38 -0
  56. package/mcp-server/dist/services/retrieval-reader.d.ts.map +1 -0
  57. package/mcp-server/dist/services/retrieval-reader.js +145 -0
  58. package/mcp-server/dist/services/retrieval-reader.js.map +1 -0
  59. package/mcp-server/dist/services/sqlite-write.d.ts +14 -0
  60. package/mcp-server/dist/services/sqlite-write.d.ts.map +1 -0
  61. package/mcp-server/dist/services/sqlite-write.js +94 -0
  62. package/mcp-server/dist/services/sqlite-write.js.map +1 -0
  63. package/mcp-server/dist/services/sqlite.d.ts +39 -0
  64. package/mcp-server/dist/services/sqlite.d.ts.map +1 -1
  65. package/mcp-server/dist/services/sqlite.js +249 -8
  66. package/mcp-server/dist/services/sqlite.js.map +1 -1
  67. package/mcp-server/dist/services/tool-catalog.d.ts +1 -1
  68. package/mcp-server/dist/services/typesafe-config.d.ts +7 -1
  69. package/mcp-server/dist/services/typesafe-config.d.ts.map +1 -1
  70. package/mcp-server/dist/services/typesafe-config.js +32 -10
  71. package/mcp-server/dist/services/typesafe-config.js.map +1 -1
  72. package/mcp-server/dist/services/typesafe.d.ts.map +1 -1
  73. package/mcp-server/dist/services/typesafe.js +9 -7
  74. package/mcp-server/dist/services/typesafe.js.map +1 -1
  75. package/mcp-server/dist/services/vector-cache.d.ts +32 -0
  76. package/mcp-server/dist/services/vector-cache.d.ts.map +1 -1
  77. package/mcp-server/dist/services/vector-cache.js +161 -8
  78. package/mcp-server/dist/services/vector-cache.js.map +1 -1
  79. package/mcp-server/dist/tools/agent-definition.d.ts +2 -2
  80. package/mcp-server/dist/tools/agents.d.ts +11 -7
  81. package/mcp-server/dist/tools/agents.d.ts.map +1 -1
  82. package/mcp-server/dist/tools/agents.js +27 -9
  83. package/mcp-server/dist/tools/agents.js.map +1 -1
  84. package/mcp-server/dist/tools/browser-advanced.d.ts +1 -1
  85. package/mcp-server/dist/tools/browser-advanced.d.ts.map +1 -1
  86. package/mcp-server/dist/tools/browser-advanced.js +10 -3
  87. package/mcp-server/dist/tools/browser-advanced.js.map +1 -1
  88. package/mcp-server/dist/tools/browser-extension-setup.d.ts +5 -0
  89. package/mcp-server/dist/tools/browser-extension-setup.d.ts.map +1 -0
  90. package/mcp-server/dist/tools/browser-extension-setup.js +23 -0
  91. package/mcp-server/dist/tools/browser-extension-setup.js.map +1 -0
  92. package/mcp-server/dist/tools/browser-interact.d.ts.map +1 -1
  93. package/mcp-server/dist/tools/browser-interact.js +6 -1
  94. package/mcp-server/dist/tools/browser-interact.js.map +1 -1
  95. package/mcp-server/dist/tools/fb-groups.d.ts +2 -2
  96. package/mcp-server/dist/tools/skill-tools.d.ts +4 -4
  97. package/mcp-server/dist/tools/tool-groups.d.ts +1 -1
  98. package/mcp-server/package-lock.json +2 -2
  99. package/mcp-server/package.json +1 -1
  100. package/mcp-server/src/http.ts +20 -2
  101. package/mcp-server/src/index.ts +59 -17
  102. package/mcp-server/src/services/memory-maintenance.ts +31 -28
  103. package/mcp-server/src/services/memory-migration-copy.ts +419 -0
  104. package/mcp-server/src/services/memory-migration-worker.ts +55 -0
  105. package/mcp-server/src/services/memory-retrieval.ts +173 -32
  106. package/mcp-server/src/services/memory-schema.ts +194 -12
  107. package/mcp-server/src/services/memory-sessions.ts +54 -21
  108. package/mcp-server/src/services/memory-verification.ts +7 -4
  109. package/mcp-server/src/services/neural-interface.ts +22 -2
  110. package/mcp-server/src/services/retrieval-reader-worker.ts +67 -0
  111. package/mcp-server/src/services/retrieval-reader.ts +131 -0
  112. package/mcp-server/src/services/sqlite-write.ts +60 -0
  113. package/mcp-server/src/services/sqlite.ts +246 -8
  114. package/mcp-server/src/services/typesafe-config.ts +25 -6
  115. package/mcp-server/src/services/typesafe.ts +9 -7
  116. package/mcp-server/src/services/vector-cache.ts +154 -9
  117. package/mcp-server/src/tools/agents.ts +26 -9
  118. package/mcp-server/src/tools/browser-advanced.ts +10 -3
  119. package/mcp-server/src/tools/browser-extension-setup.ts +30 -0
  120. package/mcp-server/src/tools/browser-interact.ts +5 -1
  121. package/neural-interface/i18n/en.json +263 -1
  122. package/neural-interface/i18n/pt-BR.json +264 -2
  123. package/neural-interface/lib/agents/split.js +32 -4
  124. package/neural-interface/lib/assistant-api.js +19 -8
  125. package/neural-interface/lib/assistant-brains/claude.js +2 -0
  126. package/neural-interface/lib/assistant-catalog.js +2 -2
  127. package/neural-interface/lib/assistant-config.js +0 -7
  128. package/neural-interface/lib/assistant-dispatch.js +257 -95
  129. package/neural-interface/lib/assistant-persona.js +16 -4
  130. package/neural-interface/lib/assistant-pricing.js +65 -14
  131. package/neural-interface/lib/assistant-router.js +131 -47
  132. package/neural-interface/lib/assistant-run-wait.js +45 -28
  133. package/neural-interface/lib/assistant-runtime.js +39 -33
  134. package/neural-interface/lib/backup-contents.js +158 -0
  135. package/neural-interface/lib/backup-crypto-io.js +330 -0
  136. package/neural-interface/lib/backup-crypto-worker.js +130 -0
  137. package/neural-interface/lib/backup-crypto.js +525 -0
  138. package/neural-interface/lib/backup-download.js +268 -0
  139. package/neural-interface/lib/backup-encryption.js +318 -0
  140. package/neural-interface/lib/backup-groups.js +287 -0
  141. package/neural-interface/lib/backup-restore-session.js +176 -0
  142. package/neural-interface/lib/backup-restore-stage.js +60 -0
  143. package/neural-interface/lib/backup-service.js +788 -233
  144. package/neural-interface/lib/backup-zip-reader.js +30 -18
  145. package/neural-interface/lib/backup-zip-writer.js +34 -10
  146. package/neural-interface/lib/browser-extension-adapter.js +89 -13
  147. package/neural-interface/lib/browser-extension-bridge.js +18 -7
  148. package/neural-interface/lib/claude-agent-bridge.js +1 -0
  149. package/neural-interface/lib/claude-session-cleanup.js +5 -1
  150. package/neural-interface/lib/cli-update-planner.js +105 -6
  151. package/neural-interface/lib/client-diagnostics.js +42 -0
  152. package/neural-interface/lib/confined-fs.js +7 -2
  153. package/neural-interface/lib/coordination/README.md +8 -2
  154. package/neural-interface/lib/coordination/contract.js +161 -0
  155. package/neural-interface/lib/coordination/database.js +999 -0
  156. package/neural-interface/lib/coordination/operations.js +436 -0
  157. package/neural-interface/lib/coordination/service.js +68 -537
  158. package/neural-interface/lib/coordination/storage-worker.js +101 -0
  159. package/neural-interface/lib/coordination/store.js +219 -1111
  160. package/neural-interface/lib/db.js +70 -32
  161. package/neural-interface/lib/health-count.js +37 -0
  162. package/neural-interface/lib/loop-stall.js +139 -0
  163. package/neural-interface/lib/maritaca/client.js +2 -2
  164. package/neural-interface/lib/maritaca/models.js +12 -17
  165. package/neural-interface/lib/maritaca/opencode.js +4 -2
  166. package/neural-interface/lib/memory-api.js +9 -1
  167. package/neural-interface/lib/memory-session-capture.js +42 -10
  168. package/neural-interface/lib/memory-store-gate.js +313 -0
  169. package/neural-interface/lib/memory-store-migrate.js +65 -0
  170. package/neural-interface/lib/memory-timers.js +7 -7
  171. package/neural-interface/lib/native-loop-providers.js +13 -16
  172. package/neural-interface/lib/native-loop-runtime.js +28 -7
  173. package/neural-interface/lib/opencode-build-preflight.js +18 -1
  174. package/neural-interface/lib/opencode-native-boundary.js +69 -8
  175. package/neural-interface/lib/opencode-provider-view.js +14 -3
  176. package/neural-interface/lib/opencode-v2-ws-requests.js +31 -1
  177. package/neural-interface/lib/opencode2-client.js +2 -1
  178. package/neural-interface/lib/recall-impact.js +122 -0
  179. package/neural-interface/lib/scratch-evidence.js +420 -0
  180. package/neural-interface/lib/scratch-process-guard.js +139 -0
  181. package/neural-interface/lib/scratch-references.js +279 -0
  182. package/neural-interface/lib/scratch-retention-core.js +385 -0
  183. package/neural-interface/lib/scratch-retention-worker.js +37 -0
  184. package/neural-interface/lib/scratch-retention.js +151 -0
  185. package/neural-interface/lib/session-cache-builder.js +31 -43
  186. package/neural-interface/lib/session-cache-worker.js +157 -0
  187. package/neural-interface/lib/session-indexer.js +28 -21
  188. package/neural-interface/lib/session-search-index.js +85 -0
  189. package/neural-interface/lib/skills/creation.js +1 -1
  190. package/neural-interface/lib/sqlite-integrity-worker.js +3 -1
  191. package/neural-interface/lib/style-guide/store.js +43 -3
  192. package/neural-interface/lib/system-restore.js +50 -0
  193. package/neural-interface/lib/teams/api.js +15 -6
  194. package/neural-interface/lib/teams/claims.js +67 -31
  195. package/neural-interface/lib/teams/index.js +7 -7
  196. package/neural-interface/lib/teams/integration.js +40 -40
  197. package/neural-interface/lib/teams/landing.js +6 -6
  198. package/neural-interface/lib/teams/recovery.js +24 -23
  199. package/neural-interface/lib/teams/scheduler.js +194 -95
  200. package/neural-interface/lib/teams/state.js +14 -14
  201. package/neural-interface/lib/teams/worktrees.js +27 -27
  202. package/neural-interface/lib/whatsapp/bridge.js +2 -1
  203. package/neural-interface/lib/worker-confinement.js +47 -2
  204. package/neural-interface/lib/worker-mcp-channel.js +2 -0
  205. package/neural-interface/lib/worker-resume.js +5 -0
  206. package/neural-interface/lib/worker-stop.js +86 -0
  207. package/neural-interface/package-lock.json +2 -2
  208. package/neural-interface/package.json +1 -1
  209. package/neural-interface/public/index.html +233 -24
  210. package/neural-interface/public/onboarding.html +259 -34
  211. package/neural-interface/public/shared/agents/studio/ax-library.js +0 -6
  212. package/neural-interface/public/shared/agents/studio/ax-main.js +14 -7
  213. package/neural-interface/public/shared/agy/agy-options.js +11 -0
  214. package/neural-interface/public/shared/agy/agy-panel.js +29 -10
  215. package/neural-interface/public/shared/agy/agy-styles.js +14 -12
  216. package/neural-interface/public/shared/agy/agy-tabs-logic.js +4 -1
  217. package/neural-interface/public/shared/api.js +1 -1
  218. package/neural-interface/public/shared/assistant/asst-api.js +3 -3
  219. package/neural-interface/public/shared/assistant/asst-brain-picker.js +13 -6
  220. package/neural-interface/public/shared/assistant/asst-control.js +2 -0
  221. package/neural-interface/public/shared/assistant/asst-motion-gate.js +78 -4
  222. package/neural-interface/public/shared/assistant/asst-panel.js +18 -2
  223. package/neural-interface/public/shared/assistant/asst-rack-styles.js +4 -0
  224. package/neural-interface/public/shared/assistant/asst-render.js +105 -38
  225. package/neural-interface/public/shared/assistant/asst-route.js +100 -21
  226. package/neural-interface/public/shared/assistant/asst-routes-editor.js +1 -1
  227. package/neural-interface/public/shared/assistant/asst-sidepanel.js +4 -2
  228. package/neural-interface/public/shared/assistant/asst-state.js +11 -0
  229. package/neural-interface/public/shared/assistant/asst-styles.js +10 -23
  230. package/neural-interface/public/shared/assistant/route-identity.js +2 -1
  231. package/neural-interface/public/shared/cdx/cdx-render.js +9 -0
  232. package/neural-interface/public/shared/cdx/cdx-settings.js +3 -1
  233. package/neural-interface/public/shared/cdx/cdx-styles.js +6 -0
  234. package/neural-interface/public/shared/cdx/cdx-tabs.js +29 -9
  235. package/neural-interface/public/shared/client-diagnostics.js +94 -0
  236. package/neural-interface/public/shared/cp/cp-markdown.js +7 -2
  237. package/neural-interface/public/shared/cp/cp-styles.js +1 -1
  238. package/neural-interface/public/shared/effort-i18n.js +118 -0
  239. package/neural-interface/public/shared/html-shell.js +4 -52
  240. package/neural-interface/public/shared/loading-diagnostic-entry.js +64 -0
  241. package/neural-interface/public/shared/memory-store-wait.js +52 -0
  242. package/neural-interface/public/shared/morelogin-profile-field.js +1 -1
  243. package/neural-interface/public/shared/mtc/mtc-logic.js +2 -1
  244. package/neural-interface/public/shared/mtc/mtc-panel.js +8 -1
  245. package/neural-interface/public/shared/mtc/mtc-styles.js +13 -12
  246. package/neural-interface/public/shared/ocp-v2/ocp-v2-childpanel.js +7 -0
  247. package/neural-interface/public/shared/ocp-v2/ocp-v2-location-logic.js +109 -0
  248. package/neural-interface/public/shared/ocp-v2/ocp-v2-modelpicker.js +8 -1
  249. package/neural-interface/public/shared/ocp-v2/ocp-v2-panel.js +118 -6
  250. package/neural-interface/public/shared/ocp-v2/ocp-v2-render.js +27 -3
  251. package/neural-interface/public/shared/ocp-v2/ocp-v2-send.js +13 -0
  252. package/neural-interface/public/shared/ocp-v2/ocp-v2-session-actions.js +2 -1
  253. package/neural-interface/public/shared/ocp-v2/ocp-v2-styles.js +27 -93
  254. package/neural-interface/public/shared/ocp-v2/ocp-v2-variantpicker.js +17 -6
  255. package/neural-interface/public/shared/output-format.js +294 -0
  256. package/neural-interface/public/shared/provider-icons.js +6 -0
  257. package/neural-interface/public/shared/schedules-view.js +2 -1
  258. package/neural-interface/public/shared/server-presence.js +77 -0
  259. package/neural-interface/public/shared/settings/settings-backup-contents.js +241 -0
  260. package/neural-interface/public/shared/settings/settings-backup-download.js +298 -0
  261. package/neural-interface/public/shared/settings/settings-backup-encryption-pane.js +335 -0
  262. package/neural-interface/public/shared/settings/settings-backup-encryption.js +545 -0
  263. package/neural-interface/public/shared/settings/settings-ia.js +1 -1
  264. package/neural-interface/public/shared/skills/studio/sx-geometry.js +12 -3
  265. package/neural-interface/public/shared/skills/studio/sx-main.js +14 -7
  266. package/neural-interface/public/shared/studio-attention.js +6 -0
  267. package/neural-interface/public/shared/styles.css +341 -437
  268. package/neural-interface/public/shared/transcript-rows.js +28 -3
  269. package/neural-interface/public/shared/tray-auto-close.js +18 -5
  270. package/neural-interface/public/shared/ui-agents.js +1 -2
  271. package/neural-interface/public/shared/ui-automation-studio.js +168 -108
  272. package/neural-interface/public/shared/ui-claude-panel.js +42 -65
  273. package/neural-interface/public/shared/ui-loading.js +124 -17
  274. package/neural-interface/public/shared/ui-native-loop-router.js +10 -0
  275. package/neural-interface/public/shared/ui-navbar.js +2 -1
  276. package/neural-interface/public/shared/ui-output.js +533 -0
  277. package/neural-interface/public/shared/ui-schedules-studio.js +165 -128
  278. package/neural-interface/public/shared/ui-scroll-follow.js +97 -6
  279. package/neural-interface/public/shared/ui-sessions.js +2 -2
  280. package/neural-interface/public/shared/ui-settings-entry.js +18 -0
  281. package/neural-interface/public/shared/ui-settings.js +224 -65
  282. package/neural-interface/public/shared/ui-sidepanel-tray.js +3 -2
  283. package/neural-interface/public/shared/ui-tooltip.js +16 -0
  284. package/neural-interface/public/shared/ui-tutorial.js +5 -6
  285. package/neural-interface/public/shared/ui-worker-end.js +27 -8
  286. package/neural-interface/public/shared/worker-end.js +9 -4
  287. package/neural-interface/public/variant/2d/main.js +5 -0
  288. package/neural-interface/public/variant/3d/app.js +10 -0
  289. package/neural-interface/public/variant/3d/main.js +5 -1
  290. package/neural-interface/scripts/scratch-retention.mjs +20 -0
  291. package/neural-interface/server.js +477 -139
  292. package/npm-shrinkwrap.json +2 -2
  293. package/package.json +1 -1
  294. package/scripts/restore-data-home-from-backup.mjs +175 -8
  295. 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
@@ -319,7 +338,7 @@ import { registerMaritacaRoutes } from './lib/maritaca/api.js';
319
338
  import { createMaritacaOpencodeSync, maritacaWorkerChannelProvider } from './lib/maritaca/opencode.js';
320
339
  import { createMaritacaOpencodeProxy, maritacaOpencodeProxyBaseUrl } from './lib/maritaca/opencode-proxy.js';
321
340
  import { antigravityHomeDir, antigravityHomesRoot, pruneAntigravityHomes } from './lib/antigravity/home.js';
322
- import { antigravityStores, findUserConversation, parseAntigravityTranscript, readTranscriptText } from './lib/antigravity/transcripts.js';
341
+ import { findUserConversation, parseAntigravityTranscript, readTranscriptText } from './lib/antigravity/transcripts.js';
323
342
  import {
324
343
  buildAgentDisallowedTools,
325
344
  agentAccessFrom,
@@ -460,14 +479,24 @@ import {
460
479
  getMemoriesByCategory, updateMemoriesCategory,
461
480
  getCategories as dbGetCategories, saveCategories as dbSaveCategories,
462
481
  countSessionChunks, searchSessionChunks as dbSearchSessionChunks,
463
- getKvConfig, setKvConfig, EMBEDDING_MODEL,
482
+ getKvConfig, setKvConfig, saveEmbeddingMetadata, EMBEDDING_MODEL,
464
483
  searchSessionFts, listSessionCache, getSessionCacheEntry, clearSessionCacheProvider,
465
484
  memoryVectors, getRecentXEngagements, getXActionBudget, getXEngagementTier, X_ACTION_TYPES,
466
485
  getFbActionBudget, getFbEngagementTier, FB_ACTION_TYPES,
467
486
  } from './lib/db.js';
468
- import {
469
- rebuildClaudeCache, rebuildCodexCache, rebuildOpencodeCache, rebuildAntigravityCache,
470
- } 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();
471
500
  import {
472
501
  clearOpenCodeHistory,
473
502
  getOpenCodeHistoryStats,
@@ -569,7 +598,7 @@ const requestGates = createRequestGates({
569
598
  settingsHint: () => ENV_PATH,
570
599
  });
571
600
  app.use(requestGates.host);
572
- app.use(express.json({ limit: '25mb' }));
601
+ app.use(express.json({ limit: '25mb', type: useDefaultJsonParser }));
573
602
 
574
603
  // Clean body-parser error handler: ui-state / whiteboard persist base64 images and can
575
604
  // exceed the JSON limit. Default Express handler dumps a 10-line raw-body stack with no
@@ -651,13 +680,15 @@ _peerIdentity.probe();
651
680
  const _ownerAuthority = createOwnerAuthority({ pageSession: () => _pageSession, isRemote: (req) => requestGates.isRemote(req), peer: _peerIdentity, log: (line) => console.warn(line), automationBrowserAllowed: () => _automationBrowserOwnerAccess.enabled() });
652
681
  app.use(_peerIdentity.middleware({ needs: peerLookupWanted }));
653
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);
654
685
 
655
686
  import { registerCodexPlanRoutes } from './lib/codex-plan-store.js';
656
687
  import { createOpencodeHiddenModelsRouter, createOpencodeHiddenModelsStore } from './lib/opencode-hidden-models.js';
657
688
  import { createEditorFilesRouter, EDITOR_BACKUP_CAPABILITIES, EDITOR_BACKUP_NAMESPACE } from './lib/editor-files-api.js';
658
689
  import { createEditorGitRouter, EDITOR_GIT_CAPABILITIES } from './lib/editor-git-api.js';
659
690
  import { confinedFolder, createFileExplorerRouter, EXPLORER_CAPABILITIES } from './lib/file-explorer-api.js';
660
- import { folderPickerCommand } from './lib/file-explorer-system.js';
691
+ import { createRevealer, folderPickerCommand } from './lib/file-explorer-system.js';
661
692
  import { createEditorConfigRouter, createEditorConfigStore, createEndpointKeyStore, EDITOR_CONFIG_CAPABILITIES } from './lib/editor-config.js';
662
693
  import {
663
694
  COMPLETION_SYSTEM, EDITOR_COMPLETION_CAPABILITIES, createEditorCompletionRouter, createEditorCompletionService, createUsageStore,
@@ -1089,6 +1120,7 @@ function peerLookupWanted(req) {
1089
1120
  app.use(_pageSession.serviceWorker); // GET /sw.js: a worker that takes itself away, for a browser refused the secret
1090
1121
  app.use(_pageSession.pages);
1091
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 }));
1092
1124
  // The extension's "Connect your browser" page, opened by the one-button setup in the owner's everyday browser. One of
1093
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
1094
1126
  // status and its one ticket are the owner's, under the same owner guard; an automation browser and an agent's process
@@ -1722,32 +1754,13 @@ app.get('/api/stats', async (req, res) => {
1722
1754
  }
1723
1755
  });
1724
1756
 
1725
- // GET /api/recall-impact — Memory counts by importance threshold for recall settings UI
1726
- 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) => {
1727
1762
  try {
1728
- const d = getDb();
1729
- const rows = d.prepare(`
1730
- SELECT importance, COUNT(*) as cnt, CAST(AVG(LENGTH(content)) AS INTEGER) as avg_len,
1731
- CAST(AVG(CASE WHEN tags IS NOT NULL AND tags != '[]' THEN LENGTH(tags) ELSE 0 END) AS INTEGER) as avg_tags_len,
1732
- CAST(AVG(CASE WHEN related_files IS NOT NULL AND related_files != '[]' THEN LENGTH(related_files) ELSE 0 END) AS INTEGER) as avg_files_len
1733
- FROM memories WHERE trashed_at IS NULL GROUP BY importance ORDER BY importance
1734
- `).all();
1735
- // Session chunk stats for token estimation
1736
- let sessionStats = { count: 0, avg_summary_len: 0, avg_details_len: 0 };
1737
- try {
1738
- const sc = d.prepare(`
1739
- SELECT COUNT(*) as count,
1740
- CAST(AVG(LENGTH(summary)) AS INTEGER) as avg_summary_len,
1741
- CAST(AVG(
1742
- COALESCE(LENGTH(tools_used), 0) +
1743
- COALESCE(LENGTH(files_modified), 0) +
1744
- COALESCE(LENGTH(related_memory_ids), 0)
1745
- ) AS INTEGER) as avg_details_len
1746
- FROM session_chunks
1747
- `).get();
1748
- if (sc) sessionStats = sc;
1749
- } catch { /* session_chunks table may not exist */ }
1750
- res.json({ rows, sessionStats });
1763
+ res.json(await recallImpact.get());
1751
1764
  } catch (err) {
1752
1765
  console.error('GET /api/recall-impact error:', err.message);
1753
1766
  res.status(500).json({ error: err.message });
@@ -2612,7 +2625,8 @@ async function runGracefulShutdown(reason) {
2612
2625
  // The coordination store (agent events, the Assistant's mailbox, the follow-up outbox): closed once the workers
2613
2626
  // are stopped or suspended and what that changed is recorded. Every open wait is answered, the write-ahead log is
2614
2627
  // folded into the file. Signals and the restart/update/shutdown routes all use this teardown.
2615
- try { _assistantCoordination?.close(); } catch (err) { console.warn(' coordination close err:', err?.message); }
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); }
2616
2630
  try { closeDb(); } catch {}
2617
2631
  try { closeBlobStore(); } catch {}
2618
2632
 
@@ -3158,6 +3172,9 @@ app.post('/api/system/run-update', async (req, res) => {
3158
3172
  }
3159
3173
  });
3160
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
+
3161
3178
  // POST /api/settings/move-db — Move SQLite database to a new directory
3162
3179
  app.post('/api/settings/move-db', (req, res) => {
3163
3180
  try {
@@ -3269,7 +3286,7 @@ async function runReindex(job) {
3269
3286
  const updateStmt = d.prepare('UPDATE memories SET vector = ? WHERE id = ?');
3270
3287
  for (let i = 0; i < rows.length; i++) {
3271
3288
  try {
3272
- updateStmt.run(encodeVector(vectors[i]), rows[i].id);
3289
+ await withMemoryWrite(d, () => updateStmt.run(encodeVector(vectors[i]), rows[i].id));
3273
3290
  job.completed++;
3274
3291
  } catch {
3275
3292
  job.errors++;
@@ -3297,7 +3314,7 @@ async function runReindex(job) {
3297
3314
  const updateStmt = d.prepare('UPDATE session_chunks SET vector = ? WHERE id = ?');
3298
3315
  for (let i = 0; i < rows.length; i++) {
3299
3316
  try {
3300
- updateStmt.run(encodeVector(vectors[i]), rows[i].id);
3317
+ await withMemoryWrite(d, () => updateStmt.run(encodeVector(vectors[i]), rows[i].id));
3301
3318
  job.chunks++;
3302
3319
  } catch {
3303
3320
  job.errors++;
@@ -3312,8 +3329,7 @@ async function runReindex(job) {
3312
3329
 
3313
3330
  // Update stored model metadata
3314
3331
  try {
3315
- setKvConfig('embedding_model', EMBEDDING_MODEL);
3316
- setKvConfig('embedding_dims', String(EMBEDDING_DIMS));
3332
+ await saveEmbeddingMetadata();
3317
3333
  } catch {}
3318
3334
 
3319
3335
  job.running = false;
@@ -8388,6 +8404,7 @@ let _ocpVersion = null;
8388
8404
  // says why OpenCode cannot be used (shown by the panel, Settings and the tray).
8389
8405
  let _ocpPassword = null;
8390
8406
  let _ocpProblem = null;
8407
+ let _ocpStartRefusal = null; // The MoreLogin check that refused the last start (startOpencodeAtBoot reads it).
8391
8408
  let _ocpHistoryClearInProgress = false;
8392
8409
  let _ocpSessionCacheWarmup = null;
8393
8410
 
@@ -9516,6 +9533,9 @@ function handleOpencodeV2Ws(ws) {
9516
9533
  nativeMutationTypes: OPENCODE_NATIVE_MUTATION_TYPES,
9517
9534
  protectedRunFor: activeNativeOpenCodeRunForSession,
9518
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,
9519
9539
  });
9520
9540
  if (refused) {
9521
9541
  send({ type: `${type}:result`, id, ...refused });
@@ -9913,6 +9933,7 @@ async function ensureOpencodeServer({ allowDuringHistoryClear = false } = {}) {
9913
9933
  return false;
9914
9934
  }
9915
9935
  _ocpProblem = null;
9936
+ _ocpStartRefusal = null;
9916
9937
  // A serve already running is adopted when it answers SynaBun: only to the password SynaBun gave it, and only
9917
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
9918
9939
  // adopted, and its port with it.
@@ -9991,6 +10012,11 @@ async function ensureOpencodeServer({ allowDuringHistoryClear = false } = {}) {
9991
10012
  });
9992
10013
  } catch (err) {
9993
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
+ }
9994
10020
  return 'not-spawned';
9995
10021
  }
9996
10022
  for (let i = 0; i < 30; i++) {
@@ -15229,9 +15255,23 @@ app.post('/api/loop/stop', async (req, res) => {
15229
15255
  // No agent header at all: the owner's page, with its page secret (or an invite guest, whom the guest rules decide).
15230
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.');
15231
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
+ }
15232
15272
  let directlyStopped = false;
15233
15273
  if (targetTerminalId && _nativeLoopRuntime?.isAlive(targetTerminalId)) {
15234
- directlyStopped = await _nativeLoopRuntime.stop(targetTerminalId, 'user');
15274
+ directlyStopped = await _nativeLoopRuntime.stop(targetTerminalId, stopReason, { stopProvenance });
15235
15275
  }
15236
15276
  if (!existsSync(LOOP_DIR)) return res.json({ ok: true, stopped: directlyStopped ? 1 : 0 });
15237
15277
  const files = readdirSync(LOOP_DIR).filter(f => f.endsWith('.json') && f !== '.gitkeep');
@@ -15248,17 +15288,22 @@ app.post('/api/loop/stop', async (req, res) => {
15248
15288
  if (data.active || data.pending) {
15249
15289
  // Per-loop stop: skip loops that don't match the target
15250
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;
15251
15293
  if (!directlyStopped && (data.runtimeType === 'native' || data.driverType === 'native')) {
15252
- await _nativeLoopRuntime?.stop(data.runId || data.terminalSessionId, 'user');
15294
+ await _nativeLoopRuntime?.stop(data.runId || data.terminalSessionId, stopReason, { stopProvenance });
15253
15295
  }
15254
15296
  if (data.driverType === 'exec' && data.scheduledBy) {
15255
15297
  data.active = false;
15256
15298
  data.pending = false;
15257
15299
  data.completedAt = new Date().toISOString();
15258
- data.stoppedReason = 'user';
15300
+ data.stoppedReason = stopReason;
15301
+ data.stopProvenance = stopProvenance;
15259
15302
  try { writeFileSync(filePath, JSON.stringify(data, null, 2)); } catch {}
15260
- persistExecScheduleOutcome(data, 'stopped', 'user');
15303
+ persistExecScheduleOutcome(data, 'stopped', stopReason);
15261
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 });
15262
15307
  // Kill PTY session if still alive
15263
15308
  if (data.terminalSessionId && terminalSessions.has(data.terminalSessionId)) {
15264
15309
  const session = terminalSessions.get(data.terminalSessionId);
@@ -16324,7 +16369,8 @@ async function launchScheduledLoop(schedule) {
16324
16369
  if (isXAutomation) {
16325
16370
  try {
16326
16371
  const xAccount = (template.account || (/^cp_/.test(schedule.templateId || '') ? 'Crit_Pix' : '')).trim();
16327
- const { handles, statusIds, blocked, error: ledgerErr } = getRecentXEngagements({ account: xAccount || null, days: 7, limit: 200 });
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 });
16328
16374
  if (ledgerErr) {
16329
16375
  loopLog(terminalSessionId, 'launch:dedup', 'engagement ledger read failed (continuing)', { err: ledgerErr });
16330
16376
  } else if (handles.length || statusIds.length || blocked.length) {
@@ -16351,8 +16397,8 @@ async function launchScheduledLoop(schedule) {
16351
16397
  const tz = schedule.timezone || 'America/Sao_Paulo';
16352
16398
  const nowLocal = getNowInTimezone(tz);
16353
16399
  const msIntoDay = ((nowLocal.getHours() * 60 + nowLocal.getMinutes()) * 60 + nowLocal.getSeconds()) * 1000 + nowLocal.getMilliseconds();
16354
- const spent = getXActionBudget({ account: xAccount || null, sinceIso: new Date(Date.now() - msIntoDay).toISOString() });
16355
- const { tier, caps, source: tierSource } = getXEngagementTier({ account: xAccount || null });
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 });
16356
16402
  if (spent.error) {
16357
16403
  loopLog(terminalSessionId, 'launch:budget', 'action budget read failed (continuing)', { err: spent.error });
16358
16404
  } else {
@@ -16392,8 +16438,8 @@ async function launchScheduledLoop(schedule) {
16392
16438
  const tz = schedule.timezone || 'America/Sao_Paulo';
16393
16439
  const nowLocal = getNowInTimezone(tz);
16394
16440
  const msIntoDay = ((nowLocal.getHours() * 60 + nowLocal.getMinutes()) * 60 + nowLocal.getSeconds()) * 1000 + nowLocal.getMilliseconds();
16395
- const spent = getFbActionBudget({ sinceIso: new Date(Date.now() - msIntoDay).toISOString() });
16396
- const { tier, caps, source: tierSource } = getFbEngagementTier();
16441
+ const spent = await getFbActionBudget({ sinceIso: new Date(Date.now() - msIntoDay).toISOString() });
16442
+ const { tier, caps, source: tierSource } = await getFbEngagementTier();
16397
16443
  if (spent.error) {
16398
16444
  loopLog(terminalSessionId, 'launch:budget', 'FB action budget read failed (continuing)', { err: spent.error });
16399
16445
  } else {
@@ -16896,6 +16942,7 @@ function reconcileKeepAwake() {
16896
16942
  }
16897
16943
 
16898
16944
  function evaluateSchedules() {
16945
+ markActivity('scheduler:schedules');
16899
16946
  // P5 deterministic health shares the scheduler's tick; disabled until enabled in Skills Studio.
16900
16947
  skillsService?.health.tick().catch((error) => console.error('[skills-health]', error?.code || 'check_failed'));
16901
16948
  _scheduleEvalCount++;
@@ -18833,8 +18880,9 @@ const TOOL_DEFS = [
18833
18880
  // Google's Antigravity CLI has no npm package: a Homebrew cask's newer version is what `brew outdated` says, and
18834
18881
  // the CLI updates itself (`agy update`).
18835
18882
  { key: 'antigravity', cmd: 'agy', versionArg: '--version' },
18836
- // npm's opencode-ai is OpenCode 1: OpenCode 2's newer version is what Homebrew says (a brew install) or what OpenCode
18837
- // itself announces in its own interface.
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).
18838
18886
  { key: 'opencode', cmd: 'opencode', versionArg: '--version' },
18839
18887
  ];
18840
18888
 
@@ -18937,6 +18985,7 @@ function pruneBundledCliTools() {
18937
18985
  }
18938
18986
 
18939
18987
  async function checkToolVersions({ force = false } = {}) {
18988
+ markActivity('cli:versions');
18940
18989
  const generation = ++_toolVersionGeneration;
18941
18990
  // Every CLI exactly as the panels and launchers find it (lib/cli-resolver.js):
18942
18991
  // the path in Settings first, then PATH with the OS PATH read afresh, then the
@@ -18960,6 +19009,12 @@ async function checkToolVersions({ force = false } = {}) {
18960
19009
  // Homebrew routinely trails npm by a few releases, so comparing against it
18961
19010
  // produced a badge that lit up while `brew upgrade` answered "already
18962
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
+
18963
19018
  let upstreamLatest = null;
18964
19019
  try {
18965
19020
  const controller = new AbortController();
@@ -18972,22 +19027,31 @@ async function checkToolVersions({ force = false } = {}) {
18972
19027
  const res = await fetch(`https://api.github.com/repos/${tool.github}/releases/latest`, { signal: controller.signal });
18973
19028
  clearTimeout(timeout);
18974
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);
18975
19036
  }
18976
19037
  } catch { /* network error */ }
18977
19038
 
18978
- const installSource = status.installSource;
18979
- 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;
18980
19042
  const latest = resolveLatest({
18981
19043
  installSource,
18982
19044
  brewToken,
18983
19045
  brewOutdated,
18984
19046
  npmLatest: upstreamLatest,
19047
+ brewUpstream,
18985
19048
  installed,
18986
19049
  });
19050
+ const refreshBrew = brewNeedsRefresh({ installSource, brewToken, brewOutdated, brewUpstream, installed });
18987
19051
  // A self-updater is started by the path found, so the update reaches this
18988
19052
  // very installation even where a terminal's PATH does not name its folder.
18989
19053
  const updateCommand = installed
18990
- ? buildUpdateCommand(tool.key, installSource, { brewToken, binPath: status.path, platform: process.platform })
19054
+ ? buildUpdateCommand(tool.key, installSource, { brewToken, binPath: status.path, platform: process.platform, refreshBrew })
18991
19055
  : null;
18992
19056
 
18993
19057
  return [tool.key, {
@@ -19144,6 +19208,56 @@ app.use('/api/cli/opencode-serves', createOpencodeServeVerifyApi({ boundary: nat
19144
19208
  // FULL SYSTEM BACKUP & RESTORE
19145
19209
  // ═══════════════════════════════════════════
19146
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
+
19147
19261
  // GET /api/system/backup — Download full system backup as ZIP
19148
19262
  app.get('/api/system/backup', async (req, res) => {
19149
19263
  try {
@@ -19156,6 +19270,7 @@ app.get('/api/system/backup', async (req, res) => {
19156
19270
  kind: 'manual',
19157
19271
  appVersion: pkg.version || null,
19158
19272
  additionalEntries: getBackupAdditionalEntries(),
19273
+ groups: backupContents.groups(),
19159
19274
  }));
19160
19275
  res.download(backup.path, backup.name, error => {
19161
19276
  try { if (existsSync(backup.path)) unlinkSync(backup.path); } catch {}
@@ -19173,6 +19288,46 @@ app.get('/api/system/backup', async (req, res) => {
19173
19288
  // and a ZIP over 2 GiB cannot be read into a Buffer at all.
19174
19289
  const RESTORE_STAGING_DIR = resolve(DATA_HOME, 'backups', 'restore-staging');
19175
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
+
19176
19331
  // POST /api/system/restore/preview — Read manifest from uploaded ZIP without applying
19177
19332
  /** One sentence for a failed MCP server build (lib/mcp-build.js result), with what the compiler said when it said anything. */
19178
19333
  function mcpBuildFailureMessage(build) {
@@ -19232,6 +19387,22 @@ function markRestoredAutomationRecords(targets) {
19232
19387
  return marked;
19233
19388
  }
19234
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
+
19235
19406
  app.post('/api/system/restore/preview', async (req, res) => {
19236
19407
  if (!restoreOwnerPageCall(req)) return refuseRestoreCaller(req, res);
19237
19408
  let upload = null;
@@ -19239,17 +19410,20 @@ app.post('/api/system/restore/preview', async (req, res) => {
19239
19410
  try {
19240
19411
  upload = await saveRestoreUpload(req, RESTORE_STAGING_DIR);
19241
19412
  if (upload.sizeBytes === 0) {
19242
- return res.status(400).json({ error: 'No data received' });
19413
+ return res.status(400).json({ error: 'No data received', code: 'RESTORE_EMPTY_UPLOAD' });
19243
19414
  }
19244
- zip = await openZipArchive(upload.path);
19245
- const found = await readBackupManifest(zip);
19246
- if (!found) {
19247
- return res.status(400).json({ error: 'Invalid backup: manifest.json not found' });
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 });
19248
19421
  }
19249
- res.json({ ok: true, manifest: found.manifest });
19422
+ zip = await openZipArchive(upload.path);
19423
+ res.json(await restorePreviewOf(zip));
19250
19424
  } catch (err) {
19251
19425
  console.error('POST /api/system/restore/preview error:', err.message);
19252
- 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) });
19253
19427
  } finally {
19254
19428
  await zip?.close().catch(() => {});
19255
19429
  removeRestoreUpload(upload);
@@ -19265,32 +19439,64 @@ app.post('/api/system/restore', async (req, res) => {
19265
19439
  try {
19266
19440
  upload = await saveRestoreUpload(req, RESTORE_STAGING_DIR);
19267
19441
  if (upload.sizeBytes === 0) {
19268
- 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.' });
19269
19448
  }
19270
-
19271
- const mode = req.query.mode || 'full';
19272
19449
 
19273
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
+ });
19274
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) {
19275
19467
  // Find and validate manifest
19276
19468
  const found = await readBackupManifest(zip);
19277
19469
  if (!found) {
19278
- 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' });
19279
19471
  }
19280
19472
  const { manifest, prefix } = found;
19281
19473
  if (![1, 2, 3].includes(manifest.version)) {
19282
- 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' });
19283
19475
  }
19284
19476
 
19285
19477
  // v3 archives are published only after checksum verification. Recheck on
19286
19478
  // restore so a damaged or edited snapshot cannot partially replace state.
19287
19479
  if (manifest.version >= 3) {
19288
- try { await verifyBackupChecksums(zip, { prefix, manifest, label: 'Invalid backup' }); }
19289
- catch (error) { return res.status(400).json({ error: error.message }); }
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) }); }
19290
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);
19291
19496
 
19292
19497
  const entryAt = rel => zip.getEntry(`${prefix}/${rel}`);
19293
- 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)); } };
19294
19500
 
19295
19501
  // Restore config files
19296
19502
  if (mode === 'full' || mode === 'config-only') {
@@ -19307,9 +19513,12 @@ app.post('/api/system/restore', async (req, res) => {
19307
19513
  claudeSettings: home ? join(home, '.claude', 'settings.json') : null,
19308
19514
  });
19309
19515
  if (unsafe.length) {
19310
- 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' });
19311
19517
  }
19312
19518
 
19519
+ // From here on a failure may leave some files replaced, and its answer says so (restoreFailureFields).
19520
+ (res.locals ||= {}).restoreWriting = true;
19521
+
19313
19522
  // .env
19314
19523
  const envEntry = entryAt('env.bak');
19315
19524
  if (envEntry) {
@@ -19358,6 +19567,7 @@ app.post('/api/system/restore', async (req, res) => {
19358
19567
  if (mode === 'full' || mode === 'snapshots-only') {
19359
19568
  const dbEntry = entryAt('database/memory.db');
19360
19569
  if (dbEntry) {
19570
+ (res.locals ||= {}).restoreWriting = true;
19361
19571
  try {
19362
19572
  // Close existing database connection before replacing
19363
19573
  closeDb();
@@ -19384,6 +19594,20 @@ app.post('/api/system/restore', async (req, res) => {
19384
19594
  }
19385
19595
  }
19386
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
+
19387
19611
  // Post-restore: ensure MCP server is built (critical for fresh installs + restore). Built means dist/index.js
19388
19612
  // and every module it imports (lib/mcp-dist.js), stamped with this version and source (lib/mcp-build.js): the
19389
19613
  // builder compiles into a temp folder and swaps it in only on success, so a failure keeps whatever dist there was.
@@ -19408,14 +19632,23 @@ app.post('/api/system/restore', async (req, res) => {
19408
19632
  res.json({ ok: true, message: 'Backup restored successfully', results, ...(results.restart ? { restart: true, bootId: SERVER_BOOT_ID } : {}) });
19409
19633
  // The new build loads only in a new server: the same restart as Apps → Restart Server, once the answer is out.
19410
19634
  if (results.restart) setTimeout(() => { try { requestServerRestart(); } catch (err) { console.error('[restore] restart after the MCP build failed:', err?.message); } }, 500);
19411
- } catch (err) {
19412
- console.error('POST /api/system/restore error:', err.message);
19413
- if (!res.headersSent) res.status(500).json({ error: err.message });
19414
- } finally {
19415
- await zip?.close().catch(() => {});
19416
- removeRestoreUpload(upload);
19417
- }
19418
- });
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);
19419
19652
 
19420
19653
  // ═══════════════════════════════════════════
19421
19654
  // AUTO-BACKUP SYSTEM
@@ -19473,8 +19706,8 @@ function getBackupAdditionalEntries() {
19473
19706
  return entries;
19474
19707
  }
19475
19708
 
19476
- function backupConfigResponse(cfg = loadAutoBackupConfig()) {
19477
- const snapshots = cfg.folderPath ? listBackupSnapshots(cfg.folderPath) : [];
19709
+ async function backupConfigResponse(cfg = loadAutoBackupConfig()) {
19710
+ const snapshots = cfg.folderPath ? await listBackupSnapshots(cfg.folderPath) : [];
19478
19711
  const health = getBackupHealth(cfg, { snapshots });
19479
19712
  if (_backupOperationActive || _autoBackupPromise) {
19480
19713
  health.status = 'running';
@@ -19504,15 +19737,15 @@ async function runAutoBackup({ force = false, kind = 'scheduled', folderPath = n
19504
19737
  try {
19505
19738
  const pkg = JSON.parse(readFileSync(resolve(PACKAGE_ROOT, 'package.json'), 'utf-8'));
19506
19739
  let preRetention = null;
19507
- const backup = await serializeBackupOperation(async () => {
19740
+ const { backup, retention } = await serializeBackupOperation(async () => {
19508
19741
  if (kind === 'scheduled') {
19509
- preRetention = applyBackupRetention({
19742
+ preRetention = await applyBackupRetention({
19510
19743
  folderPath: destination,
19511
19744
  retention: cfg.retention,
19512
19745
  incomingBytes: cfg.lastBackupSize,
19513
19746
  });
19514
19747
  }
19515
- return createVerifiedBackup({
19748
+ const backup = await createVerifiedBackup({
19516
19749
  dataHome: DATA_HOME,
19517
19750
  databasePath: getDbPath(),
19518
19751
  folderPath: destination,
@@ -19520,9 +19753,13 @@ async function runAutoBackup({ force = false, kind = 'scheduled', folderPath = n
19520
19753
  appVersion: pkg.version || null,
19521
19754
  additionalEntries: getBackupAdditionalEntries(),
19522
19755
  expectedArchiveBytes: cfg.lastBackupSize,
19756
+ // The same choice as a manual backup (Settings → Backups → What to back up).
19757
+ groups: backupContents.groups(),
19523
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 };
19524
19762
  });
19525
- const retention = applyBackupRetention({ folderPath: destination, retention: cfg.retention });
19526
19763
  cfg.lastVerifiedBackup = backup.createdAt;
19527
19764
  cfg.lastBackup = backup.createdAt; // backward compatibility
19528
19765
  cfg.lastBackupPath = backup.path;
@@ -19553,6 +19790,7 @@ function startAutoBackupScheduler() {
19553
19790
  const nextDue = nextBackupDueMs(cfg, { lastAttemptMs: _autoBackupLastAttemptMs });
19554
19791
  const delay = Math.max(0, Math.min(2_147_000_000, nextDue - Date.now()));
19555
19792
  _autoBackupTimer = setTimeout(async () => {
19793
+ if (typeof markActivity === 'function') markActivity('scheduler:backup');
19556
19794
  try { await runAutoBackup(); }
19557
19795
  catch (error) { console.error(`[auto-backup] Scheduler failed safely: ${error.message}`); }
19558
19796
  finally { startAutoBackupScheduler(); }
@@ -19562,7 +19800,7 @@ function startAutoBackupScheduler() {
19562
19800
 
19563
19801
  function stopAutoBackupScheduler() {
19564
19802
  if (_autoBackupTimer) {
19565
- clearInterval(_autoBackupTimer);
19803
+ clearTimeout(_autoBackupTimer);
19566
19804
  _autoBackupTimer = null;
19567
19805
  }
19568
19806
  }
@@ -19570,13 +19808,27 @@ function stopAutoBackupScheduler() {
19570
19808
  // Boot: start scheduler if enabled
19571
19809
  startAutoBackupScheduler();
19572
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
+
19573
19824
  // GET /api/system/auto-backup — Get auto-backup config
19574
- app.get('/api/system/auto-backup', (req, res) => {
19575
- 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 }); }
19576
19828
  });
19577
19829
 
19578
19830
  // PUT /api/system/auto-backup — Update auto-backup config
19579
- app.put('/api/system/auto-backup', (req, res) => {
19831
+ app.put('/api/system/auto-backup', async (req, res) => {
19580
19832
  try {
19581
19833
  const current = loadAutoBackupConfig();
19582
19834
  const { enabled, intervalMinutes, folderPath, retention } = req.body;
@@ -19595,7 +19847,7 @@ app.put('/api/system/auto-backup', (req, res) => {
19595
19847
  stopAutoBackupScheduler();
19596
19848
  }
19597
19849
 
19598
- res.json({ ok: true, config: backupConfigResponse(current) });
19850
+ res.json({ ok: true, config: await backupConfigResponse(current) });
19599
19851
  } catch (err) {
19600
19852
  res.status(500).json({ error: err.message });
19601
19853
  }
@@ -19607,18 +19859,18 @@ app.post('/api/system/auto-backup/trigger', async (req, res) => {
19607
19859
  const cfg = loadAutoBackupConfig();
19608
19860
  if (!cfg.folderPath) return res.status(400).json({ error: 'No backup folder configured' });
19609
19861
  const result = await runAutoBackup({ force: true });
19610
- if (result?.error) return res.status(500).json({ error: result.error, ...backupConfigResponse() });
19611
- res.json(backupConfigResponse());
19862
+ if (result?.error) return res.status(500).json({ error: result.error, ...await backupConfigResponse() });
19863
+ res.json(await backupConfigResponse());
19612
19864
  } catch (err) {
19613
19865
  res.status(500).json({ error: err.message });
19614
19866
  }
19615
19867
  });
19616
19868
 
19617
19869
  // GET /api/system/backups — verified/runtime backup history for Settings.
19618
- app.get('/api/system/backups', (req, res) => {
19870
+ app.get('/api/system/backups', async (req, res) => {
19619
19871
  try {
19620
19872
  const cfg = loadAutoBackupConfig();
19621
- const snapshots = cfg.folderPath ? listBackupSnapshots(cfg.folderPath) : [];
19873
+ const snapshots = cfg.folderPath ? await listBackupSnapshots(cfg.folderPath) : [];
19622
19874
  res.json({ ok: true, snapshots, health: getBackupHealth(cfg, { snapshots }), retention: cfg.retention });
19623
19875
  } catch (err) {
19624
19876
  res.status(500).json({ error: err.message });
@@ -22601,8 +22853,7 @@ async function getSessionEntriesForRequest(projDir, { forceRefresh = false } = {
22601
22853
  let _codexSessionCatalogRefresh = null;
22602
22854
  function getCodexSessionCatalogRefresh() {
22603
22855
  if (!_codexSessionCatalogRefresh) {
22604
- _codexSessionCatalogRefresh = memoCache(() => rebuildCodexCache({
22605
- background: true,
22856
+ _codexSessionCatalogRefresh = memoCache(() => runSessionJob('codex', {
22606
22857
  accounts: loadCodexAccounts().accounts,
22607
22858
  projects: loadHookProjects(),
22608
22859
  }), { ttlMs: 15000 });
@@ -23029,15 +23280,16 @@ function antigravityHomeFor(kind, id) { return antigravityHomeDir(antigravityHom
23029
23280
  // included, into memory capture (lib/memory-session-capture.js). A pass at start, one after a panel turn ends (that
23030
23281
  // conversation only, a moment later so agy has written its last step), one every five minutes, and a fresh one
23031
23282
  // before Resume or Skills Studio searches them (at most every 15 s).
23032
- function antigravitySessionStores({ userOnly = false } = {}) {
23033
- return antigravityStores({ homesRoot: userOnly ? null : antigravityHomesRoot(DATA_HOME) });
23034
- }
23035
23283
  let _antigravityCacheAt = 0;
23284
+ let _antigravityPass = null;
23036
23285
  function refreshAntigravityCatalog({ force = false } = {}) {
23286
+ if (_antigravityPass) return _antigravityPass;
23037
23287
  if (!force && Date.now() - _antigravityCacheAt < 15_000) return null;
23038
- _antigravityCacheAt = Date.now();
23039
- try { return rebuildAntigravityCache({ stores: antigravitySessionStores() }); }
23040
- catch (err) { console.warn(' Session cache (antigravity) error:', err.message); return null; }
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;
23041
23293
  }
23042
23294
  const _antigravityRefreshTimers = new Map();
23043
23295
  function refreshAntigravitySession(sessionId) {
@@ -23045,8 +23297,9 @@ function refreshAntigravitySession(sessionId) {
23045
23297
  clearTimeout(_antigravityRefreshTimers.get(sessionId));
23046
23298
  _antigravityRefreshTimers.set(sessionId, setTimeout(() => {
23047
23299
  _antigravityRefreshTimers.delete(sessionId);
23048
- try { rebuildAntigravityCache({ stores: antigravitySessionStores({ userOnly: true }), only: sessionId }); }
23049
- 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));
23050
23303
  }, 1500));
23051
23304
  _antigravityRefreshTimers.get(sessionId).unref?.();
23052
23305
  }
@@ -23103,7 +23356,7 @@ app.get('/api/session-search', async (req, res) => {
23103
23356
  }
23104
23357
 
23105
23358
  // Antigravity's index follows its transcripts (refreshAntigravityCatalog: at most every 15 s).
23106
- if (provider === 'antigravity') refreshAntigravityCatalog();
23359
+ if (provider === 'antigravity') await refreshAntigravityCatalog();
23107
23360
 
23108
23361
  // 1. FTS5 substring hits
23109
23362
  const ftsRows = searchSessionFts(q, { provider, project: projectFilter, limit: limit * 2 });
@@ -24558,8 +24811,7 @@ skillsService = createSkillsService({
24558
24811
  operationsOptions: { notify: (item) => {
24559
24812
  const session = _assistantRuntime?.listSessions?.().find((s) => s.status !== 'ended');
24560
24813
  if (!session) return false;
24561
- _assistantRuntime.routerMailbox(session.id, item);
24562
- return true;
24814
+ return _assistantRuntime.routerMailbox(session.id, item);
24563
24815
  } },
24564
24816
  });
24565
24817
  registerSkillsV2Routes(app, {
@@ -24936,7 +25188,7 @@ async function skillSourceSessions({ provider, project = null, q = '', limit = 4
24936
25188
  } else if (provider === 'antigravity') {
24937
25189
  // The user's own Antigravity conversations (the panel's and a terminal agy's), as Resume's index keeps them,
24938
25190
  // titled as Antigravity titles them (refreshAntigravityCatalog).
24939
- refreshAntigravityCatalog();
25191
+ await refreshAntigravityCatalog();
24940
25192
  for (const entry of listSessionCache('antigravity', { limit: 100000 })) {
24941
25193
  if (entry.deleted || !entry.project_path) continue;
24942
25194
  const dir = resolve(entry.project_path);
@@ -26862,13 +27114,17 @@ app.delete('/api/skills-studio/import/stage/:stagingId', (req, res) => {
26862
27114
  });
26863
27115
 
26864
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 });
26865
27122
  app.get('/api/health', (req, res) => {
26866
27123
  try {
26867
- // getDb() auto-creates the directory, file, and schema if missing
26868
- getDb();
26869
- const count = countMemories();
27124
+ // getDb() auto-creates the directory, file, and schema if missing (inside the count's read)
27125
+ const count = healthMemoryCount();
26870
27126
  res.json({
26871
- 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,
26872
27128
  version: SERVER_VERSION, dataHomeId: DATA_HOME_ID, installEntry: INSTALL_ENTRY,
26873
27129
  // Which server this is, and whether it is on its way out for a restart: a
26874
27130
  // page showing the restart tells this one from the one that replaces it.
@@ -28121,11 +28377,14 @@ try {
28121
28377
  const { createMcpRoutes, ensureInit: mcpEnsureInit } = await import(mcpPath);
28122
28378
 
28123
28379
  // Eagerly init: DB, categories, embedding model — runs in background, doesn't block server start
28124
- mcpEnsureInit().then(() => {
28380
+ const warmMcp = () => mcpEnsureInit().then(() => {
28125
28381
  console.log(' MCP HTTP: DB + embeddings warm');
28126
28382
  }).catch(err => {
28383
+ if (isMemoryStoreRefusal(err)) return; // warmed below, once the store is back
28127
28384
  console.error(' MCP HTTP eager init failed:', err.message);
28128
28385
  });
28386
+ warmMcp();
28387
+ memoryStoreGate.subscribe((state) => { if (state === 'ready' || state === 'deferred') warmMcp(); });
28129
28388
 
28130
28389
  // A request that names a run (X-Synabun-Terminal) without that run's terminal token is not that run here either
28131
28390
  // (lib/terminal-tokens.js): the MCP server routes it as its own MCP session, so it never shares the run's identity
@@ -28137,6 +28396,13 @@ try {
28137
28396
  // /mcp mount directly" (mcpSessionProofEligible, finding 5); the MCP's own loopback check stays in front of it.
28138
28397
  const mcpRouter = createMcpRoutes({ terminalAuth, sessionProof: { eligible: (req) => mcpSessionProofEligible(req), issue: (sid) => _terminalTokens.issueSession(sid), revoke: (sid) => { endMcpSessionProof(sid); } } });
28139
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
+
28140
28406
  // Keyed path: /mcp/<key> — validates key, then forwards to MCP router
28141
28407
  app.use('/mcp/:key', (req, res, next) => {
28142
28408
  if (req.params.key !== activeMcpKey) {
@@ -29108,6 +29374,7 @@ function persistNativeScheduleOutcome(run, runningInfo = null) {
29108
29374
 
29109
29375
  const schedule = schedules[index];
29110
29376
  schedule.lastRunResult = nativeScheduleResult(run);
29377
+ schedule.lastStopProvenance = run.stopProvenance || null;
29111
29378
  schedule.updatedAt = new Date().toISOString();
29112
29379
  saveSchedules(schedules);
29113
29380
  broadcastSync({ type: 'schedule:updated', schedule });
@@ -29131,6 +29398,7 @@ function persistExecScheduleOutcome(loopState, status, reason = '') {
29131
29398
  const index = schedules.findIndex((schedule) => schedule.id === loopState.scheduledBy);
29132
29399
  if (index === -1) return;
29133
29400
  const schedule = schedules[index];
29401
+ schedule.lastStopProvenance = loopState.stopProvenance || null;
29134
29402
  schedule.lastRunResult = status === 'completed'
29135
29403
  ? 'completed'
29136
29404
  : status === 'stopped'
@@ -29872,6 +30140,7 @@ function noteMoreLoginContextClose(session, sessionId, context = session?.contex
29872
30140
  // Asked before a card's pick is approved: a held run that would refuse it keeps the card open.
29873
30141
  checkHeld: (runId, target, role) => _assistantDispatcher?.heldRouteRefusal?.(runId, target, role) || null,
29874
30142
  declineHeld: (runId, reason) => _assistantDispatcher?.declineRoute?.(runId, { reason }),
30143
+ activeRouteRuns: (sessionId, routeId) => _assistantDispatcher?.activeRouteRuns(sessionId, routeId),
29875
30144
  },
29876
30145
  log: (tag, message) => assistantLog(tag, message),
29877
30146
  clarifier: assistantClarifier,
@@ -29946,6 +30215,7 @@ function noteMoreLoginContextClose(session, sessionId, context = session?.contex
29946
30215
  // The one instance of this server (never a second createCoordinationService in this file): a stop that is not
29947
30216
  // a signal (Restart Server, /api/server/shutdown, an update) closes it at the end of runGracefulShutdown.
29948
30217
  _assistantCoordination = assistantCoordination;
30218
+ await assistantCoordination.ready;
29949
30219
  if (assistantCoordination.degraded) console.warn(`[assistant] coordination store unavailable (${assistantCoordination.degraded.message}): agent events are kept in memory until the next start`);
29950
30220
  }
29951
30221
  // ══ end Agents P2 ══════════════════════════════════════════════════════════════════════════════════════════
@@ -30105,6 +30375,7 @@ function noteMoreLoginContextClose(session, sessionId, context = session?.contex
30105
30375
  .then((m) => m.setTeamContextResolver((runId) => !!teamScheduler.member(runId)))
30106
30376
  .catch((err) => console.warn('[assistant] team tool unavailable (mcp-server needs a build):', err?.message || err));
30107
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');
30108
30379
  teamScheduler.recover().catch((err) => console.warn('[assistant] team recovery failed:', err?.message || err))
30109
30380
  .finally(() => broadcastSync({ type: 'assistant:team-changed', event: 'recovered' }));
30110
30381
  _assistantTeamScheduler = teamScheduler;
@@ -30117,6 +30388,7 @@ function noteMoreLoginContextClose(session, sessionId, context = session?.contex
30117
30388
  // then repair saved routes whose effort their model does not run (idempotent;
30118
30389
  // a provider whose list is not available yet is retried a few times).
30119
30390
  const repairRouteEfforts = async (attempt = 0) => {
30391
+ markActivity('startup:route-efforts');
30120
30392
  const { repairPreferenceEfforts } = await import('./lib/effort-levels.js');
30121
30393
  const cat = await assistantCatalog.full({ force: attempt > 0 });
30122
30394
  const { fixes, unverified } = repairPreferenceEfforts(assistantConfigStore.routing().preferences, cat);
@@ -30347,25 +30619,24 @@ function cleanupClaudeLoopMcpConfig(terminalSessionId) {
30347
30619
  * Each opencode-<sid> dir carries a ~61 MB node_modules; the per-loop cleanup
30348
30620
  * runs on graceful stop and PTY exit, but a server crash/restart (or a PTY that
30349
30621
  * never fired its exit) leaves dirs stranded forever. At boot no loop is live,
30350
- * so anything older than the cutoff is safe to remove. Mirrors the mtime-cutoff
30351
- * rmSync pattern used by cleanupOldUpdaterStages().
30622
+ * so anything older than the cutoff is safe to remove. Removal runs off the main thread even for an entire dependency tree.
30352
30623
  */
30353
- function cleanupStaleLoopConfigs(maxAgeMs = 6 * 60 * 60 * 1000) {
30624
+ async function cleanupStaleLoopConfigs(maxAgeMs = 6 * 60 * 60 * 1000) {
30354
30625
  const dir = resolve(DATA_HOME, 'data', 'loop-configs');
30355
30626
  let removedDirs = 0, removedFiles = 0;
30356
30627
  try {
30357
30628
  if (!existsSync(dir)) return { removedDirs, removedFiles };
30358
30629
  const cutoff = Date.now() - maxAgeMs;
30359
- for (const name of readdirSync(dir)) {
30630
+ for (const name of await fsp.readdir(dir)) {
30360
30631
  const isOpencodeDir = name.startsWith('opencode-');
30361
30632
  const isClaudeCfg = name.startsWith('claude-mcp-') && name.endsWith('.json');
30362
30633
  if (!isOpencodeDir && !isClaudeCfg) continue;
30363
30634
  const full = resolve(dir, name);
30364
30635
  try {
30365
- const st = statSync(full);
30636
+ const st = await fsp.stat(full);
30366
30637
  if (st.mtimeMs >= cutoff) continue;
30367
- if (st.isDirectory()) { rmSync(full, { recursive: true, force: true }); removedDirs++; }
30368
- else { unlinkSync(full); removedFiles++; }
30638
+ if (st.isDirectory()) { await fsp.rm(full, { recursive: true, force: true }); removedDirs++; }
30639
+ else { await fsp.unlink(full); removedFiles++; }
30369
30640
  } catch { /* skip unreadable/racing entries */ }
30370
30641
  }
30371
30642
  if (removedDirs || removedFiles) {
@@ -30951,6 +31222,7 @@ function scanForLeaks() {
30951
31222
 
30952
31223
  let _lastLeakHash = '';
30953
31224
  setInterval(() => {
31225
+ markActivity('timer:session-leaks');
30954
31226
  syncRegistryFromTerminals();
30955
31227
  const leaks = scanForLeaks();
30956
31228
  // Strip ageMs AND description (which embeds age as "Xm old") to prevent
@@ -31012,6 +31284,7 @@ function scanLoopInventory() {
31012
31284
 
31013
31285
  let _lastLoopHash = '';
31014
31286
  setInterval(() => {
31287
+ markActivity('timer:loop-inventory');
31015
31288
  const inventory = scanLoopInventory();
31016
31289
  // Hash on stable fields only (drop minute counters that tick every poll)
31017
31290
  const hash = JSON.stringify({
@@ -32804,9 +33077,27 @@ const extensionBridge = createExtensionBridge({
32804
33077
  log: record => console.log('[extension-bridge]', JSON.stringify(record)),
32805
33078
  onInventory: state => extensionAdapter.sync(state),
32806
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
+ };
32807
33098
  const extensionAdapter = createExtensionAdapter({
32808
33099
  bridge: extensionBridge, sessions: browserSessions, uploadRoot: extensionUploadRoot, dataHome: DATA_HOME,
32809
- caller: browserCaller, ownerPage: browserOwnerPageOnly,
33100
+ caller: browserCaller, ownerPage: browserOwnerPageOnly, evaluateGate: extensionEvaluateGate,
32810
33101
  selected: req => loadBrowserConfig().connectMode === 'extension' && !runMoreLoginPin(browserCaller(req).id),
32811
33102
  });
32812
33103
  // The extension folder the owner loads (DATA_HOME/browser-extension/unpacked): refreshed at start when the bundled
@@ -39219,9 +39510,16 @@ app.post('/api/browser/sessions/:id/upload', async (req, res) => {
39219
39510
  }
39220
39511
  markBrowserActionStarted(req);
39221
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(() => []);
39222
39520
  if (!browserV2Enabled()) await cancellableBrowserDelay(500, req);
39223
39521
  const state = await getBrowserActionState(session, routed, compact);
39224
- res.json({ ok: true, url: state.url, title: state.title });
39522
+ res.json({ ok: true, url: state.url, title: state.title, files });
39225
39523
  } catch (err) {
39226
39524
  res.status(500).json({ error: err.message });
39227
39525
  }
@@ -39502,8 +39800,10 @@ function runLaunchStep(name) {
39502
39800
  const task = LAUNCH_TASKS[name];
39503
39801
  if (!task) return Promise.resolve();
39504
39802
  return _launchQueue(async () => {
39803
+ const endActivity = beginActivity(`launch:${name}`);
39505
39804
  const started = Date.now();
39506
39805
  try { await task(); } catch (error) { console.warn(`[launch-cache] ${name}: ${error?.message || error}`); }
39806
+ finally { endActivity(); }
39507
39807
  const took = Date.now() - started;
39508
39808
  if (took > 2000) console.log(`[launch-cache] ${name} warmed in ${(took / 1000).toFixed(1)} s`);
39509
39809
  await new Promise((done) => { const timer = setTimeout(done, LAUNCH_STEP_GAP_MS); timer.unref?.(); });
@@ -39530,6 +39830,10 @@ function startLaunchWarmup() {
39530
39830
  reloadConfig();
39531
39831
 
39532
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
+ }));
39533
39837
  // Before anything else: the sessions that saved a MoreLogin profile choice (POST /api/morelogin/use) must prove
39534
39838
  // who they are again before that choice is used (retireSavedProfileChoiceOwners).
39535
39839
  try { retireSavedProfileChoiceOwners(); } catch (err) { console.warn(`[morelogin] the owners of the saved profile choices were not retired: ${err.message}`); }
@@ -39547,8 +39851,7 @@ const httpServer = app.listen(PORT, async () => {
39547
39851
 
39548
39852
  // Write embedding model metadata so mismatch can be detected later
39549
39853
  try {
39550
- setKvConfig('embedding_model', EMBEDDING_MODEL);
39551
- setKvConfig('embedding_dims', String(EMBEDDING_DIMS));
39854
+ await saveEmbeddingMetadata();
39552
39855
  } catch {}
39553
39856
 
39554
39857
  // Keep the Start Server launcher (synabun://) pointing at this install even
@@ -39583,20 +39886,32 @@ const httpServer = app.listen(PORT, async () => {
39583
39886
 
39584
39887
  // Gated: an idle tick reads one kv row + one index probe instead of the
39585
39888
  // ~9-query maintenanceStatus() and a BEGIN IMMEDIATE (see lib/memory-timers.js).
39586
- startGatedMemoryMaintenance();
39587
39889
  // The TypeSafe judge backfill runs only here: one runner per store, never in
39588
39890
  // the stdio MCP servers. It is inert until the Judgments tab starts it.
39589
- startJudgeBackfill();
39590
- 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(); });
39591
39896
 
39592
39897
  // Warm the embedding model + vector caches in the background so the first
39593
39898
  // recall/search doesn't pay the 2-5s Transformers.js model load or the
39594
39899
  // initial vector-matrix build.
39595
39900
  setTimeout(() => {
39901
+ markActivity('startup:embeddings');
39596
39902
  warmupEmbeddings()
39597
39903
  .then(() => console.log(' Embeddings: model warmed up'))
39598
39904
  .catch((err) => console.warn(' Embeddings warmup failed:', err.message));
39599
- 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(); });
39600
39915
  }, 500);
39601
39916
 
39602
39917
  // Local profiles still running from before this start (their Chrome outlives the server, as a MoreLogin profile
@@ -39604,6 +39919,7 @@ const httpServer = app.listen(PORT, async () => {
39604
39919
  // was taken meanwhile, that profile's pages fail (never a direct connection); its next start starts it again.
39605
39920
  setTimeout(async () => {
39606
39921
  try {
39922
+ markActivity('startup:local-profiles');
39607
39923
  const adopted = await moreLogin.adoptLocalProfiles();
39608
39924
  if (!adopted.length) return;
39609
39925
  const stuck = adopted.filter((p) => p.relay === 'restart-needed');
@@ -39615,6 +39931,7 @@ const httpServer = app.listen(PORT, async () => {
39615
39931
  // Activation is an explicit user choice in the MoreLogin tab (Default AI browser).
39616
39932
  setTimeout(async () => {
39617
39933
  try {
39934
+ markActivity('startup:morelogin-detection');
39618
39935
  const mlBootCfg = loadBrowserConfig();
39619
39936
  const cfg = mlBootCfg;
39620
39937
  const port = moreLogin.getMoreLoginPort(cfg);
@@ -39628,19 +39945,28 @@ const httpServer = app.listen(PORT, async () => {
39628
39945
  // Reclaim orphaned per-loop config dirs left by crashed/killed loops. At boot
39629
39946
  // no loop is live, so this is the safe choke point to drop multi-GB of stale
39630
39947
  // opencode-<sid> node_modules that never got their per-loop cleanup.
39631
- setTimeout(() => { try { cleanupStaleLoopConfigs(); } catch {} }, 1500);
39948
+ setTimeout(() => {
39949
+ markActivity('startup:loop-config-cleanup');
39950
+ void cleanupStaleLoopConfigs();
39951
+ }, 1500);
39632
39952
 
39633
39953
  // OpenCode serves an earlier SynaBun left running (it crashed, or was killed): found by their records alone and
39634
39954
  // stopped only when they are provably its own and nothing uses them (lib/opencode-serve-records.js). An
39635
39955
  // OpenCode start that comes earlier makes the same look first (and this one then finds nothing left).
39636
- setTimeout(() => { sweepLeftoverOpencodeServes(); }, 1000);
39956
+ setTimeout(() => {
39957
+ markActivity('startup:opencode-sweep');
39958
+ sweepLeftoverOpencodeServes();
39959
+ }, 1000);
39637
39960
  // The cloudflared a crashed server left running (lib/cloudflared/tunnel.js): at once, its old address points here.
39638
39961
  sweepLeftoverTunnels();
39639
39962
 
39640
39963
  // Compare the installed Claude CLI with the release the Agent SDK was built
39641
39964
  // against, once, so an older installation is named in the log before the
39642
39965
  // first session runs on it (checkClaudeCliSkew in lib/claude-model-catalog.js).
39643
- setTimeout(() => { checkClaudeCliSkew(getClaudeBin()).catch(() => {}); }, 1000);
39966
+ setTimeout(() => {
39967
+ markActivity('startup:claude-cli-skew');
39968
+ checkClaudeCliSkew(getClaudeBin()).catch(() => {});
39969
+ }, 1000);
39644
39970
 
39645
39971
  // The lists windows, menus and Settings wait for, read once in the background (see LAUNCH_TASKS above).
39646
39972
  startLaunchWarmup();
@@ -39649,6 +39975,7 @@ const httpServer = app.listen(PORT, async () => {
39649
39975
  // claude follow it); a PC with none, and an app that carries none, gets SynaBun's copy, fetched in the background.
39650
39976
  setTimeout(() => {
39651
39977
  try {
39978
+ markActivity('startup:git-bash');
39652
39979
  gitBash.refresh();
39653
39980
  if (gitBash.status().state === 'missing') gitBash.ensure({ reason: 'first run' });
39654
39981
  // What an earlier run left in the data home (a stopped attempt's work folder, an older version), off the event loop.
@@ -39657,35 +39984,42 @@ const httpServer = app.listen(PORT, async () => {
39657
39984
  }, 2500);
39658
39985
 
39659
39986
  // Warm the session_cache + session_fts tables so the hybrid search has data
39660
- // on first keystroke. The large history scans yield between sessions, and
39987
+ // on first keystroke. A worker indexes Claude, Codex and OpenCode, and
39661
39988
  // a Codex catalog request shares the same refresh with this startup pass.
39662
39989
  setTimeout(async () => {
39663
39990
  const passes = [
39664
39991
  async () => {
39665
39992
  try {
39666
- const claude = await rebuildClaudeCache({ background: true });
39993
+ markActivity('session-cache:claude');
39994
+ const claude = await runSessionJob('claude');
39667
39995
  if (claude.updated > 0) console.log(` Session cache (claude): indexed ${claude.updated}/${claude.sessions}`);
39668
39996
  } catch (err) { console.warn(' Session cache (claude) error:', err.message); }
39669
39997
  },
39670
39998
  async () => {
39671
39999
  try {
40000
+ markActivity('session-cache:codex');
39672
40001
  const codex = await refreshCodexSessionCatalog();
39673
40002
  if (codex.updated > 0) console.log(` Session cache (codex): indexed ${codex.updated}/${codex.sessions}`);
39674
40003
  } catch (err) { console.warn(' Session cache (codex) error:', err.message); }
39675
40004
  },
39676
40005
  async () => {
39677
40006
  try {
39678
- _ocpSessionCacheWarmup = rebuildOpencodeCache({ getOpencodeDb, background: true });
40007
+ markActivity('session-cache:opencode');
40008
+ _ocpSessionCacheWarmup = runSessionJob('opencode', { path: getOpencodeDbPath() });
39679
40009
  const oc = await _ocpSessionCacheWarmup;
39680
40010
  if (oc.updated > 0) console.log(` Session cache (opencode): indexed ${oc.updated}/${oc.sessions}`);
39681
40011
  } catch (err) { console.warn(' Session cache (opencode) error:', err.message); }
39682
40012
  finally { _ocpSessionCacheWarmup = null; }
39683
40013
  },
39684
- () => {
39685
- const agy = refreshAntigravityCatalog({ force: true });
40014
+ async () => {
40015
+ markActivity('session-cache:antigravity');
40016
+ const agy = await refreshAntigravityCatalog({ force: true });
39686
40017
  if (agy?.updated > 0) console.log(` Session cache (antigravity): indexed ${agy.updated}/${agy.sessions}`);
39687
40018
  // Runs and brains end on their own: their conversations are picked up by this pass, every five minutes.
39688
- setInterval(() => refreshAntigravityCatalog({ force: true }), 5 * 60 * 1000).unref?.();
40019
+ setInterval(() => {
40020
+ markActivity('session-cache:antigravity');
40021
+ refreshAntigravityCatalog({ force: true });
40022
+ }, 5 * 60 * 1000).unref?.();
39689
40023
  },
39690
40024
  ];
39691
40025
  for (const pass of passes) {
@@ -39711,6 +40045,7 @@ const httpServer = app.listen(PORT, async () => {
39711
40045
  // already self-healing via addHookToSettings; this catches damage from
39712
40046
  // previous versions of the install flow.
39713
40047
  try {
40048
+ markActivity('startup:hooks');
39714
40049
  const dedupStats = dedupeAllSettingsHooks();
39715
40050
  if (dedupStats.removed > 0 || dedupStats.repaired > 0 || dedupStats.matchers > 0) {
39716
40051
  const bits = [];
@@ -39743,6 +40078,7 @@ const httpServer = app.listen(PORT, async () => {
39743
40078
  // wait is for the rules lock another SynaBun process on this data home may
39744
40079
  // hold (2 s at most: then the installer logs one line and this boot skips it).
39745
40080
  try {
40081
+ markActivity('startup:rules');
39746
40082
  const rules = rulesetInstaller.reconcile();
39747
40083
  if (rules.updated.length) console.log(` Rules: updated to ${rules.notice?.to || 'the current version'} for ${rules.updated.join(', ')}`);
39748
40084
  if (rules.optedOut.length) console.log(` Rules: no longer managed for ${rules.optedOut.join(', ')} (the installed copy was removed)`);
@@ -39842,7 +40178,8 @@ const httpServer = app.listen(PORT, async () => {
39842
40178
  // OpenCode panel, Settings) see providers/models immediately without the
39843
40179
  // user having to click Start each time.
39844
40180
  try {
39845
- const ready = await ensureOpencodeServer();
40181
+ markActivity('startup:opencode-serve');
40182
+ const ready = await startOpencodeAtBoot(() => ensureOpencodeServer(), () => _ocpStartRefusal);
39846
40183
  if (ready) console.log(` OpenCode: auto-started on :${_ocpPort}`);
39847
40184
  else console.log(' OpenCode: auto-start skipped (binary missing or failed to launch)');
39848
40185
  } catch (err) {
@@ -40556,6 +40893,7 @@ const SERVER_START_TIME = Date.now();
40556
40893
  const RESUME_GRACE_PERIOD_MS = 120_000; // 2 min — don't delete snapshot before client can check
40557
40894
 
40558
40895
  function saveSessionSnapshot() {
40896
+ markActivity('timer:session-snapshot');
40559
40897
  const sessions = [];
40560
40898
  const seen = new Set(); // dedup — avoid resuming same Claude session twice
40561
40899