synabun 2.4.0 → 2.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (319) hide show
  1. package/CHANGELOG.md +47 -0
  2. package/README.md +1 -1
  3. package/browser-extension/content.js +73 -11
  4. package/browser-extension/engine.js +196 -15
  5. package/browser-extension/manifest.json +4 -2
  6. package/browser-extension/popup-strings.js +10 -4
  7. package/browser-extension/popup-view.js +1 -1
  8. package/browser-extension/popup.css +1 -0
  9. package/browser-extension/popup.html +4 -1
  10. package/browser-extension/popup.js +22 -10
  11. package/browser-extension/protocol.js +102 -11
  12. package/browser-extension/service-worker.js +20 -4
  13. package/browser-extension/tokens.css +1 -1
  14. package/docs/browser-extension-bridge.md +25 -5
  15. package/lib/data-home-files.js +47 -0
  16. package/lib/data-home-migration.js +34 -58
  17. package/lib/first-launch-protection.js +8 -2
  18. package/lib/update-snapshot.js +11 -4
  19. package/mcp-server/dist/http.d.ts.map +1 -1
  20. package/mcp-server/dist/http.js +25 -2
  21. package/mcp-server/dist/http.js.map +1 -1
  22. package/mcp-server/dist/index.d.ts.map +1 -1
  23. package/mcp-server/dist/index.js +62 -17
  24. package/mcp-server/dist/index.js.map +1 -1
  25. package/mcp-server/dist/services/browser-bench.d.ts +22 -22
  26. package/mcp-server/dist/services/memory-maintenance.d.ts +1 -0
  27. package/mcp-server/dist/services/memory-maintenance.d.ts.map +1 -1
  28. package/mcp-server/dist/services/memory-maintenance.js +34 -45
  29. package/mcp-server/dist/services/memory-maintenance.js.map +1 -1
  30. package/mcp-server/dist/services/memory-migration-copy.d.ts +144 -0
  31. package/mcp-server/dist/services/memory-migration-copy.d.ts.map +1 -0
  32. package/mcp-server/dist/services/memory-migration-copy.js +467 -0
  33. package/mcp-server/dist/services/memory-migration-copy.js.map +1 -0
  34. package/mcp-server/dist/services/memory-migration-worker.d.ts +2 -0
  35. package/mcp-server/dist/services/memory-migration-worker.d.ts.map +1 -0
  36. package/mcp-server/dist/services/memory-migration-worker.js +60 -0
  37. package/mcp-server/dist/services/memory-migration-worker.js.map +1 -0
  38. package/mcp-server/dist/services/memory-retrieval.d.ts +4 -0
  39. package/mcp-server/dist/services/memory-retrieval.d.ts.map +1 -1
  40. package/mcp-server/dist/services/memory-retrieval.js +188 -40
  41. package/mcp-server/dist/services/memory-retrieval.js.map +1 -1
  42. package/mcp-server/dist/services/memory-schema.d.ts +58 -2
  43. package/mcp-server/dist/services/memory-schema.d.ts.map +1 -1
  44. package/mcp-server/dist/services/memory-schema.js +190 -13
  45. package/mcp-server/dist/services/memory-schema.js.map +1 -1
  46. package/mcp-server/dist/services/memory-sessions.d.ts +19 -1
  47. package/mcp-server/dist/services/memory-sessions.d.ts.map +1 -1
  48. package/mcp-server/dist/services/memory-sessions.js +56 -20
  49. package/mcp-server/dist/services/memory-sessions.js.map +1 -1
  50. package/mcp-server/dist/services/memory-verification.d.ts.map +1 -1
  51. package/mcp-server/dist/services/memory-verification.js +8 -5
  52. package/mcp-server/dist/services/memory-verification.js.map +1 -1
  53. package/mcp-server/dist/services/neural-interface.d.ts +6 -0
  54. package/mcp-server/dist/services/neural-interface.d.ts.map +1 -1
  55. package/mcp-server/dist/services/neural-interface.js +19 -2
  56. package/mcp-server/dist/services/neural-interface.js.map +1 -1
  57. package/mcp-server/dist/services/retrieval-reader-worker.d.ts +2 -0
  58. package/mcp-server/dist/services/retrieval-reader-worker.d.ts.map +1 -0
  59. package/mcp-server/dist/services/retrieval-reader-worker.js +76 -0
  60. package/mcp-server/dist/services/retrieval-reader-worker.js.map +1 -0
  61. package/mcp-server/dist/services/retrieval-reader.d.ts +38 -0
  62. package/mcp-server/dist/services/retrieval-reader.d.ts.map +1 -0
  63. package/mcp-server/dist/services/retrieval-reader.js +145 -0
  64. package/mcp-server/dist/services/retrieval-reader.js.map +1 -0
  65. package/mcp-server/dist/services/sqlite-write.d.ts +14 -0
  66. package/mcp-server/dist/services/sqlite-write.d.ts.map +1 -0
  67. package/mcp-server/dist/services/sqlite-write.js +94 -0
  68. package/mcp-server/dist/services/sqlite-write.js.map +1 -0
  69. package/mcp-server/dist/services/sqlite.d.ts +39 -0
  70. package/mcp-server/dist/services/sqlite.d.ts.map +1 -1
  71. package/mcp-server/dist/services/sqlite.js +249 -8
  72. package/mcp-server/dist/services/sqlite.js.map +1 -1
  73. package/mcp-server/dist/services/tool-catalog.d.ts +1 -1
  74. package/mcp-server/dist/services/typesafe-config.d.ts +7 -1
  75. package/mcp-server/dist/services/typesafe-config.d.ts.map +1 -1
  76. package/mcp-server/dist/services/typesafe-config.js +32 -10
  77. package/mcp-server/dist/services/typesafe-config.js.map +1 -1
  78. package/mcp-server/dist/services/typesafe.d.ts.map +1 -1
  79. package/mcp-server/dist/services/typesafe.js +9 -7
  80. package/mcp-server/dist/services/typesafe.js.map +1 -1
  81. package/mcp-server/dist/services/vector-cache.d.ts +32 -0
  82. package/mcp-server/dist/services/vector-cache.d.ts.map +1 -1
  83. package/mcp-server/dist/services/vector-cache.js +161 -8
  84. package/mcp-server/dist/services/vector-cache.js.map +1 -1
  85. package/mcp-server/dist/tools/agent-definition.d.ts +2 -2
  86. package/mcp-server/dist/tools/agents.d.ts +13 -8
  87. package/mcp-server/dist/tools/agents.d.ts.map +1 -1
  88. package/mcp-server/dist/tools/agents.js +35 -15
  89. package/mcp-server/dist/tools/agents.js.map +1 -1
  90. package/mcp-server/dist/tools/browser-advanced.d.ts +1 -1
  91. package/mcp-server/dist/tools/browser-advanced.d.ts.map +1 -1
  92. package/mcp-server/dist/tools/browser-advanced.js +10 -3
  93. package/mcp-server/dist/tools/browser-advanced.js.map +1 -1
  94. package/mcp-server/dist/tools/browser-extension-setup.d.ts +5 -0
  95. package/mcp-server/dist/tools/browser-extension-setup.d.ts.map +1 -0
  96. package/mcp-server/dist/tools/browser-extension-setup.js +23 -0
  97. package/mcp-server/dist/tools/browser-extension-setup.js.map +1 -0
  98. package/mcp-server/dist/tools/browser-interact.d.ts.map +1 -1
  99. package/mcp-server/dist/tools/browser-interact.js +6 -1
  100. package/mcp-server/dist/tools/browser-interact.js.map +1 -1
  101. package/mcp-server/dist/tools/fb-groups.d.ts +2 -2
  102. package/mcp-server/dist/tools/skill-tools.d.ts +4 -4
  103. package/mcp-server/dist/tools/tool-groups.d.ts +1 -1
  104. package/mcp-server/package-lock.json +2 -2
  105. package/mcp-server/package.json +1 -1
  106. package/mcp-server/src/http.ts +20 -2
  107. package/mcp-server/src/index.ts +59 -17
  108. package/mcp-server/src/services/memory-maintenance.ts +31 -28
  109. package/mcp-server/src/services/memory-migration-copy.ts +419 -0
  110. package/mcp-server/src/services/memory-migration-worker.ts +55 -0
  111. package/mcp-server/src/services/memory-retrieval.ts +173 -32
  112. package/mcp-server/src/services/memory-schema.ts +194 -12
  113. package/mcp-server/src/services/memory-sessions.ts +54 -21
  114. package/mcp-server/src/services/memory-verification.ts +7 -4
  115. package/mcp-server/src/services/neural-interface.ts +23 -2
  116. package/mcp-server/src/services/retrieval-reader-worker.ts +67 -0
  117. package/mcp-server/src/services/retrieval-reader.ts +131 -0
  118. package/mcp-server/src/services/sqlite-write.ts +60 -0
  119. package/mcp-server/src/services/sqlite.ts +246 -8
  120. package/mcp-server/src/services/typesafe-config.ts +25 -6
  121. package/mcp-server/src/services/typesafe.ts +9 -7
  122. package/mcp-server/src/services/vector-cache.ts +154 -9
  123. package/mcp-server/src/tools/agents.ts +33 -14
  124. package/mcp-server/src/tools/browser-advanced.ts +10 -3
  125. package/mcp-server/src/tools/browser-extension-setup.ts +30 -0
  126. package/mcp-server/src/tools/browser-interact.ts +5 -1
  127. package/neural-interface/i18n/en.json +266 -2
  128. package/neural-interface/i18n/pt-BR.json +267 -3
  129. package/neural-interface/lib/agents/builtins.json +207 -0
  130. package/neural-interface/lib/agents/registry.js +60 -15
  131. package/neural-interface/lib/agents/resolve.js +69 -10
  132. package/neural-interface/lib/agents/split.js +32 -4
  133. package/neural-interface/lib/assistant-api.js +19 -8
  134. package/neural-interface/lib/assistant-brains/claude.js +2 -0
  135. package/neural-interface/lib/assistant-brains/opencode.js +60 -11
  136. package/neural-interface/lib/assistant-catalog.js +2 -2
  137. package/neural-interface/lib/assistant-config.js +0 -7
  138. package/neural-interface/lib/assistant-dispatch.js +384 -119
  139. package/neural-interface/lib/assistant-persona.js +17 -5
  140. package/neural-interface/lib/assistant-pricing.js +65 -14
  141. package/neural-interface/lib/assistant-router.js +181 -54
  142. package/neural-interface/lib/assistant-run-wait.js +45 -28
  143. package/neural-interface/lib/assistant-runtime.js +48 -34
  144. package/neural-interface/lib/backup-contents.js +158 -0
  145. package/neural-interface/lib/backup-crypto-io.js +330 -0
  146. package/neural-interface/lib/backup-crypto-worker.js +130 -0
  147. package/neural-interface/lib/backup-crypto.js +525 -0
  148. package/neural-interface/lib/backup-download.js +268 -0
  149. package/neural-interface/lib/backup-encryption.js +318 -0
  150. package/neural-interface/lib/backup-groups.js +287 -0
  151. package/neural-interface/lib/backup-restore-session.js +176 -0
  152. package/neural-interface/lib/backup-restore-stage.js +60 -0
  153. package/neural-interface/lib/backup-service.js +836 -322
  154. package/neural-interface/lib/backup-zip-reader.js +30 -18
  155. package/neural-interface/lib/backup-zip-writer.js +34 -10
  156. package/neural-interface/lib/browser-extension-adapter.js +109 -24
  157. package/neural-interface/lib/browser-extension-bridge.js +42 -8
  158. package/neural-interface/lib/claude-agent-bridge.js +1 -0
  159. package/neural-interface/lib/claude-session-cleanup.js +5 -1
  160. package/neural-interface/lib/cli-update-planner.js +105 -6
  161. package/neural-interface/lib/client-diagnostics.js +42 -0
  162. package/neural-interface/lib/confined-fs.js +7 -2
  163. package/neural-interface/lib/coordination/README.md +8 -2
  164. package/neural-interface/lib/coordination/contract.js +161 -0
  165. package/neural-interface/lib/coordination/database.js +999 -0
  166. package/neural-interface/lib/coordination/operations.js +436 -0
  167. package/neural-interface/lib/coordination/service.js +68 -537
  168. package/neural-interface/lib/coordination/storage-worker.js +101 -0
  169. package/neural-interface/lib/coordination/store.js +219 -1111
  170. package/neural-interface/lib/db.js +70 -32
  171. package/neural-interface/lib/health-count.js +37 -0
  172. package/neural-interface/lib/loop-stall.js +139 -0
  173. package/neural-interface/lib/maritaca/client.js +2 -2
  174. package/neural-interface/lib/maritaca/models.js +12 -17
  175. package/neural-interface/lib/maritaca/opencode.js +4 -2
  176. package/neural-interface/lib/memory-api.js +9 -1
  177. package/neural-interface/lib/memory-session-capture.js +42 -10
  178. package/neural-interface/lib/memory-store-gate.js +313 -0
  179. package/neural-interface/lib/memory-store-migrate.js +65 -0
  180. package/neural-interface/lib/memory-timers.js +7 -7
  181. package/neural-interface/lib/native-loop-providers.js +13 -16
  182. package/neural-interface/lib/native-loop-runtime.js +34 -14
  183. package/neural-interface/lib/opencode-build-preflight.js +30 -8
  184. package/neural-interface/lib/opencode-native-boundary.js +69 -8
  185. package/neural-interface/lib/opencode-provider-view.js +14 -3
  186. package/neural-interface/lib/opencode-v2-ws-requests.js +31 -1
  187. package/neural-interface/lib/opencode2-client.js +2 -1
  188. package/neural-interface/lib/peer-identity.js +13 -8
  189. package/neural-interface/lib/recall-impact.js +122 -0
  190. package/neural-interface/lib/scratch-evidence.js +420 -0
  191. package/neural-interface/lib/scratch-process-guard.js +139 -0
  192. package/neural-interface/lib/scratch-references.js +279 -0
  193. package/neural-interface/lib/scratch-retention-core.js +385 -0
  194. package/neural-interface/lib/scratch-retention-worker.js +37 -0
  195. package/neural-interface/lib/scratch-retention.js +151 -0
  196. package/neural-interface/lib/session-cache-builder.js +70 -44
  197. package/neural-interface/lib/session-cache-worker.js +157 -0
  198. package/neural-interface/lib/session-indexer.js +28 -21
  199. package/neural-interface/lib/session-search-index.js +85 -0
  200. package/neural-interface/lib/skills/creation.js +1 -1
  201. package/neural-interface/lib/sqlite-integrity-worker.js +3 -1
  202. package/neural-interface/lib/style-guide/store.js +43 -3
  203. package/neural-interface/lib/system-restore.js +50 -0
  204. package/neural-interface/lib/teams/api.js +15 -6
  205. package/neural-interface/lib/teams/claims.js +67 -31
  206. package/neural-interface/lib/teams/index.js +7 -7
  207. package/neural-interface/lib/teams/integration.js +40 -40
  208. package/neural-interface/lib/teams/landing.js +6 -6
  209. package/neural-interface/lib/teams/recovery.js +24 -23
  210. package/neural-interface/lib/teams/scheduler.js +196 -97
  211. package/neural-interface/lib/teams/schema.js +1 -1
  212. package/neural-interface/lib/teams/state.js +14 -14
  213. package/neural-interface/lib/teams/worktrees.js +27 -27
  214. package/neural-interface/lib/whatsapp/bridge.js +2 -1
  215. package/neural-interface/lib/worker-confinement.js +47 -2
  216. package/neural-interface/lib/worker-mcp-channel.js +2 -0
  217. package/neural-interface/lib/worker-resume.js +5 -0
  218. package/neural-interface/lib/worker-stop.js +86 -0
  219. package/neural-interface/package-lock.json +2 -2
  220. package/neural-interface/package.json +1 -1
  221. package/neural-interface/public/index.html +260 -0
  222. package/neural-interface/public/offline.html +4 -3
  223. package/neural-interface/public/onboarding.html +259 -34
  224. package/neural-interface/public/shared/agents/studio/ax-agent-view.js +2 -2
  225. package/neural-interface/public/shared/agents/studio/ax-editor-view.js +1 -1
  226. package/neural-interface/public/shared/agents/studio/ax-library.js +0 -6
  227. package/neural-interface/public/shared/agents/studio/ax-main.js +14 -7
  228. package/neural-interface/public/shared/agents/studio/ax-ui.js +2 -2
  229. package/neural-interface/public/shared/agy/agy-options.js +11 -0
  230. package/neural-interface/public/shared/agy/agy-panel.js +29 -10
  231. package/neural-interface/public/shared/agy/agy-styles.js +14 -12
  232. package/neural-interface/public/shared/agy/agy-tabs-logic.js +4 -1
  233. package/neural-interface/public/shared/api.js +3 -2
  234. package/neural-interface/public/shared/assistant/asst-api.js +3 -3
  235. package/neural-interface/public/shared/assistant/asst-brain-picker.js +13 -6
  236. package/neural-interface/public/shared/assistant/asst-control.js +2 -0
  237. package/neural-interface/public/shared/assistant/asst-motion-gate.js +78 -4
  238. package/neural-interface/public/shared/assistant/asst-panel.js +18 -2
  239. package/neural-interface/public/shared/assistant/asst-rack-styles.js +4 -0
  240. package/neural-interface/public/shared/assistant/asst-render.js +106 -38
  241. package/neural-interface/public/shared/assistant/asst-route.js +102 -21
  242. package/neural-interface/public/shared/assistant/asst-routes-editor.js +1 -1
  243. package/neural-interface/public/shared/assistant/asst-sidepanel.js +4 -2
  244. package/neural-interface/public/shared/assistant/asst-state.js +11 -0
  245. package/neural-interface/public/shared/assistant/asst-styles.js +10 -23
  246. package/neural-interface/public/shared/assistant/route-identity.js +2 -1
  247. package/neural-interface/public/shared/cc-dropdown.js +21 -15
  248. package/neural-interface/public/shared/cdx/cdx-render.js +9 -0
  249. package/neural-interface/public/shared/cdx/cdx-settings.js +3 -1
  250. package/neural-interface/public/shared/cdx/cdx-styles.js +6 -0
  251. package/neural-interface/public/shared/cdx/cdx-tabs.js +29 -9
  252. package/neural-interface/public/shared/client-diagnostics.js +94 -0
  253. package/neural-interface/public/shared/cp/cp-markdown.js +7 -2
  254. package/neural-interface/public/shared/cp/cp-styles.js +1 -1
  255. package/neural-interface/public/shared/effort-i18n.js +118 -0
  256. package/neural-interface/public/shared/html-shell.js +4 -51
  257. package/neural-interface/public/shared/loading-diagnostic-entry.js +64 -0
  258. package/neural-interface/public/shared/memory-store-wait.js +52 -0
  259. package/neural-interface/public/shared/morelogin-profile-field.js +1 -1
  260. package/neural-interface/public/shared/mtc/mtc-logic.js +2 -1
  261. package/neural-interface/public/shared/mtc/mtc-panel.js +8 -1
  262. package/neural-interface/public/shared/mtc/mtc-styles.js +13 -12
  263. package/neural-interface/public/shared/ocp-v2/ocp-v2-childpanel.js +7 -0
  264. package/neural-interface/public/shared/ocp-v2/ocp-v2-location-logic.js +109 -0
  265. package/neural-interface/public/shared/ocp-v2/ocp-v2-modelpicker.js +8 -1
  266. package/neural-interface/public/shared/ocp-v2/ocp-v2-panel.js +118 -6
  267. package/neural-interface/public/shared/ocp-v2/ocp-v2-render.js +27 -3
  268. package/neural-interface/public/shared/ocp-v2/ocp-v2-send.js +13 -0
  269. package/neural-interface/public/shared/ocp-v2/ocp-v2-session-actions.js +2 -1
  270. package/neural-interface/public/shared/ocp-v2/ocp-v2-styles.js +27 -93
  271. package/neural-interface/public/shared/ocp-v2/ocp-v2-variantpicker.js +17 -6
  272. package/neural-interface/public/shared/output-format.js +294 -0
  273. package/neural-interface/public/shared/owner-authority-view.js +4 -10
  274. package/neural-interface/public/shared/page-session.js +1 -1
  275. package/neural-interface/public/shared/provider-icons.js +6 -0
  276. package/neural-interface/public/shared/schedules-view.js +2 -1
  277. package/neural-interface/public/shared/server-presence.js +77 -0
  278. package/neural-interface/public/shared/settings/settings-ai-browser.js +5 -5
  279. package/neural-interface/public/shared/settings/settings-backup-contents.js +241 -0
  280. package/neural-interface/public/shared/settings/settings-backup-download.js +298 -0
  281. package/neural-interface/public/shared/settings/settings-backup-encryption-pane.js +335 -0
  282. package/neural-interface/public/shared/settings/settings-backup-encryption.js +545 -0
  283. package/neural-interface/public/shared/settings/settings-ia.js +1 -1
  284. package/neural-interface/public/shared/skills/studio/sx-geometry.js +12 -3
  285. package/neural-interface/public/shared/skills/studio/sx-main.js +14 -7
  286. package/neural-interface/public/shared/start-bridge.js +2 -2
  287. package/neural-interface/public/shared/studio-attention.js +6 -0
  288. package/neural-interface/public/shared/styles.css +354 -438
  289. package/neural-interface/public/shared/transcript-rows.js +28 -3
  290. package/neural-interface/public/shared/tray-auto-close.js +18 -5
  291. package/neural-interface/public/shared/ui-agents.js +1 -2
  292. package/neural-interface/public/shared/ui-automation-studio.js +168 -108
  293. package/neural-interface/public/shared/ui-claude-panel.js +42 -65
  294. package/neural-interface/public/shared/ui-loading.js +185 -25
  295. package/neural-interface/public/shared/ui-native-loop-router.js +59 -20
  296. package/neural-interface/public/shared/ui-navbar.js +2 -1
  297. package/neural-interface/public/shared/ui-output.js +533 -0
  298. package/neural-interface/public/shared/ui-owner-authority.js +48 -25
  299. package/neural-interface/public/shared/ui-schedules-studio.js +165 -128
  300. package/neural-interface/public/shared/ui-scroll-follow.js +97 -6
  301. package/neural-interface/public/shared/ui-sessions.js +2 -2
  302. package/neural-interface/public/shared/ui-settings-entry.js +18 -0
  303. package/neural-interface/public/shared/ui-settings.js +234 -67
  304. package/neural-interface/public/shared/ui-sidepanel-tray.js +3 -2
  305. package/neural-interface/public/shared/ui-sync.js +1 -0
  306. package/neural-interface/public/shared/ui-tooltip.js +16 -0
  307. package/neural-interface/public/shared/ui-tutorial.js +5 -6
  308. package/neural-interface/public/shared/ui-worker-end.js +27 -8
  309. package/neural-interface/public/shared/worker-end.js +9 -4
  310. package/neural-interface/public/sw.js +4 -3
  311. package/neural-interface/public/variant/2d/main.js +5 -0
  312. package/neural-interface/public/variant/3d/app.js +10 -0
  313. package/neural-interface/public/variant/3d/main.js +17 -4
  314. package/neural-interface/scripts/scratch-retention.mjs +20 -0
  315. package/neural-interface/server.js +507 -160
  316. package/npm-shrinkwrap.json +2 -2
  317. package/package.json +2 -1
  318. package/scripts/restore-data-home-from-backup.mjs +175 -8
  319. package/setup.js +18 -4
@@ -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
+ }
@@ -0,0 +1,420 @@
1
+ // Read-only evidence for scratch retention, used inside its worker thread: who owns a folder, whether its run is
2
+ // positively finished, and which of its files the run's visible output still points at. Anything that cannot be read
3
+ // keeps the folder, and says why.
4
+
5
+ import { closeSync, constants, fstatSync, lstatSync, openSync, readFileSync, readSync, readdirSync, realpathSync } from 'node:fs';
6
+ import { join, sep } from 'node:path';
7
+ import { HAS_SCRATCH, RUN_ID, collectRunRecord, collectTranscriptEntry, createReferenceIndex } from './scratch-references.js';
8
+
9
+ export const DAY_MS = 86_400_000;
10
+ const TERMINAL = new Set(['completed', 'failed', 'stopped', 'interrupted']);
11
+ const LOOP_SOURCES = new Set(['manual', 'schedule', 'schedule-manual', 'quick-timer', 'quick-timer-manual']);
12
+ const MAX_JSON = 128 * 1024 ** 2;
13
+ const CHUNK = 1024 * 1024;
14
+ const MAX_LINE = 8 * 1024 * 1024;
15
+ const LINE_OVERLAP = 4096;
16
+ const TURN_TEXT_CAP = 20_000;
17
+ const COORDINATION_SCHEMA = 1;
18
+ const READ_FLAGS = constants.O_RDONLY | (constants.O_NOFOLLOW || 0) | (constants.O_NONBLOCK || 0);
19
+ const BIG = { bigint: true };
20
+
21
+ /** A stable reason to count in the pass summary. */
22
+ export class Keep extends Error {
23
+ constructor(reason) { super(reason); this.reason = reason; }
24
+ }
25
+ export const reasonOf = (error) => (error instanceof Keep ? error.reason : 'unreadable');
26
+
27
+ const isObject = (value) => !!value && typeof value === 'object' && !Array.isArray(value);
28
+ const stampOf = (st) => `${st.dev}:${st.ino}:${st.size}:${st.mtimeNs}:${st.ctimeNs}`;
29
+ const missing = (error) => error?.code === 'ENOENT';
30
+
31
+ export function timestamp(value) {
32
+ if (typeof value === 'string' && /(?:Z|[+-]\d{2}:?\d{2})$/i.test(value.trim())) {
33
+ const when = Date.parse(value);
34
+ if (Number.isFinite(when) && when > 0) return when;
35
+ }
36
+ throw new Keep('unknown-finish');
37
+ }
38
+
39
+ export function policy(config) {
40
+ const limits = config?.scratchRetention === undefined ? {} : config.scratchRetention;
41
+ if (!isObject(limits)) throw new Keep('invalid-settings');
42
+ const number = (key, fallback, floor) => {
43
+ const value = limits[key] === undefined ? fallback : limits[key];
44
+ if (typeof value !== 'number' || !Number.isFinite(value) || value < floor) throw new Keep('invalid-settings');
45
+ return value;
46
+ };
47
+ return { ageMs: number('days', 14, 2) * DAY_MS, limitBytes: number('maxGB', 5, 0) * 1e9, floorMs: number('minHours', 48, 48) * 3_600_000 };
48
+ }
49
+
50
+ export class Evidence {
51
+ constructor(data, { pause = async () => {}, realpath = null } = {}) {
52
+ this.data = data;
53
+ this.pause = pause;
54
+ this.realpath = realpath || ((path) => { try { return realpathSync.native(path); } catch { return null; } });
55
+ this.cache = new Map();
56
+ this.sources = new Map(); // source → { refs }, each replaced or extended only when its file changed
57
+ this.sidecars = new Map(); // run → the references of its whole last message
58
+ this.eventDb = null;
59
+ this.lastEvent = 0;
60
+ this.eventRefs = createReferenceIndex();
61
+ }
62
+
63
+ /**
64
+ * One regular file, never through a link, read only if it changed. The registries are replaced atomically, many
65
+ * times a minute while a worker runs: the open descriptor is one consistent version of the file, so a replacement
66
+ * during the read is not an error. The check right before a delete reads the newer version.
67
+ */
68
+ read(path, load) {
69
+ if (realpathSync.native(path) !== path) throw new Keep('linked-record');
70
+ const fd = openSync(path, READ_FLAGS);
71
+ try {
72
+ const st = fstatSync(fd, BIG);
73
+ if (!st.isFile()) throw new Keep('invalid-record');
74
+ const stamp = stampOf(st);
75
+ const cached = this.cache.get(path);
76
+ if (cached?.stamp === stamp) return cached.value;
77
+ if (Number(st.size) > MAX_JSON) throw new Keep('oversized-record');
78
+ const value = load(readFileSync(fd, 'utf8'));
79
+ if (stampOf(fstatSync(fd, BIG)) !== stamp) throw new Keep('changing-record'); // written in place while it was read
80
+ this.cache.set(path, { stamp, value });
81
+ return value;
82
+ } finally { closeSync(fd); }
83
+ }
84
+
85
+ settings() {
86
+ try { return policy(this.read(join(this.data, 'assistant-config.json'), (text) => JSON.parse(text))); }
87
+ catch (error) {
88
+ if (missing(error)) return policy({});
89
+ throw error;
90
+ }
91
+ }
92
+
93
+ listing(path, { required = false } = {}) {
94
+ try {
95
+ if (realpathSync.native(path) !== path) throw new Keep('linked-record');
96
+ return readdirSync(path);
97
+ } catch (error) {
98
+ if (!missing(error)) throw error;
99
+ if (required) throw new Keep('unreadable-loop-owner');
100
+ return [];
101
+ }
102
+ }
103
+
104
+ ledger(name) {
105
+ return this.read(join(this.data, name), (text) => {
106
+ const rows = JSON.parse(text);
107
+ if (!Array.isArray(rows)) throw new Error('invalid ledger');
108
+ const index = new Map();
109
+ const refs = createReferenceIndex();
110
+ for (const row of rows) {
111
+ if (!isObject(row) || typeof row.runId !== 'string') throw new Error('invalid run id');
112
+ collectRunRecord(refs, row, { realpath: this.realpath });
113
+ index.set(row.runId, index.has(row.runId) ? null : row); // duplicate ownership is ambiguous for this id only
114
+ }
115
+ return { index, refs };
116
+ });
117
+ }
118
+
119
+ jsonRefs(path) {
120
+ const refs = this.read(path, (text) => {
121
+ const value = JSON.parse(text);
122
+ const out = createReferenceIndex();
123
+ if (HAS_SCRATCH.test(text)) {
124
+ out.addVisible(value);
125
+ out.addWorkdirs(value, { realpath: this.realpath });
126
+ }
127
+ return out;
128
+ });
129
+ this.sources.set(path, { refs });
130
+ }
131
+
132
+ readTeams(held) {
133
+ const base = join(this.data, 'teams');
134
+ for (const name of this.listing(base)) {
135
+ if (!name.endsWith('.json')) continue;
136
+ const path = join(base, name);
137
+ const row = this.read(path, (text) => {
138
+ const value = JSON.parse(text);
139
+ if (!isObject(value?.slices)) throw new Error('invalid team');
140
+ const refs = createReferenceIndex();
141
+ refs.addVisible(value);
142
+ refs.addWorkdirs(value, { realpath: this.realpath });
143
+ return { value, refs };
144
+ });
145
+ this.sources.set(path, { refs: row.refs });
146
+ for (const member of Object.values(row.value.slices)) {
147
+ if (member?.runId) held.set(member.runId, 'team');
148
+ for (const id of Array.isArray(member?.runIds) ? member.runIds : []) held.set(id, 'team');
149
+ }
150
+ }
151
+ }
152
+
153
+ loopRecord(path) {
154
+ return this.read(path, (text) => {
155
+ const value = JSON.parse(text);
156
+ if (!isObject(value)) throw new Error('invalid loop record');
157
+ const refs = createReferenceIndex();
158
+ collectRunRecord(refs, value, { realpath: this.realpath });
159
+ return { value, refs };
160
+ });
161
+ }
162
+
163
+ readLoops(held) {
164
+ const base = join(this.data, 'loop');
165
+ for (const name of this.listing(base, { required: true })) {
166
+ if (!name.endsWith('.json')) continue;
167
+ const stem = name.slice(0, -5);
168
+ const path = join(base, name);
169
+ try {
170
+ const row = this.loopRecord(path);
171
+ this.sources.set(path, { refs: row.refs });
172
+ const state = row.value;
173
+ if (name === 'active-pointer.json') {
174
+ if (typeof state.sessionId !== 'string') throw new Keep('unreadable-loop-owner');
175
+ held.set(state.sessionId, 'loop-pointer');
176
+ continue;
177
+ }
178
+ if (state.active !== false || state.pending !== false) {
179
+ if (stem.startsWith('pending-') && !state.terminalSessionId) throw new Keep('unreadable-loop-owner');
180
+ for (const id of [state.runId, state.terminalSessionId, stem]) if (id) held.set(id, 'live-loop');
181
+ }
182
+ } catch {
183
+ if (!RUN_ID.test(stem)) throw new Keep('unreadable-loop-owner');
184
+ held.set(stem, 'unreadable-loop');
185
+ }
186
+ }
187
+ }
188
+
189
+ /** New lines only, for a file that only grows. A line that cannot be parsed is read as plain text. */
190
+ async readTranscript(path) {
191
+ let st;
192
+ try { st = lstatSync(path, BIG); }
193
+ catch (error) {
194
+ if (!missing(error)) throw error;
195
+ this.sources.delete(path);
196
+ return;
197
+ }
198
+ if (!st.isFile()) throw new Keep('unreadable-references');
199
+ const previous = this.sources.get(path);
200
+ const grows = previous && previous.dev === st.dev && previous.ino === st.ino && Number(st.size) >= previous.offset;
201
+ if (grows && previous.size === st.size && previous.mtimeNs === st.mtimeNs) return;
202
+ const refs = grows ? previous.refs : createReferenceIndex();
203
+ let offset = grows ? previous.offset : 0;
204
+ let position = offset;
205
+ let carry = Buffer.alloc(0);
206
+ const line = (bytes) => {
207
+ const text = bytes.toString('utf8');
208
+ if (!HAS_SCRATCH.test(text)) return;
209
+ try { collectTranscriptEntry(refs, JSON.parse(text)); } catch { refs.addText(text); }
210
+ };
211
+ const fd = openSync(path, READ_FLAGS);
212
+ try {
213
+ const opened = fstatSync(fd, BIG);
214
+ if (opened.dev !== st.dev || opened.ino !== st.ino) throw new Keep('unreadable-references');
215
+ const chunk = Buffer.allocUnsafe(CHUNK);
216
+ for (;;) {
217
+ const got = readSync(fd, chunk, 0, CHUNK, position);
218
+ if (!got) break;
219
+ position += got;
220
+ let data = carry.length ? Buffer.concat([carry, chunk.subarray(0, got)]) : Buffer.from(chunk.subarray(0, got));
221
+ let start = 0;
222
+ for (let end = data.indexOf(10, start); end >= 0; end = data.indexOf(10, start)) {
223
+ line(data.subarray(start, end));
224
+ offset += end - start + 1;
225
+ start = end + 1;
226
+ }
227
+ data = data.subarray(start);
228
+ if (data.length > MAX_LINE) {
229
+ // One enormous line: read as text, keeping an overlap so a path across the cut is still seen.
230
+ refs.addText(data.toString('utf8'));
231
+ offset += data.length - LINE_OVERLAP;
232
+ data = data.subarray(data.length - LINE_OVERLAP);
233
+ }
234
+ carry = Buffer.from(data);
235
+ await this.pause();
236
+ }
237
+ } finally { closeSync(fd); }
238
+ // A line still being written: seen now, read properly once it is complete.
239
+ const partial = createReferenceIndex();
240
+ if (carry.length) partial.addText(carry.toString('utf8'));
241
+ this.sources.set(path, { refs, partial, offset, dev: st.dev, ino: st.ino, size: st.size, mtimeNs: st.mtimeNs });
242
+ }
243
+
244
+ async readTranscripts() {
245
+ const base = join(this.data, 'assistant');
246
+ const seen = new Set();
247
+ for (const name of this.listing(base)) {
248
+ const folder = join(base, name);
249
+ let st;
250
+ try { st = lstatSync(folder); } catch (error) { if (missing(error)) continue; throw error; }
251
+ if (!st.isDirectory()) continue;
252
+ const path = join(folder, 'transcript.jsonl');
253
+ seen.add(path);
254
+ await this.readTranscript(path);
255
+ }
256
+ const prefix = base + sep;
257
+ for (const key of this.sources.keys()) if (key.startsWith(prefix) && !seen.has(key)) this.sources.delete(key);
258
+ }
259
+
260
+ readSavedWork() {
261
+ for (const name of this.listing(this.data)) {
262
+ if ((name.startsWith('loop-schedules') || name.startsWith('loop-templates')) && name.endsWith('.json')) this.jsonRefs(join(this.data, name));
263
+ }
264
+ for (const path of [join(this.data, 'skills', 'reviews.json'), join(this.data, 'assistant-sessions.json')]) {
265
+ try { this.jsonRefs(path); }
266
+ catch (error) { if (!missing(error)) throw error; this.sources.delete(path); }
267
+ }
268
+ }
269
+
270
+ /** The outbox survives a restart; team claims and journal rows can outlive a registry entry. */
271
+ async readCoordination(held) {
272
+ const path = join(this.data, 'coordination.db');
273
+ let st;
274
+ try {
275
+ if (realpathSync.native(path) !== path) throw new Keep('unreadable-coordination');
276
+ st = lstatSync(path, BIG);
277
+ } catch (error) {
278
+ throw error instanceof Keep ? error : new Keep('unreadable-coordination');
279
+ }
280
+ if (!st.isFile()) throw new Keep('unreadable-coordination');
281
+ const { DatabaseSync } = await import('node:sqlite');
282
+ let db;
283
+ try {
284
+ db = new DatabaseSync(path, { readOnly: true });
285
+ db.exec('PRAGMA busy_timeout=200');
286
+ db.exec('PRAGMA query_only=ON');
287
+ if (db.prepare('SELECT MAX(version) AS v FROM migrations').get()?.v !== COORDINATION_SCHEMA) throw new Keep('unknown-coordination-schema');
288
+ const identity = `${st.dev}:${st.ino}`;
289
+ if (this.eventDb !== identity) {
290
+ this.eventDb = identity;
291
+ this.lastEvent = 0;
292
+ this.eventRefs = createReferenceIndex();
293
+ }
294
+ const last = Number(db.prepare('SELECT MAX(seq) AS s FROM events').get()?.s) || 0;
295
+ const page = db.prepare('SELECT seq, payload FROM events WHERE seq > ? AND seq <= ? ORDER BY seq LIMIT 128');
296
+ while (this.lastEvent < last) {
297
+ const before = this.lastEvent;
298
+ for (const row of page.all(before, last)) {
299
+ if (HAS_SCRATCH.test(row.payload)) {
300
+ try { this.eventRefs.addVisible(JSON.parse(row.payload)); } catch { this.eventRefs.addText(row.payload); }
301
+ }
302
+ this.lastEvent = Number(row.seq);
303
+ }
304
+ if (this.lastEvent === before) break; // the coordination pruner removed the rest of this window
305
+ await this.pause();
306
+ }
307
+ this.sources.set('coordination:events', { refs: this.eventRefs });
308
+ const outbox = createReferenceIndex();
309
+ for (const row of db.prepare('SELECT run_id, text FROM outbox WHERE sent_at IS NULL').all()) {
310
+ outbox.addText(row.text);
311
+ held.set(row.run_id, 'queued-followup');
312
+ }
313
+ this.sources.set('coordination:outbox', { refs: outbox });
314
+ for (const row of db.prepare('SELECT run_id FROM claims WHERE released_at IS NULL AND run_id IS NOT NULL UNION SELECT run_id FROM team_tasks WHERE run_id IS NOT NULL').all()) {
315
+ held.set(row.run_id, 'team');
316
+ }
317
+ } catch (error) {
318
+ throw error instanceof Keep ? error : new Keep('unreadable-coordination');
319
+ } finally {
320
+ try { db?.close(); } catch { /* already closed */ }
321
+ }
322
+ }
323
+
324
+ /** The current holds, with every reference source brought up to date. Throws when one cannot be read. */
325
+ async collect() {
326
+ const held = new Map();
327
+ this.readTeams(held);
328
+ this.readLoops(held);
329
+ await this.readTranscripts();
330
+ this.readSavedWork();
331
+ await this.readCoordination(held);
332
+ this.sources.set('ledger:dispatches', { refs: this.ledger('assistant-dispatches.json').refs });
333
+ this.sources.set('ledger:native', { refs: this.ledger('native-loop-runs.json').refs });
334
+ for (const source of this.sources.values()) {
335
+ for (const run of source.refs?.workdirs || []) if (!held.has(run)) held.set(run, 'working-directory');
336
+ }
337
+ return held;
338
+ }
339
+
340
+ /** Everything that points into this run's folder. `overflow`: more references than can be kept apart. */
341
+ referencesTo(run) {
342
+ const tails = new Set();
343
+ let overflow = false;
344
+ const take = (refs) => {
345
+ if (!refs) return;
346
+ for (const tail of refs.byRun.get(run) || []) tails.add(tail);
347
+ if (refs.overflow.has(run)) overflow = true;
348
+ };
349
+ for (const source of this.sources.values()) { take(source.refs); take(source.partial); }
350
+ take(this.sidecars.get(run));
351
+ return { tails, overflow };
352
+ }
353
+
354
+ /** The registry clips a turn's text. Its whole text must be somewhere, or a link in the cut part would be missed. */
355
+ checkComplete(run, dispatch) {
356
+ const turns = Array.isArray(dispatch.turns) ? dispatch.turns : [];
357
+ if (turns.length && turns[0]?.n !== 1) throw new Keep('incomplete-references');
358
+ this.sidecars.delete(run);
359
+ turns.forEach((turn, position) => {
360
+ const text = typeof turn?.text === 'string' ? turn.text : '';
361
+ if (text.length < TURN_TEXT_CAP) return;
362
+ const raw = turn?.result?.raw;
363
+ if (typeof raw === 'string' && raw.length >= text.length) return;
364
+ if (position !== turns.length - 1) throw new Keep('incomplete-references');
365
+ let kept;
366
+ try {
367
+ kept = this.read(join(this.data, 'run-tails', `${run}.text.json`), (body) => JSON.parse(body));
368
+ } catch { throw new Keep('incomplete-references'); }
369
+ if (!isObject(kept) || typeof kept.text !== 'string' || kept.cut === true || kept.turn !== turn.n) throw new Keep('incomplete-references');
370
+ const refs = createReferenceIndex();
371
+ refs.addText(kept.text);
372
+ this.sidecars.set(run, refs);
373
+ });
374
+ }
375
+
376
+ /** @returns {{ end: number, task: boolean }} a run that is positively over. Throws Keep for anything else. */
377
+ evaluate(run, held) {
378
+ if (!RUN_ID.test(run)) throw new Keep('unknown');
379
+ const dispatches = this.ledger('assistant-dispatches.json').index;
380
+ const natives = this.ledger('native-loop-runs.json').index;
381
+ if (held.has(run)) throw new Keep(held.get(run));
382
+ const native = natives.get(run);
383
+ const dispatch = dispatches.get(run);
384
+ if (!native || (dispatches.has(run) && !dispatch)) throw new Keep('unknown');
385
+ if (native.runMode === 'task' || native.source === 'assistant') {
386
+ if (!dispatch || native.runMode !== 'task' || native.source !== 'assistant') throw new Keep('unknown-dispatch');
387
+ } else if (native.runMode !== 'loop' || !LOOP_SOURCES.has(native.source) || dispatch) {
388
+ throw new Keep('ambiguous-owner');
389
+ }
390
+ const finished = [];
391
+ for (const [row, state, end] of [[native, 'status', 'completedAt'], [dispatch, 'state', 'finishedAt']]) {
392
+ if (!row) continue;
393
+ if (!TERMINAL.has(row[state]) || ![undefined, null, 'terminal'].includes(row.turnState) || row.active) throw new Keep('live-or-unknown-state');
394
+ const waiting = row.pending !== undefined && row.pending !== null && !(Array.isArray(row.pending) && !row.pending.length);
395
+ if (waiting || row.judging || row.resumeInfo?.inFlight) throw new Keep('pending');
396
+ if (row.team || row.teamId || String(row.workflowId).startsWith('team:')) throw new Keep('team');
397
+ finished.push(timestamp(row[end]));
398
+ }
399
+ if (dispatch) {
400
+ if (dispatch.confinement || dispatch.teamBrief) throw new Keep('team-or-review');
401
+ const own = typeof dispatch.scratchDir === 'string' ? this.realpath(dispatch.scratchDir) : null;
402
+ if (own !== join(this.data, 'scratch', run)) throw new Keep('ambiguous-owner');
403
+ this.checkComplete(run, dispatch);
404
+ }
405
+ // GET /api/loop/active and the session hooks unlink inactive markers: only a cleanly absent one is optional.
406
+ let marker;
407
+ try {
408
+ marker = this.loopRecord(join(this.data, 'loop', `${run}.json`)).value;
409
+ } catch (error) {
410
+ if (!missing(error)) throw error;
411
+ this.listing(join(this.data, 'loop'), { required: true });
412
+ return { end: Math.max(...finished), task: !!dispatch };
413
+ }
414
+ if (!isObject(marker) || marker.runId !== run || marker.terminalSessionId !== run) throw new Keep('ambiguous-owner');
415
+ if (marker.team || marker.confinement) throw new Keep('team-or-review');
416
+ if (marker.active !== false || marker.pending !== false) throw new Keep('live-loop');
417
+ finished.push(timestamp(marker.completedAt));
418
+ return { end: Math.max(...finished), task: !!dispatch };
419
+ }
420
+ }
@@ -0,0 +1,139 @@
1
+ // "No process has a file or a working directory inside this folder", on each platform, with no dependency.
2
+ // macOS the system's lsof, one full listing per check, with a positive control: lsof must see the directory
3
+ // descriptor this thread holds, or an empty answer could just mean it saw nothing.
4
+ // Linux /proc, for this user's processes (workers run as this user; another user's process is not one of them).
5
+ // Windows renaming a folder fails while a process holds a file or a working directory inside it, so the folder is
6
+ // renamed aside and straight back. A crash in between is put right at the start of the next pass.
7
+
8
+ import { execFile } from 'node:child_process';
9
+ import { existsSync, readFileSync, readdirSync, readlinkSync, renameSync, statSync } from 'node:fs';
10
+ import { join } from 'node:path';
11
+ import { promisify } from 'node:util';
12
+ import { Keep } from './scratch-evidence.js';
13
+
14
+ const run = promisify(execFile);
15
+ const LSOF = '/usr/sbin/lsof';
16
+ const LSOF_TIMEOUT_MS = 45_000;
17
+ const LSOF_MAX_BYTES = 512 * 1024 * 1024;
18
+ export const PROBE_SUFFIX = '.retention-probe';
19
+ const PROBE_NAME = /^([a-f0-9]{32})\.retention-probe$/;
20
+ const IN_USE = new Set(['EPERM', 'EBUSY', 'EACCES', 'ENOTEMPTY']);
21
+
22
+ const inside = (name, path) => name === path || name.startsWith(`${path}/`) || name.startsWith(`${path} `);
23
+
24
+ // lsof prints a byte it considers unprintable as \xNN.
25
+ function lsofName(text) {
26
+ const bytes = text.includes('\\x')
27
+ ? text.replace(/\\x([0-9a-f]{2})/gi, (_, hex) => String.fromCharCode(parseInt(hex, 16)))
28
+ : text;
29
+ return Buffer.from(bytes, 'latin1').toString('utf8');
30
+ }
31
+
32
+ /** Read an lsof -Fpfn listing. Throws Keep when another holder is inside, or when our own descriptor is not seen. */
33
+ export function checkLsofListing(output, path, fd, pid = process.pid) {
34
+ const marker = path.slice(path.lastIndexOf('/') + 1);
35
+ let owner = null, descriptor = null, control = false;
36
+ for (let start = 0; start < output.length;) {
37
+ let end = output.indexOf('\n', start);
38
+ if (end < 0) end = output.length;
39
+ const kind = output[start];
40
+ if (kind === 'p') owner = Number(output.slice(start + 1, end));
41
+ else if (kind === 'f') descriptor = output.slice(start + 1, end);
42
+ else if (kind === 'n') {
43
+ const line = output.slice(start + 1, end);
44
+ if (line.includes(marker) && inside(lsofName(line), path)) {
45
+ if (owner === pid && descriptor === String(fd)) control = true;
46
+ else throw new Keep('open-process');
47
+ }
48
+ }
49
+ start = end + 1;
50
+ }
51
+ if (!control) throw new Keep('process-check-unavailable');
52
+ }
53
+
54
+ async function lsofProbe(path, fd) {
55
+ let output;
56
+ try {
57
+ ({ stdout: output } = await run(LSOF, ['-nP', '-w', '-Fpfn'], {
58
+ encoding: 'latin1', maxBuffer: LSOF_MAX_BYTES, timeout: LSOF_TIMEOUT_MS, windowsHide: true,
59
+ env: { ...process.env, LC_ALL: 'C' },
60
+ }));
61
+ } catch (error) {
62
+ // lsof exits 1 for a process it could not read; the positive control below says whether the listing is usable.
63
+ if (error?.code !== 1 || typeof error.stdout !== 'string') throw new Keep('process-check-unavailable');
64
+ output = error.stdout;
65
+ }
66
+ checkLsofListing(output, path, fd);
67
+ }
68
+
69
+ async function procProbe(path, fd, { proc = '/proc', uid = process.getuid?.(), pid: self = process.pid, pause = async () => {} } = {}) {
70
+ let control = false;
71
+ const gone = (error) => error?.code === 'ENOENT' || error?.code === 'ESRCH';
72
+ const look = (read) => {
73
+ try { return read(); }
74
+ catch (error) {
75
+ if (gone(error)) return null;
76
+ throw new Keep('process-visibility');
77
+ }
78
+ };
79
+ let pids;
80
+ try { pids = readdirSync(proc).filter((name) => /^\d+$/.test(name)); }
81
+ catch { throw new Keep('process-check-unavailable'); }
82
+ for (const pid of pids) {
83
+ await pause();
84
+ const base = join(proc, pid);
85
+ let owner;
86
+ try { owner = statSync(base).uid; } catch { continue; }
87
+ if (owner !== uid) continue;
88
+ for (const link of ['cwd', 'root', 'exe']) {
89
+ const target = look(() => readlinkSync(join(base, link)));
90
+ if (target && inside(target, path)) throw new Keep('open-process');
91
+ }
92
+ for (const entry of look(() => readdirSync(join(base, 'fd'))) || []) {
93
+ const target = look(() => readlinkSync(join(base, 'fd', entry)));
94
+ if (!target || !inside(target, path)) continue;
95
+ if (Number(pid) === self && entry === String(fd)) control = true;
96
+ else throw new Keep('open-process');
97
+ }
98
+ const maps = look(() => readFileSync(join(base, 'maps'), 'utf8')) || '';
99
+ for (const line of maps.split('\n')) {
100
+ const at = line.indexOf('/');
101
+ if (at >= 0 && inside(line.slice(at), path)) throw new Keep('open-process');
102
+ }
103
+ }
104
+ if (!control) throw new Keep('process-check-unavailable');
105
+ }
106
+
107
+ export function renameProbe(path, { rename = renameSync } = {}) {
108
+ const aside = `${path}${PROBE_SUFFIX}`;
109
+ if (existsSync(aside)) throw new Keep('process-check-unavailable');
110
+ try { rename(path, aside); }
111
+ catch (error) { throw new Keep(IN_USE.has(error?.code) ? 'open-process' : 'process-check-unavailable'); }
112
+ let failure = null;
113
+ for (let attempt = 0; attempt < 5; attempt += 1) {
114
+ try { rename(aside, path); return; } catch (error) { failure = error; }
115
+ }
116
+ throw new Keep(`probe-not-restored:${failure?.code || 'error'}`);
117
+ }
118
+
119
+ /** A folder a crash left under its probe name goes back, unless something took its name meanwhile. */
120
+ export function recoverProbes(root, { platform = process.platform, rename = renameSync } = {}) {
121
+ if (platform !== 'win32') return 0;
122
+ let restored = 0;
123
+ for (const name of readdirSync(root)) {
124
+ const match = PROBE_NAME.exec(name);
125
+ if (!match || existsSync(join(root, match[1]))) continue;
126
+ try { rename(join(root, name), join(root, match[1])); restored += 1; } catch { /* the next pass tries again */ }
127
+ }
128
+ return restored;
129
+ }
130
+
131
+ /** The check for this platform: `(path, fd) => Promise<void>`, throwing Keep when the folder must stay. */
132
+ export function createProcessProbe({ platform = process.platform, pause } = {}) {
133
+ if (platform === 'darwin') return lsofProbe;
134
+ if (platform === 'linux') return (path, fd) => procProbe(path, fd, { pause });
135
+ if (platform === 'win32') return async (path) => renameProbe(path);
136
+ return async () => { throw new Keep('process-check-unavailable'); };
137
+ }
138
+
139
+ export { procProbe as _procProbe };