@vellumai/assistant 0.10.1 → 0.10.2-dev.202606241651.2d2b40d

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 (367) hide show
  1. package/docs/workspace-tools.md +42 -33
  2. package/eslint-rules/cli-no-daemon-internals.js +6 -0
  3. package/node_modules/@vellumai/gateway-client/src/__tests__/guardian-delivery-contract.test.ts +91 -0
  4. package/node_modules/@vellumai/gateway-client/src/__tests__/trust-verdict-contract.test.ts +31 -0
  5. package/node_modules/@vellumai/gateway-client/src/guardian-delivery-contract.ts +48 -0
  6. package/node_modules/@vellumai/gateway-client/src/index.ts +14 -0
  7. package/node_modules/@vellumai/gateway-client/src/trust-verdict-contract.ts +17 -0
  8. package/openapi.yaml +74 -1
  9. package/package.json +1 -1
  10. package/scripts/test.sh +36 -15
  11. package/src/__tests__/actor-token-service.test.ts +36 -14
  12. package/src/__tests__/agent-loop-override-profile.test.ts +1 -0
  13. package/src/__tests__/agent-wake-disk-pressure-callsite.test.ts +2 -0
  14. package/src/__tests__/agent-wake-override-profile.test.ts +2 -0
  15. package/src/__tests__/annotate-activity-metadata.test.ts +2 -0
  16. package/src/__tests__/annotate-risk-options.test.ts +2 -0
  17. package/src/__tests__/approval-cascade.test.ts +2 -0
  18. package/src/__tests__/background-workers-disk-pressure.test.ts +2 -0
  19. package/src/__tests__/btw-routes.test.ts +2 -0
  20. package/src/__tests__/build-persisted-content.test.ts +2 -0
  21. package/src/__tests__/call-controller.test.ts +19 -0
  22. package/src/__tests__/channel-guardian.test.ts +94 -58
  23. package/src/__tests__/channel-reply-delivery.test.ts +2 -0
  24. package/src/__tests__/compaction-events.test.ts +2 -0
  25. package/src/__tests__/compaction.benchmark.test.ts +2 -0
  26. package/src/__tests__/compactor-call-site-logging.test.ts +2 -0
  27. package/src/__tests__/compactor-low-watermark-cut.test.ts +2 -0
  28. package/src/__tests__/compactor-preserved-tail-count.test.ts +2 -0
  29. package/src/__tests__/compactor-summary-call-truncation.test.ts +2 -0
  30. package/src/__tests__/compactor-web-search-strip.test.ts +2 -0
  31. package/src/__tests__/computer-use-tools.test.ts +13 -0
  32. package/src/__tests__/config-loader-backfill.test.ts +5 -1
  33. package/src/__tests__/config-schema.test.ts +1 -0
  34. package/src/__tests__/confirmation-request-guardian-bridge.test.ts +31 -29
  35. package/src/__tests__/contacts-relay-reads.test.ts +13 -15
  36. package/src/__tests__/conversation-abort-tool-results.test.ts +2 -0
  37. package/src/__tests__/conversation-agent-loop-disk-pressure.test.ts +2 -0
  38. package/src/__tests__/conversation-agent-loop-inference-profile.test.ts +2 -0
  39. package/src/__tests__/conversation-agent-loop-overflow.test.ts +2 -0
  40. package/src/__tests__/conversation-agent-loop.test.ts +7 -0
  41. package/src/__tests__/conversation-analysis-routes.test.ts +2 -0
  42. package/src/__tests__/conversation-app-control-lifecycle.test.ts +2 -0
  43. package/src/__tests__/conversation-confirmation-signals.test.ts +2 -0
  44. package/src/__tests__/conversation-history-web-search.test.ts +2 -0
  45. package/src/__tests__/conversation-load-history-repair.test.ts +2 -0
  46. package/src/__tests__/conversation-load-history-stripped.test.ts +2 -0
  47. package/src/__tests__/conversation-pairing.test.ts +2 -0
  48. package/src/__tests__/conversation-process-app-control-preactivation.test.ts +2 -0
  49. package/src/__tests__/conversation-process-callsite.test.ts +2 -0
  50. package/src/__tests__/conversation-provider-retry-repair.test.ts +2 -0
  51. package/src/__tests__/conversation-queue.test.ts +91 -0
  52. package/src/__tests__/conversation-routes-guardian-reply.test.ts +14 -0
  53. package/src/__tests__/conversation-routes-slash-commands.test.ts +14 -0
  54. package/src/__tests__/conversation-slash-queue.test.ts +2 -0
  55. package/src/__tests__/conversation-slash-unknown.test.ts +2 -0
  56. package/src/__tests__/conversation-speed-override.test.ts +2 -0
  57. package/src/__tests__/conversation-surfaces-action-delivery.test.ts +65 -0
  58. package/src/__tests__/conversation-title-service.test.ts +2 -0
  59. package/src/__tests__/conversation-tool-setup-attribution.test.ts +47 -0
  60. package/src/__tests__/conversation-usage.test.ts +2 -0
  61. package/src/__tests__/conversation-workspace-cache-state.test.ts +2 -0
  62. package/src/__tests__/conversation-workspace-injection.test.ts +2 -0
  63. package/src/__tests__/conversation-workspace-tool-tracking.test.ts +2 -0
  64. package/src/__tests__/credential-security-invariants.test.ts +0 -1
  65. package/src/__tests__/db-migration-rollback.test.ts +205 -171
  66. package/src/__tests__/db-test-helpers.ts +5 -4
  67. package/src/__tests__/deterministic-verification-control-plane.test.ts +4 -2
  68. package/src/__tests__/disk-pressure-guard.test.ts +41 -0
  69. package/src/__tests__/dm-persistence.test.ts +2 -0
  70. package/src/__tests__/emit-signal-routing-intent.test.ts +10 -5
  71. package/src/__tests__/events-dev-bypass-actor.test.ts +7 -1
  72. package/src/__tests__/filing-service.test.ts +2 -0
  73. package/src/__tests__/guardian-binding-drift-heal.test.ts +75 -10
  74. package/src/__tests__/guardian-dispatch.test.ts +95 -1
  75. package/src/__tests__/guardian-outbound-http.test.ts +13 -0
  76. package/src/__tests__/heartbeat-disk-pressure.test.ts +2 -0
  77. package/src/__tests__/heartbeat-service.test.ts +2 -0
  78. package/src/__tests__/helpers/channel-test-adapter.ts +1 -7
  79. package/src/__tests__/host-app-control-routes.test.ts +24 -30
  80. package/src/__tests__/host-bash-routes.test.ts +31 -41
  81. package/src/__tests__/host-browser-routes.test.ts +26 -32
  82. package/src/__tests__/host-cu-proxy.test.ts +299 -0
  83. package/src/__tests__/host-cu-routes-targeted.test.ts +25 -33
  84. package/src/__tests__/host-file-routes-targeted.test.ts +40 -52
  85. package/src/__tests__/host-transfer-routes-targeted.test.ts +31 -43
  86. package/src/__tests__/http-user-message-parity.test.ts +167 -8
  87. package/src/__tests__/inbound-slack-persistence.test.ts +2 -0
  88. package/src/__tests__/invite-redemption-service.test.ts +43 -0
  89. package/src/__tests__/llm-context-normalization.test.ts +105 -0
  90. package/src/__tests__/llm-usage-store.test.ts +25 -0
  91. package/src/__tests__/media-stream-server-integration.test.ts +127 -0
  92. package/src/__tests__/memory-retrieval-hook.test.ts +2 -0
  93. package/src/__tests__/messaging-send-tool.test.ts +2 -0
  94. package/src/__tests__/migration-import-from-url.test.ts +2 -2
  95. package/src/__tests__/native-web-search.test.ts +2 -0
  96. package/src/__tests__/non-member-access-request.test.ts +189 -17
  97. package/src/__tests__/notification-broadcaster.test.ts +4 -0
  98. package/src/__tests__/notification-decision-recipient-context.test.ts +33 -32
  99. package/src/__tests__/notification-deep-link.test.ts +6 -0
  100. package/src/__tests__/notification-guardian-path.test.ts +19 -0
  101. package/src/__tests__/outbound-slack-persistence.test.ts +2 -0
  102. package/src/__tests__/pending-interactions-resolved-event.test.ts +7 -4
  103. package/src/__tests__/persistence-secret-redaction.test.ts +2 -0
  104. package/src/__tests__/plugin-bootstrap.test.ts +3 -73
  105. package/src/__tests__/plugin-route-contribution.test.ts +4 -17
  106. package/src/__tests__/plugin-tool-contribution.test.ts +3 -18
  107. package/src/__tests__/plugin-types.test.ts +0 -2
  108. package/src/__tests__/process-message-background-slack.test.ts +2 -0
  109. package/src/__tests__/process-message-display-content.test.ts +2 -0
  110. package/src/__tests__/provider-usage-tracking.test.ts +39 -0
  111. package/src/__tests__/regenerate-fire-and-forget-trace.test.ts +2 -0
  112. package/src/__tests__/registry.test.ts +3 -0
  113. package/src/__tests__/relay-server.test.ts +694 -25
  114. package/src/__tests__/runtime-attachment-metadata.test.ts +0 -1
  115. package/src/__tests__/secret-ingress-http.test.ts +14 -0
  116. package/src/__tests__/send-endpoint-busy.test.ts +30 -8
  117. package/src/__tests__/skills.test.ts +44 -0
  118. package/src/__tests__/slack-inbound-verification.test.ts +47 -2
  119. package/src/__tests__/sse-actor-principal-guardian-source.test.ts +102 -0
  120. package/src/__tests__/steer-on-enqueue-question.test.ts +181 -0
  121. package/src/__tests__/stt-hints.test.ts +44 -13
  122. package/src/__tests__/subagent-detail.test.ts +27 -0
  123. package/src/__tests__/subagent-disposal.test.ts +65 -0
  124. package/src/__tests__/subagent-notify-parent.test.ts +2 -0
  125. package/src/__tests__/subagent-spawn-tool-fork.test.ts +2 -0
  126. package/src/__tests__/subagent-tools.test.ts +2 -0
  127. package/src/__tests__/suggestion-routes.test.ts +2 -0
  128. package/src/__tests__/title-generate-hook.test.ts +2 -0
  129. package/src/__tests__/tool-executor-lifecycle-events.test.ts +2 -0
  130. package/src/__tests__/tool-executor.test.ts +16 -11
  131. package/src/__tests__/tool-preview-lifecycle.test.ts +2 -0
  132. package/src/__tests__/tool-result-metadata-plumbing.test.ts +2 -0
  133. package/src/__tests__/tool-start-timestamp.test.ts +2 -0
  134. package/src/__tests__/trusted-contact-inline-approval-integration.test.ts +10 -10
  135. package/src/__tests__/twilio-routes.test.ts +96 -0
  136. package/src/__tests__/verification-control-plane-policy.test.ts +2 -0
  137. package/src/__tests__/web-search-backend-failure.test.ts +2 -0
  138. package/src/__tests__/workspace-tool-loader.test.ts +195 -2
  139. package/src/agent/loop-exclusive-tool.test.ts +150 -0
  140. package/src/agent/loop.ts +56 -0
  141. package/src/api/constants/sse-replay.ts +41 -0
  142. package/src/api/index.ts +6 -0
  143. package/src/api/responses/llm-request-log-entry.ts +25 -0
  144. package/src/api/responses/subagent-detail.ts +17 -0
  145. package/src/calls/__tests__/relay-setup-router.test.ts +262 -4
  146. package/src/calls/call-domain.ts +3 -3
  147. package/src/calls/guardian-dispatch.ts +10 -8
  148. package/src/calls/inbound-trust-reader.ts +17 -1
  149. package/src/calls/media-stream-server.ts +21 -0
  150. package/src/calls/relay-server.ts +167 -50
  151. package/src/calls/relay-setup-router.ts +37 -7
  152. package/src/calls/relay-verification.ts +4 -4
  153. package/src/calls/stt-hints.ts +9 -12
  154. package/src/calls/twilio-routes.ts +14 -4
  155. package/src/cli/commands/__tests__/cache.test.ts +8 -1
  156. package/src/cli/commands/cache.ts +194 -181
  157. package/src/cli/commands/db/__tests__/repair.test.ts +6 -5
  158. package/src/cli/commands/db/status.ts +37 -1
  159. package/src/cli/commands/mcp.ts +252 -218
  160. package/src/cli/commands/memory/__tests__/worker.test.ts +302 -0
  161. package/src/cli/commands/memory/index.ts +2 -0
  162. package/src/cli/commands/memory/worker.ts +175 -0
  163. package/src/cli/commands/plugins.ts +75 -3
  164. package/src/cli/lib/__tests__/install-from-github.test.ts +102 -0
  165. package/src/cli/lib/__tests__/list-installed-plugins.test.ts +160 -1
  166. package/src/cli/lib/list-installed-plugins.ts +179 -1
  167. package/src/config/__tests__/loader-callsite-strip-fallback.test.ts +143 -0
  168. package/src/config/bundled-skills/computer-use/TOOLS.json +6 -1
  169. package/src/config/bundled-skills/contacts/tools/contact-merge.ts +27 -17
  170. package/src/config/bundled-skills/contacts/tools/contact-search.ts +13 -3
  171. package/src/config/feature-flag-registry.json +0 -8
  172. package/src/config/loader.ts +36 -5
  173. package/src/config/schemas/__tests__/memory-v3.test.ts +1 -0
  174. package/src/config/schemas/memory-lifecycle.ts +12 -0
  175. package/src/config/schemas/memory-v3.ts +7 -0
  176. package/src/config/schemas/memory.ts +4 -0
  177. package/src/config/schemas/timeouts.ts +8 -0
  178. package/src/config/seed-inference-profiles.ts +14 -5
  179. package/src/config/skills.ts +27 -5
  180. package/src/contacts/__tests__/guardian-delivery-reader.test.ts +312 -0
  181. package/src/contacts/contacts-write.ts +3 -0
  182. package/src/contacts/guardian-delivery-reader.ts +223 -0
  183. package/src/daemon/conversation-agent-loop.ts +9 -0
  184. package/src/daemon/conversation-process.ts +39 -17
  185. package/src/daemon/conversation-surfaces.ts +8 -0
  186. package/src/daemon/conversation-tool-setup.ts +49 -16
  187. package/src/daemon/conversation.ts +21 -2
  188. package/src/daemon/disk-pressure-guard.ts +12 -2
  189. package/src/daemon/event-loop-watchdog.ts +28 -1
  190. package/src/daemon/external-plugins-bootstrap.ts +4 -34
  191. package/src/daemon/handlers/__tests__/config-a2a-redeem.test.ts +25 -0
  192. package/src/daemon/handlers/__tests__/config-channels.test.ts +225 -0
  193. package/src/daemon/handlers/config-a2a.ts +6 -14
  194. package/src/daemon/handlers/config-channels.ts +78 -22
  195. package/src/daemon/handlers/conversations.ts +77 -0
  196. package/src/daemon/host-cu-proxy.ts +102 -11
  197. package/src/daemon/lifecycle.ts +4 -0
  198. package/src/daemon/memory-v2-startup.test.ts +72 -0
  199. package/src/daemon/memory-v2-startup.ts +87 -19
  200. package/src/daemon/server.ts +0 -4
  201. package/src/daemon/shutdown-handlers.ts +20 -0
  202. package/src/daemon/tool-setup-types.ts +9 -0
  203. package/src/ipc/__tests__/clients-list-ipc.test.ts +1 -1
  204. package/src/ipc/assistant-server.ts +2 -2
  205. package/src/memory/__tests__/301-create-watchdog-events.test.ts +110 -0
  206. package/src/memory/__tests__/memory-retrospective-job.test.ts +8 -0
  207. package/src/memory/__tests__/prompt-override.test.ts +192 -0
  208. package/src/memory/__tests__/watchdog-events-store.test.ts +161 -0
  209. package/src/memory/conversation-crud.ts +38 -0
  210. package/src/memory/db-connection.ts +22 -3
  211. package/src/memory/db-init.ts +36 -502
  212. package/src/memory/db-singleton.ts +6 -4
  213. package/src/memory/jobs-worker.ts +58 -0
  214. package/src/memory/llm-usage-store.ts +48 -20
  215. package/src/memory/memory-retrospective-job.ts +9 -8
  216. package/src/memory/migrations/014-backfill-inbox-thread-state.ts +13 -3
  217. package/src/memory/migrations/136-drop-assistant-id-columns.ts +52 -27
  218. package/src/memory/migrations/209-strip-thinking-from-consolidated.ts +130 -56
  219. package/src/memory/migrations/300-add-processing-started-at.ts +30 -0
  220. package/src/memory/migrations/301-create-watchdog-events.ts +45 -0
  221. package/src/memory/migrations/__tests__/014-backfill-inbox-thread-state.test.ts +108 -0
  222. package/src/memory/migrations/__tests__/136-drop-assistant-id-columns.test.ts +82 -0
  223. package/src/memory/migrations/__tests__/209-strip-thinking-from-consolidated.test.ts +224 -0
  224. package/src/memory/migrations/__tests__/run-migrations.test.ts +2 -2
  225. package/src/memory/migrations/run-migrations.ts +90 -6
  226. package/src/memory/migrations/schema-introspection.ts +14 -0
  227. package/src/memory/migrations/validate-migration-state.ts +101 -66
  228. package/src/memory/prompt-override.ts +129 -0
  229. package/src/memory/schema/conversations.ts +9 -0
  230. package/src/memory/schema/infrastructure.ts +20 -0
  231. package/src/memory/steps.ts +573 -0
  232. package/src/memory/v2/__tests__/cli-command-store.test.ts +25 -0
  233. package/src/memory/v2/__tests__/skill-store.test.ts +80 -0
  234. package/src/memory/v2/cli-command-store.ts +75 -38
  235. package/src/memory/v2/prompts/consolidation.ts +13 -82
  236. package/src/memory/v2/prompts/router.ts +21 -93
  237. package/src/memory/v2/skill-store.ts +68 -31
  238. package/src/memory/watchdog-events-store.ts +87 -0
  239. package/src/memory/worker-control.ts +118 -0
  240. package/src/memory/worker-process.ts +72 -0
  241. package/src/notifications/__tests__/broadcaster.test.ts +16 -8
  242. package/src/notifications/__tests__/connected-channels.test.ts +114 -0
  243. package/src/notifications/__tests__/decision-engine.test.ts +78 -9
  244. package/src/notifications/__tests__/destination-resolver.test.ts +256 -0
  245. package/src/notifications/broadcaster.ts +8 -1
  246. package/src/notifications/decision-engine.ts +15 -7
  247. package/src/notifications/destination-resolver.ts +68 -24
  248. package/src/notifications/emit-signal.ts +39 -14
  249. package/src/onboarding/checkin-event.test.ts +220 -0
  250. package/src/onboarding/checkin-event.ts +321 -0
  251. package/src/onboarding/schedule-checkin.ts +190 -0
  252. package/src/permissions/question-prompter.test.ts +1 -1
  253. package/src/permissions/question-prompter.ts +7 -4
  254. package/src/plugin-api/index.ts +6 -6
  255. package/src/plugin-api/types.ts +3 -5
  256. package/src/plugin-api/vision-support.test.ts +28 -4
  257. package/src/plugin-api/vision-support.ts +66 -31
  258. package/src/plugins/defaults/advisor/__tests__/consult.test.ts +161 -0
  259. package/src/plugins/defaults/advisor/__tests__/context-pack-gating.test.ts +106 -0
  260. package/src/plugins/defaults/advisor/__tests__/context-pack.test.ts +60 -0
  261. package/src/plugins/defaults/advisor/consult.ts +110 -6
  262. package/src/plugins/defaults/advisor/context-pack.ts +288 -0
  263. package/src/plugins/defaults/advisor/steering.ts +14 -2
  264. package/src/plugins/defaults/advisor/tools/advisor.ts +32 -5
  265. package/src/plugins/defaults/image-fallback/__tests__/image-fallback.test.ts +47 -7
  266. package/src/plugins/defaults/image-fallback/hooks/post-tool-use.ts +10 -11
  267. package/src/plugins/defaults/image-fallback/hooks/user-prompt-submit.ts +12 -20
  268. package/src/plugins/defaults/image-fallback/src/caption-blocks.ts +42 -11
  269. package/src/plugins/defaults/memory-v3-shadow/orchestrate.ts +11 -2
  270. package/src/plugins/defaults/memory-v3-shadow/pool-select.test.ts +146 -0
  271. package/src/plugins/defaults/memory-v3-shadow/pool-select.ts +29 -1
  272. package/src/plugins/defaults/memory-v3-shadow/shadow-plugin.ts +8 -1
  273. package/src/plugins/mtime-cache.ts +7 -2
  274. package/src/plugins/types.ts +0 -2
  275. package/src/providers/anthropic/client.ts +5 -0
  276. package/src/providers/call-site-routing.ts +4 -0
  277. package/src/providers/model-catalog.ts +16 -0
  278. package/src/providers/openai/responses-provider.ts +5 -0
  279. package/src/providers/openrouter/client.ts +5 -0
  280. package/src/providers/provider-send-message.ts +4 -0
  281. package/src/providers/ratelimit.ts +4 -0
  282. package/src/providers/retry.ts +4 -0
  283. package/src/providers/types.ts +9 -0
  284. package/src/providers/usage-tracking.ts +4 -0
  285. package/src/runtime/__tests__/channel-verification-service.test.ts +133 -0
  286. package/src/runtime/__tests__/guardian-vellum-migration.test.ts +181 -0
  287. package/src/runtime/__tests__/is-guardian-bound-for-channel.test.ts +66 -0
  288. package/src/runtime/__tests__/local-principal-trust.test.ts +164 -0
  289. package/src/runtime/__tests__/trust-verdict-consumer.test.ts +335 -3
  290. package/src/runtime/access-request-helper.ts +19 -39
  291. package/src/runtime/actor-trust-resolver.ts +2 -2
  292. package/src/runtime/anchored-guardian.test.ts +156 -0
  293. package/src/runtime/anchored-guardian.ts +135 -0
  294. package/src/runtime/assistant-event-hub.ts +1 -1
  295. package/src/runtime/assistant-stream-state.ts +9 -2
  296. package/src/runtime/auth/__tests__/require-bound-guardian.test.ts +99 -0
  297. package/src/runtime/auth/require-bound-guardian.ts +21 -11
  298. package/src/runtime/channel-verification-service.ts +56 -31
  299. package/src/runtime/confirmation-request-guardian-bridge.ts +3 -3
  300. package/src/runtime/guardian-vellum-migration.ts +66 -7
  301. package/src/runtime/invite-redemption-service.ts +50 -18
  302. package/src/runtime/local-actor-identity.ts +76 -11
  303. package/src/runtime/local-principal-trust.ts +52 -0
  304. package/src/runtime/pending-interactions.ts +11 -1
  305. package/src/runtime/routes/__tests__/channel-verification-revoke.test.ts +56 -5
  306. package/src/runtime/routes/__tests__/channel-verification-routes.test.ts +1 -1
  307. package/src/runtime/routes/__tests__/contact-routes.test.ts +212 -0
  308. package/src/runtime/routes/__tests__/global-search-routes.test.ts +93 -0
  309. package/src/runtime/routes/__tests__/surface-action-routes.test.ts +215 -1
  310. package/src/runtime/routes/browser-routes.ts +1 -1
  311. package/src/runtime/routes/channel-verification-routes.ts +3 -3
  312. package/src/runtime/routes/contact-routes.ts +8 -32
  313. package/src/runtime/routes/conversation-cli-routes.ts +4 -5
  314. package/src/runtime/routes/conversation-list-routes.ts +4 -7
  315. package/src/runtime/routes/conversation-routes.ts +74 -81
  316. package/src/runtime/routes/events-routes.ts +2 -2
  317. package/src/runtime/routes/global-search-routes.ts +3 -1
  318. package/src/runtime/routes/guardian-action-routes.ts +4 -5
  319. package/src/runtime/routes/host-app-control-routes.ts +5 -4
  320. package/src/runtime/routes/host-bash-routes.ts +5 -4
  321. package/src/runtime/routes/host-browser-routes.ts +9 -11
  322. package/src/runtime/routes/host-cu-routes.ts +5 -4
  323. package/src/runtime/routes/host-file-routes.ts +5 -4
  324. package/src/runtime/routes/host-transfer-routes.ts +6 -6
  325. package/src/runtime/routes/http-adapter.ts +1 -1
  326. package/src/runtime/routes/identity-routes.ts +3 -2
  327. package/src/runtime/routes/inbound-message-handler.ts +5 -5
  328. package/src/runtime/routes/inbound-stages/acl-enforcement.test.ts +97 -5
  329. package/src/runtime/routes/inbound-stages/acl-enforcement.ts +61 -49
  330. package/src/runtime/routes/inbound-stages/background-dispatch.ts +16 -4
  331. package/src/runtime/routes/inbound-stages/escalation-intercept.ts +7 -7
  332. package/src/runtime/routes/inbound-stages/guardian-activation-intercept.test.ts +21 -8
  333. package/src/runtime/routes/inbound-stages/guardian-activation-intercept.ts +14 -3
  334. package/src/runtime/routes/index.ts +2 -0
  335. package/src/runtime/routes/llm-context-normalization.ts +71 -0
  336. package/src/runtime/routes/mcp-auth-routes.ts +38 -15
  337. package/src/runtime/routes/migration-rollback-routes.ts +4 -3
  338. package/src/runtime/routes/migration-routes.ts +4 -1
  339. package/src/runtime/routes/onboarding-checkin-routes.ts +86 -0
  340. package/src/runtime/routes/subagents-routes.ts +5 -0
  341. package/src/runtime/routes/surface-action-routes.ts +51 -55
  342. package/src/runtime/services/__tests__/conversation-serializer.test.ts +1 -0
  343. package/src/runtime/services/conversation-serializer.ts +7 -9
  344. package/src/runtime/tool-grant-request-helper.ts +3 -3
  345. package/src/runtime/trust-verdict-consumer.ts +85 -9
  346. package/src/runtime/verification-outbound-actions.ts +18 -18
  347. package/src/signals/user-message.ts +16 -0
  348. package/src/subagent/manager.ts +9 -0
  349. package/src/telemetry/types.ts +34 -1
  350. package/src/telemetry/usage-telemetry-reporter.test.ts +3 -2
  351. package/src/telemetry/usage-telemetry-reporter.ts +87 -3
  352. package/src/tools/ask-question/ask-question-tool.test.ts +29 -0
  353. package/src/tools/ask-question/ask-question-tool.ts +13 -0
  354. package/src/tools/computer-use/definitions.ts +8 -2
  355. package/src/tools/executor.ts +4 -4
  356. package/src/tools/registry.ts +18 -0
  357. package/src/tools/tool-approval-handler.ts +1 -1
  358. package/src/tools/tool-defaults.ts +9 -2
  359. package/src/tools/types.ts +17 -2
  360. package/src/tools/workspace-tools/loader.ts +348 -244
  361. package/src/util/platform.ts +5 -0
  362. package/src/util/telemetry-db-path.ts +24 -0
  363. package/src/workspace/migrations/017-seed-persona-dirs.ts +3 -34
  364. package/src/workspace/migrations/019-scope-journal-to-guardian.ts +3 -24
  365. package/src/__tests__/workspace-tools-watcher-flag.test.ts +0 -70
  366. package/src/daemon/workspace-tools-watcher.ts +0 -328
  367. package/src/memory/migrations/registry.ts +0 -573
@@ -93,6 +93,7 @@ import {
93
93
  memoryV2ConsolidateJob,
94
94
  } from "./v2/consolidation-job.js";
95
95
  import { memoryV2SweepJob } from "./v2/sweep-job.js";
96
+ import { spawnMemoryWorkerProcess } from "./worker-control.js";
96
97
 
97
98
  const log = getLogger("memory-jobs-worker");
98
99
 
@@ -161,7 +162,64 @@ export interface MemoryJobsWorker {
161
162
  stop(): void;
162
163
  }
163
164
 
165
+ /**
166
+ * Start the memory jobs worker using the configured implementation.
167
+ *
168
+ * `memory.worker.enabled` selects between two implementations:
169
+ * - enabled: spawn the worker as a separate OS process (the same path as
170
+ * `assistant memory worker start`), keeping long-running jobs off the
171
+ * caller's event loop.
172
+ * - disabled (default): run the worker in-process on the caller's event
173
+ * loop.
174
+ *
175
+ * The flag is read here so callers don't branch on it themselves. It only
176
+ * governs which implementation starts; shutdown stops whichever worker is
177
+ * actually running (see daemon/shutdown-handlers.ts), so the handle returned
178
+ * for the out-of-process implementation has a no-op `stop()`.
179
+ *
180
+ * This dispatcher must not be used as the standalone worker process's entry —
181
+ * that would recurse and fork-bomb. `worker-process.ts` calls
182
+ * {@link startInProcessMemoryJobsWorker} directly.
183
+ */
164
184
  export function startMemoryJobsWorker(): MemoryJobsWorker {
185
+ if (getConfig().memory.worker?.enabled === true) {
186
+ void spawnMemoryWorkerProcess()
187
+ .then(({ pid, alreadyRunning }) =>
188
+ log.info(
189
+ { pid, alreadyRunning },
190
+ alreadyRunning
191
+ ? "Memory worker process already running — reusing it"
192
+ : "Memory worker process started",
193
+ ),
194
+ )
195
+ .catch((err) =>
196
+ log.warn(
197
+ { err },
198
+ "Failed to start memory worker process — memory jobs will not be processed",
199
+ ),
200
+ );
201
+ return {
202
+ async runOnce(): Promise<number> {
203
+ return 0;
204
+ },
205
+ // No-op: shutdown always stops the worker process via the live-state
206
+ // PID probe in daemon/shutdown-handlers.ts, since it can't know whether
207
+ // the process was started here or out of band (e.g. `assistant memory
208
+ // worker start`) after boot.
209
+ stop(): void {},
210
+ };
211
+ }
212
+
213
+ return startInProcessMemoryJobsWorker();
214
+ }
215
+
216
+ /**
217
+ * Run the memory jobs worker in-process on the caller's event loop: poll for
218
+ * claimable jobs with adaptive backoff until {@link MemoryJobsWorker.stop} is
219
+ * called. This is the worker loop itself — used directly by the daemon (when
220
+ * `memory.worker.enabled` is off) and by the standalone worker process.
221
+ */
222
+ export function startInProcessMemoryJobsWorker(): MemoryJobsWorker {
165
223
  const recovered = resetRunningJobsToPending();
166
224
  if (recovered > 0) {
167
225
  log.info({ recovered }, "Recovered stale running memory jobs");
@@ -525,7 +525,32 @@ export function getUsageTotals(
525
525
  };
526
526
  }
527
527
 
528
- /** Fetch raw events in a time range for in-memory bucketing. */
528
+ /**
529
+ * Width of the SQL pre-aggregation bucket used by the time-series read paths,
530
+ * in milliseconds. The series/daily endpoints bucket events into local-day or
531
+ * local-hour buckets in JavaScript (SQLite's `strftime` is UTC-only and can't
532
+ * honor an IANA timezone). To avoid materializing one JS object per usage event
533
+ * — which on a 90-day window can mean hundreds of thousands of rows on the
534
+ * daemon's main thread — we first roll events up in SQL into fixed UTC buckets,
535
+ * then feed those far-fewer rows into the same JS bucketing logic.
536
+ *
537
+ * 15 minutes is the finest quantum every real-world IANA UTC offset divides
538
+ * into (whole-hour offsets, plus the :30 and :45 zones like Asia/Kolkata and
539
+ * Asia/Kathmandu). Because every local-day and local-hour boundary therefore
540
+ * lands on a 15-minute UTC boundary, no pre-aggregation bucket can straddle a
541
+ * local bucket boundary — so rolling up to 15-minute UTC buckets and then
542
+ * re-bucketing in local time is exactly equal to bucketing each raw event.
543
+ * DST fall-back hours stay distinct because their instants fall in different
544
+ * 15-minute UTC buckets (and the JS layer disambiguates them by UTC offset).
545
+ */
546
+ const USAGE_PREAGG_BUCKET_MS = 15 * 60 * 1000;
547
+
548
+ /**
549
+ * Fetch usage rows for a time range, pre-aggregated into {@link
550
+ * USAGE_PREAGG_BUCKET_MS} UTC buckets, for in-memory local-time bucketing. Each
551
+ * returned row's `created_at` is its UTC bucket start, which the JS bucketing
552
+ * maps to the same local bucket every raw event in that window would map to.
553
+ */
529
554
  function fetchRawBucketRows(
530
555
  range: UsageTimeRange,
531
556
  filter?: UsageAggregationFilter,
@@ -534,13 +559,14 @@ function fetchRawBucketRows(
534
559
  return rawAll<UsageEventBucketRow>(
535
560
  /*sql*/ `
536
561
  SELECT
537
- created_at,
538
- input_tokens,
539
- output_tokens,
540
- estimated_cost_usd,
541
- llm_call_count
562
+ (created_at / ${USAGE_PREAGG_BUCKET_MS}) * ${USAGE_PREAGG_BUCKET_MS} AS created_at,
563
+ COALESCE(SUM(input_tokens), 0) AS input_tokens,
564
+ COALESCE(SUM(output_tokens), 0) AS output_tokens,
565
+ SUM(estimated_cost_usd) AS estimated_cost_usd,
566
+ SUM(COALESCE(llm_call_count, 1)) AS llm_call_count
542
567
  FROM llm_usage_events
543
568
  WHERE ${where.sql}
569
+ GROUP BY (created_at / ${USAGE_PREAGG_BUCKET_MS})
544
570
  ORDER BY created_at ASC
545
571
  `,
546
572
  ...where.params,
@@ -829,17 +855,18 @@ export function getUsageGroupedSeries(
829
855
  WHERE ${where.sql}
830
856
  )
831
857
  SELECT
832
- schedule_usage.created_at,
833
- schedule_usage.input_tokens,
834
- schedule_usage.output_tokens,
835
- schedule_usage.estimated_cost_usd,
836
- schedule_usage.llm_call_count,
837
- schedule_usage.group_key,
838
- schedule_group_jobs.name AS group_label
858
+ (schedule_usage.created_at / ${USAGE_PREAGG_BUCKET_MS}) * ${USAGE_PREAGG_BUCKET_MS} AS created_at,
859
+ COALESCE(SUM(schedule_usage.input_tokens), 0) AS input_tokens,
860
+ COALESCE(SUM(schedule_usage.output_tokens), 0) AS output_tokens,
861
+ SUM(schedule_usage.estimated_cost_usd) AS estimated_cost_usd,
862
+ SUM(COALESCE(schedule_usage.llm_call_count, 1)) AS llm_call_count,
863
+ schedule_usage.group_key AS group_key,
864
+ MAX(schedule_group_jobs.name) AS group_label
839
865
  FROM schedule_usage
840
866
  LEFT JOIN cron_jobs schedule_group_jobs
841
867
  ON schedule_group_jobs.id = schedule_usage.group_key
842
- ORDER BY schedule_usage.created_at ASC
868
+ GROUP BY (schedule_usage.created_at / ${USAGE_PREAGG_BUCKET_MS}), schedule_usage.group_key
869
+ ORDER BY created_at ASC
843
870
  `,
844
871
  ...groupKeySubquery.params,
845
872
  ...where.params,
@@ -850,15 +877,16 @@ export function getUsageGroupedSeries(
850
877
  rows = rawAll<UsageGroupedBucketRow>(
851
878
  /*sql*/ `
852
879
  SELECT
853
- e.created_at,
854
- e.input_tokens,
855
- e.output_tokens,
856
- e.estimated_cost_usd,
857
- e.llm_call_count,
880
+ (e.created_at / ${USAGE_PREAGG_BUCKET_MS}) * ${USAGE_PREAGG_BUCKET_MS} AS created_at,
881
+ COALESCE(SUM(e.input_tokens), 0) AS input_tokens,
882
+ COALESCE(SUM(e.output_tokens), 0) AS output_tokens,
883
+ SUM(e.estimated_cost_usd) AS estimated_cost_usd,
884
+ SUM(COALESCE(e.llm_call_count, 1)) AS llm_call_count,
858
885
  e.${column} AS group_key
859
886
  FROM llm_usage_events e
860
887
  WHERE ${where.sql}
861
- ORDER BY e.created_at ASC
888
+ GROUP BY (e.created_at / ${USAGE_PREAGG_BUCKET_MS}), e.${column}
889
+ ORDER BY created_at ASC
862
890
  `,
863
891
  ...where.params,
864
892
  );
@@ -44,7 +44,6 @@ import {
44
44
  } from "../channels/types.js";
45
45
  import type { AssistantConfig } from "../config/types.js";
46
46
  import { extractTurnContextTimestamp } from "../context/compactor.js";
47
- import { findConversation } from "../daemon/conversation-registry.js";
48
47
  import {
49
48
  formatLocalTimestamp,
50
49
  resolveTurnTimezoneContext,
@@ -63,6 +62,7 @@ import {
63
62
  forkConversationForRetrospective,
64
63
  getConversation,
65
64
  getMessagesAfter,
65
+ isConversationProcessing,
66
66
  resolveOverrideProfile,
67
67
  } from "./conversation-crud.js";
68
68
  import {
@@ -145,14 +145,15 @@ export async function runForkBasedRetrospective(
145
145
 
146
146
  // Forking mid-turn would capture a half-finished display turn — incremental
147
147
  // checkpoint persistence writes complete tool turns to the DB while the
148
- // agent loop is still running. Peek the in-memory registry only (an
149
- // unloaded conversation is by definition not processing); never load the
150
- // conversation just to check. Bump `lastRunAt` so the cooldown gate
151
- // applies, leave `lastProcessedMessageId` untouched so the next
152
- // interval/message-count trigger re-processes the same messages — nothing
153
- // is lost. Returning (not throwing) keeps the jobs-worker from
148
+ // agent loop is still running. Check the persisted `processing_started_at`
149
+ // column (the cross-process source of truth) instead of the in-memory
150
+ // registry, so this guard works even when running in a separate CLI
151
+ // process with an empty conversation registry. Bump `lastRunAt` so the
152
+ // cooldown gate applies, leave `lastProcessedMessageId` untouched so the
153
+ // next interval/message-count trigger re-processes the same messages —
154
+ // nothing is lost. Returning (not throwing) keeps the jobs-worker from
154
155
  // retry-with-backoff.
155
- if (findConversation(sourceConversationId)?.isProcessing()) {
156
+ if (isConversationProcessing(sourceConversationId)) {
156
157
  bumpRetrospectiveLastRunAt(sourceConversationId, Date.now());
157
158
  log.info(
158
159
  { sourceConversationId },
@@ -1,4 +1,5 @@
1
1
  import { type DrizzleDb, getSqliteFrom } from "../db-connection.js";
2
+ import { tableHasColumn } from "./schema-introspection.js";
2
3
 
3
4
  /**
4
5
  * One-shot migration: seed assistant_inbox_thread_state from existing
@@ -39,12 +40,22 @@ export function migrateBackfillInboxThreadStateFromBindings(
39
40
  return;
40
41
  }
41
42
 
43
+ // The assistant_id column was dropped from assistant_inbox_thread_state by a
44
+ // later migration (drop-assistant-id-columns). When the backfill checkpoint
45
+ // hasn't been written yet but that drop has already run, the table no longer
46
+ // carries assistant_id, so only reference the column when it still exists.
47
+ const hasAssistantId = tableHasColumn(
48
+ database,
49
+ "assistant_inbox_thread_state",
50
+ "assistant_id",
51
+ );
52
+
42
53
  try {
43
54
  raw.exec("BEGIN");
44
55
 
45
56
  raw.exec(/*sql*/ `
46
57
  INSERT OR IGNORE INTO assistant_inbox_thread_state (
47
- conversation_id, assistant_id, source_channel, external_chat_id,
58
+ conversation_id, ${hasAssistantId ? "assistant_id, " : ""}source_channel, external_chat_id,
48
59
  external_user_id, display_name, username,
49
60
  last_inbound_at, last_outbound_at, last_message_at,
50
61
  unread_count, pending_escalation_count, has_pending_escalation,
@@ -52,8 +63,7 @@ export function migrateBackfillInboxThreadStateFromBindings(
52
63
  )
53
64
  SELECT
54
65
  conversation_id,
55
- 'self',
56
- source_channel,
66
+ ${hasAssistantId ? "'self',\n " : ""}source_channel,
57
67
  external_chat_id,
58
68
  external_user_id,
59
69
  display_name,
@@ -1,5 +1,6 @@
1
1
  import { getLogger } from "../../util/logger.js";
2
2
  import { type DrizzleDb, getSqliteFrom } from "../db-connection.js";
3
+ import { tableExists } from "./schema-introspection.js";
3
4
 
4
5
  /**
5
6
  * Reverse v19: add assistant_id columns back to all 16 tables via
@@ -101,10 +102,7 @@ export function migrateDropAssistantIdColumns(database: DrizzleDb): void {
101
102
  );
102
103
 
103
104
  if (!cols.has("assistant_id")) {
104
- log.info(
105
- { table },
106
- "Table does not have assistant_id column — skipping",
107
- );
105
+ log.info({ table }, "Table does not have assistant_id column — skipping");
108
106
  continue;
109
107
  }
110
108
 
@@ -143,9 +141,7 @@ export function migrateDropAssistantIdColumns(database: DrizzleDb): void {
143
141
 
144
142
  // assistant_ingress_invites indexes (migration 112)
145
143
  raw.exec(/*sql*/ `DROP INDEX IF EXISTS idx_ingress_invites_channel_status`);
146
- raw.exec(
147
- /*sql*/ `DROP INDEX IF EXISTS idx_ingress_invites_channel_created`,
148
- );
144
+ raw.exec(/*sql*/ `DROP INDEX IF EXISTS idx_ingress_invites_channel_created`);
149
145
 
150
146
  // assistant_inbox_thread_state indexes (migration 112)
151
147
  raw.exec(/*sql*/ `DROP INDEX IF EXISTS idx_inbox_thread_state_channel`);
@@ -225,86 +221,115 @@ export function migrateDropAssistantIdColumns(database: DrizzleDb): void {
225
221
  // Each index below is the equivalent of the dropped index but with the
226
222
  // assistant_id column removed. Index names are updated to avoid
227
223
  // collisions with the old names.
224
+ //
225
+ // Some of these tables may have been dropped or renamed by earlier
226
+ // migrations. `CREATE INDEX IF NOT EXISTS` only guards against the index
227
+ // already existing — it still throws "no such table" when the underlying
228
+ // table is gone — so recreate each index only when its table is present.
229
+ const recreateIndex = (table: string, sql: string): void => {
230
+ if (!tableExists(database, table)) return;
231
+ raw.exec(sql);
232
+ };
228
233
 
229
234
  // channel_guardian_verification_challenges
230
- raw.exec(
235
+ recreateIndex(
236
+ "channel_guardian_verification_challenges",
231
237
  /*sql*/ `CREATE INDEX IF NOT EXISTS idx_channel_guardian_challenges_lookup ON channel_guardian_verification_challenges(channel, challenge_hash, status)`,
232
238
  );
233
- raw.exec(
239
+ recreateIndex(
240
+ "channel_guardian_verification_challenges",
234
241
  /*sql*/ `CREATE INDEX IF NOT EXISTS idx_guardian_sessions_active ON channel_guardian_verification_challenges(channel, status)`,
235
242
  );
236
- raw.exec(
243
+ recreateIndex(
244
+ "channel_guardian_verification_challenges",
237
245
  /*sql*/ `CREATE INDEX IF NOT EXISTS idx_guardian_sessions_identity ON channel_guardian_verification_challenges(channel, expected_external_user_id, expected_chat_id, status)`,
238
246
  );
239
- raw.exec(
247
+ recreateIndex(
248
+ "channel_guardian_verification_challenges",
240
249
  /*sql*/ `CREATE INDEX IF NOT EXISTS idx_guardian_sessions_destination ON channel_guardian_verification_challenges(channel, destination_address)`,
241
250
  );
242
- raw.exec(
251
+ recreateIndex(
252
+ "channel_guardian_verification_challenges",
243
253
  /*sql*/ `CREATE INDEX IF NOT EXISTS idx_guardian_sessions_bootstrap ON channel_guardian_verification_challenges(channel, bootstrap_token_hash, status)`,
244
254
  );
245
255
 
246
256
  // channel_guardian_rate_limits
247
- raw.exec(
257
+ recreateIndex(
258
+ "channel_guardian_rate_limits",
248
259
  /*sql*/ `CREATE UNIQUE INDEX IF NOT EXISTS idx_channel_guardian_rate_limits_actor ON channel_guardian_rate_limits(channel, actor_external_user_id, actor_chat_id)`,
249
260
  );
250
261
 
251
262
  // assistant_ingress_invites
252
- raw.exec(
263
+ recreateIndex(
264
+ "assistant_ingress_invites",
253
265
  /*sql*/ `CREATE INDEX IF NOT EXISTS idx_ingress_invites_channel_status ON assistant_ingress_invites(source_channel, status, expires_at)`,
254
266
  );
255
- raw.exec(
267
+ recreateIndex(
268
+ "assistant_ingress_invites",
256
269
  /*sql*/ `CREATE INDEX IF NOT EXISTS idx_ingress_invites_channel_created ON assistant_ingress_invites(source_channel, created_at)`,
257
270
  );
258
271
 
259
272
  // assistant_inbox_thread_state
260
- raw.exec(
273
+ recreateIndex(
274
+ "assistant_inbox_thread_state",
261
275
  /*sql*/ `CREATE UNIQUE INDEX IF NOT EXISTS idx_inbox_thread_state_channel ON assistant_inbox_thread_state(source_channel, external_chat_id)`,
262
276
  );
263
- raw.exec(
277
+ recreateIndex(
278
+ "assistant_inbox_thread_state",
264
279
  /*sql*/ `CREATE INDEX IF NOT EXISTS idx_inbox_thread_state_last_msg ON assistant_inbox_thread_state(last_message_at)`,
265
280
  );
266
- raw.exec(
281
+ recreateIndex(
282
+ "assistant_inbox_thread_state",
267
283
  /*sql*/ `CREATE INDEX IF NOT EXISTS idx_inbox_thread_state_escalation ON assistant_inbox_thread_state(has_pending_escalation, last_message_at)`,
268
284
  );
269
285
 
270
286
  // notification_preferences
271
- raw.exec(
287
+ recreateIndex(
288
+ "notification_preferences",
272
289
  /*sql*/ `CREATE INDEX IF NOT EXISTS idx_notification_preferences_priority ON notification_preferences(priority DESC)`,
273
290
  );
274
291
 
275
292
  // notification_events
276
- raw.exec(
293
+ recreateIndex(
294
+ "notification_events",
277
295
  /*sql*/ `CREATE INDEX IF NOT EXISTS idx_notification_events_event_created ON notification_events(source_event_name, created_at)`,
278
296
  );
279
- raw.exec(
297
+ recreateIndex(
298
+ "notification_events",
280
299
  /*sql*/ `CREATE UNIQUE INDEX IF NOT EXISTS idx_notification_events_dedupe ON notification_events(dedupe_key) WHERE dedupe_key IS NOT NULL`,
281
300
  );
282
301
 
283
302
  // notification_deliveries
284
- raw.exec(
303
+ recreateIndex(
304
+ "notification_deliveries",
285
305
  /*sql*/ `CREATE INDEX IF NOT EXISTS idx_notification_deliveries_status ON notification_deliveries(status)`,
286
306
  );
287
307
 
288
308
  // conversation_attention_events
289
- raw.exec(
309
+ recreateIndex(
310
+ "conversation_attention_events",
290
311
  /*sql*/ `CREATE INDEX IF NOT EXISTS idx_conv_attn_events_observed ON conversation_attention_events(observed_at)`,
291
312
  );
292
313
 
293
314
  // conversation_assistant_attention_state
294
- raw.exec(
315
+ recreateIndex(
316
+ "conversation_assistant_attention_state",
295
317
  /*sql*/ `CREATE INDEX IF NOT EXISTS idx_conv_attn_state_latest_msg ON conversation_assistant_attention_state(latest_assistant_message_at)`,
296
318
  );
297
- raw.exec(
319
+ recreateIndex(
320
+ "conversation_assistant_attention_state",
298
321
  /*sql*/ `CREATE INDEX IF NOT EXISTS idx_conv_attn_state_last_seen ON conversation_assistant_attention_state(last_seen_assistant_message_at)`,
299
322
  );
300
323
 
301
324
  // actor_token_records
302
- raw.exec(
325
+ recreateIndex(
326
+ "actor_token_records",
303
327
  /*sql*/ `CREATE UNIQUE INDEX IF NOT EXISTS idx_actor_tokens_active_device ON actor_token_records(guardian_principal_id, hashed_device_id) WHERE status = 'active'`,
304
328
  );
305
329
 
306
330
  // actor_refresh_token_records
307
- raw.exec(
331
+ recreateIndex(
332
+ "actor_refresh_token_records",
308
333
  /*sql*/ `CREATE UNIQUE INDEX IF NOT EXISTS idx_refresh_tokens_active_device ON actor_refresh_token_records(guardian_principal_id, hashed_device_id) WHERE status = 'active'`,
309
334
  );
310
335
 
@@ -1,6 +1,86 @@
1
+ import { getLogger } from "../../util/logger.js";
2
+ import { getDbPath } from "../../util/platform.js";
3
+ import { runAsyncSqlite } from "../db-async-query.js";
1
4
  import type { DrizzleDb } from "../db-connection.js";
2
5
  import { getSqliteFrom } from "../db-connection.js";
3
6
 
7
+ const log = getLogger("db-init");
8
+
9
+ /**
10
+ * Checkpoint key holding the highest `messages.rowid` already swept by this
11
+ * migration. Persisted after every window so an interrupted run resumes from
12
+ * where it left off instead of restarting the whole table scan. The value is a
13
+ * plain integer string — deliberately not `started`/`rolling_back`, so
14
+ * `recoverCrashedMigrations` never mistakes it for a stalled step and clears
15
+ * it, and not `step:`-prefixed, so `validateMigrationState` ignores it.
16
+ */
17
+ const WATERMARK_KEY = "migration_209_strip_thinking_watermark";
18
+
19
+ /**
20
+ * Number of `rowid` values swept per `runAsyncSqlite` dispatch. Each window is
21
+ * one off-thread subprocess transaction, so the size bounds both the WAL growth
22
+ * per statement and how long a single write lock is held, while keeping the
23
+ * number of subprocess spawns low on a large table.
24
+ */
25
+ const ROWID_WINDOW = 100_000;
26
+
27
+ /** SQL predicate: this `json_each` element is an internal reasoning block. */
28
+ const IS_THINKING = `json_extract(value, '$.type') IN ('thinking', 'redacted_thinking')`;
29
+
30
+ /**
31
+ * SQL predicate: this `json_each` element is kept. `IS NOT` (not `!=`) so a
32
+ * block with a NULL/absent `type` is preserved, matching the JS filter the
33
+ * original migration used (`b.type !== 'thinking'`).
34
+ */
35
+ const IS_KEPT = `json_extract(value, '$.type') IS NOT 'thinking' AND json_extract(value, '$.type') IS NOT 'redacted_thinking'`;
36
+
37
+ /**
38
+ * Build the two set-based UPDATEs that sweep one rowid window `(lo, hi]`.
39
+ *
40
+ * - Statement A strips thinking/redacted_thinking blocks from rows that retain
41
+ * at least one kept block, rebuilding the content array in place. `json(value)`
42
+ * re-embeds each surviving element as JSON rather than a quoted string.
43
+ * - Statement B replaces all-thinking rows (no kept block survives) with the
44
+ * null-byte placeholder sentinel so the message isn't left empty. `char(0)`
45
+ * is evaluated inside SQLite, so the literal NUL is produced in the database
46
+ * and never written into the SQL piped to the sqlite3 CLI.
47
+ *
48
+ * Both are gated by a cheap `content LIKE '%thinking%'` substring prefilter
49
+ * (covers both `thinking` and `redacted_thinking`) so the expensive `json_each`
50
+ * work only runs for rows that could possibly contain a reasoning block. The
51
+ * two statements touch disjoint row sets (A requires a kept block, B requires
52
+ * none), so their order within the window is immaterial.
53
+ */
54
+ function windowSql(lo: number, hi: number): string {
55
+ const scope = `role = 'assistant'
56
+ AND rowid > ${lo} AND rowid <= ${hi}
57
+ AND content LIKE '%thinking%'
58
+ AND json_valid(content)
59
+ AND json_type(content) = 'array'`;
60
+
61
+ const stripMixed = /*sql*/ `
62
+ UPDATE messages
63
+ SET content = (
64
+ SELECT json_group_array(json(value))
65
+ FROM json_each(messages.content)
66
+ WHERE ${IS_KEPT}
67
+ )
68
+ WHERE ${scope}
69
+ AND EXISTS (SELECT 1 FROM json_each(messages.content) WHERE ${IS_THINKING})
70
+ AND EXISTS (SELECT 1 FROM json_each(messages.content) WHERE ${IS_KEPT});`;
71
+
72
+ const placeholderOnly = /*sql*/ `
73
+ UPDATE messages
74
+ SET content = json_array(
75
+ json_object('type', 'text', 'text', char(0) || '__PLACEHOLDER__[internal blocks omitted]')
76
+ )
77
+ WHERE ${scope}
78
+ AND EXISTS (SELECT 1 FROM json_each(messages.content) WHERE ${IS_THINKING})
79
+ AND NOT EXISTS (SELECT 1 FROM json_each(messages.content) WHERE ${IS_KEPT});`;
80
+
81
+ return `${stripMixed}\n${placeholderOnly}`;
82
+ }
83
+
4
84
  /**
5
85
  * Strip thinking and redacted_thinking blocks from all assistant messages.
6
86
  *
@@ -11,68 +91,62 @@ import { getSqliteFrom } from "../db-connection.js";
11
91
  * provider no longer needs to strip, enabling append-only conversation
12
92
  * history and stable prefix caching.
13
93
  *
14
- * Idempotent — safe to re-run.
94
+ * The rewrite runs entirely inside SQLite (via JSON1), dispatched through
95
+ * {@link runAsyncSqlite} a rowid window at a time. On a host with the `sqlite3`
96
+ * CLI each window executes in a subprocess, leaving the daemon's event loop
97
+ * free to answer `/healthz` while a multi-GB table is rewritten — the original
98
+ * synchronous in-process loop blocked the loop for minutes and tripped the
99
+ * startup probe into a restart loop. Progress is checkpointed per window, so an
100
+ * interrupted run resumes instead of rescanning from the start.
101
+ *
102
+ * Idempotent — safe to re-run. Already-cleaned rows no longer contain a
103
+ * thinking block, so the substring prefilter skips them.
15
104
  */
16
- export function migrateStripThinkingFromConsolidated(
105
+ export async function migrateStripThinkingFromConsolidated(
17
106
  database: DrizzleDb,
18
- ): void {
107
+ ): Promise<void> {
19
108
  const raw = getSqliteFrom(database);
109
+ const dbPath = getDbPath();
20
110
 
21
- const BATCH_SIZE = 100;
22
- let lastRowid = 0;
23
-
24
- for (;;) {
25
- const rows = raw
26
- .query(
27
- `SELECT rowid, id, content FROM messages
28
- WHERE role = 'assistant'
29
- AND rowid > ?
30
- ORDER BY rowid
31
- LIMIT ?`,
32
- )
33
- .all(lastRowid, BATCH_SIZE) as Array<{
34
- rowid: number;
35
- id: string;
36
- content: string;
37
- }>;
38
-
39
- if (rows.length === 0) break;
40
-
41
- for (const row of rows) {
42
- lastRowid = row.rowid;
43
-
44
- let blocks: Array<{ type: string }>;
45
- try {
46
- const parsed = JSON.parse(row.content);
47
- if (!Array.isArray(parsed)) continue;
48
- blocks = parsed;
49
- } catch {
50
- continue;
51
- }
52
-
53
- const hasThinking = blocks.some(
54
- (b) => b.type === "thinking" || b.type === "redacted_thinking",
55
- );
56
- if (!hasThinking) continue;
111
+ const maxRow = (
112
+ raw.query(`SELECT MAX(rowid) AS m FROM messages`).get() as {
113
+ m: number | null;
114
+ }
115
+ ).m;
116
+ if (maxRow == null) return; // empty table — nothing to sweep
57
117
 
58
- const stripped = blocks.filter(
59
- (b) => b.type !== "thinking" && b.type !== "redacted_thinking",
60
- );
118
+ const watermarkRow = raw
119
+ .query(`SELECT value FROM memory_checkpoints WHERE key = ?`)
120
+ .get(WATERMARK_KEY) as { value: string } | undefined;
121
+ let lo = watermarkRow ? Number.parseInt(watermarkRow.value, 10) || 0 : 0;
122
+
123
+ const setWatermark = raw.query(
124
+ `INSERT OR REPLACE INTO memory_checkpoints (key, value, updated_at) VALUES (?, ?, ?)`,
125
+ );
61
126
 
62
- // Preserve at least one block so the message isn't empty.
63
- const finalContent =
64
- stripped.length > 0
65
- ? stripped
66
- : [
67
- {
68
- type: "text" as const,
69
- text: "\x00__PLACEHOLDER__[internal blocks omitted]",
70
- },
71
- ];
72
-
73
- raw
74
- .query(`UPDATE messages SET content = ? WHERE id = ?`)
75
- .run(JSON.stringify(finalContent), row.id);
127
+ while (lo < maxRow) {
128
+ const hi = Math.min(lo + ROWID_WINDOW, maxRow);
129
+
130
+ const res = await runAsyncSqlite(windowSql(lo, hi), { dbPath });
131
+ if (!res.ok) {
132
+ // Leave the watermark at the last completed window; throwing reports the
133
+ // step failed so the runner retries it (from the watermark) next boot
134
+ // rather than checkpointing it as done.
135
+ throw new Error(
136
+ `strip-thinking window (${lo}, ${hi}] failed: ${res.error}`,
137
+ );
76
138
  }
139
+
140
+ lo = hi;
141
+ setWatermark.run(WATERMARK_KEY, String(lo), Date.now());
77
142
  }
143
+
144
+ // Bound WAL growth left by the windowed rewrites, then drop the watermark so
145
+ // a future re-run (e.g. after a rollback) starts clean.
146
+ await runAsyncSqlite(`PRAGMA wal_checkpoint(TRUNCATE);`, { dbPath });
147
+ raw.query(`DELETE FROM memory_checkpoints WHERE key = ?`).run(WATERMARK_KEY);
148
+
149
+ log.info(
150
+ "Migration 209: stripped thinking blocks from consolidated messages",
151
+ );
78
152
  }
@@ -0,0 +1,30 @@
1
+ import type { DrizzleDb } from "../db-connection.js";
2
+ import { tableHasColumn } from "./schema-introspection.js";
3
+
4
+ const COLUMN_NAME = "processing_started_at";
5
+ const COLUMN_DEFINITION = "processing_started_at INTEGER";
6
+
7
+ /**
8
+ * Add `processing_started_at` column to the `conversations` table.
9
+ *
10
+ * The column is a nullable epoch-ms timestamp: non-NULL means the agent loop
11
+ * is mid-turn for this conversation, NULL means idle. This is the
12
+ * cross-process source of truth for processing state — the in-memory
13
+ * `Conversation._processing` flag is the hot-path read for resident
14
+ * conversations, but out-of-process callers (e.g. the retrospective CLI)
15
+ * read this column directly via `isConversationProcessing()`.
16
+ *
17
+ * No backfill is needed — all existing rows default to NULL (not processing),
18
+ * which is correct for any conversation that isn't actively mid-turn at
19
+ * migration time.
20
+ *
21
+ * Idempotent: guarded with `tableHasColumn` so a crash between the `ALTER
22
+ * TABLE` and the checkpoint write doesn't cause a duplicate-column error on
23
+ * the next boot.
24
+ */
25
+ export function migrateAddProcessingStartedAt(database: DrizzleDb): void {
26
+ if (tableHasColumn(database, "conversations", COLUMN_NAME)) {
27
+ return;
28
+ }
29
+ database.run(`ALTER TABLE conversations ADD COLUMN ${COLUMN_DEFINITION}`);
30
+ }