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 { mayEndSuspendedRun, shutdownStopReason, stampStopProvenance } from './worker-stop.js';
1
2
  import { isolatedServeFailure } from './opencode-launch-error.js';
2
3
  import { retainExternalRefs } from './mcp-external-servers.js';
3
4
  import { storedToolList, toolListRecord, readStoredToolListRecord } from './tool-lists.js';
@@ -59,6 +60,7 @@ function rawDescriptor(record) {
59
60
  updatedAt: record.updatedAt,
60
61
  completedAt: record.completedAt || null,
61
62
  stoppedReason: record.stoppedReason || null,
63
+ ...(record.stopProvenance && { stopProvenance: record.stopProvenance }),
62
64
  browserSessionId: record.browserSessionId || null,
63
65
  browserTabId: record.browserTabId || null,
64
66
  scheduleId: record.scheduleId || null,
@@ -310,6 +312,7 @@ export class NativeLoopRuntime {
310
312
  record.stoppedReason = 'server_restart';
311
313
  record.completedAt = record.completedAt || iso(this.now());
312
314
  record.updatedAt = iso(this.now());
315
+ record.stopProvenance = stampStopProvenance('server_restart', record.stopProvenance, record.completedAt);
313
316
  const state = this._readState(record.runId);
314
317
  if (state) {
315
318
  this._writeState(record.runId, {
@@ -318,6 +321,7 @@ export class NativeLoopRuntime {
318
321
  pending: false,
319
322
  completedAt: record.completedAt,
320
323
  stoppedReason: 'server_restart',
324
+ stopProvenance: record.stopProvenance,
321
325
  });
322
326
  }
323
327
  }
@@ -398,7 +402,7 @@ export class NativeLoopRuntime {
398
402
  _writeTerminalState(record, patch) {
399
403
  try {
400
404
  const state = this._readState(record.runId);
401
- if (state) this._writeState(record.runId, { ...state, ...patch });
405
+ if (state) this._writeState(record.runId, { ...state, ...patch, ...(record.stopProvenance && { stopProvenance: record.stopProvenance }) });
402
406
  } catch (error) {
403
407
  this.log(record.runId, 'native:state-write-error', error?.message || String(error));
404
408
  }
@@ -635,6 +639,7 @@ export class NativeLoopRuntime {
635
639
  setTurnState: (turnState) => this.setTurnState(runId, turnState),
636
640
  setPendingRequests: (requests) => this.setPendingRequests(runId, requests),
637
641
  setOutcome: (outcome) => this.setOutcome(runId, outcome),
642
+ noteTabClose: provenance => { if (!record.stopping) record.stopProvenance = provenance; },
638
643
  readState: () => this._readState(runId),
639
644
  })
640
645
  : adapter;
@@ -788,6 +793,7 @@ export class NativeLoopRuntime {
788
793
  record.status = 'interrupted';
789
794
  record.stoppedReason = reason || record.suspendReason || 'server_restart';
790
795
  record.completedAt = iso(this.now());
796
+ record.stopProvenance = stampStopProvenance(record.stoppedReason, { actor: 'server', action: 'resume_refused' }, record.completedAt);
791
797
  if (error) record.error = scrubTokenText(String(error));
792
798
  this._writeTerminalState(record, { active: false, pending: false, completedAt: record.completedAt, stoppedReason: record.stoppedReason, ...(error ? { error: record.error } : {}) });
793
799
  this._releaseRuntimeRefs(record);
@@ -815,8 +821,10 @@ export class NativeLoopRuntime {
815
821
  try { await record.adapter?.dispose?.({ preserveSession: true, terminate: true }); } catch {}
816
822
  // A suspended run has no process: nothing may act as it until its resume gives the new process a new token.
817
823
  try { this.terminalTokens?.revoke?.(runId); } catch { /* the suspension goes on */ }
818
- this._releaseRuntimeRefs(record, { turnState: 'suspended' });
819
824
  record.stopping = false;
825
+ // A person stopped it while its CLI was ending: that stop already ended the record.
826
+ if (record.status !== 'suspended') return true;
827
+ this._releaseRuntimeRefs(record, { turnState: 'suspended' });
820
828
  this._emit('sidepanel:run-updated', record, { reason: 'suspended' });
821
829
  return true;
822
830
  }
@@ -963,6 +971,7 @@ export class NativeLoopRuntime {
963
971
  if (error?.code) { const safe = isolatedServeFailure(error); record.errorCode = safe.code; record.offenders = safe.offenders; }
964
972
  record.stoppedReason = reason;
965
973
  record.completedAt = iso(this.now());
974
+ if (record.status === 'interrupted') record.stopProvenance = stampStopProvenance(reason, null, record.completedAt);
966
975
  if (record._resolveIdentity) { record._resolveIdentity(null); record._resolveIdentity = null; }
967
976
  try { record.startupAbortController?.abort(reason); } catch {}
968
977
  if (record._cancelStartup) { record._cancelStartup(reason); record._cancelStartup = null; }
@@ -976,11 +985,22 @@ export class NativeLoopRuntime {
976
985
 
977
986
  /**
978
987
  * `terminate` (a server shutdown): the provider's process is ended at once (the Claude adapter's dispose), never
979
- * left to finish its tool call after the server is gone. A suspended run (waiting for its resume) ends as stopped.
988
+ * left to finish its tool call after the server is gone. A suspended run (waiting for its resume) ends as stopped
989
+ * only for a caller that may end it (worker-stop.js mayEndSuspendedRun); for any other this returns false and it
990
+ * stays suspended. A caller that names no reason is recorded as unknown, never as the user.
980
991
  */
981
- async stop(runId, reason = 'user', { terminate = false } = {}) {
992
+ async stop(runId, reason = 'unknown', { terminate = false, stopProvenance = null } = {}) {
982
993
  const record = this.records.get(runId);
983
- if (record?.status === 'suspended' && !record.stopping) {
994
+ if (!record || !LIVE_STATUSES.has(record.status)) return false;
995
+ // `stopping` on a suspended record is its CLI still ending: a person's stop in that moment counts.
996
+ if (record.stopping && record.status !== 'suspended') return false;
997
+ const provenance = stampStopProvenance(reason, stopProvenance, iso(this.now()));
998
+ if (record.status === 'suspended' && !mayEndSuspendedRun(provenance)) {
999
+ this.log(runId, 'native:stop-refused', 'a suspended run stays suspended: this caller may not end it', { reason, stopProvenance: provenance });
1000
+ return false;
1001
+ }
1002
+ record.stopProvenance = provenance;
1003
+ if (record.status === 'suspended') {
984
1004
  this._clearHold(record);
985
1005
  record.status = 'stopped';
986
1006
  record.stoppedReason = reason;
@@ -991,7 +1011,6 @@ export class NativeLoopRuntime {
991
1011
  try { await this.onFinish(cleanDescriptor(record)); } catch {}
992
1012
  return true;
993
1013
  }
994
- if (!record || !['starting', 'running'].includes(record.status) || record.stopping) return false;
995
1014
  record.stopping = true;
996
1015
  clearTimeout(record.timer);
997
1016
  record.status = 'stopped';
@@ -1134,7 +1153,9 @@ export class NativeLoopRuntime {
1134
1153
  const kept = new Set((Array.isArray(keep) ? keep : []).map(String));
1135
1154
  await Promise.allSettled([...this.records.values()]
1136
1155
  .filter((record) => ['starting', 'running'].includes(record.status))
1137
- .map((record) => (kept.has(record.runId) ? this.suspend(record.runId, reason) : this.stop(record.runId, reason, { terminate: true }))));
1156
+ .map((record) => (kept.has(record.runId)
1157
+ ? this.suspend(record.runId, reason)
1158
+ : this.stop(record.runId, shutdownStopReason(reason), { terminate: true, stopProvenance: { actor: 'server', action: 'shutdown', cause: String(reason) } }))));
1138
1159
  for (const timer of this._holdTimers.values()) clearTimeout(timer);
1139
1160
  this._holdTimers.clear();
1140
1161
  this._persistLedger({ force: true });
@@ -45,7 +45,9 @@ export async function reconcilePreflightProfiles(profiles, list, { requested = [
45
45
  log('MoreLogin local API unavailable (MORELOGIN_UNREACHABLE) and no MoreLogin browser processes found; continuing OpenCode build verification without profile port exclusions. Native browser attachment still requires verified serves.');
46
46
  return [];
47
47
  }
48
- throw profileError('MORELOGIN_LIST_UNREADABLE', `MoreLogin profile listing failed: ${moreLoginFailureDetail(error)}. OpenCode build verification has not started.`);
48
+ // `transient`: the read got no answer (a deadline, a reset), which says nothing about the profiles.
49
+ throw Object.assign(profileError('MORELOGIN_LIST_UNREADABLE', `MoreLogin profile listing failed: ${moreLoginFailureDetail(error)}. OpenCode build verification has not started.`),
50
+ { transient: error?.code === 'MORELOGIN_UNREACHABLE' });
49
51
  }
50
52
  if (!Array.isArray(live) || live.moreloginError || live.some(p => !p?.id)) throw profileError('MORELOGIN_LIST_UNREADABLE', 'MoreLogin profile listing is malformed or incomplete.');
51
53
  const byId = new Map(live.map(p => [String(p.id), p]));
@@ -58,6 +60,21 @@ export async function reconcilePreflightProfiles(profiles, list, { requested = [
58
60
  });
59
61
  }
60
62
 
63
+ /**
64
+ * OpenCode's start at server boot. A MoreLogin read that got no answer while the server is still busy starting is no
65
+ * verdict: the start is tried again once things settle, a bounded number of times. Each try is a whole start with its
66
+ * own single bounded read, and no start lock is held while waiting. Any other refusal stands at once.
67
+ */
68
+ export async function startOpencodeAtBoot(start, lastRefusal, { attempts = 2, delayMs = 5000,
69
+ wait = (ms) => new Promise((done) => setTimeout(done, ms)) } = {}) {
70
+ let ready = await start();
71
+ for (let attempt = 0; !ready && attempt < attempts && lastRefusal()?.transient === true; attempt += 1) {
72
+ await wait(delayMs);
73
+ ready = await start();
74
+ }
75
+ return ready;
76
+ }
77
+
61
78
  export async function preflightExcludedPorts(profiles, readDetail) {
62
79
  const ports = new Set();
63
80
  for (const profile of profiles) {
@@ -47,6 +47,11 @@ export const NATIVE_SERVE_MIN_VERSION = '2.1.0';
47
47
  export const NATIVE_WATCH_MS = 15_000;
48
48
  // How long a watch pass waits for a foreign serve that failed only by not answering to be confirmed gone (ensureWatch).
49
49
  export const NATIVE_EXIT_GRACE_MS = 3_000;
50
+ // How long a foreign serve that passed keeps its verdict while its executable cannot be asked its version (a check
51
+ // that could not run on a busy machine, not a finding about the serve), counted from the last version that was read.
52
+ export const NATIVE_VERSION_GRACE_MS = 60_000;
53
+ // How long a watch pass waits for a look that is still under way before it treats "not finished" as a failure.
54
+ export const NATIVE_CHECK_PATIENCE_MS = 20_000;
50
55
 
51
56
  /** "2.3.0", "v2.3.0", "opencode v2.3.0" → "2.3.0"; null for anything else (a prerelease, four parts, extra words). */
52
57
  export function nativeServeVersionOf(version) {
@@ -292,14 +297,27 @@ const sameIdentity = (a, b) => (!a && !b) || (!!a && !!b && a.realpath === b.rea
292
297
  // No shell, no server launch and bounded output/time. A foreign listener's version is not public over HTTP when
293
298
  // its authentication works; ask the executable the OS identified instead. Interpreters cannot identify the script
294
299
  // they run this way, so those foreign serves fail closed rather than treating `node --version` as OpenCode.
295
- export function readOpencodeBinaryVersion(identity, { run = execFile } = {}) {
300
+ // How long `--version` of an OpenCode executable may take: a first, quick try, then one patient one. The quick limit
301
+ // alone failed healthy checks: on 2026-11-21 a server whose loop was held for 2.8 s (and whose disk was busy with a
302
+ // backup) could not read a version in 2 s, and the serve it belonged to cost a live browser context.
303
+ export const NATIVE_VERSION_TIMEOUTS_MS = Object.freeze([2_000, 10_000]);
304
+
305
+ export function readOpencodeBinaryVersion(identity, { run = execFile, timeouts = NATIVE_VERSION_TIMEOUTS_MS } = {}) {
296
306
  if (!identity?.native || !isOpencodePath(identity.realpath)) return Promise.resolve(null);
297
- return new Promise((resolve) => {
307
+ const once = (timeout) => new Promise((resolve) => {
298
308
  try {
299
- run(identity.realpath, ['--version'], { timeout: 2000, maxBuffer: 16_384, windowsHide: true },
309
+ run(identity.realpath, ['--version'], { timeout, maxBuffer: 16_384, windowsHide: true },
300
310
  (error, stdout) => resolve(error ? null : nativeServeVersionOf(stdout)?.text || null));
301
311
  } catch { resolve(null); }
302
312
  });
313
+ // An answer that is not a version is tried again too: a timer that fired late cuts the output off.
314
+ return (async () => {
315
+ for (const timeout of timeouts) {
316
+ const version = await once(timeout);
317
+ if (version) return version;
318
+ }
319
+ return null;
320
+ })();
303
321
  }
304
322
  const INTERPRETER = /^(?:node|nodejs|bun|deno)(?:\.exe)?$/i;
305
323
  const exited = (proc) => !proc || proc.exitCode != null || proc.signalCode != null;
@@ -314,7 +332,8 @@ export function createNativeServeBoundary({ probe = probeOpencodeServe, identify
314
332
  scan = scanOpencodeServes, readGeneration = readServeGeneration, portListeners = listPortListenersAsync, pidAlive = pidExists,
315
333
  signalPid = (pid, signal) => process.kill(pid, signal), revoke = revokeNativeContext, platform = process.platform,
316
334
  now = Date.now, retryMs = 5_000, termMs = 3_000, killMs = 3_000, gonePollMs = 100, refreshMs = 8_000, foreignTtlMs = 5 * 60_000,
317
- watchMs = NATIVE_WATCH_MS, exitGraceMs = NATIVE_EXIT_GRACE_MS, exitPollMs = 250, preflight = null, log = () => {} } = {}) {
335
+ watchMs = NATIVE_WATCH_MS, exitGraceMs = NATIVE_EXIT_GRACE_MS, exitPollMs = 250, versionGraceMs = NATIVE_VERSION_GRACE_MS,
336
+ checkPatienceMs = NATIVE_CHECK_PATIENCE_MS, preflight = null, log = () => {} } = {}) {
318
337
  const processes = new Map();
319
338
  // Process-local admission evidence: persisted diagnostic verdicts and ordinary runtime passes cannot grant it.
320
339
  const builds = new Map(), buildChecks = new Map();
@@ -499,7 +518,18 @@ export function createNativeServeBoundary({ probe = probeOpencodeServe, identify
499
518
  // and a version change must invalidate the verdict even when those two fields stayed the same.
500
519
  const cacheKey = identity && policy.ok ? `${key}|${serve.executable}|${binaryKey(identity, policy.version)}` : null;
501
520
  const v = rec?.verdict;
502
- if (cacheKey && rec?.cacheKey === cacheKey && v && now() - v.at < foreignTtlMs && !(v.transient && now() - v.at >= retryMs)) return v;
521
+ // The executable gave no version at all (readVersion already tried twice): a check that could not run, which says
522
+ // nothing about the serve. One that passed as this very process (the key) started from this very file keeps its
523
+ // verdict for `versionGraceMs` since its version was last read; after that it fails as any unreadable version.
524
+ if (identity && version == null && v?.ok && sameIdentity(identity, rec.identity) && now() - (rec.versionAt || 0) < versionGraceMs) {
525
+ if (!rec.versionLate) log(`OpenCode serve pid ${serve.pid} (${serve.executable || '?'}), not started by SynaBun: its executable did not answer --version in time; the verdict it passed with is kept for up to ${Math.round(versionGraceMs / 1000)} s while it is asked again`);
526
+ rec.versionLate = true;
527
+ return v;
528
+ }
529
+ if (cacheKey && rec?.cacheKey === cacheKey && v && now() - v.at < foreignTtlMs && !(v.transient && now() - v.at >= retryMs)) {
530
+ if (v.ok) { rec.versionAt = now(); rec.versionLate = false; }
531
+ return v;
532
+ }
503
533
  if (!rec) { rec = { serve, verdict: null, probing: null }; foreign.verdicts.set(key, rec); }
504
534
  rec.serve = serve;
505
535
  rec.cacheKey = cacheKey;
@@ -537,6 +567,10 @@ export function createNativeServeBoundary({ probe = probeOpencodeServe, identify
537
567
  verdict.version = policy.version;
538
568
  verdict.checks.push(...extra);
539
569
  rec.verdict = verdict;
570
+ // What a later pass may lean on when the executable cannot be asked (versionGraceMs): the file and the moment.
571
+ rec.identity = verdict.ok ? identity : null;
572
+ rec.versionAt = verdict.ok ? now() : 0;
573
+ rec.versionLate = false;
540
574
  if (!verdict.ok) log(`OpenCode serve pid ${serve.pid} port ${verdict.port ?? '?'} (${serve.executable || serve.command || '?'}), not started by SynaBun, failed the runtime check "${verdict.failed}": ${verdict.detail}`);
541
575
  return verdict;
542
576
  })().finally(() => { rec.probing = null; });
@@ -647,15 +681,42 @@ export function createNativeServeBoundary({ probe = probeOpencodeServe, identify
647
681
  }
648
682
  }
649
683
 
684
+ // A watch pass that is only late: its look is still under way (lsof, --version or a probe on a busy machine), or the
685
+ // list of listening processes could not be read once. Neither is a finding. The pass waits for the look, bounded by
686
+ // `checkPatienceMs` in all, and reads the list once more; what is still unfinished or unreadable then is revoked as
687
+ // before (fail closed). A finished look that found something is never waited on.
688
+ const onlyChecking = (list) => list.length > 0 && list.every((o) => o.reason === 'foreign-checking');
689
+ async function settledForeignOffenders() {
690
+ const end = now() + Math.max(0, checkPatienceMs);
691
+ let rescanned = false;
692
+ for (;;) {
693
+ if (foreign.result && !foreign.result.ok && !foreign.scanning) {
694
+ if (rescanned || now() >= end) return { scanFailed: true, bad: [] };
695
+ rescanned = true;
696
+ await within(refreshForeign(), Math.max(1, end - now()));
697
+ continue;
698
+ }
699
+ const bad = foreignOffenders(new Set());
700
+ if (!onlyChecking(bad) || now() >= end) return { scanFailed: !foreign.result?.ok && !foreign.scanning, bad };
701
+ const pending = [foreign.scanning, ...[...foreign.verdicts.values()].map((rec) => rec.probing)].filter(Boolean);
702
+ await within(pending.length ? Promise.allSettled(pending) : defaultSleep(exitPollMs), Math.max(1, Math.min(end - now(), pending.length ? end - now() : exitPollMs)));
703
+ }
704
+ }
705
+
706
+ let watching = false;
650
707
  function ensureWatch() {
651
708
  if (watchTimer || !(watchMs > 0)) return;
652
709
  watchTimer = setInterval(() => {
653
710
  if (!attachedContexts().length) { clearInterval(watchTimer); watchTimer = null; return; }
711
+ // One pass at a time: a patient pass must not be overtaken by the next tick's impatient one.
712
+ if (watching) return;
713
+ watching = true;
654
714
  refresh().then(async () => {
655
- if (!foreign.result?.ok) { revokeAll('the OpenCode listening processes could not be verified'); return; }
656
- const bad = await withoutExitingForeign(foreignOffenders(new Set()));
715
+ const settled = await settledForeignOffenders();
716
+ if (settled.scanFailed) { revokeAll('the OpenCode listening processes could not be verified'); return; }
717
+ const bad = await withoutExitingForeign(settled.bad);
657
718
  if (bad.length) revokeAll(`an OpenCode serve SynaBun did not start could not be verified (pid ${bad[0].pid || '?'}, port ${bad[0].port || '?'}, check "${bad[0].check || bad[0].reason}")`);
658
- }).catch(() => {});
719
+ }).catch(() => {}).finally(() => { watching = false; });
659
720
  }, watchMs);
660
721
  watchTimer.unref?.();
661
722
  }
@@ -10,6 +10,8 @@
10
10
  // out what none of them reads (credentials and request options included).
11
11
  // Pure: no I/O, so the route, the catalog's in-process read and the tests share it.
12
12
 
13
+ import { applyOpencodeCostOverride } from './assistant-pricing.js';
14
+
13
15
  const PROVIDER_FIELDS_LEFT_OUT = new Set(['env', 'options', 'key', 'npm', 'api']);
14
16
  const MODEL_FIELDS_LEFT_OUT = new Set(['options', 'headers', 'provider']);
15
17
 
@@ -24,20 +26,29 @@ function providersOf(data) {
24
26
  return data?.all && typeof data.all === 'object' ? Object.values(data.all) : [];
25
27
  }
26
28
 
27
- function slimModel(model) {
29
+ function slimModel(model, providerId = null, modelId = null) {
28
30
  if (!model || typeof model !== 'object') return model;
29
31
  const out = {};
30
32
  for (const [key, value] of Object.entries(model)) if (!MODEL_FIELDS_LEFT_OUT.has(key)) out[key] = value;
33
+ const pid = providerId || model.providerID || null;
34
+ const mid = model.id || model.modelID || modelId || null;
35
+ // Like the catalog and the OpenCode 2 client: an overridden model gets its price even when the
36
+ // upstream row has no cost; a row with neither keeps no cost key.
37
+ if (pid && mid) {
38
+ const cost = applyOpencodeCostOverride(pid, mid, out.cost);
39
+ if (cost !== undefined) out.cost = cost;
40
+ }
31
41
  return out;
32
42
  }
33
43
 
34
44
  function slimProvider(provider) {
35
45
  const out = {};
46
+ const pid = provider?.id || provider?.providerID || null;
36
47
  for (const [key, value] of Object.entries(provider || {})) {
37
48
  if (PROVIDER_FIELDS_LEFT_OUT.has(key)) continue;
38
49
  if (key === 'models') {
39
- if (Array.isArray(value)) out.models = value.map(slimModel);
40
- else if (value && typeof value === 'object') out.models = Object.fromEntries(Object.entries(value).map(([id, model]) => [id, slimModel(model)]));
50
+ if (Array.isArray(value)) out.models = value.map((model) => slimModel(model, pid));
51
+ else if (value && typeof value === 'object') out.models = Object.fromEntries(Object.entries(value).map(([id, model]) => [id, slimModel(model, pid, id)]));
41
52
  else out.models = value;
42
53
  continue;
43
54
  }
@@ -34,6 +34,8 @@
34
34
  import { OPENCODE_SESSION_TABLES } from './opencode-db-schema.js';
35
35
  import { opencodeMcpServerEntry } from './opencode-config.js';
36
36
  import { storedToolList } from './tool-lists.js';
37
+ import { statSync } from 'node:fs';
38
+ import { LOCATION_MISSING_CODE, locationNotFoundMessage } from '../public/shared/ocp-v2/ocp-v2-location-logic.js';
37
39
 
38
40
  // Types answered by the switch in server.js.
39
41
  export const OPENCODE_V2_WS_INLINE_TYPES = Object.freeze([
@@ -89,13 +91,37 @@ export function canonicalizeOpencodeV2Message(msg) {
89
91
  return null;
90
92
  }
91
93
 
94
+ // ── A folder that does not exist ────────────────────────────────────────────
95
+ // OpenCode 2 creates a session in a folder that does not exist and then
96
+ // refuses every prompt of it (404 "Location not found: <folder>"); a session is
97
+ // bound to its folder for good. So a request that starts work in a folder is
98
+ // refused here, in OpenCode's own words (the panel reads one sentence for both:
99
+ // public/shared/ocp-v2/ocp-v2-location-logic.js), before a session is made
100
+ // that can never run or a serve is started for a turn that cannot begin.
101
+ export const OPENCODE_V2_WS_FOLDER_TYPES = Object.freeze(['session:create', 'message:send', 'command:run', 'session:shell']);
102
+
103
+ /**
104
+ * Whether `folder` is certainly not a folder that exists: nothing is there, or
105
+ * something that is not a folder. A folder that cannot be asked (no permission,
106
+ * a disk that does not answer) is not called gone: OpenCode decides.
107
+ */
108
+ export function folderIsGone(folder, stat = statSync) {
109
+ try {
110
+ return !stat(folder).isDirectory();
111
+ } catch (err) {
112
+ return err?.code === 'ENOENT' || err?.code === 'ENOTDIR';
113
+ }
114
+ }
115
+
92
116
  /**
93
117
  * Everything that must hold before a request is answered, in one place so it
94
118
  * can be tested: a canonical session id, no write while history is being
95
119
  * cleared, and the native-automation ownership rules. Returns null to let the
96
120
  * request through, or `{ status, error }`.
97
121
  * ctx: { historyClearing, historyWriteTypes, nativeMutationTypes,
98
- * protectedRunFor(sessionId), ownsRun(run) }
122
+ * protectedRunFor(sessionId), ownsRun(run),
123
+ * folderGone(folder) } folderIsGone, or absent to check no folder
124
+ * A refusal for a folder that is gone also carries `code` (LOCATION_MISSING).
99
125
  */
100
126
  export function guardOpencodeV2Request(msg, ctx = {}) {
101
127
  const malformed = canonicalizeOpencodeV2Message(msg);
@@ -111,6 +137,10 @@ export function guardOpencodeV2Request(msg, ctx = {}) {
111
137
  if (protectedRun && ctx.nativeMutationTypes?.has(type)) {
112
138
  return { status: 409, error: 'Stop the native automation before modifying its session' };
113
139
  }
140
+ const folder = OPENCODE_V2_WS_FOLDER_TYPES.includes(type) ? directoryOf(msg) : undefined;
141
+ if (folder && ctx.folderGone?.(folder)) {
142
+ return { status: 404, code: LOCATION_MISSING_CODE, error: locationNotFoundMessage(folder) };
143
+ }
114
144
  return null;
115
145
  }
116
146
 
@@ -26,6 +26,7 @@
26
26
 
27
27
  import { basicAuthHeader } from './opencode-protocol.js';
28
28
  import { opencodeMcpServerEntry } from './opencode-config.js';
29
+ import { applyOpencodeCostOverride } from './assistant-pricing.js';
29
30
  import {
30
31
  answersToForm,
31
32
  createEventTranslator,
@@ -446,7 +447,7 @@ export function createOpencode2Client({ baseUrl, password, fetchImpl = globalThi
446
447
  output: flags(output),
447
448
  interleaved: false,
448
449
  },
449
- cost: { input: Number(cost.input) || 0, output: Number(cost.output) || 0, cache: { read: Number(cost.cache?.read) || 0, write: Number(cost.cache?.write) || 0 } },
450
+ cost: applyOpencodeCostOverride(str(model.providerID), str(model.id), { input: Number(cost.input) || 0, output: Number(cost.output) || 0, cache: { read: Number(cost.cache?.read) || 0, write: Number(cost.cache?.write) || 0 } }),
450
451
  limit: { context: Number(model.limit?.context) || 0, ...(model.limit?.input ? { input: Number(model.limit.input) } : {}), output: Number(model.limit?.output) || 0 },
451
452
  status: str(model.status) || 'active',
452
453
  options: {},
@@ -0,0 +1,122 @@
1
+ // What Settings → Memory shows beside the recall controls (GET /api/recall-impact), read off the server's thread.
2
+ //
3
+ // The route ran two aggregates on the server's own connection: memories grouped by importance with the average
4
+ // length of content, tags and related files, and the count and average lengths of every session chunk. Both read
5
+ // every row whole, because in a row the vector and the content come before the columns they measure: on the owner's
6
+ // store (2.6 GB, 35k memories, about 150k session chunks) the second one held the only thread for 5,287 ms
7
+ // (2026-11-21; the stall line named `timer:memory-maintenance`, the label that had marked last, not the cause).
8
+ //
9
+ // Here the same numbers are read on the retrieval reader's thread (mcp-server retrieval-reader.ts: a read-only
10
+ // connection of its own) in slices of `sliceRows` rows by rowid, each a statement of a few milliseconds:
11
+ // - recall's own reads on that thread take their turn between two slices instead of waiting for a whole scan;
12
+ // - a shutdown never waits for a long native call;
13
+ // - when the reader cannot serve a slice, readRows runs that one slice on the caller's connection: still short,
14
+ // and the event loop gets a turn before the next one.
15
+ // The sums are added here and divided once, which is exactly CAST(AVG(x) AS INTEGER) of the old statements: SQLite
16
+ // averages integers as their exact sum over the count, and the cast drops the fraction.
17
+ //
18
+ // The slices are not one snapshot: a row written while the read is under way is counted if its rowid is still
19
+ // ahead, and every row is counted at most once. The answer is kept for `freshMs` (a minute) per open connection, so
20
+ // a count or an average on the Settings page can be up to a minute behind the store, plus the length of one read.
21
+ // Nothing decides anything from these numbers: they are the token estimate the page shows. Requests that arrive
22
+ // while a read is under way share it; a failed read is never kept.
23
+ import { readRows } from '../../mcp-server/dist/services/retrieval-reader.js';
24
+ import { getDb } from './db.js';
25
+ import { isMemoryStoreRefusal } from './memory-store-gate.js';
26
+
27
+ const MEMORY_SLICE = `
28
+ SELECT importance, live, COUNT(*) AS cnt, SUM(len) AS len, SUM(tags_len) AS tags_len, SUM(files_len) AS files_len, MAX(r) AS last
29
+ FROM (SELECT rowid AS r, importance, trashed_at IS NULL AS live, LENGTH(content) AS len,
30
+ CASE WHEN tags IS NOT NULL AND tags != '[]' THEN LENGTH(tags) ELSE 0 END AS tags_len,
31
+ CASE WHEN related_files IS NOT NULL AND related_files != '[]' THEN LENGTH(related_files) ELSE 0 END AS files_len
32
+ FROM memories WHERE rowid > ? ORDER BY rowid LIMIT ?)
33
+ GROUP BY importance, live`;
34
+
35
+ const CHUNK_SLICE = `
36
+ SELECT COUNT(*) AS count, MAX(r) AS last, COUNT(summary_len) AS summaries, SUM(summary_len) AS summary_len, SUM(details_len) AS details_len
37
+ FROM (SELECT rowid AS r, LENGTH(summary) AS summary_len,
38
+ COALESCE(LENGTH(tools_used), 0) + COALESCE(LENGTH(files_modified), 0) + COALESCE(LENGTH(related_memory_ids), 0) AS details_len
39
+ FROM session_chunks WHERE rowid > ? ORDER BY rowid LIMIT ?)`;
40
+
41
+ /** CAST(AVG(x) AS INTEGER) from the sum and the count of the values that were not NULL; NULL when there were none. */
42
+ const average = (sum, count) => (count > 0 ? Math.trunc(Number(sum) / count) : null);
43
+
44
+ // Between two slices the event loop gets a turn of its own. A slice the reader served already gave it one; a slice
45
+ // that ran on the caller's connection (the reader's fallback) resolved in the same turn, and the next one would
46
+ // follow it at once: the whole scan in one turn again, a slice at a time.
47
+ const turn = () => new Promise((resolve) => { setImmediate(resolve); });
48
+
49
+ /** Memories that are not in the trash, by importance: the old GROUP BY, slice by slice. */
50
+ async function memoryRows(read, sliceRows) {
51
+ const groups = new Map();
52
+ for (let after = 0; ;) {
53
+ const slice = await read(MEMORY_SLICE, [after, sliceRows]);
54
+ let seen = 0;
55
+ for (const row of slice) {
56
+ seen += row.cnt;
57
+ after = Math.max(after, row.last);
58
+ if (!row.live) continue;
59
+ const group = groups.get(row.importance) ?? { cnt: 0, len: 0, tags_len: 0, files_len: 0 };
60
+ group.cnt += row.cnt; group.len += Number(row.len ?? 0); group.tags_len += row.tags_len; group.files_len += row.files_len;
61
+ groups.set(row.importance, group);
62
+ }
63
+ if (seen < sliceRows) break;
64
+ await turn();
65
+ }
66
+ return [...groups.entries()].sort(([a], [b]) => a - b).map(([importance, group]) => ({
67
+ importance, cnt: group.cnt,
68
+ avg_len: average(group.len, group.cnt), avg_tags_len: average(group.tags_len, group.cnt), avg_files_len: average(group.files_len, group.cnt),
69
+ }));
70
+ }
71
+
72
+ /** Count and average lengths of every session chunk: the old single aggregate, slice by slice. */
73
+ async function chunkStats(read, sliceRows) {
74
+ const total = { count: 0, summaries: 0, summary_len: 0, details_len: 0 };
75
+ for (let after = 0; ;) {
76
+ const [slice] = await read(CHUNK_SLICE, [after, sliceRows]);
77
+ if (!slice?.count) break;
78
+ total.count += slice.count; total.summaries += slice.summaries;
79
+ total.summary_len += slice.summary_len ?? 0; total.details_len += slice.details_len ?? 0;
80
+ after = slice.last;
81
+ if (slice.count < sliceRows) break;
82
+ await turn();
83
+ }
84
+ return { count: total.count, avg_summary_len: average(total.summary_len, total.summaries), avg_details_len: average(total.details_len, total.count) };
85
+ }
86
+
87
+ /**
88
+ * @param {{
89
+ * read?: (sql: string, params: any[]) => Promise<object[]>, one read-only statement, off this thread
90
+ * store?: () => object, the open store's connection; throws while the store is closed or migrating
91
+ * sliceRows?: number, freshMs?: number, now?: () => number,
92
+ * }} [options]
93
+ */
94
+ export function createRecallImpact({ read = readRows, store = getDb, sliceRows = 1000, freshMs = 60_000, now = Date.now } = {}) {
95
+ let kept = null; // { connection, data, at }: the last answer, for the connection it was read for
96
+ let flight = null; // { connection, promise }: the read under way
97
+
98
+ async function load() {
99
+ const rows = await memoryRows(read, sliceRows);
100
+ // A store without the table answers zeros, as the route always did; a store that closed meanwhile does not.
101
+ let sessionStats = { count: 0, avg_summary_len: 0, avg_details_len: 0 };
102
+ try { sessionStats = await chunkStats(read, sliceRows); }
103
+ catch (error) { if (isMemoryStoreRefusal(error)) throw error; }
104
+ return { rows, sessionStats };
105
+ }
106
+
107
+ /** `{ rows, sessionStats }` as the route answers it. Rejects with the store's refusal while it is closed. */
108
+ async function get() {
109
+ const connection = store();
110
+ if (kept && kept.connection === connection && now() - kept.at < freshMs) return kept.data;
111
+ if (flight?.connection !== connection) {
112
+ const started = { connection, promise: null };
113
+ started.promise = load()
114
+ .then((data) => { if (flight === started) kept = { connection, data, at: now() }; return data; })
115
+ .finally(() => { if (flight === started) flight = null; });
116
+ flight = started;
117
+ }
118
+ return flight.promise;
119
+ }
120
+
121
+ return { get, forget() { kept = null; } };
122
+ }