@otium-team/negotium 0.0.0-stage → 0.23.13

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 (572) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +329 -2
  3. package/bin/codex-sdk-window-hide.mjs +40 -0
  4. package/bin/negotium.mjs +22 -0
  5. package/dist/agent-helpers.js +23090 -0
  6. package/dist/agent-helpers.js.map +171 -0
  7. package/dist/background-bash.js +535 -0
  8. package/dist/background-bash.js.map +16 -0
  9. package/dist/browser-runtime.js +2334 -0
  10. package/dist/browser-runtime.js.map +35 -0
  11. package/dist/canonical-mcp-bridge.js +13 -0
  12. package/dist/canonical-mcp-bridge.js.map +9 -0
  13. package/dist/chunk-22kg3fsw.js +79 -0
  14. package/dist/chunk-22kg3fsw.js.map +9 -0
  15. package/dist/chunk-d4j77adx.js +336 -0
  16. package/dist/chunk-d4j77adx.js.map +13 -0
  17. package/dist/chunk-mk9x18jn.js +172 -0
  18. package/dist/chunk-mk9x18jn.js.map +12 -0
  19. package/dist/chunk-qd0vtfm2.js +3923 -0
  20. package/dist/chunk-qd0vtfm2.js.map +47 -0
  21. package/dist/chunk-wf7ny8eq.js +206 -0
  22. package/dist/chunk-wf7ny8eq.js.map +10 -0
  23. package/dist/chunk-ww8a4ej4.js +54 -0
  24. package/dist/chunk-ww8a4ej4.js.map +10 -0
  25. package/dist/cron.js +1 -0
  26. package/dist/hosted-agent.js +5982 -0
  27. package/dist/hosted-agent.js.map +62 -0
  28. package/dist/main.js +60229 -0
  29. package/dist/main.js.map +340 -0
  30. package/dist/mcp-catalog.js +39 -0
  31. package/dist/mcp-catalog.js.map +10 -0
  32. package/dist/mcp-factories.js +25767 -0
  33. package/dist/mcp-factories.js.map +181 -0
  34. package/dist/mcp-servers.js +50 -0
  35. package/dist/mcp-servers.js.map +10 -0
  36. package/dist/media.js +570 -0
  37. package/dist/media.js.map +15 -0
  38. package/dist/outbox.js +354 -0
  39. package/dist/outbox.js.map +15 -0
  40. package/dist/platform-runtime.js +73 -0
  41. package/dist/platform-runtime.js.map +12 -0
  42. package/dist/prompts.js +892 -0
  43. package/dist/prompts.js.map +15 -0
  44. package/dist/query-runtime.js +1071 -0
  45. package/dist/query-runtime.js.map +26 -0
  46. package/dist/registry.js +335 -0
  47. package/dist/registry.js.map +14 -0
  48. package/dist/rollout.js +57 -0
  49. package/dist/rollout.js.map +10 -0
  50. package/dist/runtime/cron/background-sessions.ts +119 -0
  51. package/dist/runtime/cron/context.ts +123 -0
  52. package/dist/runtime/cron/host.ts +67 -0
  53. package/dist/runtime/cron/index.ts +95 -0
  54. package/dist/runtime/cron/mcp-server.ts +556 -0
  55. package/dist/runtime/cron/module.ts +174 -0
  56. package/dist/runtime/cron/package.json +6 -0
  57. package/dist/runtime/cron/schedule.ts +211 -0
  58. package/dist/runtime/cron/scheduler.ts +444 -0
  59. package/dist/runtime/cron/scripts.ts +203 -0
  60. package/dist/runtime/cron/store.ts +1163 -0
  61. package/dist/runtime/cron/summarize.ts +115 -0
  62. package/dist/runtime/package.json +6 -0
  63. package/dist/runtime/scripts/faster-whisper-wrapper.py +87 -0
  64. package/dist/runtime/src/agents/api-topic-agent-switch.ts +179 -0
  65. package/dist/runtime/src/agents/archiver.ts +677 -0
  66. package/dist/runtime/src/agents/auth-check.ts +156 -0
  67. package/dist/runtime/src/agents/claude-notices.ts +130 -0
  68. package/dist/runtime/src/agents/claude-provider.ts +941 -0
  69. package/dist/runtime/src/agents/claude-registry.ts +117 -0
  70. package/dist/runtime/src/agents/claude-runtime-inspection.ts +43 -0
  71. package/dist/runtime/src/agents/codex-app-server.ts +138 -0
  72. package/dist/runtime/src/agents/codex-native-multi-agent.ts +360 -0
  73. package/dist/runtime/src/agents/codex-provider.ts +1193 -0
  74. package/dist/runtime/src/agents/codex-registry.ts +116 -0
  75. package/dist/runtime/src/agents/codex-tier-resolver.ts +74 -0
  76. package/dist/runtime/src/agents/codex-tree-kill.ts +54 -0
  77. package/dist/runtime/src/agents/codex-tree-manager.ts +230 -0
  78. package/dist/runtime/src/agents/codex-vault-hook-bridge.ts +240 -0
  79. package/dist/runtime/src/agents/codex-vault-hook.mjs +50 -0
  80. package/dist/runtime/src/agents/codex-windows-wrapper.ts +174 -0
  81. package/dist/runtime/src/agents/compaction-support.ts +75 -0
  82. package/dist/runtime/src/agents/compaction-tool-projection.ts +125 -0
  83. package/dist/runtime/src/agents/contracts.ts +75 -0
  84. package/dist/runtime/src/agents/deep-map.ts +13 -0
  85. package/dist/runtime/src/agents/execution-host.ts +118 -0
  86. package/dist/runtime/src/agents/explicit-agent-switch.ts +106 -0
  87. package/dist/runtime/src/agents/fixtures/claude-attachments.jsonl +2 -0
  88. package/dist/runtime/src/agents/fixtures/codex-shell.jsonl +5 -0
  89. package/dist/runtime/src/agents/fork.ts +100 -0
  90. package/dist/runtime/src/agents/hosted-agent.ts +78 -0
  91. package/dist/runtime/src/agents/idle-archiver.ts +225 -0
  92. package/dist/runtime/src/agents/idle-compact.ts +225 -0
  93. package/dist/runtime/src/agents/index.ts +225 -0
  94. package/dist/runtime/src/agents/maestro-provider.ts +246 -0
  95. package/dist/runtime/src/agents/maestro-registry.ts +189 -0
  96. package/dist/runtime/src/agents/mcp-tools/ask-user.ts +653 -0
  97. package/dist/runtime/src/agents/mcp-tools/common.ts +23 -0
  98. package/dist/runtime/src/agents/mcp-tools/inline-assets.ts +203 -0
  99. package/dist/runtime/src/agents/mcp-tools/publish-html.ts +183 -0
  100. package/dist/runtime/src/agents/mcp-tools/request-vault.ts +684 -0
  101. package/dist/runtime/src/agents/mcp-tools/self-config.ts +353 -0
  102. package/dist/runtime/src/agents/mcp-tools/spawn-subagent.ts +1349 -0
  103. package/dist/runtime/src/agents/mcp-tools/visual-compat.ts +18 -0
  104. package/dist/runtime/src/agents/mcp-tools/visuals.ts +60 -0
  105. package/dist/runtime/src/agents/memory-archive-policy.ts +54 -0
  106. package/dist/runtime/src/agents/model-catalog.ts +439 -0
  107. package/dist/runtime/src/agents/public-helpers.ts +149 -0
  108. package/dist/runtime/src/agents/registry.ts +35 -0
  109. package/dist/runtime/src/agents/rollout/claude.ts +336 -0
  110. package/dist/runtime/src/agents/rollout/codex.ts +910 -0
  111. package/dist/runtime/src/agents/rollout/index.ts +26 -0
  112. package/dist/runtime/src/agents/rollout/shared.ts +293 -0
  113. package/dist/runtime/src/agents/self-config-core.ts +704 -0
  114. package/dist/runtime/src/agents/task-events.ts +59 -0
  115. package/dist/runtime/src/agents/tool-format.ts +613 -0
  116. package/dist/runtime/src/agents/topic-agent-switch.ts +189 -0
  117. package/dist/runtime/src/agents/topic-cleanup.ts +285 -0
  118. package/dist/runtime/src/agents/vault-tool-policy.ts +36 -0
  119. package/dist/runtime/src/application/execute-external-user-turn.ts +23 -0
  120. package/dist/runtime/src/application/submit-runtime-gateway-turn.ts +484 -0
  121. package/dist/runtime/src/application/submit-user-message.ts +60 -0
  122. package/dist/runtime/src/application/switch-topic-effort.ts +48 -0
  123. package/dist/runtime/src/application/switch-topic-model.ts +79 -0
  124. package/dist/runtime/src/application/topic-service.ts +190 -0
  125. package/dist/runtime/src/application/turn-follow-ups.ts +291 -0
  126. package/dist/runtime/src/application/vault-command.ts +170 -0
  127. package/dist/runtime/src/bus.ts +409 -0
  128. package/dist/runtime/src/config-public.ts +2 -0
  129. package/dist/runtime/src/cron-host.ts +33 -0
  130. package/dist/runtime/src/cron-mcp-host.ts +5 -0
  131. package/dist/runtime/src/identifiers.ts +49 -0
  132. package/dist/runtime/src/index.ts +573 -0
  133. package/dist/runtime/src/mcp/agent-health-server.ts +8 -0
  134. package/dist/runtime/src/mcp/canonical-bridge-config.ts +84 -0
  135. package/dist/runtime/src/mcp/canonical-proxy-server.ts +308 -0
  136. package/dist/runtime/src/mcp/compaction-log-server.ts +25 -0
  137. package/dist/runtime/src/mcp/decision-server.ts +21 -0
  138. package/dist/runtime/src/mcp/dm-ipc.ts +60 -0
  139. package/dist/runtime/src/mcp/factories/agent-health.ts +394 -0
  140. package/dist/runtime/src/mcp/factories/compaction-log.ts +135 -0
  141. package/dist/runtime/src/mcp/factories/decision.ts +186 -0
  142. package/dist/runtime/src/mcp/factories/index.ts +73 -0
  143. package/dist/runtime/src/mcp/factories/session-comm.ts +184 -0
  144. package/dist/runtime/src/mcp/factories/session-history.ts +103 -0
  145. package/dist/runtime/src/mcp/factories/stdio-protection.ts +24 -0
  146. package/dist/runtime/src/mcp/factories/system-health.ts +259 -0
  147. package/dist/runtime/src/mcp/factories/task.ts +185 -0
  148. package/dist/runtime/src/mcp/factories/token-stats.ts +145 -0
  149. package/dist/runtime/src/mcp/factories/vault.ts +32 -0
  150. package/dist/runtime/src/mcp/mcp-helpers.ts +40 -0
  151. package/dist/runtime/src/mcp/peer-bridge.ts +119 -0
  152. package/dist/runtime/src/mcp/runtime-spec.ts +473 -0
  153. package/dist/runtime/src/mcp/session-comm/actor-policy.ts +160 -0
  154. package/dist/runtime/src/mcp/session-comm/bridge-ipc-config.ts +27 -0
  155. package/dist/runtime/src/mcp/session-comm/context.ts +113 -0
  156. package/dist/runtime/src/mcp/session-comm/default-host.ts +723 -0
  157. package/dist/runtime/src/mcp/session-comm/history-target.ts +89 -0
  158. package/dist/runtime/src/mcp/session-comm/history-tools.ts +113 -0
  159. package/dist/runtime/src/mcp/session-comm/hub-remote-session.ts +553 -0
  160. package/dist/runtime/src/mcp/session-comm/limits.ts +8 -0
  161. package/dist/runtime/src/mcp/session-comm/peer-forward.ts +251 -0
  162. package/dist/runtime/src/mcp/session-comm/runtime.ts +128 -0
  163. package/dist/runtime/src/mcp/session-comm/server.ts +1036 -0
  164. package/dist/runtime/src/mcp/session-comm/tell-permissions.ts +79 -0
  165. package/dist/runtime/src/mcp/session-comm/topic-catalog.ts +155 -0
  166. package/dist/runtime/src/mcp/session-comm/topic-config.ts +137 -0
  167. package/dist/runtime/src/mcp/session-comm/topics.ts +313 -0
  168. package/dist/runtime/src/mcp/session-history-limits.ts +36 -0
  169. package/dist/runtime/src/mcp/session-history-reader.ts +359 -0
  170. package/dist/runtime/src/mcp/session-history-server.ts +19 -0
  171. package/dist/runtime/src/mcp/stdio-protect.ts +7 -0
  172. package/dist/runtime/src/mcp/system-health-server.ts +5 -0
  173. package/dist/runtime/src/mcp/task-server.ts +17 -0
  174. package/dist/runtime/src/mcp/token-stats-server.ts +10 -0
  175. package/dist/runtime/src/mcp/vault-server.ts +12 -0
  176. package/dist/runtime/src/mcp/wiki-search-index.ts +359 -0
  177. package/dist/runtime/src/mcp/wiki-server.ts +2386 -0
  178. package/dist/runtime/src/mcp-runtime-host.ts +81 -0
  179. package/dist/runtime/src/media/file-events.ts +33 -0
  180. package/dist/runtime/src/media/text-extractor.ts +334 -0
  181. package/dist/runtime/src/media/video.ts +92 -0
  182. package/dist/runtime/src/node-host.ts +211 -0
  183. package/dist/runtime/src/outbox/coalescing-runner.ts +157 -0
  184. package/dist/runtime/src/outbox/file-ops.ts +267 -0
  185. package/dist/runtime/src/outbox/index.ts +26 -0
  186. package/dist/runtime/src/outbox/utils.ts +74 -0
  187. package/dist/runtime/src/platform/background-bash/context.ts +9 -0
  188. package/dist/runtime/src/platform/background-bash/manager.ts +292 -0
  189. package/dist/runtime/src/platform/background-bash/output-buffer.ts +323 -0
  190. package/dist/runtime/src/platform/config-helpers.ts +47 -0
  191. package/dist/runtime/src/platform/config.ts +618 -0
  192. package/dist/runtime/src/platform/constants.ts +30 -0
  193. package/dist/runtime/src/platform/debug-users.ts +14 -0
  194. package/dist/runtime/src/platform/delay.ts +1 -0
  195. package/dist/runtime/src/platform/error.ts +9 -0
  196. package/dist/runtime/src/platform/file-utils.ts +35 -0
  197. package/dist/runtime/src/platform/ipc.ts +55 -0
  198. package/dist/runtime/src/platform/jsonl.ts +277 -0
  199. package/dist/runtime/src/platform/lifecycle.ts +176 -0
  200. package/dist/runtime/src/platform/log-rotation.ts +45 -0
  201. package/dist/runtime/src/platform/logger.ts +42 -0
  202. package/dist/runtime/src/platform/maestro-bootstrap-env.ts +3 -0
  203. package/dist/runtime/src/platform/mcp-catalog-policy.ts +63 -0
  204. package/dist/runtime/src/platform/mcp-config.ts +1329 -0
  205. package/dist/runtime/src/platform/memoize-import.ts +26 -0
  206. package/dist/runtime/src/platform/modules.ts +145 -0
  207. package/dist/runtime/src/platform/node-plugins.ts +46 -0
  208. package/dist/runtime/src/platform/paths.ts +62 -0
  209. package/dist/runtime/src/platform/playwright/browser-processes.ts +300 -0
  210. package/dist/runtime/src/platform/playwright/capability.ts +5 -0
  211. package/dist/runtime/src/platform/playwright/headed-launch.ts +61 -0
  212. package/dist/runtime/src/platform/playwright/manager-utils.ts +128 -0
  213. package/dist/runtime/src/platform/playwright/manager.ts +1502 -0
  214. package/dist/runtime/src/platform/playwright/mcp-transport.ts +35 -0
  215. package/dist/runtime/src/platform/playwright/profile-management.ts +33 -0
  216. package/dist/runtime/src/platform/playwright/public-runtime.ts +52 -0
  217. package/dist/runtime/src/platform/playwright/transport-probe.ts +89 -0
  218. package/dist/runtime/src/platform/playwright/vault-broker.ts +261 -0
  219. package/dist/runtime/src/platform/public-runtime.ts +18 -0
  220. package/dist/runtime/src/prompts/agents/wiki-archiver.md +194 -0
  221. package/dist/runtime/src/prompts/builders.ts +696 -0
  222. package/dist/runtime/src/prompts/sessions/_shared-tools.md +38 -0
  223. package/dist/runtime/src/prompts/sessions/channel-system.md +13 -0
  224. package/dist/runtime/src/prompts/sessions/manager-system.md +34 -0
  225. package/dist/runtime/src/prompts/sessions/surfaces/cli.md +6 -0
  226. package/dist/runtime/src/prompts/sessions/surfaces/otium-manager.md +18 -0
  227. package/dist/runtime/src/prompts/sessions/surfaces/otium.md +6 -0
  228. package/dist/runtime/src/prompts/sessions/surfaces/telegram.md +5 -0
  229. package/dist/runtime/src/prompts/sessions/surfaces/terminal.md +6 -0
  230. package/dist/runtime/src/prompts/sessions/topic-system.md +9 -0
  231. package/dist/runtime/src/prompts/sessions/visual-design.md +38 -0
  232. package/dist/runtime/src/query/active-rooms.ts +514 -0
  233. package/dist/runtime/src/query/index.ts +23 -0
  234. package/dist/runtime/src/query/public-runtime.ts +28 -0
  235. package/dist/runtime/src/query/room-query-registry.ts +217 -0
  236. package/dist/runtime/src/query/session-inbox-cleanup.ts +45 -0
  237. package/dist/runtime/src/query/session-inbox-path.ts +42 -0
  238. package/dist/runtime/src/query/state.ts +116 -0
  239. package/dist/runtime/src/query/types.ts +8 -0
  240. package/dist/runtime/src/runtime/actor-topic-reach.ts +123 -0
  241. package/dist/runtime/src/runtime/actor-topic-scope.ts +255 -0
  242. package/dist/runtime/src/runtime/ask-callbacks.ts +217 -0
  243. package/dist/runtime/src/runtime/attachments.ts +149 -0
  244. package/dist/runtime/src/runtime/background-session-policy.ts +1 -0
  245. package/dist/runtime/src/runtime/background-sessions.ts +288 -0
  246. package/dist/runtime/src/runtime/bashrs-completions.ts +350 -0
  247. package/dist/runtime/src/runtime/channel-context.ts +115 -0
  248. package/dist/runtime/src/runtime/context-warning.ts +131 -0
  249. package/dist/runtime/src/runtime/cron-sessions.ts +35 -0
  250. package/dist/runtime/src/runtime/delivery-ack.ts +112 -0
  251. package/dist/runtime/src/runtime/errors.ts +70 -0
  252. package/dist/runtime/src/runtime/event-heartbeat.ts +77 -0
  253. package/dist/runtime/src/runtime/file-hooks.ts +81 -0
  254. package/dist/runtime/src/runtime/footer.ts +23 -0
  255. package/dist/runtime/src/runtime/gateway-capabilities.ts +22 -0
  256. package/dist/runtime/src/runtime/inbox.ts +1307 -0
  257. package/dist/runtime/src/runtime/playwright-turn-abort.ts +59 -0
  258. package/dist/runtime/src/runtime/public-helpers.ts +78 -0
  259. package/dist/runtime/src/runtime/remote-session-grant.ts +221 -0
  260. package/dist/runtime/src/runtime/remote-session-inbox.ts +943 -0
  261. package/dist/runtime/src/runtime/remote-session-reply-outbox.ts +168 -0
  262. package/dist/runtime/src/runtime/task-format.ts +18 -0
  263. package/dist/runtime/src/runtime/tasks.ts +53 -0
  264. package/dist/runtime/src/runtime/thread-context.ts +123 -0
  265. package/dist/runtime/src/runtime/thread-read.ts +67 -0
  266. package/dist/runtime/src/runtime/topic-config.ts +29 -0
  267. package/dist/runtime/src/runtime/turn-event-stream.ts +1051 -0
  268. package/dist/runtime/src/runtime/turn-runner.ts +2311 -0
  269. package/dist/runtime/src/runtime/turn-session.ts +116 -0
  270. package/dist/runtime/src/runtime/usage-alert.ts +51 -0
  271. package/dist/runtime/src/runtime/user-turn-envelope.ts +94 -0
  272. package/dist/runtime/src/runtime/visual-html.ts +175 -0
  273. package/dist/runtime/src/runtime/visual-store.ts +480 -0
  274. package/dist/runtime/src/runtime/visuals.ts +209 -0
  275. package/dist/runtime/src/runtime-gateway.ts +1045 -0
  276. package/dist/runtime/src/security/sanitize.ts +27 -0
  277. package/dist/runtime/src/security/sensitive-path.ts +41 -0
  278. package/dist/runtime/src/storage/activity-log.ts +167 -0
  279. package/dist/runtime/src/storage/api-messages.ts +766 -0
  280. package/dist/runtime/src/storage/api-topic-brief.ts +134 -0
  281. package/dist/runtime/src/storage/api-topic-config.ts +197 -0
  282. package/dist/runtime/src/storage/api-topics.ts +1647 -0
  283. package/dist/runtime/src/storage/app-settings.ts +50 -0
  284. package/dist/runtime/src/storage/ask-user-gates.ts +359 -0
  285. package/dist/runtime/src/storage/browser-profiles.ts +186 -0
  286. package/dist/runtime/src/storage/conversation-migration.ts +180 -0
  287. package/dist/runtime/src/storage/conversations.ts +377 -0
  288. package/dist/runtime/src/storage/decisions.ts +231 -0
  289. package/dist/runtime/src/storage/forum/agent-settings.ts +20 -0
  290. package/dist/runtime/src/storage/forum/index.ts +4 -0
  291. package/dist/runtime/src/storage/forum/repository.ts +283 -0
  292. package/dist/runtime/src/storage/forum/schema.ts +314 -0
  293. package/dist/runtime/src/storage/forum-db.ts +4 -0
  294. package/dist/runtime/src/storage/remote-session.ts +1028 -0
  295. package/dist/runtime/src/storage/runtime-events.ts +209 -0
  296. package/dist/runtime/src/storage/runtime-follow-ups.ts +212 -0
  297. package/dist/runtime/src/storage/runtime-gateway-submissions.ts +132 -0
  298. package/dist/runtime/src/storage/runtime-leases.ts +190 -0
  299. package/dist/runtime/src/storage/runtime-process-leases.ts +288 -0
  300. package/dist/runtime/src/storage/runtime-topic-state.ts +181 -0
  301. package/dist/runtime/src/storage/runtime-turn-requests.ts +846 -0
  302. package/dist/runtime/src/storage/self-schedules.ts +306 -0
  303. package/dist/runtime/src/storage/session-asks.ts +468 -0
  304. package/dist/runtime/src/storage/session-inbox-signal.ts +76 -0
  305. package/dist/runtime/src/storage/session-inbox.ts +161 -0
  306. package/dist/runtime/src/storage/sqlite.ts +154 -0
  307. package/dist/runtime/src/storage/storage-contract.ts +54 -0
  308. package/dist/runtime/src/storage/storage-host.ts +336 -0
  309. package/dist/runtime/src/storage/storage-public-host.ts +16 -0
  310. package/dist/runtime/src/storage/storage-public.ts +66 -0
  311. package/dist/runtime/src/storage/tasks.ts +172 -0
  312. package/dist/runtime/src/storage/token-stats.ts +432 -0
  313. package/dist/runtime/src/storage/topic-archive-state.ts +226 -0
  314. package/dist/runtime/src/storage/topic-archive.ts +169 -0
  315. package/dist/runtime/src/storage/topic-host-mcp-grants.ts +54 -0
  316. package/dist/runtime/src/storage/topic-link-records.ts +1085 -0
  317. package/dist/runtime/src/storage/topic-settings.ts +67 -0
  318. package/dist/runtime/src/storage/topic-tool-capabilities.ts +89 -0
  319. package/dist/runtime/src/storage/topic-transcript.ts +98 -0
  320. package/dist/runtime/src/storage/vault-crypto-core.ts +65 -0
  321. package/dist/runtime/src/storage/vault-crypto.ts +31 -0
  322. package/dist/runtime/src/storage/vault-public.ts +27 -0
  323. package/dist/runtime/src/storage/vault-request-gates.ts +359 -0
  324. package/dist/runtime/src/storage/vault.ts +388 -0
  325. package/dist/runtime/src/storage/wiki-summary-names.ts +52 -0
  326. package/dist/runtime/src/storage/wiki.ts +90 -0
  327. package/dist/runtime/src/topics/claim-abort.ts +190 -0
  328. package/dist/runtime/src/topics/create.ts +192 -0
  329. package/dist/runtime/src/topics/derive.ts +600 -0
  330. package/dist/runtime/src/topics/lifecycle.ts +425 -0
  331. package/dist/runtime/src/topics/links.ts +7 -0
  332. package/dist/runtime/src/topics/personal-general.ts +91 -0
  333. package/dist/runtime/src/topics/session.ts +1041 -0
  334. package/dist/runtime/src/topics/update.ts +287 -0
  335. package/dist/runtime/src/types/api.ts +591 -0
  336. package/dist/runtime/src/types.ts +418 -0
  337. package/dist/runtime/src/version.ts +1 -0
  338. package/dist/runtime/tsconfig.json +13 -0
  339. package/dist/runtime-gateway.js +514 -0
  340. package/dist/runtime-gateway.js.map +10 -0
  341. package/dist/runtime-helpers.js +1792 -0
  342. package/dist/runtime-helpers.js.map +40 -0
  343. package/dist/sqlite.js +66 -0
  344. package/dist/sqlite.js.map +10 -0
  345. package/dist/storage.js +5223 -0
  346. package/dist/storage.js.map +47 -0
  347. package/dist/types/apps/negotium/src/mcp-servers.d.ts +20 -0
  348. package/dist/types/packages/core/src/agents/api-topic-agent-switch.d.ts +38 -0
  349. package/dist/types/packages/core/src/agents/archiver.d.ts +87 -0
  350. package/dist/types/packages/core/src/agents/auth-check.d.ts +19 -0
  351. package/dist/types/packages/core/src/agents/claude-notices.d.ts +15 -0
  352. package/dist/types/packages/core/src/agents/claude-provider.d.ts +25 -0
  353. package/dist/types/packages/core/src/agents/claude-registry.d.ts +3 -0
  354. package/dist/types/packages/core/src/agents/claude-runtime-inspection.d.ts +9 -0
  355. package/dist/types/packages/core/src/agents/codex-app-server.d.ts +13 -0
  356. package/dist/types/packages/core/src/agents/codex-native-multi-agent.d.ts +20 -0
  357. package/dist/types/packages/core/src/agents/codex-provider.d.ts +64 -0
  358. package/dist/types/packages/core/src/agents/codex-registry.d.ts +3 -0
  359. package/dist/types/packages/core/src/agents/codex-tier-resolver.d.ts +10 -0
  360. package/dist/types/packages/core/src/agents/codex-tree-kill.d.ts +13 -0
  361. package/dist/types/packages/core/src/agents/codex-tree-manager.d.ts +28 -0
  362. package/dist/types/packages/core/src/agents/codex-vault-hook-bridge.d.ts +28 -0
  363. package/dist/types/packages/core/src/agents/codex-windows-wrapper.d.ts +30 -0
  364. package/dist/types/packages/core/src/agents/compaction-support.d.ts +5 -0
  365. package/dist/types/packages/core/src/agents/compaction-tool-projection.d.ts +9 -0
  366. package/dist/types/packages/core/src/agents/contracts.d.ts +68 -0
  367. package/dist/types/packages/core/src/agents/deep-map.d.ts +2 -0
  368. package/dist/types/packages/core/src/agents/execution-host.d.ts +33 -0
  369. package/dist/types/packages/core/src/agents/explicit-agent-switch.d.ts +26 -0
  370. package/dist/types/packages/core/src/agents/fork.d.ts +50 -0
  371. package/dist/types/packages/core/src/agents/hosted-agent.d.ts +15 -0
  372. package/dist/types/packages/core/src/agents/idle-archiver.d.ts +35 -0
  373. package/dist/types/packages/core/src/agents/idle-compact.d.ts +37 -0
  374. package/dist/types/packages/core/src/agents/index.d.ts +8 -0
  375. package/dist/types/packages/core/src/agents/maestro-provider.d.ts +75 -0
  376. package/dist/types/packages/core/src/agents/maestro-registry.d.ts +3 -0
  377. package/dist/types/packages/core/src/agents/mcp-tools/ask-user.d.ts +147 -0
  378. package/dist/types/packages/core/src/agents/mcp-tools/common.d.ts +14 -0
  379. package/dist/types/packages/core/src/agents/mcp-tools/inline-assets.d.ts +24 -0
  380. package/dist/types/packages/core/src/agents/mcp-tools/publish-html.d.ts +18 -0
  381. package/dist/types/packages/core/src/agents/mcp-tools/request-vault.d.ts +124 -0
  382. package/dist/types/packages/core/src/agents/mcp-tools/self-config.d.ts +45 -0
  383. package/dist/types/packages/core/src/agents/mcp-tools/spawn-subagent.d.ts +148 -0
  384. package/dist/types/packages/core/src/agents/mcp-tools/visual-compat.d.ts +55 -0
  385. package/dist/types/packages/core/src/agents/mcp-tools/visuals.d.ts +70 -0
  386. package/dist/types/packages/core/src/agents/memory-archive-policy.d.ts +24 -0
  387. package/dist/types/packages/core/src/agents/model-catalog.d.ts +132 -0
  388. package/dist/types/packages/core/src/agents/public-helpers.d.ts +17 -0
  389. package/dist/types/packages/core/src/agents/registry.d.ts +5 -0
  390. package/dist/types/packages/core/src/agents/rollout/claude.d.ts +77 -0
  391. package/dist/types/packages/core/src/agents/rollout/codex.d.ts +119 -0
  392. package/dist/types/packages/core/src/agents/rollout/index.d.ts +6 -0
  393. package/dist/types/packages/core/src/agents/rollout/shared.d.ts +56 -0
  394. package/dist/types/packages/core/src/agents/self-config-core.d.ts +199 -0
  395. package/dist/types/packages/core/src/agents/task-events.d.ts +19 -0
  396. package/dist/types/packages/core/src/agents/tool-format.d.ts +25 -0
  397. package/dist/types/packages/core/src/agents/topic-cleanup.d.ts +83 -0
  398. package/dist/types/packages/core/src/agents/vault-tool-policy.d.ts +2 -0
  399. package/dist/types/packages/core/src/bus.d.ts +141 -0
  400. package/dist/types/packages/core/src/identifiers.d.ts +27 -0
  401. package/dist/types/packages/core/src/mcp/canonical-bridge-config.d.ts +21 -0
  402. package/dist/types/packages/core/src/mcp/factories/agent-health.d.ts +5 -0
  403. package/dist/types/packages/core/src/mcp/factories/compaction-log.d.ts +8 -0
  404. package/dist/types/packages/core/src/mcp/factories/decision.d.ts +18 -0
  405. package/dist/types/packages/core/src/mcp/factories/index.d.ts +13 -0
  406. package/dist/types/packages/core/src/mcp/factories/session-comm.d.ts +38 -0
  407. package/dist/types/packages/core/src/mcp/factories/session-history.d.ts +11 -0
  408. package/dist/types/packages/core/src/mcp/factories/stdio-protection.d.ts +10 -0
  409. package/dist/types/packages/core/src/mcp/factories/system-health.d.ts +37 -0
  410. package/dist/types/packages/core/src/mcp/factories/task.d.ts +13 -0
  411. package/dist/types/packages/core/src/mcp/factories/token-stats.d.ts +20 -0
  412. package/dist/types/packages/core/src/mcp/factories/vault.d.ts +9 -0
  413. package/dist/types/packages/core/src/mcp/mcp-helpers.d.ts +26 -0
  414. package/dist/types/packages/core/src/mcp/peer-bridge.d.ts +92 -0
  415. package/dist/types/packages/core/src/mcp/runtime-spec.d.ts +147 -0
  416. package/dist/types/packages/core/src/mcp/session-comm/actor-policy.d.ts +120 -0
  417. package/dist/types/packages/core/src/mcp/session-comm/bridge-ipc-config.d.ts +6 -0
  418. package/dist/types/packages/core/src/mcp/session-comm/context.d.ts +44 -0
  419. package/dist/types/packages/core/src/mcp/session-comm/history-tools.d.ts +31 -0
  420. package/dist/types/packages/core/src/mcp/session-comm/hub-remote-session.d.ts +149 -0
  421. package/dist/types/packages/core/src/mcp/session-comm/limits.d.ts +8 -0
  422. package/dist/types/packages/core/src/mcp/session-comm/peer-forward.d.ts +85 -0
  423. package/dist/types/packages/core/src/mcp/session-comm/tell-permissions.d.ts +29 -0
  424. package/dist/types/packages/core/src/mcp/session-comm/topic-catalog.d.ts +59 -0
  425. package/dist/types/packages/core/src/mcp/session-history-limits.d.ts +20 -0
  426. package/dist/types/packages/core/src/mcp/session-history-reader.d.ts +35 -0
  427. package/dist/types/packages/core/src/mcp/wiki-search-index.d.ts +59 -0
  428. package/dist/types/packages/core/src/mcp/wiki-server.d.ts +53 -0
  429. package/dist/types/packages/core/src/media/file-events.d.ts +14 -0
  430. package/dist/types/packages/core/src/media/text-extractor.d.ts +34 -0
  431. package/dist/types/packages/core/src/outbox/coalescing-runner.d.ts +68 -0
  432. package/dist/types/packages/core/src/outbox/file-ops.d.ts +79 -0
  433. package/dist/types/packages/core/src/outbox/index.d.ts +3 -0
  434. package/dist/types/packages/core/src/outbox/utils.d.ts +16 -0
  435. package/dist/types/packages/core/src/platform/background-bash/context.d.ts +1 -0
  436. package/dist/types/packages/core/src/platform/background-bash/manager.d.ts +34 -0
  437. package/dist/types/packages/core/src/platform/config-helpers.d.ts +20 -0
  438. package/dist/types/packages/core/src/platform/config.d.ts +178 -0
  439. package/dist/types/packages/core/src/platform/constants.d.ts +20 -0
  440. package/dist/types/packages/core/src/platform/delay.d.ts +1 -0
  441. package/dist/types/packages/core/src/platform/error.d.ts +6 -0
  442. package/dist/types/packages/core/src/platform/file-utils.d.ts +16 -0
  443. package/dist/types/packages/core/src/platform/ipc.d.ts +32 -0
  444. package/dist/types/packages/core/src/platform/jsonl.d.ts +46 -0
  445. package/dist/types/packages/core/src/platform/lifecycle.d.ts +40 -0
  446. package/dist/types/packages/core/src/platform/logger.d.ts +20 -0
  447. package/dist/types/packages/core/src/platform/maestro-bootstrap-env.d.ts +0 -0
  448. package/dist/types/packages/core/src/platform/mcp-catalog-policy.d.ts +73 -0
  449. package/dist/types/packages/core/src/platform/mcp-config.d.ts +286 -0
  450. package/dist/types/packages/core/src/platform/memoize-import.d.ts +15 -0
  451. package/dist/types/packages/core/src/platform/paths.d.ts +18 -0
  452. package/dist/types/packages/core/src/platform/playwright/browser-processes.d.ts +60 -0
  453. package/dist/types/packages/core/src/platform/playwright/capability.d.ts +1 -0
  454. package/dist/types/packages/core/src/platform/playwright/headed-launch.d.ts +13 -0
  455. package/dist/types/packages/core/src/platform/playwright/manager-utils.d.ts +34 -0
  456. package/dist/types/packages/core/src/platform/playwright/manager.d.ts +194 -0
  457. package/dist/types/packages/core/src/platform/playwright/mcp-transport.d.ts +4 -0
  458. package/dist/types/packages/core/src/platform/playwright/profile-management.d.ts +8 -0
  459. package/dist/types/packages/core/src/platform/playwright/public-runtime.d.ts +6 -0
  460. package/dist/types/packages/core/src/platform/playwright/transport-probe.d.ts +13 -0
  461. package/dist/types/packages/core/src/platform/playwright/vault-broker.d.ts +6 -0
  462. package/dist/types/packages/core/src/platform/public-runtime.d.ts +3 -0
  463. package/dist/types/packages/core/src/prompts/builders.d.ts +78 -0
  464. package/dist/types/packages/core/src/query/active-rooms.d.ts +240 -0
  465. package/dist/types/packages/core/src/query/public-runtime.d.ts +4 -0
  466. package/dist/types/packages/core/src/query/room-query-registry.d.ts +71 -0
  467. package/dist/types/packages/core/src/query/session-inbox-cleanup.d.ts +5 -0
  468. package/dist/types/packages/core/src/query/session-inbox-path.d.ts +8 -0
  469. package/dist/types/packages/core/src/query/state.d.ts +25 -0
  470. package/dist/types/packages/core/src/query/types.d.ts +6 -0
  471. package/dist/types/packages/core/src/runtime/actor-topic-reach.d.ts +63 -0
  472. package/dist/types/packages/core/src/runtime/actor-topic-scope.d.ts +127 -0
  473. package/dist/types/packages/core/src/runtime/ask-callbacks.d.ts +53 -0
  474. package/dist/types/packages/core/src/runtime/attachments.d.ts +36 -0
  475. package/dist/types/packages/core/src/runtime/background-session-policy.d.ts +1 -0
  476. package/dist/types/packages/core/src/runtime/background-sessions.d.ts +27 -0
  477. package/dist/types/packages/core/src/runtime/bashrs-completions.d.ts +50 -0
  478. package/dist/types/packages/core/src/runtime/channel-context.d.ts +13 -0
  479. package/dist/types/packages/core/src/runtime/context-warning.d.ts +46 -0
  480. package/dist/types/packages/core/src/runtime/cron-sessions.d.ts +9 -0
  481. package/dist/types/packages/core/src/runtime/errors.d.ts +6 -0
  482. package/dist/types/packages/core/src/runtime/event-heartbeat.d.ts +17 -0
  483. package/dist/types/packages/core/src/runtime/file-hooks.d.ts +38 -0
  484. package/dist/types/packages/core/src/runtime/playwright-turn-abort.d.ts +12 -0
  485. package/dist/types/packages/core/src/runtime/public-helpers.d.ts +17 -0
  486. package/dist/types/packages/core/src/runtime/remote-session-grant.d.ts +91 -0
  487. package/dist/types/packages/core/src/runtime/remote-session-inbox.d.ts +206 -0
  488. package/dist/types/packages/core/src/runtime/remote-session-reply-outbox.d.ts +37 -0
  489. package/dist/types/packages/core/src/runtime/task-format.d.ts +4 -0
  490. package/dist/types/packages/core/src/runtime/tasks.d.ts +3 -0
  491. package/dist/types/packages/core/src/runtime/thread-context.d.ts +62 -0
  492. package/dist/types/packages/core/src/runtime/topic-config.d.ts +24 -0
  493. package/dist/types/packages/core/src/runtime/turn-event-stream.d.ts +47 -0
  494. package/dist/types/packages/core/src/runtime/turn-runner.d.ts +284 -0
  495. package/dist/types/packages/core/src/runtime/turn-session.d.ts +49 -0
  496. package/dist/types/packages/core/src/runtime/usage-alert.d.ts +11 -0
  497. package/dist/types/packages/core/src/runtime/user-turn-envelope.d.ts +37 -0
  498. package/dist/types/packages/core/src/runtime/visual-html.d.ts +13 -0
  499. package/dist/types/packages/core/src/runtime/visual-store.d.ts +71 -0
  500. package/dist/types/packages/core/src/runtime/visuals.d.ts +33 -0
  501. package/dist/types/packages/core/src/runtime-gateway.d.ts +282 -0
  502. package/dist/types/packages/core/src/security/sanitize.d.ts +16 -0
  503. package/dist/types/packages/core/src/security/sensitive-path.d.ts +1 -0
  504. package/dist/types/packages/core/src/storage/activity-log.d.ts +25 -0
  505. package/dist/types/packages/core/src/storage/api-messages.d.ts +156 -0
  506. package/dist/types/packages/core/src/storage/api-topic-brief.d.ts +39 -0
  507. package/dist/types/packages/core/src/storage/api-topic-config.d.ts +23 -0
  508. package/dist/types/packages/core/src/storage/api-topics.d.ts +274 -0
  509. package/dist/types/packages/core/src/storage/app-settings.d.ts +4 -0
  510. package/dist/types/packages/core/src/storage/ask-user-gates.d.ts +65 -0
  511. package/dist/types/packages/core/src/storage/browser-profiles.d.ts +31 -0
  512. package/dist/types/packages/core/src/storage/conversations.d.ts +149 -0
  513. package/dist/types/packages/core/src/storage/decisions.d.ts +45 -0
  514. package/dist/types/packages/core/src/storage/forum/agent-settings.d.ts +3 -0
  515. package/dist/types/packages/core/src/storage/forum/index.d.ts +4 -0
  516. package/dist/types/packages/core/src/storage/forum/repository.d.ts +42 -0
  517. package/dist/types/packages/core/src/storage/forum/schema.d.ts +38 -0
  518. package/dist/types/packages/core/src/storage/forum-db.d.ts +2 -0
  519. package/dist/types/packages/core/src/storage/remote-session.d.ts +318 -0
  520. package/dist/types/packages/core/src/storage/runtime-events.d.ts +33 -0
  521. package/dist/types/packages/core/src/storage/runtime-leases.d.ts +27 -0
  522. package/dist/types/packages/core/src/storage/runtime-process-leases.d.ts +47 -0
  523. package/dist/types/packages/core/src/storage/runtime-topic-state.d.ts +39 -0
  524. package/dist/types/packages/core/src/storage/runtime-turn-requests.d.ts +163 -0
  525. package/dist/types/packages/core/src/storage/self-schedules.d.ts +54 -0
  526. package/dist/types/packages/core/src/storage/session-asks.d.ts +78 -0
  527. package/dist/types/packages/core/src/storage/session-inbox-signal.d.ts +35 -0
  528. package/dist/types/packages/core/src/storage/session-inbox.d.ts +36 -0
  529. package/dist/types/packages/core/src/storage/sqlite.d.ts +20 -0
  530. package/dist/types/packages/core/src/storage/storage-contract.d.ts +46 -0
  531. package/dist/types/packages/core/src/storage/storage-host.d.ts +41 -0
  532. package/dist/types/packages/core/src/storage/storage-public-host.d.ts +7 -0
  533. package/dist/types/packages/core/src/storage/storage-public.d.ts +45 -0
  534. package/dist/types/packages/core/src/storage/tasks.d.ts +49 -0
  535. package/dist/types/packages/core/src/storage/token-stats.d.ts +69 -0
  536. package/dist/types/packages/core/src/storage/topic-archive-state.d.ts +33 -0
  537. package/dist/types/packages/core/src/storage/topic-archive.d.ts +42 -0
  538. package/dist/types/packages/core/src/storage/topic-host-mcp-grants.d.ts +5 -0
  539. package/dist/types/packages/core/src/storage/topic-link-records.d.ts +281 -0
  540. package/dist/types/packages/core/src/storage/topic-settings.d.ts +19 -0
  541. package/dist/types/packages/core/src/storage/topic-tool-capabilities.d.ts +37 -0
  542. package/dist/types/packages/core/src/storage/topic-transcript.d.ts +38 -0
  543. package/dist/types/packages/core/src/storage/vault-crypto-core.d.ts +6 -0
  544. package/dist/types/packages/core/src/storage/vault-crypto.d.ts +12 -0
  545. package/dist/types/packages/core/src/storage/vault-public.d.ts +3 -0
  546. package/dist/types/packages/core/src/storage/vault-request-gates.d.ts +69 -0
  547. package/dist/types/packages/core/src/storage/vault.d.ts +49 -0
  548. package/dist/types/packages/core/src/storage/wiki-summary-names.d.ts +13 -0
  549. package/dist/types/packages/core/src/storage/wiki.d.ts +15 -0
  550. package/dist/types/packages/core/src/topics/derive.d.ts +83 -0
  551. package/dist/types/packages/core/src/topics/lifecycle.d.ts +75 -0
  552. package/dist/types/packages/core/src/topics/links.d.ts +2 -0
  553. package/dist/types/packages/core/src/topics/personal-general.d.ts +15 -0
  554. package/dist/types/packages/core/src/topics/session.d.ts +70 -0
  555. package/dist/types/packages/core/src/types/api.d.ts +551 -0
  556. package/dist/types/packages/core/src/types.d.ts +405 -0
  557. package/dist/types/packages/core/src/version.d.ts +1 -0
  558. package/dist/types/packages/module-cron/src/background-sessions.d.ts +2 -0
  559. package/dist/types/packages/module-cron/src/context.d.ts +15 -0
  560. package/dist/types/packages/module-cron/src/host.d.ts +23 -0
  561. package/dist/types/packages/module-cron/src/index.d.ts +14 -0
  562. package/dist/types/packages/module-cron/src/module.d.ts +13 -0
  563. package/dist/types/packages/module-cron/src/schedule.d.ts +23 -0
  564. package/dist/types/packages/module-cron/src/scheduler.d.ts +46 -0
  565. package/dist/types/packages/module-cron/src/scripts.d.ts +29 -0
  566. package/dist/types/packages/module-cron/src/store.d.ts +152 -0
  567. package/dist/types/packages/module-cron/src/summarize.d.ts +4 -0
  568. package/dist/vault.js +848 -0
  569. package/dist/vault.js.map +18 -0
  570. package/install-bash-rs.mjs +90 -0
  571. package/install-browser-rs.mjs +83 -0
  572. package/package.json +171 -4
@@ -0,0 +1,47 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../packages/core/src/storage/activity-log.ts", "../../../packages/core/src/platform/jsonl.ts", "../../../packages/core/src/platform/file-utils.ts", "../../../packages/core/src/platform/logger.ts", "../../../packages/core/src/security/sanitize.ts", "../../../packages/core/src/storage/storage-host.ts", "../../../packages/core/src/storage/sqlite.ts", "../../../packages/core/src/storage/forum-db.ts", "../../../packages/core/src/storage/api-messages.ts", "../../../packages/core/src/storage/wiki-summary-names.ts", "../../../packages/core/src/storage/api-topic-brief.ts", "../../../packages/core/src/storage/api-topic-config.ts", "../../../packages/core/src/types.ts", "../../../packages/core/src/platform/config-helpers.ts", "../../../packages/core/src/platform/constants.ts", "../../../packages/core/src/storage/runtime-topic-state.ts", "../../../packages/core/src/storage/topic-link-records.ts", "../../../packages/core/src/storage/api-topics.ts", "../../../packages/core/src/storage/app-settings.ts", "../../../packages/core/src/storage/ask-user-gates.ts", "../../../packages/core/src/storage/conversations.ts", "../../../packages/core/src/storage/decisions.ts", "../../../packages/core/src/platform/error.ts", "../../../packages/core/src/storage/forum/schema.ts", "../../../packages/core/src/storage/forum/agent-settings.ts", "../../../packages/core/src/storage/forum/repository.ts", "../../../packages/core/src/storage/runtime-leases.ts", "../../../packages/core/src/storage/runtime-process-leases.ts", "../../../packages/core/src/storage/session-asks.ts", "../../../packages/core/src/storage/storage-public-host.ts", "../../../packages/core/src/storage/tasks.ts", "../../../packages/core/src/storage/token-stats.ts", "../../../packages/core/src/storage/topic-archive.ts", "../../../packages/core/src/agents/memory-archive-policy.ts", "../../../packages/core/src/storage/topic-transcript.ts", "../../../packages/core/src/storage/wiki.ts", "../../../packages/core/src/storage/topic-archive-state.ts", "../../../packages/core/src/storage/topic-settings.ts"],
4
+ "sourcesContent": [
5
+ "import {\n existsSync,\n mkdirSync,\n readdirSync,\n renameSync,\n statSync,\n unlinkSync,\n writeFileSync,\n} from \"node:fs\";\nimport { basename, join } from \"node:path\";\nimport { appendJsonlEntry, readJsonlLines } from \"#platform/jsonl\";\nimport { logger } from \"#platform/logger\";\nimport { sanitizeTopicName } from \"#security/sanitize\";\nimport { resolveStorageLogDir, resolveStorageUsersLogDir } from \"#storage/storage-host\";\nimport type { TokenUsage } from \"#types\";\n\n// --- Log rotation config ---\nconst MAX_FILE_SIZE = 5 * 1024 * 1024; // 5MB per log file\nconst MAX_TOTAL_SIZE = 200 * 1024 * 1024; // 200MB total log budget\nconst ROTATION_CHECK_INTERVAL = 60 * 60 * 1000; // check every hour\nlet rotationTimer: ReturnType<typeof setInterval> | null = null;\n\nfunction startLogRotation(): void {\n if (rotationTimer) return;\n rotateOldLogs();\n rotationTimer = setInterval(rotateOldLogs, ROTATION_CHECK_INTERVAL);\n rotationTimer.unref?.();\n}\n\nexport interface LogEntry {\n timestamp: string;\n userId: number;\n sessionId: string | null;\n session: string;\n prompt: string;\n response: string;\n usage?: TokenUsage;\n}\n\nexport function writeLog(entry: LogEntry) {\n startLogRotation();\n const logDir = resolveStorageLogDir();\n mkdirSync(logDir, { recursive: true });\n const safeSession = sanitizeTopicName(entry.session);\n const sidShort = entry.sessionId ? entry.sessionId.slice(0, 8) : \"new\";\n const file = join(logDir, `${entry.userId}_${safeSession}_${sidShort}.jsonl`);\n\n // Rotate if file is too large\n try {\n const stat = statSync(file);\n if (stat.size >= MAX_FILE_SIZE) {\n const rotated = file.replace(/\\.jsonl$/, `.${Date.now()}.jsonl`);\n renameSync(file, rotated);\n }\n } catch {\n // File doesn't exist yet, fine\n }\n\n try {\n appendJsonlEntry(file, entry);\n } catch (e) {\n // Activity logging is telemetry: a contended append must never take down\n // the turn that produced the entry. Matches `writeSentFileLog` below.\n logger.warn({ err: e, userId: entry.userId, session: entry.session }, \"Failed to write log\");\n }\n}\n\n/** Remove oldest log files when total size exceeds budget */\nexport function rotateOldLogs() {\n const logDir = resolveStorageLogDir();\n mkdirSync(logDir, { recursive: true });\n try {\n const files = readdirSync(logDir)\n .filter((f) => f.endsWith(\".jsonl\"))\n .map((f) => {\n try {\n const stat = statSync(join(logDir, f));\n return { name: f, size: stat.size, mtimeMs: stat.mtimeMs };\n } catch {\n return null;\n }\n })\n .filter((f): f is NonNullable<typeof f> => f !== null);\n\n const totalSize = files.reduce((sum, f) => sum + f.size, 0);\n if (totalSize <= MAX_TOTAL_SIZE) return;\n\n // Delete oldest files first until under budget\n files.sort((a, b) => a.mtimeMs - b.mtimeMs);\n let freed = 0;\n const toFree = totalSize - MAX_TOTAL_SIZE;\n for (const file of files) {\n if (freed >= toFree) break;\n try {\n unlinkSync(join(logDir, file.name));\n freed += file.size;\n logger.info(\n { file: file.name, sizeKB: (file.size / 1024).toFixed(0) },\n \"Rotated out old log\",\n );\n } catch (e) {\n logger.warn({ err: e, file: file.name }, \"Log rotation: failed to delete old log file\");\n }\n }\n } catch (e) {\n logger.warn({ err: e }, \"Log rotation failed\");\n }\n}\n\nexport interface SentFileEntry {\n timestamp: string;\n userId: number;\n topicName: string;\n sessionId: string | null;\n filePath: string;\n fileName: string;\n}\n\nexport function writeSentFileLog(entry: Omit<SentFileEntry, \"fileName\">) {\n const dir = join(resolveStorageUsersLogDir(), String(entry.userId));\n mkdirSync(dir, { recursive: true });\n const file = join(dir, \"sent-files.jsonl\");\n try {\n appendJsonlEntry(file, { ...entry, fileName: basename(entry.filePath) });\n } catch (e) {\n logger.warn({ err: e, entry }, \"Failed to write sent-file log\");\n }\n}\n\nfunction entryMatchesTopic(e: SentFileEntry, topicName: string): boolean {\n return e.topicName === topicName;\n}\n\nexport function readSentFilesForTopic(userId: number, topicName: string): SentFileEntry[] {\n const file = join(resolveStorageUsersLogDir(), String(userId), \"sent-files.jsonl\");\n if (!existsSync(file)) return [];\n try {\n return readJsonlLines(file)\n .map((line) => JSON.parse(line) as SentFileEntry)\n .filter((e) => entryMatchesTopic(e, topicName));\n } catch (e) {\n logger.warn({ err: e, userId, topicName }, \"Failed to read sent-files log\");\n return [];\n }\n}\n\n/** 토픽 삭제 후 JSONL에서 해당 토픽 항목 제거 */\nexport function removeSentFilesForTopic(userId: number, topicName: string): void {\n const file = join(resolveStorageUsersLogDir(), String(userId), \"sent-files.jsonl\");\n if (!existsSync(file)) return;\n try {\n const remaining = readJsonlLines(file).filter((line) => {\n try {\n return !entryMatchesTopic(JSON.parse(line) as SentFileEntry, topicName);\n } catch {\n return true;\n }\n });\n if (remaining.length > 0) {\n writeFileSync(file, `${remaining.join(\"\\n\")}\\n`);\n } else {\n unlinkSync(file);\n }\n } catch (e) {\n logger.warn({ err: e, userId, topicName }, \"Failed to remove sent-files for topic\");\n }\n}\n",
6
+ "import {\n appendFileSync,\n closeSync,\n fsyncSync,\n mkdirSync,\n openSync,\n readFileSync,\n renameSync,\n statSync,\n unlinkSync,\n writeFileSync,\n} from \"node:fs\";\nimport { dirname } from \"node:path\";\nimport { safeUnlink } from \"#platform/file-utils\";\n\nexport function readJsonlLines(filePath: string): string[] {\n return readFileSync(filePath, \"utf-8\").trim().split(\"\\n\").filter(Boolean);\n}\n\n/**\n * Parse a JSONL string (one JSON value per line) into an array of `T`.\n * Throws on malformed lines — use when a corrupt fixture/log should fail\n * loudly rather than silently drop entries (paired with `readJsonlLines`'\n * resilient counterpart for live data streams).\n */\nexport function parseJsonlText<T = unknown>(raw: string): T[] {\n return raw\n .trim()\n .split(\"\\n\")\n .filter(Boolean)\n .map((line) => JSON.parse(line) as T);\n}\n\n/**\n * Read and JSON-parse a file. Returns null if the file is missing or contains\n * invalid JSON. Use when a missing/corrupt file should fall through to a\n * default rather than throw.\n */\nexport function readJsonFile<T = unknown>(filePath: string): T | null {\n try {\n return JSON.parse(readFileSync(filePath, \"utf-8\")) as T;\n } catch {\n return null;\n }\n}\n\n/** Atomically replace a JSON file and fsync the new contents before rename. */\nexport function writeJsonFileAtomic(filePath: string, value: unknown): void {\n const dir = dirname(filePath);\n mkdirSync(dir, { recursive: true });\n const tmpPath = `${filePath}.tmp-${process.pid}-${Date.now()}-${Math.random()\n .toString(16)\n .slice(2)}`;\n let fd: number | null = null;\n try {\n fd = openSync(tmpPath, \"wx\", 0o600);\n writeFileSync(fd, JSON.stringify(value, null, 2));\n fsyncSync(fd);\n closeSync(fd);\n fd = null;\n renameSync(tmpPath, filePath);\n fsyncDirectoryBestEffort(dir);\n } catch (err) {\n if (fd !== null) {\n try {\n closeSync(fd);\n } catch {}\n }\n safeUnlink(tmpPath);\n throw err;\n }\n}\n\n// --- Cross-process append lock ---\n// POSIX `O_APPEND` is only atomic when the write payload fits in PIPE_BUF\n// (Linux 4096, macOS 512). MCP servers and the bot run as separate\n// processes that all `appendFileSync` to shared inbox/outbox files; a long\n// `tell_session` prompt or large `ask_session` reply is comfortably above\n// PIPE_BUF, and a concurrent append from another process can interleave at\n// the byte level — the result fails JSON parse and the entire entry is\n// silently dropped by `parseOutboxLine`.\n//\n// Mitigation: a sidecar `<filePath>.lock` created with `O_EXCL` serializes\n// every append at the OS level. Lock is held for the duration of one\n// `appendFileSync`, so the contention window is microseconds. Stale locks\n// (process crashed mid-write) are detected via mtime and forcibly removed\n// after `LOCK_STALE_MS`.\n//\n// When the lock still cannot be acquired within `LOCK_TIMEOUT_MS`, the append\n// FAILS. It used to fall through to an unlocked `appendFileSync` on the theory\n// that a possibly-interleaved entry beats a dropped one — but an interleaved\n// write is exactly the corruption the lock exists to prevent, it can damage a\n// neighbouring well-formed entry as well as its own, and `parseOutboxLine`\n// discards the wreckage later and far from the cause. The caller was told the\n// write succeeded. Failing loudly lets each caller choose: surface the error to\n// its client, or log and continue.\n//\n// The timeout MUST outlast the staleness threshold. A writer killed while\n// holding the lock leaves the file behind, and only the mtime check reclaims\n// it. With a timeout shorter than `LOCK_STALE_MS` every append issued in the\n// first few seconds after such a crash gave up *before* the reclaim could fire\n// — measured as a ~3.5s window in which every append to that file failed, all\n// of which the pre-throw fallback used to deliver. Waiting past the staleness\n// threshold means a dead holder is always reclaimed rather than waited out, so\n// a timeout now means a *live* holder has been stuck for over five seconds,\n// which is a genuine fault worth reporting.\nconst LOCK_SUFFIX = \".lock\";\nconst LOCK_RETRY_MS = 5;\nconst DEFAULT_LOCK_STALE_MS = 5000;\n/** Headroom so a waiter never gives up exactly as the reclaim becomes due. */\nconst LOCK_TIMEOUT_HEADROOM_MS = 1500;\n\n/**\n * Staleness threshold, overridable so tests can exercise the timeout path\n * without blocking a real five seconds.\n *\n * Read per call rather than captured at import: the constants are consulted\n * once per append, which is nothing next to the file I/O that follows, and a\n * module-level snapshot could not be adjusted by a test that imports this\n * module transitively.\n */\nfunction lockStaleMs(): number {\n const raw = Number.parseInt(process.env.NEGOTIUM_JSONL_LOCK_STALE_MS ?? \"\", 10);\n return Number.isFinite(raw) && raw > 0 ? raw : DEFAULT_LOCK_STALE_MS;\n}\n\n/** Always > `lockStaleMs()`, so a dead holder is reclaimed rather than waited out. */\nfunction lockTimeoutMs(): number {\n return lockStaleMs() + LOCK_TIMEOUT_HEADROOM_MS;\n}\nconst LOCK_SLEEP = new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));\n\n/**\n * The append lock could not be acquired, so nothing was written.\n *\n * Distinguishable from an I/O error so callers can retry, degrade, or report\n * contention specifically. Nothing was appended when this is thrown.\n */\nexport class JsonlLockTimeoutError extends Error {\n constructor(\n readonly filePath: string,\n readonly timeoutMs: number,\n ) {\n super(`jsonl append lock busy after ${timeoutMs}ms; nothing written to ${filePath}`);\n this.name = \"JsonlLockTimeoutError\";\n }\n}\n\n/** Synchronous, non-spinning sleep supported by both Bun and Node MCP workers. */\nfunction sleepForAppendLock(ms: number): void {\n Atomics.wait(LOCK_SLEEP, 0, 0, ms);\n}\n\nfunction tryAcquireAppendLock(lockPath: string): boolean {\n try {\n closeSync(openSync(lockPath, \"wx\")); // O_CREAT | O_EXCL — atomic\n return true;\n } catch (e) {\n if ((e as NodeJS.ErrnoException).code !== \"EEXIST\") throw e;\n return false;\n }\n}\n\nfunction isStaleLock(lockPath: string): boolean {\n try {\n return Date.now() - statSync(lockPath).mtimeMs > lockStaleMs();\n } catch {\n return false;\n }\n}\n\n/**\n * Append a JSON-encoded entry + newline to a JSONL file. Ensures the parent\n * directory exists and serializes concurrent multi-process appends through a\n * sidecar lock so payloads larger than PIPE_BUF do not interleave.\n *\n * The drainer side (`outbox/file-ops.ts`) claims the file via atomic rename\n * and handles recovery of leftover `.processing` files from crashes.\n */\nexport function appendJsonlEntry(filePath: string, entry: unknown): void {\n appendJsonlLine(filePath, `${JSON.stringify(entry)}\\n`);\n}\n\n/**\n * Append an already-serialized JSONL line (must end with \"\\n\") under the\n * same cross-process append lock as `appendJsonlEntry`. Use when you\n * want to write back a raw line **exactly** — e.g. flusher tail-writeback\n * preserving lines that current parser can't decode, so a future parser\n * release still sees them.\n */\nexport function appendJsonlLine(filePath: string, line: string): void {\n mkdirSync(dirname(filePath), { recursive: true });\n const lockPath = `${filePath}${LOCK_SUFFIX}`;\n const payload = line.endsWith(\"\\n\") ? line : `${line}\\n`;\n\n let acquired = tryAcquireAppendLock(lockPath);\n // Pre-check: if the existing lock is already stale (writer crashed before\n // unlinking), reclaim it before sleeping. Saves the entire retry budget\n // for the common stale-leftover case.\n if (!acquired && isStaleLock(lockPath)) {\n safeUnlink(lockPath);\n acquired = tryAcquireAppendLock(lockPath);\n }\n if (!acquired) {\n const start = Date.now();\n const timeoutMs = lockTimeoutMs();\n while (!acquired && Date.now() - start < timeoutMs) {\n // Codex launches built-in stdio MCPs under Node+tsx while the runtime\n // itself uses Bun. Atomics.wait gives both processes a blocking sleep\n // without a CPU-spinning fallback or a Bun-only global.\n sleepForAppendLock(LOCK_RETRY_MS);\n acquired = tryAcquireAppendLock(lockPath);\n // Recheck staleness inside the loop so a writer that crashes mid-wait\n // doesn't leave us spinning the whole timeout.\n if (!acquired && isStaleLock(lockPath)) {\n safeUnlink(lockPath);\n acquired = tryAcquireAppendLock(lockPath);\n }\n }\n }\n\n if (!acquired) throw new JsonlLockTimeoutError(filePath, lockTimeoutMs());\n\n try {\n appendFileSync(filePath, payload);\n } finally {\n safeUnlink(lockPath);\n }\n}\n\n/** Overwrite a JSONL file with the given entries. Trailing newline included. */\nexport function writeJsonlFile(filePath: string, entries: readonly unknown[]): void {\n const dir = dirname(filePath);\n mkdirSync(dir, { recursive: true });\n const tmpPath = `${filePath}.tmp-${process.pid}-${Date.now()}-${Math.random()\n .toString(16)\n .slice(2)}`;\n const payload = `${entries.map((e) => JSON.stringify(e)).join(\"\\n\")}\\n`;\n let fd: number | null = null;\n try {\n fd = openSync(tmpPath, \"w\");\n writeFileSync(fd, payload);\n fsyncSync(fd);\n closeSync(fd);\n fd = null;\n renameSync(tmpPath, filePath);\n fsyncDirectoryBestEffort(dir);\n } catch (err) {\n if (fd !== null) {\n try {\n closeSync(fd);\n } catch {}\n }\n try {\n unlinkSync(tmpPath);\n } catch {}\n throw err;\n }\n}\n\nfunction fsyncDirectoryBestEffort(dir: string): void {\n let fd: number | null = null;\n try {\n fd = openSync(dir, \"r\");\n fsyncSync(fd);\n } catch {\n // Directory fsync is not portable across every runtime/filesystem. The\n // file fsync + rename above is the important integrity boundary; this is\n // best-effort durability for the directory entry.\n } finally {\n if (fd !== null) {\n try {\n closeSync(fd);\n } catch {}\n }\n }\n}\n",
7
+ "import { unlinkSync } from \"node:fs\";\nimport { logger } from \"#platform/logger\";\n\nexport interface SafeUnlinkHost {\n unlink(path: string): void;\n warn(context: { err: unknown; path: string }, message: string): void;\n}\n\nexport type SafeUnlink = (path: string, warnLabel?: string) => void;\n\n/** Create an isolated best-effort unlink helper using caller-owned I/O and logging. */\nexport function createSafeUnlink(host: SafeUnlinkHost): SafeUnlink {\n return (path, warnLabel) => {\n try {\n host.unlink(path);\n } catch (e) {\n if ((e as NodeJS.ErrnoException)?.code === \"ENOENT\") return;\n if (warnLabel) host.warn({ err: e, path }, warnLabel);\n }\n };\n}\n\nconst defaultSafeUnlink = createSafeUnlink({\n unlink: unlinkSync,\n warn: (context, message) => logger.warn(context, message),\n});\n\n/**\n * Best-effort unlink. ENOENT is always swallowed (the file is already gone).\n * Other errors are silent unless `warnLabel` is provided, in which case they\n * are logged at warn level with `{ err, path }` context.\n */\nexport function safeUnlink(path: string, warnLabel?: string): void {\n defaultSafeUnlink(path, warnLabel);\n}\n",
8
+ "import pino from \"pino\";\n\nexport interface StdioLoggerOptions {\n level?: string;\n development?: boolean;\n}\n\n/**\n * Always write logs to stderr (fd 2), never stdout.\n *\n * MCP servers under `src/mcp/**` run as stdio subprocesses where stdout is the\n * JSON-RPC transport channel. A single log line on stdout corrupts the next\n * message and the MCP client closes the transport (\"Transport closed\"). The\n * main bot process is also fine with stderr — pm2 captures both streams.\n *\n * In dev mode pino spawns a `pino-pretty` worker that owns its own sink, so we\n * pass `destination: 2` through transport.options. In prod (no transport) the\n * second arg to `pino()` sets the destination directly.\n */\nexport function createStdioLogger(options: StdioLoggerOptions = {}) {\n const development = options.development ?? process.env.NODE_ENV === \"development\";\n return pino(\n {\n level: options.level ?? process.env.LOG_LEVEL ?? \"info\",\n transport: development\n ? {\n target: \"pino-pretty\",\n options: {\n colorize: true,\n translateTime: \"SYS:yyyy-mm-dd HH:MM:ss\",\n destination: 2,\n },\n }\n : undefined,\n },\n pino.destination(2),\n );\n}\n\nexport type StdioLogger = ReturnType<typeof createStdioLogger>;\n\nexport const logger = createStdioLogger();\n",
9
+ "/** Sanitize a topic/session name for use in file paths.\n * Replaces non-alphanumeric characters (excluding Korean) with underscores.\n * Empty input (or input consisting only of disallowed chars) returns \"_\" so\n * callers always get a non-empty single path component.\n * @param name The raw topic or session name.\n * @param lowercase Whether to lowercase the result (default: false).\n * Use true for wiki paths; leave false for log file paths.\n */\nexport function sanitizeTopicName(name: string, lowercase = false): string {\n const safe = name.replace(/[^a-zA-Z0-9가-힣_-]/g, \"_\") || \"_\";\n return lowercase ? safe.toLowerCase() : safe;\n}\n\n/** Sanitize a file name for use in file paths. Allows dots.\n * Pure-dot results (\".\", \"..\") are replaced with \"_\" to block path-traversal\n * when the sanitized value is used as a standalone path component.\n */\nexport function sanitizeFileName(name: string): string {\n const safe = name.replace(/[^a-zA-Z0-9._-]/g, \"_\") || \"_\";\n if (safe === \".\" || safe === \"..\") return \"_\";\n return safe;\n}\n\n/** Sanitize an arbitrary ID (no Korean, no dots) for use in file paths. */\nexport function sanitizeId(id: string): string {\n return id.replace(/[^a-zA-Z0-9_-]/g, \"_\") || \"_\";\n}\n",
10
+ "import { mkdirSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { closeDatabase, Database } from \"#storage/sqlite\";\nimport type { StorageDatabase, StorageHostConfig } from \"#storage/storage-contract\";\n\nexport type {\n StorageDatabase,\n StorageDatabaseAdapter,\n StorageDatabaseInput,\n StorageHostConfig,\n StorageHostOptions,\n StorageStatement,\n StorageTransaction,\n} from \"#storage/storage-contract\";\n\ntype InternalStorageDatabase = InstanceType<typeof Database>;\ntype OwnedStorageDatabase = InternalStorageDatabase & { close(): void };\n\ninterface StorageHostFrame {\n active: boolean;\n patch: Readonly<StorageHostConfig>;\n}\n\ntype StorageSchemaInitializer = (database: InternalStorageDatabase) => void;\ninterface RegisteredSchemaInitializer {\n initialize: StorageSchemaInitializer;\n priority: number;\n}\n\ninterface StorageHostState {\n configuredHost: Readonly<StorageHostConfig>;\n fallbackDatabase: OwnedStorageDatabase | null;\n fallbackDatabasePath: string | null;\n frames: StorageHostFrame[];\n schemaInitializers: RegisteredSchemaInitializer[];\n initializedSchemas: WeakMap<InternalStorageDatabase, Set<StorageSchemaInitializer>>;\n initializingDatabases: WeakSet<InternalStorageDatabase>;\n}\n\n/**\n * Which database an embedded Negotium uses is a property of the *process*, so\n * the state deciding it is keyed off a registered symbol rather than held in\n * module scope.\n *\n * Module scope would be equivalent only if every caller resolved to the same\n * module instance, and in the published package they do not:\n * `build-negotium-package.ts` emits most public entrypoints as independent\n * graphs, so each gets a private copy of this file. A host that configured\n * `negotium/storage` therefore left `negotium/agent-helpers` unconfigured, and\n * that copy opened a second database under the default state directory — with\n * no error, since both files are valid and writable.\n *\n * Merging those entrypoints into one graph looks tidier and does cut ~3MB from\n * `dist`, but Bun 1.2.15 (the pinned version) emits a shared chunk's export\n * list twice and the result is invalid ESM — \"Cannot export a duplicate name\".\n * That is bundler output with no counterpart in this source, so there is\n * nothing to de-duplicate here; it is fixed in Bun 1.3.14. Until the floor\n * moves, correctness cannot depend on how the package is chunked.\n */\nconst STORAGE_HOST_STATE = Symbol.for(\"negotium.storage-host.state.v1\");\n\nfunction storageState(): StorageHostState {\n const holder = globalThis as typeof globalThis & { [STORAGE_HOST_STATE]?: StorageHostState };\n const existing = holder[STORAGE_HOST_STATE];\n if (existing) return existing;\n const created: StorageHostState = {\n configuredHost: {},\n fallbackDatabase: null,\n fallbackDatabasePath: null,\n frames: [],\n schemaInitializers: [],\n initializedSchemas: new WeakMap(),\n initializingDatabases: new WeakSet(),\n };\n Object.defineProperty(holder, STORAGE_HOST_STATE, {\n value: created,\n enumerable: false,\n writable: false,\n configurable: false,\n });\n return created;\n}\n\nfunction envPath(name: string, fallback: string): string {\n const value = process.env[name]?.trim();\n return resolve(value || fallback);\n}\n\nfunction defaultStateDir(): string {\n return envPath(\"NEGOTIUM_STATE_DIR\", join(homedir(), \".negotium\"));\n}\n\nfunction defaultDataDir(): string {\n return envPath(\"NEGOTIUM_DATA_DIR\", join(defaultStateDir(), \"data\"));\n}\n\nfunction defaultLogDir(): string {\n return envPath(\"NEGOTIUM_LOG_DIR\", join(defaultStateDir(), \"logs\"));\n}\n\nfunction defaultWorkspaceDir(): string {\n return envPath(\"NEGOTIUM_WORKSPACE_DIR\", join(defaultStateDir(), \"workspace\"));\n}\n\nfunction defaultSessionAsksDir(): string {\n const runDir = envPath(\"NEGOTIUM_RUN_DIR\", join(defaultStateDir(), \"runtime\"));\n return join(runDir, \"session-asks\");\n}\n\nfunction defaultSessionsDatabasePath(): string {\n return envPath(\"SESSIONS_DB_PATH\", join(resolveStorageDataDir(), \"sessions.db\"));\n}\n\nconst SQLITE_INIT_RETRY_MS = 25;\nconst SQLITE_INIT_TIMEOUT_MS = 5_000;\nconst SQLITE_INIT_SLEEP = new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));\n\nfunction isSqliteBusy(error: unknown): boolean {\n const message = error instanceof Error ? error.message : String(error);\n return /database is (?:locked|busy)|SQLITE_(?:BUSY|LOCKED)/i.test(message);\n}\n\nfunction execWithBusyRetry(\n database: InternalStorageDatabase,\n sql: string,\n timeoutMs = SQLITE_INIT_TIMEOUT_MS,\n): void {\n const deadline = Date.now() + timeoutMs;\n while (true) {\n try {\n database.exec(sql);\n return;\n } catch (error) {\n if (!isSqliteBusy(error) || Date.now() >= deadline) throw error;\n Atomics.wait(SQLITE_INIT_SLEEP, 0, 0, Math.min(SQLITE_INIT_RETRY_MS, deadline - Date.now()));\n }\n }\n}\n\nexport function initializeDatabase(database: InternalStorageDatabase): void {\n // busy_timeout FIRST. Switching to WAL needs a brief exclusive lock, so when\n // two processes open the same database at the same moment — the node daemon\n // and an adapter, or two MCP servers — one of them hits SQLITE_BUSY. With the\n // timeout configured afterwards there was no retry budget in effect for the\n // statement that needed it most. Older Bun releases can still surface\n // SQLITE_BUSY immediately for journal_mode, so keep a bounded host-level\n // retry around that one exclusive transition as well.\n database.exec(\"PRAGMA busy_timeout = 5000\");\n execWithBusyRetry(database, \"PRAGMA journal_mode = WAL\");\n database.exec(\"PRAGMA foreign_keys = ON\");\n database.exec(\"PRAGMA wal_autocheckpoint = 1000\");\n try {\n database.exec(\"PRAGMA wal_checkpoint(TRUNCATE)\");\n } catch {\n // Non-fatal; a concurrent writer may hold the WAL briefly.\n }\n}\n\nfunction defaultDatabase(): InternalStorageDatabase {\n const path = defaultSessionsDatabasePath();\n const state = storageState();\n if (state.fallbackDatabase && state.fallbackDatabasePath === path) return state.fallbackDatabase;\n if (state.fallbackDatabase) closeDatabase(state.fallbackDatabase);\n mkdirSync(dirname(path), { recursive: true });\n state.fallbackDatabase = new Database(path, { create: true }) as unknown as OwnedStorageDatabase;\n state.fallbackDatabasePath = path;\n initializeDatabase(state.fallbackDatabase);\n return state.fallbackDatabase;\n}\n\nexport function resolveStorageDatabase(): InternalStorageDatabase {\n return (storageState().configuredHost.database ?? defaultDatabase()) as InternalStorageDatabase;\n}\n\n/**\n * The host-injected connection, or null when Negotium owns its own store.\n *\n * Unlike {@link resolveStorageDatabase} this never opens anything. Callers that\n * manage their own short-lived connections need to know whether a host store\n * exists *before* deciding to open one by path: opening it anyway is how an\n * embedded Negotium ends up writing half its state into the host's database and\n * the other half into `~/.negotium`, with nothing reporting an error.\n */\nexport function configuredStorageDatabase(): InternalStorageDatabase | null {\n return (storageState().configuredHost.database as InternalStorageDatabase | undefined) ?? null;\n}\n\nexport function resolveStorageDataDir(): string {\n return storageState().configuredHost.dataDir ?? defaultDataDir();\n}\n\nexport function resolveStorageLogDir(): string {\n return storageState().configuredHost.logDir ?? defaultLogDir();\n}\n\nexport function resolveStorageSessionAsksDir(): string {\n return storageState().configuredHost.sessionAsksDir ?? defaultSessionAsksDir();\n}\n\nexport function resolveStorageWorkspaceDir(): string {\n return storageState().configuredHost.workspaceDir ?? defaultWorkspaceDir();\n}\n\nexport function resolveStorageSharedWikiDir(): string {\n return storageState().configuredHost.sharedWikiDir ?? join(resolveStorageWorkspaceDir(), \"wiki\");\n}\n\nexport function resolveStorageUsersLogDir(): string {\n return storageState().configuredHost.usersLogDir ?? join(resolveStorageDataDir(), \"users\");\n}\n\nconst STORAGE_PATH_KEYS = [\n \"dataDir\",\n \"logDir\",\n \"sessionAsksDir\",\n \"workspaceDir\",\n \"sharedWikiDir\",\n \"usersLogDir\",\n] as const;\n\nfunction normalizeStorageHostPatch(options: StorageHostConfig): Readonly<StorageHostConfig> {\n const patch: StorageHostConfig = {};\n if (options.database !== undefined) {\n options.database.exec(\"PRAGMA foreign_keys = ON\");\n patch.database = options.database;\n }\n for (const key of STORAGE_PATH_KEYS) {\n const value = options[key];\n if (value === undefined) continue;\n if (!value.trim()) throw new TypeError(`${key} must not be empty`);\n patch[key] = resolve(value);\n }\n return Object.freeze(patch);\n}\n\nfunction refreshConfiguredHost(): void {\n const state = storageState();\n state.configuredHost = Object.freeze(\n Object.assign({}, ...state.frames.filter((frame) => frame.active).map((frame) => frame.patch)),\n );\n}\n\n/**\n * Configure the process-local storage boundary for an embedding host.\n *\n * Resolution is lazy: importing `negotium/storage` never opens a database or\n * touches a filesystem path. The returned disposer restores the exact prior\n * host, which keeps tests and nested embeddings isolated.\n */\nexport function configureStorageHost(options: StorageHostConfig): () => void {\n const frame: StorageHostFrame = { active: true, patch: normalizeStorageHostPatch(options) };\n storageState().frames.push(frame);\n refreshConfiguredHost();\n return () => {\n if (!frame.active) return;\n frame.active = false;\n const frames = storageState().frames;\n const index = frames.indexOf(frame);\n if (index >= 0) frames.splice(index, 1);\n refreshConfiguredHost();\n };\n}\n\n/** Remove every configured host layer and restore standalone fallbacks. */\nexport function resetStorageHost(): void {\n const frames = storageState().frames;\n for (const frame of frames) frame.active = false;\n frames.length = 0;\n refreshConfiguredHost();\n}\n\n/** Close only Negotium's fallback connection. Injected connections are borrowed. */\nexport function closeStorageDatabase(): void {\n const state = storageState();\n if (!state.fallbackDatabase) return;\n closeDatabase(state.fallbackDatabase);\n state.fallbackDatabase = null;\n state.fallbackDatabasePath = null;\n}\n\nexport function registerStorageSchemaInitializer(\n initialize: StorageSchemaInitializer,\n priority = 100,\n): void {\n const initializers = storageState().schemaInitializers;\n initializers.push({ initialize, priority });\n initializers.sort((a, b) => a.priority - b.priority);\n}\n\nexport function ensureStorageSchemas(\n database: InternalStorageDatabase = resolveStorageDatabase(),\n): void {\n const state = storageState();\n if (state.initializingDatabases.has(database)) return;\n let initialized = state.initializedSchemas.get(database);\n if (!initialized) {\n initialized = new Set();\n state.initializedSchemas.set(database, initialized);\n }\n state.initializingDatabases.add(database);\n try {\n for (const entry of state.schemaInitializers) {\n if (initialized.has(entry.initialize)) continue;\n // Mark first so a migration that calls through the public db proxy does\n // not recursively invoke itself. Remove on failure so the next call can retry.\n initialized.add(entry.initialize);\n try {\n entry.initialize(database);\n } catch (error) {\n initialized.delete(entry.initialize);\n throw error;\n }\n }\n } finally {\n state.initializingDatabases.delete(database);\n }\n}\n\n/** Stable proxy identity used by legacy imports and embedding hosts. */\nexport const internalStorageDatabase = new Proxy({} as InternalStorageDatabase, {\n get(_target, property) {\n const database = resolveStorageDatabase();\n ensureStorageSchemas(database);\n const value = Reflect.get(database as object, property, database);\n return typeof value === \"function\" ? value.bind(database) : value;\n },\n set(_target, property, value) {\n const database = resolveStorageDatabase();\n ensureStorageSchemas(database);\n return Reflect.set(database as object, property, value, database);\n },\n});\n\n/** Structurally typed view intended for embedding hosts. */\nexport const storageDatabase = internalStorageDatabase as unknown as StorageDatabase;\n",
11
+ "// Runtime-adaptive SQLite façade.\n//\n// Why this exists: Otium normally runs on bun and uses `bun:sqlite` (native,\n// fast, zero-build). But the `codex` agent's MCP servers must run on pure node\n// — codex 0.135's rmcp stdio client can't handshake with bun-spawned servers\n// (see serverLaunch in platform/mcp-config.ts). `bun:sqlite` doesn't exist\n// under node, so any MCP server that touches the DB would crash on import.\n//\n// This module picks the backend at runtime and re-exports it as `Database`:\n// - under bun → the real `bun:sqlite` Database (unchanged behavior)\n// - under node → a thin shim over node:sqlite's DatabaseSync exposing the\n// exact subset Otium uses: new Database(path, {readonly?,create?}),\n// .query()/.prepare() → statement, .exec(), .run(), .transaction(fn),\n// .close(); statements support positional `?` params via .run()/.get()/\n// .all(). (No named-object params / .values()/.iterate()/.as() are used in\n// this codebase, so the shim intentionally omits them.)\n//\n// The TYPE of the exported `Database` is bun:sqlite's own class type (imported\n// type-only, so it's erased at runtime and never resolved under node). That\n// keeps every existing call site — including generic `.query<Row, Params>()`\n// usages — type-checking exactly as before with zero changes.\n//\n// The bun branch uses a dynamic import so node never resolves the `bun:sqlite`\n// specifier (dead code under node), and the node branch's `node:sqlite` import\n// never runs under bun.\n\nimport type { Database as BunDatabase } from \"bun:sqlite\";\n\n// `mock.module()` can replace the Bun global while a test graph is being\n// evaluated. The runtime version flag is stable and is also the documented\n// cross-runtime discriminator.\nconst isBun = typeof process.versions.bun === \"string\";\n\ntype DatabaseCtor = typeof BunDatabase;\n\nlet Database: DatabaseCtor;\n\nif (isBun) {\n ({ Database } = await import(\"bun:sqlite\"));\n} else {\n // node:sqlite has no type declarations under our tsconfig (`types: bun-types`\n // only), and `bun-types` doesn't ship them — so type the dynamic import\n // locally and use a `string` specifier to keep tsc from trying to resolve it.\n type NodeStatement = {\n run(...params: unknown[]): unknown;\n get(...params: unknown[]): unknown;\n all(...params: unknown[]): unknown[];\n };\n type NodeDatabaseSync = {\n prepare(sql: string): NodeStatement;\n exec(sql: string): void;\n close(): void;\n };\n type NodeSqliteModule = {\n DatabaseSync: new (path: string, options?: { readOnly?: boolean }) => NodeDatabaseSync;\n };\n // Keep Bun's resolver from eagerly resolving the Node-only builtin even\n // though this branch is dead there (notably under `bun test` + mock.module).\n const nodeSqliteSpecifier = [\"node\", \"sqlite\"].join(\":\");\n const { DatabaseSync } = (await import(nodeSqliteSpecifier)) as NodeSqliteModule;\n\n type DbOptions = { readonly?: boolean; create?: boolean };\n\n class NodeDatabase {\n #db: NodeDatabaseSync;\n\n constructor(path: string, options: DbOptions = {}) {\n // node:sqlite opens read-write and creates-if-missing by default, which\n // matches bun's `{create:true}`. For readonly we must not create.\n this.#db = options.readonly\n ? new DatabaseSync(path, { readOnly: true })\n : new DatabaseSync(path);\n }\n\n query(sql: string) {\n return this.#db.prepare(sql);\n }\n\n prepare(sql: string) {\n return this.#db.prepare(sql);\n }\n\n exec(sql: string): void {\n this.#db.exec(sql);\n }\n\n run(sql: string, ...params: unknown[]) {\n return this.#db.prepare(sql).run(...params);\n }\n\n transaction<Args extends unknown[], R>(fn: (...args: Args) => R): (...args: Args) => R {\n // bun's db.transaction(fn) returns a function that runs fn inside a\n // transaction when called. node:sqlite has no helper, so emulate with\n // BEGIN/COMMIT/ROLLBACK. It also exposes deferred/immediate/exclusive\n // variants; mirror those so Node-launched MCP servers can share call\n // sites with Bun.\n const run =\n (begin: \"BEGIN\" | \"BEGIN DEFERRED\" | \"BEGIN IMMEDIATE\" | \"BEGIN EXCLUSIVE\") =>\n (...args: Args): R => {\n this.#db.exec(begin);\n try {\n const result = fn(...args);\n this.#db.exec(\"COMMIT\");\n return result;\n } catch (err) {\n this.#db.exec(\"ROLLBACK\");\n throw err;\n }\n };\n const tx = run(\"BEGIN\") as ((...args: Args) => R) & {\n deferred: (...args: Args) => R;\n immediate: (...args: Args) => R;\n exclusive: (...args: Args) => R;\n };\n tx.deferred = run(\"BEGIN DEFERRED\");\n tx.immediate = run(\"BEGIN IMMEDIATE\");\n tx.exclusive = run(\"BEGIN EXCLUSIVE\");\n return tx;\n }\n\n close(): void {\n this.#db.close();\n }\n }\n\n Database = NodeDatabase as unknown as DatabaseCtor;\n}\n\nexport { Database };\n\n/**\n * Close a database and release its underlying file handle.\n *\n * `bun:sqlite`'s no-argument `close()` does not finalize prepared statements\n * that are still reachable, so the file stays open. POSIX hides this — the\n * path can be unlinked while a handle remains — but Windows refuses to delete\n * or rename the file at all (`EBUSY`), which is how the leak surfaces. Passing\n * `true` finalizes eagerly and drops the handle.\n *\n * The node shim's `close()` ignores the argument, so one call covers both\n * backends; the fallback only matters for a backend that rejects the extra\n * parameter outright.\n */\nexport function closeDatabase(database: { close(throwOnError?: boolean): void }): void {\n try {\n database.close(true);\n } catch {\n try {\n database.close();\n } catch {\n // Already closed: nothing left to release.\n }\n }\n}\n",
12
+ "import type { StorageDatabase } from \"#storage/storage-contract\";\nimport { internalStorageDatabase } from \"#storage/storage-host\";\n\nexport const db = internalStorageDatabase as unknown as StorageDatabase;\n",
13
+ "// Persistent message store for the REST/WS API channel (Otium).\n//\n// Replaces the previous in-memory `Map<topicId, MessageDto[]>` so messages\n// survive server restarts. Backed by the shared sessions SQLite DB — the same\n// database the Telegram channel uses — which is the foundation for unifying\n// conversation state across channels later.\n//\n// Ordering is by the implicit SQLite `rowid` (monotonic insert order). Cursor\n// pagination resolves the cursor id → its rowid and returns rows after it.\n\nimport { db } from \"#storage/forum-db\";\nimport { registerStorageSchemaInitializer } from \"#storage/storage-host\";\nimport type { AgentKind } from \"#types\";\nimport type { MessageDto } from \"#types/api\";\n\nfunction initializeApiMessagesSchema(): void {\n db.exec(`\n CREATE TABLE IF NOT EXISTS api_messages (\n id TEXT PRIMARY KEY,\n topic_id TEXT NOT NULL,\n parent_id TEXT,\n author_id TEXT NOT NULL,\n source_adapter TEXT,\n source_node TEXT,\n source_message_id TEXT,\n text TEXT NOT NULL,\n query_id TEXT,\n agent_type TEXT,\n model TEXT,\n attachments TEXT,\n usage TEXT,\n deleted INTEGER NOT NULL DEFAULT 0,\n edited_at TEXT,\n reactions TEXT,\n kind TEXT,\n ask_user_question TEXT,\n tell_card TEXT,\n mentions TEXT,\n thread_root_id TEXT,\n created_at TEXT NOT NULL\n )\n`);\n try {\n db.exec(\"ALTER TABLE api_messages ADD COLUMN source_adapter TEXT\");\n } catch {\n // Column already exists.\n }\n try {\n db.exec(\"ALTER TABLE api_messages ADD COLUMN source_node TEXT\");\n } catch {}\n try {\n db.exec(\"ALTER TABLE api_messages ADD COLUMN source_message_id TEXT\");\n } catch {}\n try {\n db.exec(\"ALTER TABLE api_messages ADD COLUMN deleted INTEGER NOT NULL DEFAULT 0\");\n } catch {}\n try {\n db.exec(\"ALTER TABLE api_messages ADD COLUMN edited_at TEXT\");\n } catch {}\n try {\n db.exec(\"ALTER TABLE api_messages ADD COLUMN reactions TEXT\");\n } catch {}\n try {\n db.exec(\"ALTER TABLE api_messages ADD COLUMN kind TEXT\");\n } catch {}\n try {\n db.exec(\"ALTER TABLE api_messages ADD COLUMN ask_user_question TEXT\");\n } catch {}\n try {\n db.exec(\"ALTER TABLE api_messages ADD COLUMN tell_card TEXT\");\n } catch {}\n try {\n db.exec(\"ALTER TABLE api_messages ADD COLUMN mentions TEXT\");\n } catch {}\n try {\n // Slack-style threads: a reply carries the ROOT message id (flat, no nesting).\n // Distinct from parent_id (which is a Telegram-style inline quote-reply).\n db.exec(\"ALTER TABLE api_messages ADD COLUMN thread_root_id TEXT\");\n } catch {}\n try {\n db.exec(\"ALTER TABLE api_messages ADD COLUMN subagent_card TEXT\");\n } catch {}\n try {\n db.exec(\"ALTER TABLE api_messages ADD COLUMN vault_secret_request TEXT\");\n } catch {}\n // Index on topic_id; SQLite appends the implicit rowid to every index entry,\n // so `WHERE topic_id=? AND rowid>? ORDER BY rowid` stays index-driven.\n db.exec(\"CREATE INDEX IF NOT EXISTS idx_api_messages_topic ON api_messages(topic_id)\");\n db.exec(\n \"CREATE INDEX IF NOT EXISTS idx_api_messages_thread_root ON api_messages(thread_root_id)\",\n );\n}\n\nregisterStorageSchemaInitializer(initializeApiMessagesSchema, 30);\n\nexport interface ApiMessageRow {\n id: string;\n topic_id: string;\n parent_id: string | null;\n author_id: string;\n source_adapter: string | null;\n source_node: string | null;\n source_message_id: string | null;\n text: string;\n query_id: string | null;\n agent_type: string | null;\n model: string | null;\n attachments: string | null;\n usage: string | null;\n deleted: number;\n edited_at: string | null;\n reactions: string | null;\n kind: string | null;\n ask_user_question: string | null;\n tell_card: string | null;\n subagent_card: string | null;\n vault_secret_request: string | null;\n mentions: string | null;\n thread_root_id: string | null;\n created_at: string;\n rowid?: number;\n}\n\nexport type ApiMessageAppendHook = (msg: MessageDto) => void | Promise<void>;\nconst appendHooks = new Set<ApiMessageAppendHook>();\n\nexport interface AppendApiMessageOptions {\n notify?: boolean;\n updateTopicLastMessageAt?: boolean;\n}\n\nexport function registerApiMessageAppendHook(hook: ApiMessageAppendHook): () => void {\n appendHooks.add(hook);\n return () => {\n appendHooks.delete(hook);\n };\n}\n\nfunction emitApiMessageAppended(msg: MessageDto): void {\n for (const hook of appendHooks) {\n queueMicrotask(() => {\n try {\n void Promise.resolve(hook(msg)).catch(() => undefined);\n } catch {\n // Hooks are post-persist side effects; never make message writes fail.\n }\n });\n }\n}\n\nfunction rowToDto(r: ApiMessageRow): MessageDto {\n return {\n id: r.id,\n topicId: r.topic_id,\n parentId: r.parent_id ?? undefined,\n authorId: r.author_id,\n sourceAdapter: r.source_adapter ?? undefined,\n sourceNode: r.source_node ?? undefined,\n sourceMessageId: r.source_message_id ?? undefined,\n text: r.text,\n queryId: r.query_id ?? undefined,\n agentType: (r.agent_type as AgentKind | null) ?? undefined,\n model: r.model ?? undefined,\n attachments: r.attachments ? JSON.parse(r.attachments) : undefined,\n usage: r.usage ? JSON.parse(r.usage) : undefined,\n deleted: r.deleted !== 0,\n editedAt: r.edited_at ?? undefined,\n reactions: r.reactions ? JSON.parse(r.reactions) : undefined,\n kind: (r.kind as MessageDto[\"kind\"] | null) ?? undefined,\n askUserQuestion: r.ask_user_question ? JSON.parse(r.ask_user_question) : undefined,\n tellCard: r.tell_card ? JSON.parse(r.tell_card) : undefined,\n subagentCard: r.subagent_card ? JSON.parse(r.subagent_card) : undefined,\n vaultSecretRequest: r.vault_secret_request ? JSON.parse(r.vault_secret_request) : undefined,\n mentions: r.mentions ? JSON.parse(r.mentions) : undefined,\n threadRootId: r.thread_root_id ?? undefined,\n createdAt: r.created_at,\n };\n}\n\nfunction attachmentListHasFileId(raw: string | null, fileId: string): boolean {\n if (!raw) return false;\n try {\n const attachments = JSON.parse(raw) as unknown;\n return (\n Array.isArray(attachments) &&\n attachments.some(\n (attachment) =>\n typeof attachment === \"object\" &&\n attachment !== null &&\n \"id\" in attachment &&\n attachment.id === fileId,\n )\n );\n } catch {\n return false;\n }\n}\n\n/** Persist a single message. Idempotent on id: duplicate appends do not rewrite edited/reaction state. */\nexport function appendApiMessage(msg: MessageDto, options: AppendApiMessageOptions = {}): void {\n const notify = options.notify ?? true;\n const updateTopicLastMessageAt = options.updateTopicLastMessageAt ?? true;\n let inserted = false;\n db.transaction(() => {\n const result = db\n .query(\n `INSERT INTO api_messages\n (id, topic_id, parent_id, author_id, source_adapter, source_node, source_message_id, text, query_id, agent_type, model, attachments, usage, deleted, edited_at, reactions, kind, ask_user_question, tell_card, subagent_card, vault_secret_request, mentions, thread_root_id, created_at)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT(id) DO NOTHING`,\n )\n .run(\n msg.id,\n msg.topicId,\n msg.parentId ?? null,\n msg.authorId,\n msg.sourceAdapter ?? null,\n msg.sourceNode ?? null,\n msg.sourceMessageId ?? null,\n msg.text,\n msg.queryId ?? null,\n msg.agentType ?? null,\n msg.model ?? null,\n msg.attachments ? JSON.stringify(msg.attachments) : null,\n msg.usage ? JSON.stringify(msg.usage) : null,\n msg.deleted ? 1 : 0,\n msg.editedAt ?? null,\n msg.reactions?.length ? JSON.stringify(msg.reactions) : null,\n msg.kind ?? null,\n msg.askUserQuestion ? JSON.stringify(msg.askUserQuestion) : null,\n msg.tellCard ? JSON.stringify(msg.tellCard) : null,\n msg.subagentCard ? JSON.stringify(msg.subagentCard) : null,\n msg.vaultSecretRequest ? JSON.stringify(msg.vaultSecretRequest) : null,\n msg.mentions?.length ? JSON.stringify(msg.mentions) : null,\n msg.threadRootId ?? null,\n msg.createdAt,\n );\n inserted = Number(result.changes ?? 0) > 0;\n if (inserted && updateTopicLastMessageAt && !msg.deleted) {\n db.query(\n `UPDATE api_topics\n SET last_message_at = CASE\n WHEN last_message_at IS NULL OR last_message_at < ? THEN ?\n ELSE last_message_at\n END\n WHERE id = ?`,\n ).run(msg.createdAt, msg.createdAt, msg.topicId);\n }\n })();\n if (inserted && notify && !msg.deleted) emitApiMessageAppended(msg);\n}\n\nexport function getApiMessage(topicId: string, messageId: string): MessageDto | null {\n const row = db\n .query(\"SELECT * FROM api_messages WHERE topic_id = ? AND id = ?\")\n .get(topicId, messageId) as ApiMessageRow | undefined;\n return row ? rowToDto(row) : null;\n}\n\nexport function topicHasAttachmentFileId(topicId: string, fileId: string): boolean {\n const rows = db\n .query<{ attachments: string | null }, [string]>(\n \"SELECT attachments FROM api_messages WHERE topic_id = ? AND deleted = 0 AND attachments IS NOT NULL\",\n )\n .all(topicId);\n return rows.some((row) => attachmentListHasFileId(row.attachments, fileId));\n}\n\nexport function updateApiMessageText(\n topicId: string,\n messageId: string,\n text: string,\n editedAt = new Date().toISOString(),\n): MessageDto | null {\n const res = db\n .query(\n `UPDATE api_messages\n SET text = ?, edited_at = ?\n WHERE topic_id = ? AND id = ? AND deleted = 0`,\n )\n .run(text, editedAt, topicId, messageId);\n if (Number(res.changes ?? 0) === 0) return null;\n return getApiMessage(topicId, messageId);\n}\n\n/** Attach terminal turn usage to an already-persisted assistant segment. */\nexport function updateApiMessageUsage(\n topicId: string,\n messageId: string,\n usage: NonNullable<MessageDto[\"usage\"]>,\n): MessageDto | null {\n const res = db\n .query(\n `UPDATE api_messages\n SET usage = ?\n WHERE topic_id = ? AND id = ? AND deleted = 0`,\n )\n .run(JSON.stringify(usage), topicId, messageId);\n if (Number(res.changes ?? 0) === 0) return null;\n return getApiMessage(topicId, messageId);\n}\n\nexport function updateApiMessageAskUserQuestion(\n topicId: string,\n messageId: string,\n askUserQuestion: NonNullable<MessageDto[\"askUserQuestion\"]>,\n editedAt = new Date().toISOString(),\n): MessageDto | null {\n const res = db\n .query(\n `UPDATE api_messages\n SET ask_user_question = ?, edited_at = ?\n WHERE topic_id = ? AND id = ? AND deleted = 0 AND kind = 'ask_user_question'`,\n )\n .run(JSON.stringify(askUserQuestion), editedAt, topicId, messageId);\n if (Number(res.changes ?? 0) === 0) return null;\n return getApiMessage(topicId, messageId);\n}\n\nexport function updateApiMessageSubagentCard(\n topicId: string,\n messageId: string,\n subagentCard: NonNullable<MessageDto[\"subagentCard\"]>,\n editedAt = new Date().toISOString(),\n): MessageDto | null {\n const res = db\n .query(\n `UPDATE api_messages\n SET subagent_card = ?, edited_at = ?\n WHERE topic_id = ? AND id = ? AND deleted = 0 AND kind = 'subagent'`,\n )\n .run(JSON.stringify(subagentCard), editedAt, topicId, messageId);\n if (Number(res.changes ?? 0) === 0) return null;\n return getApiMessage(topicId, messageId);\n}\n\n/** All non-deleted messages of one kind, across topics (boot-time sweeps). */\nexport function listApiMessagesByKind(kind: NonNullable<MessageDto[\"kind\"]>): MessageDto[] {\n const rows = db\n .query(\"SELECT * FROM api_messages WHERE kind = ? AND deleted = 0\")\n .all(kind) as ApiMessageRow[];\n return rows.map(rowToDto);\n}\n\n/** Replace a message's full reactions array. Toggle logic lives in the route. */\nexport function setApiMessageReactions(\n topicId: string,\n messageId: string,\n reactions: NonNullable<MessageDto[\"reactions\"]>,\n): MessageDto | null {\n const res = db\n .query(\n `UPDATE api_messages\n SET reactions = ?\n WHERE topic_id = ? AND id = ? AND deleted = 0`,\n )\n .run(reactions.length ? JSON.stringify(reactions) : null, topicId, messageId);\n if (Number(res.changes ?? 0) === 0) return null;\n return getApiMessage(topicId, messageId);\n}\n\nexport function softDeleteApiMessage(topicId: string, messageId: string): MessageDto | null {\n const res = db\n .query(\n `UPDATE api_messages\n SET deleted = 1, text = ''\n WHERE topic_id = ? AND id = ? AND deleted = 0`,\n )\n .run(topicId, messageId);\n if (Number(res.changes ?? 0) === 0) return null;\n return getApiMessage(topicId, messageId);\n}\n\n/** Soft-delete every live message whose id starts with a caller-owned prefix. */\nexport function softDeleteApiMessagesByIdPrefix(topicId: string, prefix: string): string[] {\n if (!prefix) return [];\n const rows = db\n .query(\n `SELECT id FROM api_messages\n WHERE topic_id = ? AND deleted = 0 AND substr(id, 1, ?) = ?`,\n )\n .all(topicId, prefix.length, prefix) as { id: string }[];\n if (rows.length === 0) return [];\n db.query(\n `UPDATE api_messages\n SET deleted = 1, text = ''\n WHERE topic_id = ? AND deleted = 0 AND substr(id, 1, ?) = ?`,\n ).run(topicId, prefix.length, prefix);\n return rows.map((row) => row.id);\n}\n\nexport interface MessagePage {\n page: MessageDto[];\n cursor?: string;\n hasMore: boolean;\n}\n\nexport interface ListApiMessagesOptions {\n cursor?: string | null;\n limit?: number;\n}\n\n/**\n * List messages for a topic, NEWEST-FIRST by default (bug G).\n *\n * The chat client loads once on mount and renders whatever it gets, so the\n * initial page must be the *latest* N messages, not the oldest. We therefore\n * query newest→oldest (`ORDER BY rowid DESC`) and then reverse the page back to\n * chronological (oldest→newest) order for display.\n *\n * Pagination is BACKWARD (toward older history): pass the returned `cursor`\n * (the oldest id currently loaded) to fetch the page of messages *older* than\n * it. `hasMore` therefore means \"there are older messages above this page\".\n */\nexport function listApiMessages(topicId: string, options?: ListApiMessagesOptions): MessagePage {\n const limit = Math.max(1, Math.min(options?.limit ?? 50, 200));\n\n let anchorRowid: number | null = null;\n if (options?.cursor) {\n const cur = db\n .query(\"SELECT rowid AS rowid FROM api_messages WHERE topic_id = ? AND id = ?\")\n .get(topicId, options.cursor) as { rowid: number } | undefined;\n if (cur) anchorRowid = cur.rowid;\n }\n\n const rows = (\n anchorRowid !== null\n ? db\n .query(\n `SELECT *, rowid AS rowid FROM api_messages\n WHERE topic_id = ? AND deleted = 0 AND thread_root_id IS NULL AND rowid < ?\n ORDER BY rowid DESC\n LIMIT ?`,\n )\n .all(topicId, anchorRowid, limit + 1)\n : db\n .query(\n `SELECT *, rowid AS rowid FROM api_messages\n WHERE topic_id = ? AND deleted = 0 AND thread_root_id IS NULL\n ORDER BY rowid DESC\n LIMIT ?`,\n )\n .all(topicId, limit + 1)\n ) as (ApiMessageRow & { rowid: number })[];\n\n const hasMore = rows.length > limit;\n // rows are newest→oldest; trim the look-ahead row, then flip to chronological.\n const pageRows = (hasMore ? rows.slice(0, limit) : rows).reverse();\n const page = pageRows.map(rowToDto);\n\n // Stamp thread reply counts onto the messages that are thread roots.\n const summaries = getThreadSummaries(page.map((m) => m.id));\n if (summaries.size > 0) {\n for (const m of page) {\n const s = summaries.get(m.id);\n if (s) {\n m.threadReplyCount = s.replyCount;\n m.threadLastReplyAt = s.lastReplyAt;\n }\n }\n }\n\n return {\n page,\n // Oldest loaded id — pass back as `cursor` to load the previous (older) page.\n cursor: page.length > 0 ? page[0].id : undefined,\n hasMore,\n };\n}\n\n/**\n * Reply count + last reply time per thread root, computed on read (no\n * denormalized counters to drift). Only non-deleted replies are counted.\n */\nexport function getThreadSummaries(\n rootIds: readonly string[],\n): Map<string, { replyCount: number; lastReplyAt: string }> {\n const out = new Map<string, { replyCount: number; lastReplyAt: string }>();\n const ids = [...new Set(rootIds)].filter(Boolean);\n if (ids.length === 0) return out;\n const rows = db\n .query(\n `SELECT thread_root_id AS rootId, COUNT(*) AS replyCount, MAX(created_at) AS lastReplyAt\n FROM api_messages\n WHERE thread_root_id IN (${ids.map(() => \"?\").join(\",\")}) AND deleted = 0\n GROUP BY thread_root_id`,\n )\n .all(...ids) as { rootId: string; replyCount: number; lastReplyAt: string }[];\n for (const r of rows) {\n out.set(r.rootId, { replyCount: Number(r.replyCount), lastReplyAt: r.lastReplyAt });\n }\n return out;\n}\n\n/** The root message plus its thread replies (chronological). */\nexport function listThreadMessages(\n topicId: string,\n rootId: string,\n): { root: MessageDto | null; replies: MessageDto[] } {\n const root = getApiMessage(topicId, rootId);\n const rows = db\n .query(\n `SELECT *, rowid AS rowid FROM api_messages\n WHERE topic_id = ? AND thread_root_id = ? AND deleted = 0\n ORDER BY rowid ASC\n LIMIT 200`,\n )\n .all(topicId, rootId) as ApiMessageRow[];\n return { root, replies: rows.map(rowToDto) };\n}\n\n/**\n * The root message and its replies as raw rows, oldest first.\n *\n * Row-shaped rather than DTO-shaped because the caller renders them with\n * `formatChannelTranscriptLine`, so a thread read to the model looks exactly\n * like the channel transcript it may appear next to.\n */\nexport function listThreadMessageRows(\n topicId: string,\n rootId: string,\n limit = 200,\n): { root: ApiMessageRow | null; replies: ApiMessageRow[] } {\n const root =\n (db\n .query(\"SELECT *, rowid AS rowid FROM api_messages WHERE topic_id = ? AND id = ?\")\n .get(topicId, rootId) as ApiMessageRow | null) ?? null;\n // Newest-first with a LIMIT, then reversed: when a thread is longer than the\n // budget the recent end is the part worth keeping.\n const rows = db\n .query(\n `SELECT *, rowid AS rowid FROM api_messages\n WHERE topic_id = ? AND thread_root_id = ? AND deleted = 0\n ORDER BY rowid DESC\n LIMIT ?`,\n )\n .all(topicId, rootId, Math.max(1, limit)) as ApiMessageRow[];\n return { root, replies: rows.reverse() };\n}\n\n/** Total undeleted replies in a thread, for reporting what a read left out. */\nexport function countThreadReplies(topicId: string, rootId: string): number {\n const row = db\n .query(\n `SELECT COUNT(*) AS n FROM api_messages\n WHERE topic_id = ? AND thread_root_id = ? AND deleted = 0`,\n )\n .get(topicId, rootId) as { n: number } | null;\n return Number(row?.n ?? 0);\n}\n\n/**\n * Thread roots in a topic whose id starts with `prefix`, ignoring separators.\n *\n * Resolved in SQL over the whole topic rather than over a page of recent\n * threads: the short tag a model reads in a transcript may belong to a thread\n * that has not been touched in months, and a capped scan reports that thread as\n * nonexistent. Returns every match so the caller can refuse an ambiguous\n * prefix instead of guessing a room's newest thread.\n */\nexport function findThreadRootsByPrefix(topicId: string, prefix: string): string[] {\n const bare = prefix.replace(/[^0-9A-Za-z]/g, \"\");\n if (!bare) return [];\n const rows = db\n .query(\n `SELECT DISTINCT thread_root_id AS rootId FROM api_messages\n WHERE topic_id = ? AND thread_root_id IS NOT NULL AND deleted = 0`,\n )\n .all(topicId) as { rootId: string }[];\n return rows\n .filter((row) => row.rootId.replace(/[^0-9A-Za-z]/g, \"\").startsWith(bare))\n .map((row) => row.rootId);\n}\n\n/** Threads in a topic that have at least one reply, most recently active first. */\nexport function listTopicThreadRoots(\n topicId: string,\n limit = 20,\n): { rootId: string; replyCount: number; lastReplyAt: string }[] {\n return db\n .query(\n `SELECT thread_root_id AS rootId, COUNT(*) AS replyCount, MAX(created_at) AS lastReplyAt\n FROM api_messages\n WHERE topic_id = ? AND thread_root_id IS NOT NULL AND deleted = 0\n GROUP BY thread_root_id\n ORDER BY lastReplyAt DESC\n LIMIT ?`,\n )\n .all(topicId, Math.max(1, limit)) as {\n rootId: string;\n replyCount: number;\n lastReplyAt: string;\n }[];\n}\n\n/**\n * Find the newest same-user/same-text message that is recent enough to be the\n * message just posted before a follow-up `/ai` call. This is a compatibility\n * fallback for clients that persist attachments through `/messages` but do not\n * repeat their file ids in the `/ai` request body.\n */\nexport function findRecentUserMessage(\n topicId: string,\n authorId: string,\n text: string,\n maxAgeMs: number,\n): MessageDto | undefined {\n const row = db\n .query(\n `SELECT * FROM api_messages\n WHERE topic_id = ? AND author_id = ? AND text = ?\n AND deleted = 0\n ORDER BY rowid DESC\n LIMIT 1`,\n )\n .get(topicId, authorId, text) as ApiMessageRow | undefined;\n if (!row) return undefined;\n\n const createdMs = Date.parse(row.created_at);\n if (!Number.isFinite(createdMs) || Date.now() - createdMs > maxAgeMs) return undefined;\n return rowToDto(row);\n}\n\n/**\n * Latest message text per topic, keyed by topic_id. Used to render a preview\n * subtitle in the topic list. One index-driven query (MAX(rowid) per topic)\n * instead of N round-trips. Empty topics are simply absent from the map.\n */\nexport function getLastMessagePreviews(topicIds?: readonly string[]): Map<string, string> {\n const uniqueTopicIds = topicIds ? [...new Set(topicIds)] : undefined;\n if (uniqueTopicIds && uniqueTopicIds.length === 0) return new Map();\n const topicFilter = uniqueTopicIds\n ? `AND topic_id IN (${uniqueTopicIds.map(() => \"?\").join(\",\")})`\n : \"\";\n const rows = db\n .query(\n `SELECT m.topic_id AS topic_id, m.text AS text\n FROM api_messages m\n JOIN (\n SELECT topic_id, MAX(rowid) AS mx FROM api_messages\n WHERE deleted = 0 AND thread_root_id IS NULL\n ${topicFilter}\n GROUP BY topic_id\n ) last ON m.topic_id = last.topic_id AND m.rowid = last.mx`,\n )\n .all(...(uniqueTopicIds ?? [])) as { topic_id: string; text: string }[];\n\n const out = new Map<string, string>();\n for (const r of rows) {\n const preview = (r.text ?? \"\").replace(/\\s+/g, \" \").trim().slice(0, 120);\n if (preview) out.set(r.topic_id, preview);\n }\n return out;\n}\n\n/** Hard-delete every message in a topic (used when a topic is deleted). */\nexport function deleteMessagesForTopic(topicId: string): number {\n const res = db.query(\"DELETE FROM api_messages WHERE topic_id = ?\").run(topicId);\n return Number(res.changes ?? 0);\n}\n\n/** Anonymize all messages authored by a deleted user. */\nexport function anonymizeApiMessages(userId: string): void {\n db.query(\"UPDATE api_messages SET author_id = 'deleted-user' WHERE author_id = ?\").run(userId);\n}\n\n/** Topic ids whose persisted attachment JSON references this exact upload id.\n * Used only as a compatibility bridge for uploads created before ACL metadata\n * was introduced. JSON UUIDs are quoted, avoiding substring matches. */\nexport function listTopicIdsForAttachment(fileId: string): string[] {\n const needle = `%\"${fileId.replace(/[\\\\%_]/g, (char) => `\\\\${char}`)}\"%`;\n // The ESCAPE literal must reach SQLite as a SINGLE backslash. SQLite string\n // literals do no backslash processing, so '\\\\' there is two characters and\n // fails at row-evaluation time (\"ESCAPE expression must be a single\n // character\") — which only surfaces once api_messages has any rows.\n const rows = db\n .query<{ topic_id: string }, [string]>(\n \"SELECT DISTINCT topic_id FROM api_messages WHERE attachments LIKE ? ESCAPE '\\\\'\",\n )\n .all(needle);\n return rows.map((row) => row.topic_id);\n}\n\n/**\n * Copy all messages from one topic to another (used by fork).\n * Each message gets a new UUID but retains original content, author, and timestamps.\n * Returns the number of messages copied.\n */\nexport function copyMessagesForTopic(sourceTopicId: string, targetTopicId: string): number {\n return copyMessageSnapshotToTopic(captureMessageSnapshotForTopic(sourceTopicId), targetTopicId);\n}\n\nexport interface TopicMessageSnapshot {\n sourceTopicId: string;\n rows: ApiMessageRow[];\n capturedAt: string;\n maxRowid: number;\n}\n\n/** Capture immutable message rows for point-in-time fork/compaction work. */\nexport function captureMessageSnapshotForTopic(topicId: string): TopicMessageSnapshot {\n const rows = db\n .query(\n \"SELECT *, rowid AS rowid FROM api_messages WHERE topic_id = ? AND deleted = 0 ORDER BY rowid ASC\",\n )\n .all(topicId) as ApiMessageRow[];\n return {\n sourceTopicId: topicId,\n rows: rows.map((row) => ({ ...row })),\n capturedAt: new Date().toISOString(),\n maxRowid: rows.at(-1)?.rowid ?? 0,\n };\n}\n\n/** Copy only rows captured by captureMessageSnapshotForTopic; never re-read the source. */\nexport function copyMessageSnapshotToTopic(\n snapshot: TopicMessageSnapshot,\n targetTopicId: string,\n): number {\n const { rows } = snapshot;\n if (rows.length === 0) return 0;\n\n const idMap = new Map(rows.map((r) => [r.id, crypto.randomUUID()]));\n let copied = 0;\n for (const r of rows) {\n const newId = idMap.get(r.id);\n if (!newId) continue;\n appendApiMessage(\n {\n ...rowToDto(r),\n id: newId,\n topicId: targetTopicId,\n parentId: r.parent_id ? (idMap.get(r.parent_id) ?? r.parent_id) : undefined,\n threadRootId: r.thread_root_id\n ? (idMap.get(r.thread_root_id) ?? r.thread_root_id)\n : undefined,\n },\n { notify: false, updateTopicLastMessageAt: false },\n );\n copied++;\n }\n\n return copied;\n}\n\n/**\n * Get all messages for a topic in chronological order (used by export).\n */\nexport function getAllMessagesForTopic(topicId: string): ApiMessageRow[] {\n return db\n .query(\n \"SELECT *, rowid AS rowid FROM api_messages WHERE topic_id = ? AND deleted = 0 ORDER BY rowid ASC\",\n )\n .all(topicId) as ApiMessageRow[];\n}\n\nexport function getMessagesForTopicAfterRowid(\n topicId: string,\n afterRowid: number,\n): ApiMessageRow[] {\n return db\n .query(\n \"SELECT *, rowid AS rowid FROM api_messages WHERE topic_id = ? AND rowid > ? AND deleted = 0 ORDER BY rowid ASC\",\n )\n .all(topicId, afterRowid) as ApiMessageRow[];\n}\n",
14
+ "const WIKI_SUMMARY_DATE_PREFIX = /^\\d{4}-\\d{2}-\\d{2}-/;\n\nexport function wikiSummarySlug(value: string): string {\n return value.replaceAll(/[^a-zA-Z0-9가-힣_-]+/g, \"-\").slice(0, 120) || \"_\";\n}\n\n/**\n * Wiki memory is a title-keyed namespace. Reopening or recreating a room with\n * the same title must continue the same accumulated topic memory.\n */\nexport function wikiSummaryStorageSlug(rawTopic: string, _topicId?: string): string {\n return wikiSummarySlug(rawTopic);\n}\n\n/**\n * Resolve the canonical filename key for a topic brief.\n */\nexport function wikiBriefStorageKey(rawTopic: string, topicId?: string): string {\n return wikiSummaryStorageSlug(rawTopic, topicId);\n}\n\nexport function wikiSummaryFilename(date: string, rawTopic: string, topicId?: string): string {\n return `${date}-${wikiSummaryStorageSlug(rawTopic, topicId)}.md`;\n}\n\nexport function isTopicSummaryFile(\n filename: string,\n topicId: string,\n topicTitle?: string,\n): boolean {\n if (!WIKI_SUMMARY_DATE_PREFIX.test(filename)) return false;\n if (topicTitle) {\n const titleSlug = wikiSummarySlug(topicTitle);\n if (\n new RegExp(`^\\\\d{4}-\\\\d{2}-\\\\d{2}-${escapeRegExp(titleSlug)}(?:~\\\\d+)?\\\\.md$`).test(filename)\n ) {\n return true;\n }\n }\n const idSlug = wikiSummarySlug(topicId);\n return filename.endsWith(`--${idSlug}.md`) || filename.endsWith(`-${idSlug}.md`);\n}\n\nexport function isTopicBriefFile(filename: string, topicId: string, topicTitle?: string): boolean {\n if (topicTitle && filename === `${wikiSummarySlug(topicTitle)}.md`) return true;\n const idSlug = wikiSummarySlug(topicId);\n return filename === `${idSlug}.md` || filename.endsWith(`--${idSlug}.md`);\n}\n\nfunction escapeRegExp(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n",
15
+ "// Persistent title-scoped wiki brief store, backed by shared SQLite.\n// Topic IDs remain readable as a migration fallback for older rows.\n//\n// Briefs are injected into AI-invited topic turns at session start. The\n// wiki-archiver updates them post-session.\nimport { db } from \"#storage/forum-db\";\nimport { registerStorageSchemaInitializer } from \"#storage/storage-host\";\nimport { wikiSummarySlug } from \"#storage/wiki-summary-names\";\n\nregisterStorageSchemaInitializer((database) => {\n database.exec(`\n CREATE TABLE IF NOT EXISTS api_topic_brief (\n topic_id TEXT PRIMARY KEY,\n brief_md TEXT NOT NULL DEFAULT '',\n latest_summary_md TEXT,\n summary_date TEXT,\n updated_at TEXT NOT NULL DEFAULT (datetime('now'))\n )\n `);\n}, 30);\n\nexport interface TopicBrief {\n topicId: string;\n /** Lightweight topic brief (300-600 tokens, injected at session start). */\n briefMd: string;\n /** Latest session summary markdown (full source-summary). */\n latestSummaryMd?: string;\n /** Date of the latest summary (YYYY-MM-DD). */\n summaryDate?: string;\n /** ISO-8601 timestamp of last update. */\n updatedAt: string;\n}\n\ninterface BriefRow {\n topic_id: string;\n brief_md: string;\n latest_summary_md: string | null;\n summary_date: string | null;\n updated_at: string;\n}\n\nfunction rowToBrief(r: BriefRow): TopicBrief {\n return {\n topicId: r.topic_id,\n briefMd: r.brief_md,\n latestSummaryMd: r.latest_summary_md ?? undefined,\n summaryDate: r.summary_date ?? undefined,\n updatedAt: r.updated_at,\n };\n}\n\n/**\n * Get the topic brief for a storage key. Returns null when no brief\n * has been written yet (fresh topic, no archiver run).\n */\nexport function getTopicBrief(storageKey: string): TopicBrief | null {\n const row = db\n .query(\n \"SELECT topic_id, brief_md, latest_summary_md, summary_date, updated_at FROM api_topic_brief WHERE topic_id = ?\",\n )\n .get(storageKey) as BriefRow | null;\n if (!row) return null;\n return rowToBrief(row);\n}\n\n/** Resolve title-keyed memory first, retaining id-keyed rows as a migration fallback. */\nexport function resolveTopicBrief(\n topicId: string,\n legacyTitle: string,\n): { brief: TopicBrief; storageKey: string } | null {\n const titleKey = wikiSummarySlug(legacyTitle);\n const titleBrief = getTopicBrief(titleKey);\n if (titleBrief) return { brief: titleBrief, storageKey: titleKey };\n const current = getTopicBrief(topicId);\n if (current) return { brief: current, storageKey: topicId };\n const legacy = titleKey === legacyTitle ? null : getTopicBrief(legacyTitle);\n return legacy ? { brief: legacy, storageKey: legacyTitle } : null;\n}\n\n/**\n * Upsert the topic brief. `briefMd` and `latestSummaryMd` are\n * independently optional — callers can update just one field without\n * wiping the other. `summaryDate` should be the date of the summary\n * (YYYY-MM-DD), set alongside `latestSummaryMd`.\n */\nexport function setTopicBrief(\n topicId: string,\n fields: {\n briefMd?: string;\n latestSummaryMd?: string;\n summaryDate?: string;\n },\n): TopicBrief {\n const existing = getTopicBrief(topicId);\n\n const briefMd = fields.briefMd !== undefined ? fields.briefMd : (existing?.briefMd ?? \"\");\n const latestSummaryMd =\n fields.latestSummaryMd !== undefined\n ? fields.latestSummaryMd\n : (existing?.latestSummaryMd ?? null);\n const summaryDate =\n fields.summaryDate !== undefined ? fields.summaryDate : (existing?.summaryDate ?? null);\n\n db.query(\n `INSERT INTO api_topic_brief\n (topic_id, brief_md, latest_summary_md, summary_date, updated_at)\n VALUES (?, ?, ?, ?, datetime('now'))\n ON CONFLICT(topic_id) DO UPDATE SET\n brief_md = excluded.brief_md,\n latest_summary_md = excluded.latest_summary_md,\n summary_date = excluded.summary_date,\n updated_at = excluded.updated_at`,\n ).run(topicId, briefMd, latestSummaryMd, summaryDate);\n\n return getTopicBrief(topicId)!;\n}\n\n/** Remove a topic's brief row entirely (e.g. on topic hard-delete). */\nexport function deleteTopicBrief(topicId: string): void {\n db.query(\"DELETE FROM api_topic_brief WHERE topic_id = ?\").run(topicId);\n}\n\n/**\n * List all topic briefs for browsing (wiki UI). Returns briefMd\n * only (no full summary body) to keep the payload light.\n */\nexport function listTopicBriefs(): TopicBrief[] {\n const rows = db\n .query(\n \"SELECT topic_id, brief_md, latest_summary_md, summary_date, updated_at FROM api_topic_brief ORDER BY updated_at DESC\",\n )\n .all() as BriefRow[];\n return rows.map(rowToBrief);\n}\n",
16
+ "// Persistent per-topic model/effort/MCP overrides and user locks.\n// SQLite. Mirrors api-topics.ts. This replaces the previous in-memory Map in\n// routes/topic-config.ts, which lost every override on server restart — a\n// regression now that topic config is the canonical path for model/effort\n// switching (the MCP-based direction), not just a transient convenience.\nimport { db } from \"#storage/forum-db\";\nimport { registerStorageSchemaInitializer } from \"#storage/storage-host\";\nimport type { EffortLevel } from \"#types\";\n\nfunction tableColumns(table: string): Set<string> {\n const rows = db.query(`PRAGMA table_info(${table})`).all() as Array<{ name: string }>;\n return new Set(rows.map((row) => row.name));\n}\n\nfunction createCanonicalConfigTable(name = \"api_topic_config\"): void {\n db.exec(`\n CREATE TABLE IF NOT EXISTS ${name} (\n topic_id TEXT PRIMARY KEY REFERENCES api_topics(id) ON DELETE CASCADE,\n model TEXT,\n effort TEXT CHECK (effort IS NULL OR effort IN ('low','medium','high','xhigh','max')),\n mcp TEXT,\n agent_locked INTEGER NOT NULL DEFAULT 0 CHECK (agent_locked IN (0,1)),\n model_locked INTEGER NOT NULL DEFAULT 0 CHECK (model_locked IN (0,1)),\n effort_locked INTEGER NOT NULL DEFAULT 0 CHECK (effort_locked IN (0,1))\n )\n `);\n}\n\nfunction initializeApiTopicConfigSchema(): void {\n const existingConfigColumns = tableColumns(\"api_topic_config\");\n if (existingConfigColumns.size === 0) {\n createCanonicalConfigTable();\n } else if (\n existingConfigColumns.has(\"agent\") ||\n existingConfigColumns.has(\"agent_pinned\") ||\n existingConfigColumns.has(\"runtime_locked\") ||\n existingConfigColumns.has(\"model_pinned\") ||\n existingConfigColumns.has(\"effort_pinned\") ||\n existingConfigColumns.has(\"last_shown_agent\")\n ) {\n // Complete the old agent-override migration before dropping the column. The\n // selected agent itself belongs to api_topics; only its user lock belongs here.\n const topicColumns = tableColumns(\"api_topics\");\n const agentColumn = topicColumns.has(\"agent\")\n ? \"agent\"\n : topicColumns.has(\"runtime_agent\")\n ? \"runtime_agent\"\n : null;\n if (agentColumn && existingConfigColumns.has(\"agent\")) {\n db.exec(\n `UPDATE api_topics\n SET ${agentColumn} = (\n SELECT c.agent FROM api_topic_config c WHERE c.topic_id = api_topics.id\n )\n WHERE ${agentColumn} IS NULL\n AND EXISTS (\n SELECT 1 FROM api_topic_config c\n WHERE c.topic_id = api_topics.id AND c.agent IS NOT NULL\n )`,\n );\n }\n\n const previousForeignKeys = db\n .query<{ foreign_keys: number }, []>(\"PRAGMA foreign_keys\")\n .get()?.foreign_keys;\n db.exec(\"PRAGMA foreign_keys = OFF\");\n try {\n const agentLockSource = existingConfigColumns.has(\"runtime_locked\")\n ? \"runtime_locked\"\n : existingConfigColumns.has(\"agent_pinned\")\n ? \"agent_pinned\"\n : \"0\";\n const modelLockSource = existingConfigColumns.has(\"model_locked\")\n ? \"model_locked\"\n : existingConfigColumns.has(\"model_pinned\")\n ? \"model_pinned\"\n : \"0\";\n const effortLockSource = existingConfigColumns.has(\"effort_locked\")\n ? \"effort_locked\"\n : existingConfigColumns.has(\"effort_pinned\")\n ? \"effort_pinned\"\n : \"0\";\n db.transaction(() => {\n createCanonicalConfigTable(\"api_topic_config_next\");\n db.exec(`\n INSERT INTO api_topic_config_next\n (topic_id, model, effort, mcp, agent_locked, model_locked, effort_locked)\n SELECT\n topic_id,\n model,\n effort,\n mcp,\n COALESCE(${agentLockSource}, 0),\n COALESCE(${modelLockSource}, 0),\n COALESCE(${effortLockSource}, 0)\n FROM api_topic_config\n WHERE EXISTS (SELECT 1 FROM api_topics t WHERE t.id = api_topic_config.topic_id)\n `);\n db.exec(\"DROP TABLE api_topic_config\");\n db.exec(\"ALTER TABLE api_topic_config_next RENAME TO api_topic_config\");\n })();\n } finally {\n db.exec(`PRAGMA foreign_keys = ${previousForeignKeys ? \"ON\" : \"OFF\"}`);\n }\n } else {\n createCanonicalConfigTable();\n }\n}\n\nregisterStorageSchemaInitializer(initializeApiTopicConfigSchema, 40);\n\nexport interface TopicConfig {\n model?: string;\n effort?: EffortLevel;\n mcp?: string[]; // enabled optional MCP server names\n // Per-field user locks: when true, AI self-config cannot override the field.\n agentLocked?: boolean;\n modelLocked?: boolean;\n effortLocked?: boolean;\n}\n\ninterface ConfigRow {\n topic_id: string;\n model: string | null;\n effort: string | null;\n mcp: string | null;\n agent_locked: number;\n model_locked: number;\n effort_locked: number;\n}\n\nfunction rowToConfig(r: ConfigRow): TopicConfig {\n const cfg: TopicConfig = {};\n if (r.model) cfg.model = r.model;\n if (r.effort) cfg.effort = r.effort as EffortLevel;\n if (r.mcp) {\n try {\n const parsed = JSON.parse(r.mcp);\n if (Array.isArray(parsed)) cfg.mcp = parsed as string[];\n } catch {\n // corrupt JSON — treat as no mcp override\n }\n }\n if (r.agent_locked) cfg.agentLocked = true;\n if (r.model_locked) cfg.modelLocked = true;\n if (r.effort_locked) cfg.effortLocked = true;\n return cfg;\n}\n\n/**\n * Per-topic override set via `PATCH /config` (and, going forward, the MCP\n * self-config tools). Returns `undefined` when the topic has no stored row,\n * so callers can distinguish \"no override\" from \"override with empty fields\".\n */\nexport function getApiTopicConfig(topicId: string): TopicConfig | undefined {\n const row = db\n .query(\n \"SELECT topic_id, model, effort, mcp, agent_locked, model_locked, effort_locked FROM api_topic_config WHERE topic_id = ?\",\n )\n .get(topicId) as ConfigRow | null;\n if (!row) return undefined;\n const config = rowToConfig(row);\n return Object.keys(config).length > 0 ? config : undefined;\n}\n\n/**\n * Upsert the full override for a topic. Fields set to `undefined` are cleared\n * (stored as SQL NULL), matching the previous Map semantics where the route\n * built a complete `updated` object before persisting.\n */\nexport function setApiTopicConfig(topicId: string, config: TopicConfig): void {\n db.query(\n `INSERT INTO api_topic_config\n (topic_id, model, effort, mcp, agent_locked, model_locked, effort_locked)\n VALUES (?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT(topic_id) DO UPDATE SET\n model = excluded.model,\n effort = excluded.effort,\n mcp = excluded.mcp,\n agent_locked = excluded.agent_locked,\n model_locked = excluded.model_locked,\n effort_locked = excluded.effort_locked`,\n ).run(\n topicId,\n config.model ?? null,\n config.effort ?? null,\n config.mcp ? JSON.stringify(config.mcp) : null,\n config.agentLocked ? 1 : 0,\n config.modelLocked ? 1 : 0,\n config.effortLocked ? 1 : 0,\n );\n}\n\n/** Remove a topic's override row entirely (e.g. on topic hard-delete). */\nexport function deleteApiTopicConfig(topicId: string): void {\n db.query(\"DELETE FROM api_topic_config WHERE topic_id = ?\").run(topicId);\n}\n",
17
+ "import type { HostMcpServerSpec } from \"#runtime-gateway\";\n\nexport interface TokenUsage {\n /** Aggregate billable input across every model call made during this turn. */\n inputTokens: number;\n outputTokens: number;\n cacheCreationInputTokens?: number;\n cacheReadInputTokens?: number;\n /** Provider-reported query cost when available. */\n costUsd?: number;\n /** Tokens occupied by the latest model call, not aggregate turn spend. */\n contextTokens?: number;\n /** Provider-reported context window for the latest model call. */\n contextWindow?: number;\n}\n\n/** Agent identifier — one of the supported AI provider backends. */\nexport type AgentKind = \"maestro\" | \"claude\" | \"codex\";\n\nexport const SUPPORTED_AGENTS: readonly AgentKind[] = [\"maestro\", \"claude\", \"codex\"] as const;\n\nexport function isAgentKind(value: unknown): value is AgentKind {\n return typeof value === \"string\" && (SUPPORTED_AGENTS as readonly string[]).includes(value);\n}\n\n/**\n * Per-agent supported reasoning efforts. Single source of truth for both the\n * `EffortLevel` type and each registry's `validEfforts` runtime list — the\n * registries import these directly so adding a value in one place\n * propagates to validation, footer rendering, and zod enums.\n *\n * Claude SDK rejects 'minimal'; Codex SDK rejects 'max'. The two sets\n * intersect on low/medium/high/xhigh. Maestro (TS port) currently piggybacks\n * on the Anthropic provider, so its efforts mirror the Claude set; this can\n * narrow per-provider once Phase 5 lands.\n *\n * 'minimal' removed from codex: Codex API rejects it when default tools\n * (image_gen, web_search) are active, making agent sessions unusable.\n */\nexport const CLAUDE_EFFORT_VALUES = [\"low\", \"medium\", \"high\", \"xhigh\", \"max\"] as const;\nexport const CODEX_EFFORT_VALUES = [\"low\", \"medium\", \"high\", \"xhigh\", \"max\"] as const;\nexport const MAESTRO_EFFORT_VALUES = [\"low\", \"medium\", \"high\", \"xhigh\", \"max\"] as const;\n\nexport type EffortLevel =\n | (typeof CLAUDE_EFFORT_VALUES)[number]\n | (typeof CODEX_EFFORT_VALUES)[number]\n | (typeof MAESTRO_EFFORT_VALUES)[number];\n\n/**\n * Runtime iteration list (used by zod enums and any callers that need to\n * loop over every accepted value). Manually ordered for readability; the\n * `satisfies` check fails the build if an entry here isn't covered by the\n * per-agent unions above.\n */\nexport const EFFORT_VALUES = [\n \"low\",\n \"medium\",\n \"high\",\n \"xhigh\",\n \"max\",\n] as const satisfies readonly EffortLevel[];\n\n/**\n * Normalized events yielded by any agent provider (claudeProvider, codexProvider).\n * The handler/event-processor consumes these without caring which backend produced them.\n *\n * `user_message` is the lone \"into-the-log\" variant — no provider yields it.\n * The query handler writes it directly to the conversation log right before\n * `runAgent()` starts, so cross-agent rollout reconstruction can pair every\n * assistant turn with the user prompt that triggered it. Consumers that only\n * react to provider output (e.g. processAgentEvent) can safely ignore it.\n */\n/**\n * Wire-safe projection of one task, carried by the `tasks` UnifiedEvent.\n *\n * This is also the on-disk shape of Otium's shared task store, so claude,\n * codex, and maestro render the same live panel from the same source of truth.\n */\nexport interface TaskSnapshot {\n id: string;\n subject: string;\n status: \"pending\" | \"in_progress\" | \"completed\";\n /** Task ids this one is blocked by; omitted when empty. */\n blockedBy?: string[];\n /** Present-continuous label for spinners, when set. */\n activeForm?: string;\n /** Owner / agent name for multi-agent runs, when set. */\n owner?: string;\n}\n\n/** One topic-scoped decision and its incoming causal edges. */\nexport interface DecisionSnapshot {\n id: string;\n action: string;\n reasoning: string;\n agent: AgentKind;\n model?: string;\n status: \"proposed\" | \"accepted\" | \"executed\" | \"rejected\" | \"superseded\";\n /** Upstream decision ids. Each entry forms a directed upstream -> this edge. */\n causedBy?: string[];\n timestamp: number;\n}\n\nexport type UnifiedEvent =\n | {\n type: \"user_message\";\n content: string;\n synthetic?: \"compaction\";\n /** Total ordered user submissions represented by one preempting provider turn. */\n consecutiveBatchSize?: number;\n /** Zero-based position within the ordered preemption batch. */\n consecutiveBatchIndex?: number;\n }\n | { type: \"session\"; sessionId: string }\n | {\n type: \"tool_use\";\n name: string;\n input: Record<string, unknown>;\n /** Provider-assigned id so the client can match tool_use→tool_result pairs. */\n toolUseId?: string;\n }\n | { type: \"tool_progress\"; toolName: string; elapsed: number }\n | { type: \"tool_use_summary\"; summary: string }\n // Provider reasoning/thinking summary text (Codex `reasoning` items; Claude\n // extended-thinking). Surfaced so background runs (cron/archiver) show the\n // agent's thought process, not just tool calls.\n | { type: \"reasoning\"; content: string }\n // Full task-list snapshot (replace, not delta) from Otium's shared task\n // store. Provider-native task/todo stores are not authoritative.\n | { type: \"tasks\"; tasks: TaskSnapshot[] }\n | {\n type: \"tool_result\";\n toolUseId: string;\n content: string;\n /** True when the tool call failed; absent/false means success. */\n isError?: boolean;\n metadata?: {\n truncatedForModel: boolean;\n originalBytes: number;\n returnedBytes: number;\n omittedBytes?: number;\n outputPath?: string;\n };\n }\n | { type: \"text_delta\"; content: string }\n /**\n * Live display text for the assistant block being written. Only room\n * previews (`message_stream`) use it; it is never saved, archived or\n * replayed. The provider still emits the completed block as `text`, which\n * replaces this preview. For providers whose completed message is the only\n * source of block order (Claude).\n */\n | { type: \"text_preview\"; content: string }\n | { type: \"text\"; content: string }\n | { type: \"result\"; content: string; stopReason: string; usage?: TokenUsage }\n | { type: \"file\"; path: string; source: string; origin: \"tag\" | \"extension\" }\n | {\n type: \"error\";\n content: string;\n usage?: TokenUsage;\n /**\n * - `budget_exceeded`: the Claude spend budget (max USD) was hit.\n * - `context_budget_exceeded`: maestro-agent-sdk refused a request that is\n * still over the model's context budget after trimming (SDK >= 0.5.4).\n */\n code?: \"budget_exceeded\" | \"context_budget_exceeded\";\n }\n | { type: \"status\"; content: string };\n\nexport interface AgentInputAttachment {\n id: string;\n type: \"image\" | \"file\" | \"audio\";\n filename: string;\n mimeType: string;\n sizeBytes: number;\n path: string;\n}\n\n/** Worker-side runtime tools proxy user-facing state back to the canonical\n * hub topic identified here. */\nexport interface PeerRuntimeBridgeContext {\n hubCellId: string;\n hostTopicId: string;\n hostQueryId: string;\n canSpawnSubagents: boolean;\n}\n\n/**\n * The rooms the turn's human actor may reach on this node, asserted by the\n * hub that owns per-person membership for the `otium` surface.\n *\n * Node topic ids, valid on the node the turn was submitted to. `visible` is\n * every room the actor participates in (owner or member); `owned` is the\n * subset the actor owns. The assertion rides the signed per-turn MCP token,\n * so the agent can never widen it. With one, it is authoritative: reachable is\n * exactly the current room plus `visible`, owned exactly `owned` — the node\n * adds nothing of its own, not even subagent lineage. A turn without one\n * (older hub, or a turn no person started: cron, self-schedule, a subagent's\n * spawn/report/follow-up) is fail-closed to the current room plus the node's\n * own subagent lineage (direct parent, `grant_subagent_tell` targets, own\n * child workers).\n *\n * `issuedAt` (epoch ms) bounds how long the assertion is believed: this node\n * stamps it when the turn request arrives (the earlier of the hub's own\n * `issuedAt`, if sent, and the receipt time). Past\n * `actorTopicScopeMaxAgeMs()` — or with no `issuedAt` at all — the assertion\n * is stale and grants no cross-room reach (see `isActorTopicScopeFresh`).\n */\nexport interface ActorTopicScope {\n visibleNodeTopicIds: string[];\n ownedNodeTopicIds: string[];\n issuedAt?: number;\n}\n\n/**\n * Hub-issued authority for the `node/topic` branches of `session-comm` on\n * the `otium` surface, one per turn. `capability` is an opaque bearer\n * (`rsc1.<payload>.<hmac>`) only the hub can verify: it binds the person who\n * spoke, the origin room and this turn's request id, and the hub re-checks\n * the person's membership of the origin and target rooms on every call. The\n * node holds no key, so it can neither mint nor verify one; the only thing it\n * reads out of the payload is `e` (expiry), base64-decoded untrusted to order\n * grants when several requests fold into one turn. `hubUrl` is where the\n * node presents it (`/api/v1/session-comm/remote/*`). Absent — an older hub,\n * a hub with the feature off, or a turn no person started (cron,\n * self-schedule, subagent lineage) — remote session-comm stays fail-closed.\n */\nexport interface RemoteSessionGrant {\n hubUrl: string;\n capability: string;\n}\n\n/** A message a person sent while a turn runs, for that turn to read at its next step. */\nexport interface MidTurnMessage {\n /** Canonical message id. The provider names it back once the turn has read it. */\n id: string;\n /** The rendered prompt, as the turn's own first message is rendered. */\n text: string;\n}\n\n/**\n * How a running turn takes messages sent while it works (Codex-style steer: the\n * work goes on, and the agent reads the message after the step it is on).\n * Only a provider that can feed a live turn opens it; for any other the\n * message stays queued for the next turn.\n */\nexport interface MidTurnInput {\n /** The turn can take messages from now on. `deliver` returns false once it no longer can. */\n open(deliver: (message: MidTurnMessage) => boolean): void;\n /** The turn ended. `read` are the delivered ids it read inside the turn; the rest were not read. */\n close(read: readonly string[]): void;\n}\n\nexport interface AgentQueryOptions {\n agent: AgentKind;\n prompt: string;\n /** Present on a person's turn: messages they send while it runs are read inside it. */\n midTurn?: MidTurnInput;\n attachments?: AgentInputAttachment[];\n sessionId?: string | null;\n cwd: string;\n systemPrompt: string;\n /**\n * Trusted system-level instructions for this Maestro invocation only.\n * Maestro projects them onto the invocation-start user message without\n * persisting them in session history or compaction. Omitted for Claude/Codex.\n */\n ephemeralSystemPrompt?: string;\n userId?: string;\n /** Product actor identity when execution uses a canonical node principal. */\n actorUserId?: string;\n /** Hub-asserted rooms the product actor may reach; absent means fail-closed. */\n actorTopicScope?: ActorTopicScope;\n /** Hub-issued per-turn authority for remote (`node/topic`) session-comm. */\n remoteSession?: RemoteSessionGrant;\n /** Credential namespace when it differs from the execution principal. */\n vaultUserId?: string;\n session?: string;\n playwrightPort?: number;\n playwrightCapability?: string;\n bgBashPort?: number;\n sessionType?: \"dm\" | \"forum\" | \"ephemeral\" | \"manager\" | \"cron\";\n /** API topic id (REST/WS world). Carries per-query topic context for MCP servers. */\n topicId?: string;\n /** Direct parent topic id when this query runs inside a subagent room. */\n subagentParentTopicId?: string;\n /** API query id for the currently running turn. Used by runtime MCP tools. */\n queryId?: string;\n /** Optional wiki-memory topic id. Derived topics use their root origin here\n * while other per-topic MCP servers keep `topicId` bound to the live room. */\n wikiTopicId?: string;\n /** Whether self-config MCP may enqueue an automatic continue turn after set_* changes. */\n autoContinue?: boolean;\n /** Expose Otium-only visual panel tools for this turn. Default-deny. */\n visualTools?: boolean;\n /** Expose adapter-backed file-delivery tools for this turn. Default-deny. */\n fileDeliveryTools?: boolean;\n /** Validated host MCPs resolved from durable manager-room grants at execution time. */\n hostMcpServers?: Record<string, HostMcpServerSpec>;\n /**\n * Thread this turn answers inside, so the turn's runtime MCP can default\n * `thread_read` to it. Turn-scoped, unlike the session, which is per topic.\n */\n threadRootId?: string;\n abortController?: AbortController;\n model?: string;\n /** Provider-side hard budget when the selected SDK supports one. */\n maxBudgetUsd?: number;\n depth?: number;\n agents?: Record<\n string,\n {\n description: string;\n prompt: string;\n model?: string;\n tools?: string[];\n maxTurns?: number;\n effort?: EffortLevel | number;\n }\n >;\n effort?: EffortLevel;\n /**\n * Per-API-call `max_tokens` ceiling on the assistant's output. Wired\n * through to the underlying provider request body for every agent\n * (claude/codex/maestro). Omit to inherit each provider SDK's per-model\n * default — for maestro that's the v0.1.21+ `getNativeMaxOutputTokens`\n * catalog (deepseek-pro=64K, kimi-k3=64K, kimi-k2.7-code=32K).\n *\n * Pass an explicit number when a specific topic / surface needs a tighter\n * latency cap or a higher ceiling for long-form generation (legal\n * report writing, multi-K Write/Edit file bodies). Pre-0.1.21 maestro\n * builds silently clamped at 4096 and truncated outputs mid-string;\n * setting this field is now the supported way to lift that ceiling.\n */\n maxTokens?: number;\n /**\n * v0.1.22+: Claude-Code-style deferred tool catalog + `ToolSearch` built-in.\n *\n * Wired straight through to `maestro-agent-sdk`'s\n * `AgentQueryOptions.enableToolSearch`. When `true`, the maestro provider\n * registers every MCP tool as deferred — schemas stay off the wire until\n * the model promotes them via `ToolSearch(\"select:Name1,Name2\")` or\n * `ToolSearch(\"keyword\")`. Active set persists across resume.\n *\n * Otium's maestro provider supplies `true` when the caller leaves this\n * option unset, because most forum turns carry enough MCP surface for the\n * reminder-token savings to outweigh the first-use `ToolSearch` round-trip.\n * Callers can still pass `false` per call when a narrow surface or\n * latency-sensitive workflow is better served by eager MCP schemas.\n *\n * No-op for claude / codex agents — they have their own deferred-tool\n * machinery owned by their respective SDKs.\n */\n enableToolSearch?: boolean;\n /**\n * Bounded tool results with the full output kept on disk.\n *\n * Wired to `maestro-agent-sdk`'s `AgentQueryOptions.toolResultTruncation`.\n * The SDK caps a string tool result, writes the untruncated bytes to a file,\n * and splices an opaque `maestro://tool-output/<id>` reference into the text\n * that the `ReadToolOutput` tool can page back through.\n *\n * The maestro provider enables it by default. Left unset, every tool result\n * — a whole-file `Read`, a wide `Grep`, a `WebFetch` of a large page —\n * entered the context at full size, and the `\"ReadToolOutput\"` entry in the\n * provider's builtin list was dead, because the SDK only registers that tool\n * when truncation is on with `saveFullOutput`.\n *\n * Pass an explicit object to tune the budget, or `{ enabled: false }` for a\n * call whose tool results must arrive whole.\n *\n * No-op for claude / codex agents — their SDKs do their own truncation.\n */\n toolResultTruncation?: {\n enabled?: boolean;\n maxBytes?: number;\n headBytes?: number;\n tailBytes?: number;\n saveFullOutput?: boolean;\n outputDir?: string;\n retentionDays?: number;\n ignoreTools?: string[];\n };\n /**\n * Claude-Code-compatible exact tool denylist. Maestro v0.1.42+ hides these\n * tools from provider schemas / ToolSearch and blocks dispatch if a stale\n * call still arrives. Claude maps this to its SDK option. Codex does not\n * support this name-based list; its provider-native multi-agent tool family\n * is disabled separately through the Codex feature config.\n */\n disallowedTools?: readonly string[];\n /**\n * Hard provider tool policy for auxiliary model calls.\n *\n * `\"none\"` removes MCP and provider-native tools before the request is\n * dispatched. `\"compaction-log\"` keeps provider-native tools disabled and\n * exposes only the host-scoped immutable log reader. Use these for untrusted\n * transcript transforms; reacting to tool events after dispatch is not a\n * security boundary.\n */\n toolPolicy?: \"none\" | \"compaction-log\";\n mcpEnabled?: string[] | null;\n peerBridge?: PeerRuntimeBridgeContext;\n mcpExtra?: Record<string, unknown>;\n /**\n * true for silent fork runs generating ask_session replies — restricts session-comm\n * outbound tools (ask/tell/abort) so the forked session can only produce text\n */\n silent?: boolean;\n}\n\n/** State file written to data/users/{userId}/active-queries/{topicId}.json while a query is running. */\nexport interface QueryState {\n topicId?: string;\n topicName?: string;\n task?: string; // first 100 chars of prompt, newlines normalized\n since: string; // ISO timestamp\n}\n",
18
+ "import { resolve } from \"node:path\";\nimport { type AgentKind, isAgentKind } from \"#types\";\n\nexport type RuntimeEnvironment = Readonly<Record<string, string | undefined>>;\n\nexport function readEnvText(env: RuntimeEnvironment, key: string): string | undefined {\n const value = env[key]?.trim();\n return value || undefined;\n}\n\n/**\n * Node-wide default agent (FALLBACK_AGENT env, legacy DEFAULT_AGENT, else\n * \"claude\"). Lives in this side-effect-free leaf module — not #platform/config\n * — so storage layers that only need this one value (e.g. the forum/api-topics\n * repositories, re-exported through the public storage facade) don't drag in\n * config.ts's eager `mkdirSync` of every node data directory just by\n * importing it.\n */\nexport function resolveFallbackAgent(env: RuntimeEnvironment = process.env): AgentKind {\n const value = readEnvText(env, \"FALLBACK_AGENT\") ?? readEnvText(env, \"DEFAULT_AGENT\");\n return isAgentKind(value) ? value : \"claude\";\n}\n\nexport function parseRuntimePort(value: string | undefined, fallback: number): number {\n if (!value) return fallback;\n const port = Number.parseInt(value, 10);\n return Number.isInteger(port) && port > 0 && port <= 65_535 ? port : fallback;\n}\n\nexport function resolveRuntimeStateDir(options: {\n env: RuntimeEnvironment;\n envKey: string;\n fallbackRoot: string;\n fallbackName: string;\n}): string {\n const configured = readEnvText(options.env, options.envKey);\n return configured ? resolve(configured) : resolve(options.fallbackRoot, options.fallbackName);\n}\n\nexport function safeRuntimePathSegment(value: string, fallback: string, maxLength = 160): string {\n const cleaned = value\n .trim()\n .replace(/[^A-Za-z0-9._-]/g, \"_\")\n .replace(/^_+|_+$/g, \"\")\n .slice(0, maxLength);\n return cleaned || fallback;\n}\n",
19
+ "/** \"from\" field for session-inbox entries injected after a setting change. */\nexport const FROM_AUTO_CONTINUE = \"auto-continue\";\n\n/** \"from\" field for durable delayed continuations created by schedule_self. */\nexport const FROM_SELF_SCHEDULE = \"self-schedule\";\n\n/** Topic names that collide with internal sentinels and must not be used. */\nexport const RESERVED_TOPIC_NAMES: ReadonlySet<string> = new Set([\n FROM_AUTO_CONTINUE,\n FROM_SELF_SCHEDULE,\n \"general\",\n]);\n\n/** Legacy shared General id. New General rooms use per-user UUIDs. */\nexport const GENERAL_TOPIC_ID = \"general\";\n\n/**\n * Sanitized log name every private General resolves to.\n *\n * `general` is reserved above, so a manager room is the only room that can\n * produce it — which is what lets conversation storage qualify just that one\n * file per owner instead of namespacing the whole directory.\n */\nexport const MANAGER_TOPIC_LOG_NAME = \"general\";\n\n/** The principal a standalone node runs as when no hub names another. */\nexport const NODE_LOCAL_USER_ID = \"local\";\n\n/** Internal topic name for the forum manager session (General topic). */\nexport const TOPIC_MANAGER = \"__manager__\";\n",
20
+ "import { randomUUID } from \"node:crypto\";\nimport { db } from \"#storage/forum-db\";\nimport { registerStorageSchemaInitializer } from \"#storage/storage-host\";\n\nexport const TOPIC_MAINTENANCE_STALE_MS = 30_000;\nexport const TOPIC_MAINTENANCE_HEARTBEAT_MS = 1_000;\n\nexport interface RuntimeTopicState {\n topicId: string;\n epoch: number;\n maintenance: boolean;\n maintenanceOwner?: string;\n heartbeatAt?: number;\n}\n\nexport interface RuntimeTopicMaintenanceHandle {\n topicId: string;\n epoch: number;\n ownerId: string;\n isOwned(): boolean;\n finish(options?: { deleteState?: boolean }): void;\n}\n\ninterface RuntimeTopicStateRow {\n topic_id: string;\n epoch: number | bigint;\n maintenance: number;\n maintenance_owner: string | null;\n heartbeat_at: number | bigint | null;\n}\n\nregisterStorageSchemaInitializer((database) => {\n database.exec(`\n CREATE TABLE IF NOT EXISTS runtime_topic_state (\n topic_id TEXT PRIMARY KEY,\n epoch INTEGER NOT NULL DEFAULT 0,\n maintenance INTEGER NOT NULL DEFAULT 0 CHECK (maintenance IN (0, 1)),\n maintenance_owner TEXT,\n heartbeat_at INTEGER\n )\n `);\n}, 32);\n\ntype MaintenanceReleasedListener = (topicId: string) => void;\nconst maintenanceReleasedListeners = new Set<MaintenanceReleasedListener>();\n\n/**\n * Observe maintenance fences released by THIS process (`finish()`). Listeners\n * run synchronously after the release and must not throw into the caller;\n * anything that writes should defer itself out of the caller's transaction.\n * Releases in other processes are not observed — pair with a timer.\n */\nexport function onRuntimeTopicMaintenanceReleased(\n listener: MaintenanceReleasedListener,\n): () => void {\n maintenanceReleasedListeners.add(listener);\n return () => {\n maintenanceReleasedListeners.delete(listener);\n };\n}\n\nfunction notifyMaintenanceReleased(topicId: string): void {\n for (const listener of maintenanceReleasedListeners) {\n try {\n listener(topicId);\n } catch {\n // A diagnostic hook never breaks a maintenance release.\n }\n }\n}\n\nfunction rowToState(row: RuntimeTopicStateRow, now = Date.now()): RuntimeTopicState {\n const heartbeatAt = row.heartbeat_at === null ? undefined : Number(row.heartbeat_at);\n const maintenance =\n row.maintenance !== 0 &&\n heartbeatAt !== undefined &&\n now - heartbeatAt <= TOPIC_MAINTENANCE_STALE_MS;\n return {\n topicId: row.topic_id,\n epoch: Number(row.epoch),\n maintenance,\n maintenanceOwner: maintenance ? (row.maintenance_owner ?? undefined) : undefined,\n heartbeatAt,\n };\n}\n\nexport function getRuntimeTopicState(topicId: string, now = Date.now()): RuntimeTopicState {\n const row = db\n .query<RuntimeTopicStateRow, [string]>(\"SELECT * FROM runtime_topic_state WHERE topic_id = ?\")\n .get(topicId);\n return row ? rowToState(row, now) : { topicId, epoch: 0, maintenance: false };\n}\n\nexport function getRuntimeTopicEpoch(topicId: string): number {\n return getRuntimeTopicState(topicId).epoch;\n}\n\nexport function isRuntimeTopicMaintenance(topicId: string, now = Date.now()): boolean {\n return getRuntimeTopicState(topicId, now).maintenance;\n}\n\n/**\n * Advance the topic execution epoch and hold an exclusive maintenance fence.\n * Turns from an older epoch can be identified and discarded in every process.\n */\nexport function beginRuntimeTopicMaintenance(\n topicId: string,\n options: { ownerId?: string; now?: number; heartbeatMs?: number } = {},\n): RuntimeTopicMaintenanceHandle | null {\n const ownerId = options.ownerId ?? `${process.pid}-${randomUUID()}`;\n const now = options.now ?? Date.now();\n const result = db\n .query(\n `INSERT INTO runtime_topic_state\n (topic_id, epoch, maintenance, maintenance_owner, heartbeat_at)\n VALUES (?, 1, 1, ?, ?)\n ON CONFLICT(topic_id) DO UPDATE SET\n epoch = runtime_topic_state.epoch + 1,\n maintenance = 1,\n maintenance_owner = excluded.maintenance_owner,\n heartbeat_at = excluded.heartbeat_at\n WHERE runtime_topic_state.maintenance = 0\n OR runtime_topic_state.heartbeat_at IS NULL\n OR runtime_topic_state.heartbeat_at < ?`,\n )\n .run(topicId, ownerId, now, now - TOPIC_MAINTENANCE_STALE_MS);\n if (Number(result.changes ?? 0) === 0) return null;\n\n const epoch = getRuntimeTopicEpoch(topicId);\n let finished = false;\n const heartbeatMs = options.heartbeatMs ?? TOPIC_MAINTENANCE_HEARTBEAT_MS;\n const timer = setInterval(() => {\n if (finished) return;\n const updated = db\n .query(\n `UPDATE runtime_topic_state\n SET heartbeat_at = ?\n WHERE topic_id = ? AND epoch = ? AND maintenance_owner = ? AND maintenance = 1`,\n )\n .run(Date.now(), topicId, epoch, ownerId);\n if (Number(updated.changes ?? 0) > 0) return;\n finished = true;\n clearInterval(timer);\n }, heartbeatMs);\n timer.unref?.();\n\n return {\n topicId,\n epoch,\n ownerId,\n isOwned() {\n if (finished) return false;\n const row = db\n .query<{ owned: number }, [string, number, string]>(\n `SELECT 1 AS owned FROM runtime_topic_state\n WHERE topic_id = ? AND epoch = ? AND maintenance_owner = ? AND maintenance = 1`,\n )\n .get(topicId, epoch, ownerId);\n return Boolean(row);\n },\n finish(finishOptions = {}) {\n if (finished) return;\n finished = true;\n clearInterval(timer);\n if (finishOptions.deleteState) {\n db.query(\n `DELETE FROM runtime_topic_state\n WHERE topic_id = ? AND epoch = ? AND maintenance_owner = ?`,\n ).run(topicId, epoch, ownerId);\n notifyMaintenanceReleased(topicId);\n return;\n }\n db.query(\n `UPDATE runtime_topic_state\n SET maintenance = 0, maintenance_owner = NULL, heartbeat_at = NULL\n WHERE topic_id = ? AND epoch = ? AND maintenance_owner = ?`,\n ).run(topicId, epoch, ownerId);\n notifyMaintenanceReleased(topicId);\n },\n };\n}\n",
21
+ "/**\n * Durable evidence for the hub↔node topic link (topic-link design v2 §4.2,\n * §4.5, PR7). Two tables, both written by the node and only ever read by a\n * host through the authenticated Runtime Gateway:\n *\n * - `api_topic_create_claims` — one row per host `requestId` on a room-creating\n * request (`POST /topics`, `POST /topics/:id/derive`). Written inside the same\n * SQLite transaction that inserts the topic, so a response lost after commit\n * can always be replayed by id instead of being guessed at (title/parent\n * heuristics are forbidden by the design).\n * - `api_topic_tombstones` — one row per topic that left the host-visible\n * surface, stamped with THIS node's identity. Written by SQLite triggers on\n * `api_topics`, so every delete path (gateway, MCP, CLI, account deletion,\n * future ones) records it in the very statement that removes the row; there\n * is no code path that can delete a topic and forget the tombstone.\n *\n * `api_node_identity` holds the node id the triggers stamp. The node process\n * records its `NODE_ID` there at start (and the delete cascade re-asserts it)\n * via {@link recordTopicLinkNodeIdentity}: a database copied to another install\n * keeps the old id on its old tombstones, so the existence API — which only\n * answers `gone` for a tombstone written under the identity it is answering\n * as — can never turn a copied store's history into a delete on the new node.\n * Until an identity is recorded, tombstones carry NULL and never count as\n * `gone` (fail-safe). This module deliberately does not import\n * `#platform/config`: that would create state paths merely by importing the\n * public storage facade.\n */\n\nimport { createHash } from \"node:crypto\";\nimport { GENERAL_TOPIC_ID } from \"#platform/constants\";\n// Side effect: registers `api_messages`, which the message fence trigger\n// guards (and orders it before this schema).\nimport \"#storage/api-messages\";\nimport { db } from \"#storage/forum-db\";\n// Side effect: registers `runtime_topic_state`, which the message fence\n// trigger reads (and orders it before this schema).\nimport \"#storage/runtime-topic-state\";\nimport { registerStorageSchemaInitializer } from \"#storage/storage-host\";\n\nexport type TopicCreateClaimOp = \"create\" | \"derive\" | \"abort\";\nexport type TopicCreateClaimState = \"committed\" | \"aborted\";\nexport type TopicTombstoneReason = \"deleted\" | \"unshared\";\n\nexport interface TopicCreateClaim {\n principalKey: string;\n requestId: string;\n op: TopicCreateClaimOp;\n payloadHash: string;\n topicId: string | null;\n state: TopicCreateClaimState;\n nodeId: string | null;\n /** Highest `api_messages.rowid` of the topic when the claim committed (seeded history). */\n seedMaxMessageRowid: number;\n /** Derive only: the source topic the claim was made for (null on create / legacy rows). */\n sourceTopicId: string | null;\n /** Message count of the topic when the claim committed (null on legacy rows). */\n seedMessageCount: number | null;\n /** sha256 of the sorted message ids at claim time (null on legacy rows). */\n seedMessageIdsHash: string | null;\n createdAt: string;\n updatedAt: string;\n}\n\nexport interface TopicTombstone {\n seq: number;\n topicId: string;\n nodeId: string | null;\n reason: TopicTombstoneReason;\n surface: string | null;\n surfaceScope: string | null;\n deletedAt: string;\n /**\n * Present on feed entries that come from `api_topic_scope_moves`: the room\n * was moved OUT of `surfaceScope` by an admin scope repair (reported to the\n * old scope as `unshared`). Not a row of `api_topic_tombstones`.\n */\n scopeMoved?: true;\n}\n\ninterface ClaimRow {\n principal_key: string;\n request_id: string;\n op: string;\n payload_hash: string;\n topic_id: string | null;\n state: string;\n node_id: string | null;\n seed_max_message_rowid: number | bigint | null;\n source_topic_id?: string | null;\n seed_message_count?: number | bigint | null;\n seed_message_ids_hash?: string | null;\n created_at: string;\n updated_at: string;\n}\n\ninterface TombstoneRow {\n seq: number | bigint;\n topic_id: string;\n node_id: string | null;\n reason: string;\n surface: string | null;\n surface_scope: string | null;\n deleted_at: string;\n}\n\n/** Claims are kept at least this long (design v2 §4.2: ≥ 30 days). */\nexport const TOPIC_CREATE_CLAIM_RETENTION_MS = 30 * 24 * 60 * 60_000;\n\nconst NODE_IDENTITY_SQL = \"(SELECT node_id FROM api_node_identity WHERE singleton = 1)\";\nconst NOW_SQL = \"strftime('%Y-%m-%dT%H:%M:%fZ','now')\";\nconst TOMBSTONE_SEQ_SQL = \"(SELECT seq FROM api_topic_tombstone_seq WHERE singleton = 1)\";\n// Advances the never-decreasing tombstone sequence. Runs as the first\n// statement of every tombstone-writing trigger, so the new row's seq is read\n// back from the counter within the same statement/transaction.\nconst BUMP_TOMBSTONE_SEQ_SQL =\n \"UPDATE api_topic_tombstone_seq SET seq = seq + 1 WHERE singleton = 1\";\nconst NEW_EPOCH_SQL = \"lower(hex(randomblob(16)))\";\n\n/**\n * Owner-id prefix of the runtime maintenance fence a claim abort holds while\n * it deletes the claimed topic. While such a fence is live, the\n * `api_messages_claim_abort_fence` trigger refuses every message insert into\n * that topic (any writer, any process), so nothing can land between the\n * abort's \"no new messages\" check and the delete.\n */\nexport const TOPIC_CLAIM_ABORT_OWNER_PREFIX = \"topic-link-abort:\";\n/** The message the fence trigger raises; matched by ingress to answer 409. */\nexport const TOPIC_CLAIM_ABORT_FENCE_ERROR = \"topic_claim_abort_in_progress\";\n// Same staleness rule as `runtime-topic-state` (TOPIC_MAINTENANCE_STALE_MS):\n// a crashed abort never blocks a room for longer than a stale fence.\nconst CLAIM_ABORT_FENCE_STALE_MS = 30_000;\nconst NOW_MS_SQL = \"CAST((julianday('now') - 2440587.5) * 86400000 AS INTEGER)\";\nconst CLAIM_ABORT_FENCE_PREDICATE = `maintenance = 1\n AND maintenance_owner LIKE '${TOPIC_CLAIM_ABORT_OWNER_PREFIX}%'\n AND heartbeat_at IS NOT NULL\n AND heartbeat_at >= ${NOW_MS_SQL} - ${CLAIM_ABORT_FENCE_STALE_MS}`;\n\ntype SchemaDatabase = {\n exec(sql: string): unknown;\n transaction<T>(fn: () => T): (() => T) & { immediate?: () => T };\n query(sql: string): { all(...params: never[]): unknown[] };\n};\n\nconst SCHEMA_TABLES = [\n \"api_node_identity\",\n \"api_topic_create_claims\",\n \"api_topic_tombstones\",\n \"api_topic_tombstone_seq\",\n \"api_topic_scope_repair_grants\",\n \"api_topic_scope_moves\",\n];\nconst SCHEMA_INDEXES = [\n \"idx_api_topic_create_claims_topic\",\n \"idx_api_topic_create_claims_created\",\n \"idx_api_topic_create_claims_principal\",\n \"idx_api_topic_create_claims_settled_at\",\n \"idx_api_topic_scope_moves_seq\",\n];\n/** Columns added to `api_topic_create_claims` after its first release. */\nconst CLAIM_ADDED_COLUMNS: Record<string, string> = {\n source_topic_id: \"TEXT\",\n seed_message_count: \"INTEGER\",\n seed_message_ids_hash: \"TEXT\",\n settled_at: \"TEXT\",\n};\nconst SCHEMA_INDEXES_TOMBSTONES = [\"idx_api_topic_tombstones_seq\"];\n/** Trigger → a marker its current SQL must contain (older builds lack it). */\nconst SCHEMA_TRIGGERS: Record<string, string> = {\n api_topics_tombstone_on_delete: \"api_topic_tombstone_seq\",\n api_topics_tombstone_on_unshare: \"api_topic_tombstone_seq\",\n api_topics_tombstone_on_reshare: \"surface_scope IS NEW.surface_scope\",\n api_topics_tombstone_on_insert: \"api_topic_tombstones\",\n api_messages_claim_abort_fence: TOPIC_CLAIM_ABORT_OWNER_PREFIX,\n api_topics_otium_scope_immutable: \"api_topic_scope_repair_grants\",\n};\n\n/** The message the scope-immutability trigger raises. */\nexport const OTIUM_TOPIC_SCOPE_IMMUTABLE_ERROR = \"otium_topic_scope_immutable\";\n\n/**\n * Read-only: whether the schema (and identity) is already current. Every\n * process start runs the initializer, so the common path must not write — a\n * write here would take the database lock on every boot and can fail with\n * SQLITE_BUSY while other processes start concurrently.\n */\nfunction topicLinkSchemaIsCurrent(database: SchemaDatabase, nodeId?: string): boolean {\n const objects = new Map(\n (\n database\n .query(\"SELECT name, sql FROM sqlite_master WHERE type IN ('table','index','trigger')\")\n .all() as Array<{ name: string; sql: string | null }>\n ).map((row) => [row.name, row.sql ?? \"\"]),\n );\n for (const name of [...SCHEMA_TABLES, ...SCHEMA_INDEXES, ...SCHEMA_INDEXES_TOMBSTONES]) {\n if (!objects.has(name)) return false;\n }\n for (const [name, marker] of Object.entries(SCHEMA_TRIGGERS)) {\n if (!objects.get(name)?.includes(marker)) return false;\n }\n if (!columnNames(database, \"api_node_identity\").has(\"epoch_id\")) return false;\n const claimColumns = columnNames(database, \"api_topic_create_claims\");\n for (const column of Object.keys(CLAIM_ADDED_COLUMNS)) {\n if (!claimColumns.has(column)) return false;\n }\n const identity = database\n .query(\"SELECT node_id, epoch_id FROM api_node_identity WHERE singleton = 1\")\n .all() as Array<{ node_id: string; epoch_id: string | null }>;\n if (identity.some((row) => row.epoch_id === null)) return false;\n if (nodeId && identity[0]?.node_id !== nodeId) return false;\n const counter = database\n .query(\n `SELECT (SELECT seq FROM api_topic_tombstone_seq WHERE singleton = 1) AS counter,\n MAX((SELECT COALESCE(MAX(seq), 0) FROM api_topic_tombstones),\n (SELECT COALESCE(MAX(seq), 0) FROM api_topic_scope_moves)) AS max_seq`,\n )\n .all() as Array<{ counter: number | bigint | null; max_seq: number | bigint }>;\n const row = counter[0];\n return row?.counter !== null && row?.counter !== undefined && row.counter >= row.max_seq;\n}\n\nfunction columnNames(database: SchemaDatabase, table: string): Set<string> {\n const rows = database.query(`PRAGMA table_info(${table})`).all() as Array<{ name: string }>;\n return new Set(rows.map((row) => row.name));\n}\n\n/**\n * Idempotent, and all-or-nothing: every statement is `IF NOT EXISTS` / an\n * upsert / a drop-and-recreate of a trigger, and the whole set runs in one\n * transaction so a crash half-way never leaves triggers without the table\n * they write to.\n */\nexport function initializeTopicLinkRecordsSchema(database: SchemaDatabase, nodeId?: string): void {\n if (topicLinkSchemaIsCurrent(database, nodeId)) return;\n const migrate = database.transaction(() => {\n database.exec(`\n CREATE TABLE IF NOT EXISTS api_node_identity (\n singleton INTEGER PRIMARY KEY CHECK (singleton = 1),\n node_id TEXT NOT NULL,\n epoch_id TEXT,\n updated_at TEXT NOT NULL\n )\n `);\n // PR7 fix: a random id minted when this store first records an identity.\n // Survives NODE_ID changes; a wiped/recreated store gets a new one.\n if (!columnNames(database, \"api_node_identity\").has(\"epoch_id\")) {\n database.exec(\"ALTER TABLE api_node_identity ADD COLUMN epoch_id TEXT\");\n }\n database.exec(\n `UPDATE api_node_identity SET epoch_id = ${NEW_EPOCH_SQL} WHERE epoch_id IS NULL`,\n );\n database.exec(`\n CREATE TABLE IF NOT EXISTS api_topic_create_claims (\n principal_key TEXT NOT NULL,\n request_id TEXT NOT NULL,\n op TEXT NOT NULL CHECK (op IN ('create','derive','abort')),\n payload_hash TEXT NOT NULL,\n topic_id TEXT,\n state TEXT NOT NULL CHECK (state IN ('committed','aborted')),\n node_id TEXT,\n seed_max_message_rowid INTEGER NOT NULL DEFAULT 0,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL,\n source_topic_id TEXT,\n seed_message_count INTEGER,\n seed_message_ids_hash TEXT,\n settled_at TEXT,\n PRIMARY KEY (principal_key, request_id)\n )\n `);\n // Review fixes (additive): the derive source a claim was made for, and the\n // exact message set the created topic was seeded with.\n const claimColumns = columnNames(database, \"api_topic_create_claims\");\n for (const [column, type] of Object.entries(CLAIM_ADDED_COLUMNS)) {\n if (!claimColumns.has(column)) {\n database.exec(`ALTER TABLE api_topic_create_claims ADD COLUMN ${column} ${type}`);\n }\n }\n database.exec(\n `CREATE INDEX IF NOT EXISTS idx_api_topic_create_claims_principal\n ON api_topic_create_claims(principal_key, state, topic_id)`,\n );\n // Retention anchor of a settled (aborted) claim is its settlement time.\n database.exec(\n `CREATE INDEX IF NOT EXISTS idx_api_topic_create_claims_settled_at\n ON api_topic_create_claims(state, settled_at)`,\n );\n // Scope repair (review fix 6): the one sanctioned way to change an otium\n // topic's surface_scope. A grant row exists only inside the repair's own\n // transaction (inserted and deleted before commit), so no other\n // connection ever observes it.\n database.exec(`\n CREATE TABLE IF NOT EXISTS api_topic_scope_repair_grants (\n topic_id TEXT PRIMARY KEY\n )\n `);\n // Scope move history + audit (one row per admin repair). Its seq comes\n // from the tombstone counter, so moves merge into the tombstone feed in\n // order: a hub bound to the OLD scope sees the move as `unshared`.\n database.exec(`\n CREATE TABLE IF NOT EXISTS api_topic_scope_moves (\n seq INTEGER PRIMARY KEY,\n topic_id TEXT NOT NULL,\n node_id TEXT,\n from_scope TEXT,\n to_scope TEXT NOT NULL,\n actor TEXT NOT NULL,\n reason TEXT NOT NULL,\n claims_left INTEGER NOT NULL,\n moved_at TEXT NOT NULL\n )\n `);\n database.exec(\n \"CREATE INDEX IF NOT EXISTS idx_api_topic_scope_moves_seq ON api_topic_scope_moves(topic_id, seq)\",\n );\n database.exec(\n \"CREATE INDEX IF NOT EXISTS idx_api_topic_create_claims_topic ON api_topic_create_claims(topic_id)\",\n );\n database.exec(\n \"CREATE INDEX IF NOT EXISTS idx_api_topic_create_claims_created ON api_topic_create_claims(created_at)\",\n );\n database.exec(`\n CREATE TABLE IF NOT EXISTS api_topic_tombstones (\n topic_id TEXT PRIMARY KEY,\n seq INTEGER NOT NULL,\n node_id TEXT,\n reason TEXT NOT NULL CHECK (reason IN ('deleted','unshared')),\n surface TEXT,\n surface_scope TEXT,\n deleted_at TEXT NOT NULL\n )\n `);\n database.exec(\n \"CREATE INDEX IF NOT EXISTS idx_api_topic_tombstones_seq ON api_topic_tombstones(seq)\",\n );\n // Never-decreasing tombstone sequence (PR7 fix). `api_topic_tombstones` is\n // a current-state table whose rows are deleted on reshare/reinsert, so\n // MAX(seq)+1 could hand out a seq a cursor already passed. Seeded from the\n // table on every init, and never lowered.\n database.exec(`\n CREATE TABLE IF NOT EXISTS api_topic_tombstone_seq (\n singleton INTEGER PRIMARY KEY CHECK (singleton = 1),\n seq INTEGER NOT NULL\n )\n `);\n database.exec(`\n INSERT INTO api_topic_tombstone_seq (singleton, seq)\n VALUES (1, (SELECT MAX(\n (SELECT COALESCE(MAX(seq), 0) FROM api_topic_tombstones),\n (SELECT COALESCE(MAX(seq), 0) FROM api_topic_scope_moves))))\n ON CONFLICT(singleton) DO UPDATE SET seq = MAX(api_topic_tombstone_seq.seq, excluded.seq)\n `);\n // Recreated on every init so a store migrated by an earlier build (whose\n // triggers computed MAX(seq)+1) gets the counter-based versions.\n for (const name of [\n \"api_topics_tombstone_on_delete\",\n \"api_topics_tombstone_on_unshare\",\n \"api_topics_tombstone_on_reshare\",\n \"api_topics_tombstone_on_insert\",\n \"api_messages_claim_abort_fence\",\n \"api_topics_otium_scope_immutable\",\n ]) {\n database.exec(`DROP TRIGGER IF EXISTS ${name}`);\n }\n // Hard delete, from any writer. `DROP TABLE` (the legacy schema rebuild)\n // does not fire row triggers, so a migration never fabricates tombstones.\n database.exec(`\n CREATE TRIGGER api_topics_tombstone_on_delete\n AFTER DELETE ON api_topics\n BEGIN\n ${BUMP_TOMBSTONE_SEQ_SQL};\n INSERT OR REPLACE INTO api_topic_tombstones\n (topic_id, seq, node_id, reason, surface, surface_scope, deleted_at)\n VALUES\n (OLD.id, ${TOMBSTONE_SEQ_SQL}, ${NODE_IDENTITY_SQL}, 'deleted',\n OLD.surface, OLD.surface_scope, ${NOW_SQL});\n END\n `);\n // Left the Otium surface (moved to another surface or hidden). Evidence of\n // a withdrawal, never of a deletion: the existence API still answers\n // `present` for such a topic.\n database.exec(`\n CREATE TRIGGER api_topics_tombstone_on_unshare\n AFTER UPDATE OF surface, visibility ON api_topics\n WHEN OLD.surface = 'otium' AND COALESCE(OLD.visibility, 'visible') != 'hidden'\n AND (NEW.surface IS NOT 'otium' OR NEW.visibility = 'hidden')\n BEGIN\n ${BUMP_TOMBSTONE_SEQ_SQL};\n INSERT OR REPLACE INTO api_topic_tombstones\n (topic_id, seq, node_id, reason, surface, surface_scope, deleted_at)\n VALUES\n (OLD.id, ${TOMBSTONE_SEQ_SQL}, ${NODE_IDENTITY_SQL}, 'unshared',\n OLD.surface, OLD.surface_scope, ${NOW_SQL});\n END\n `);\n database.exec(`\n CREATE TRIGGER api_topics_tombstone_on_reshare\n AFTER UPDATE OF surface, visibility ON api_topics\n WHEN NEW.surface = 'otium' AND COALESCE(NEW.visibility, 'visible') != 'hidden'\n BEGIN\n -- Only the withdrawal from the scope the room is back in is undone; an\n -- unshare from another workspace stays that workspace's evidence.\n DELETE FROM api_topic_tombstones\n WHERE topic_id = NEW.id AND reason = 'unshared' AND surface_scope IS NEW.surface_scope;\n END\n `);\n // An otium room's workspace is fixed (review fix 6): a claim, a tombstone\n // and the host's mapping all bind to it, and one topic_id-keyed tombstone\n // cannot express several past scopes. Only the audited scope repair\n // (`adminRepairOtiumTopicScope`) may change it, through a grant row that exists\n // only inside its own transaction. Leaving the otium surface is allowed\n // (that is an unshare, tombstoned with the old scope).\n database.exec(`\n CREATE TRIGGER api_topics_otium_scope_immutable\n BEFORE UPDATE OF surface, surface_scope ON api_topics\n WHEN NEW.surface = 'otium'\n AND OLD.surface_scope IS NOT NEW.surface_scope\n AND NOT EXISTS (SELECT 1 FROM api_topic_scope_repair_grants WHERE topic_id = OLD.id)\n BEGIN\n SELECT RAISE(ABORT, '${OTIUM_TOPIC_SCOPE_IMMUTABLE_ERROR}');\n END\n `);\n // A row that exists again (restored or re-inserted id) is not gone.\n database.exec(`\n CREATE TRIGGER api_topics_tombstone_on_insert\n AFTER INSERT ON api_topics\n BEGIN\n DELETE FROM api_topic_tombstones WHERE topic_id = NEW.id;\n END\n `);\n // A topic a claim abort is deleting accepts no message (PR7 fix): see\n // TOPIC_CLAIM_ABORT_OWNER_PREFIX. Checked by SQLite on every insert path,\n // atomically with the insert itself.\n database.exec(`\n CREATE TRIGGER api_messages_claim_abort_fence\n BEFORE INSERT ON api_messages\n WHEN EXISTS (SELECT 1 FROM runtime_topic_state\n WHERE topic_id = NEW.topic_id AND ${CLAIM_ABORT_FENCE_PREDICATE})\n BEGIN\n SELECT RAISE(ABORT, '${TOPIC_CLAIM_ABORT_FENCE_ERROR}');\n END\n `);\n if (nodeId) {\n database.exec(\n `INSERT INTO api_node_identity (singleton, node_id, epoch_id, updated_at)\n VALUES (1, '${nodeId.replaceAll(\"'\", \"''\")}', ${NEW_EPOCH_SQL}, ${NOW_SQL})\n ON CONFLICT(singleton) DO UPDATE SET node_id = excluded.node_id, updated_at = excluded.updated_at\n WHERE api_node_identity.node_id IS NOT excluded.node_id`,\n );\n }\n });\n // BEGIN IMMEDIATE when available: a migrating process waits on the busy\n // timeout for another one instead of failing its read→write upgrade.\n if (migrate.immediate) migrate.immediate();\n else migrate();\n}\n\n// After api_topics (20), api_messages (30) and runtime_topic_state (32): the\n// triggers name their columns, so the tables must already have their shape.\nregisterStorageSchemaInitializer((database) => initializeTopicLinkRecordsSchema(database), 45);\n\n// ── canonical payload hash ────────────────────────────────────────────────\n\nfunction canonicalJson(value: unknown): string {\n if (Array.isArray(value)) return `[${value.map(canonicalJson).join(\",\")}]`;\n if (value && typeof value === \"object\") {\n const entries = Object.entries(value as Record<string, unknown>)\n .filter(([, entry]) => entry !== undefined)\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));\n return `{${entries.map(([key, entry]) => `${JSON.stringify(key)}:${canonicalJson(entry)}`).join(\",\")}}`;\n }\n return JSON.stringify(value ?? null);\n}\n\n/**\n * sha256 (hex) of the canonical JSON of a room-creating request body without\n * the saga's own `requestId`/`payloadHash` — byte-for-byte the hub's\n * `linkPayloadHash` (otium `link/link-intents.ts`): keys sorted at every depth\n * by UTF-16 code unit, compact separators, `undefined` members dropped.\n *\n * For derive the caller passes `{ sourceTopicId: <path id>, ...body }` (the\n * same body forked from two parents must not hash equal).\n */\nexport function topicLinkPayloadHash(body: Record<string, unknown>): string {\n const { requestId: _requestId, payloadHash: _payloadHash, ...payload } = body;\n return createHash(\"sha256\").update(canonicalJson(payload)).digest(\"hex\");\n}\n\n// ── node identity ─────────────────────────────────────────────────────────\n\n/** Record the identity new tombstones and claims are stamped with (no-op when unchanged). */\nexport function recordTopicLinkNodeIdentity(nodeId: string): void {\n const id = nodeId.trim();\n if (!id) return;\n db.query(\n `INSERT INTO api_node_identity (singleton, node_id, epoch_id, updated_at)\n VALUES (1, ?, ${NEW_EPOCH_SQL}, ${NOW_SQL})\n ON CONFLICT(singleton) DO UPDATE SET node_id = excluded.node_id, updated_at = excluded.updated_at\n WHERE api_node_identity.node_id IS NOT excluded.node_id`,\n ).run(id);\n}\n\n/**\n * Random id minted when this store first recorded an identity (`dbEpoch` on\n * the wire). A wiped/recreated store answering under the same `NODE_ID` has a\n * different one; a restore of a backup of the SAME store does not (residual\n * risk, see the contract). Null until an identity is recorded.\n */\nexport function topicLinkDbEpoch(): string | null {\n return (\n db\n .query<{ epoch_id: string | null }, []>(\n \"SELECT epoch_id FROM api_node_identity WHERE singleton = 1\",\n )\n .get()?.epoch_id ?? null\n );\n}\n\n/**\n * The highest tombstone seq ever handed out (never decreases, also counts\n * rows later removed by a reshare/reinsert). A hub whose recorded cursor is\n * above this value is talking to a rolled-back store.\n */\nexport function topicTombstoneHighWater(): number {\n const row = db\n .query<{ seq: number | bigint }, []>(\n \"SELECT seq FROM api_topic_tombstone_seq WHERE singleton = 1\",\n )\n .get();\n return Number(row?.seq ?? 0);\n}\n\n/** The identity new tombstones and claims are stamped with. */\nexport function topicLinkNodeIdentity(): string | null {\n return (\n db\n .query<{ node_id: string }, []>(\"SELECT node_id FROM api_node_identity WHERE singleton = 1\")\n .get()?.node_id ?? null\n );\n}\n\n// ── create claims ─────────────────────────────────────────────────────────\n\nfunction toClaim(row: ClaimRow): TopicCreateClaim {\n return {\n principalKey: row.principal_key,\n requestId: row.request_id,\n op: row.op as TopicCreateClaimOp,\n payloadHash: row.payload_hash,\n topicId: row.topic_id,\n state: row.state as TopicCreateClaimState,\n nodeId: row.node_id,\n seedMaxMessageRowid: Number(row.seed_max_message_rowid ?? 0),\n sourceTopicId: row.source_topic_id ?? null,\n seedMessageCount:\n row.seed_message_count === null || row.seed_message_count === undefined\n ? null\n : Number(row.seed_message_count),\n seedMessageIdsHash: row.seed_message_ids_hash ?? null,\n createdAt: row.created_at,\n updatedAt: row.updated_at,\n };\n}\n\nexport function getTopicCreateClaim(\n principalKey: string,\n requestId: string,\n): TopicCreateClaim | null {\n const row = db\n .query<ClaimRow, [string, string]>(\n \"SELECT * FROM api_topic_create_claims WHERE principal_key = ? AND request_id = ?\",\n )\n .get(principalKey, requestId);\n return row ? toClaim(row) : null;\n}\n\n/**\n * Committed claims of one principal for exactly these topics — for\n * `hostCreate` on topic DTOs. Bounded by the ids asked for (index\n * `(principal_key, state, topic_id)`), never the principal's whole history.\n */\nexport function committedClaimsByTopic(\n principalKey: string,\n topicIds: readonly string[],\n): Map<string, TopicCreateClaim> {\n const byTopic = new Map<string, TopicCreateClaim>();\n const unique = [...new Set(topicIds)];\n for (let start = 0; start < unique.length; start += 500) {\n const chunk = unique.slice(start, start + 500);\n const rows = db\n .query<ClaimRow, string[]>(\n `SELECT * FROM api_topic_create_claims\n WHERE principal_key = ? AND state = 'committed'\n AND topic_id IN (${chunk.map(() => \"?\").join(\",\")})`,\n )\n .all(principalKey, ...chunk);\n for (const row of rows) if (row.topic_id) byTopic.set(row.topic_id, toClaim(row));\n }\n return byTopic;\n}\n\nfunction maxMessageRowid(topicId: string): number {\n const row = db\n .query<{ max_rowid: number | bigint | null }, [string]>(\n \"SELECT MAX(rowid) AS max_rowid FROM api_messages WHERE topic_id = ?\",\n )\n .get(topicId);\n return Number(row?.max_rowid ?? 0);\n}\n\n/** Count and sha256 of the sorted message ids of a topic: its exact message set. */\nfunction messageSetOf(topicId: string): { count: number; hash: string } {\n const ids = db\n .query<{ id: string }, [string]>(\"SELECT id FROM api_messages WHERE topic_id = ? ORDER BY id\")\n .all(topicId)\n .map((row) => row.id);\n return { count: ids.length, hash: createHash(\"sha256\").update(ids.join(\"\\n\")).digest(\"hex\") };\n}\n\n/**\n * Record a committed claim. MUST be called inside the transaction that inserts\n * the topic row (the `withinCreateTransaction` hook of `registerTopic` /\n * `createDerivedTopic`): a plain INSERT, so a concurrent second request with\n * the same key fails the primary key and rolls its own topic back.\n */\nexport function insertCommittedTopicCreateClaim(input: {\n principalKey: string;\n requestId: string;\n op: \"create\" | \"derive\";\n payloadHash: string;\n topicId: string;\n /** Derive: the path source topic the claim is bound to. */\n sourceTopicId?: string;\n}): TopicCreateClaim {\n const now = new Date().toISOString();\n const seed = maxMessageRowid(input.topicId);\n const seeded = messageSetOf(input.topicId);\n db.query(\n `INSERT INTO api_topic_create_claims\n (principal_key, request_id, op, payload_hash, topic_id, state, node_id,\n seed_max_message_rowid, created_at, updated_at,\n source_topic_id, seed_message_count, seed_message_ids_hash)\n VALUES (?, ?, ?, ?, ?, 'committed', ${NODE_IDENTITY_SQL}, ?, ?, ?, ?, ?, ?)`,\n ).run(\n input.principalKey,\n input.requestId,\n input.op,\n input.payloadHash,\n input.topicId,\n seed,\n now,\n now,\n input.sourceTopicId ?? null,\n seeded.count,\n seeded.hash,\n );\n const claim = getTopicCreateClaim(input.principalKey, input.requestId);\n if (!claim) throw new Error(\"topic create claim was not recorded\");\n return claim;\n}\n\n/**\n * Write the aborted fence for a key that has no claim yet, so a create that\n * arrives after the abort is refused rather than orphaned. No-op (false) when\n * any claim already exists for the key. Callers deciding \"no claim\" MUST do so\n * in the same transaction (see `abortTopicCreateClaim`).\n */\nexport function insertTopicCreateAbortFence(principalKey: string, requestId: string): boolean {\n const now = new Date().toISOString();\n const inserted = db\n .query(\n `INSERT OR IGNORE INTO api_topic_create_claims\n (principal_key, request_id, op, payload_hash, topic_id, state, node_id,\n seed_max_message_rowid, created_at, updated_at, settled_at)\n VALUES (?, ?, 'abort', '', NULL, 'aborted', ${NODE_IDENTITY_SQL}, 0, ?, ?, ?)`,\n )\n .run(principalKey, requestId, now, now, now);\n return Number(inserted.changes ?? 0) > 0;\n}\n\n/**\n * CAS a committed claim to aborted. Only for a caller that has decided the\n * claim's topic in the same transaction (deleted it, or found it gone): a\n * committed claim must never become aborted while its topic lives on.\n */\nexport function flipCommittedTopicCreateClaimToAborted(\n principalKey: string,\n requestId: string,\n): boolean {\n const updated = db\n .query(\n `UPDATE api_topic_create_claims SET state = 'aborted', updated_at = ?1, settled_at = ?1\n WHERE principal_key = ?2 AND request_id = ?3 AND state = 'committed'`,\n )\n .run(new Date().toISOString(), principalKey, requestId);\n return Number(updated.changes ?? 0) > 0;\n}\n\n/**\n * Settle a claim as aborted where that is safe without deleting anything, in\n * one `BEGIN IMMEDIATE`: no claim → aborted fence; committed claim whose topic\n * row is already gone → aborted. A committed claim whose topic still exists is\n * returned UNCHANGED (deleting it is `abortTopicCreateClaim`'s job). Returns\n * the stored claim.\n */\nexport function markTopicCreateClaimAborted(\n principalKey: string,\n requestId: string,\n): TopicCreateClaim {\n return db\n .transaction(() => {\n const current = getTopicCreateClaim(principalKey, requestId);\n if (!current) {\n insertTopicCreateAbortFence(principalKey, requestId);\n } else if (current.state === \"committed\" && !topicRowExists(current.topicId)) {\n flipCommittedTopicCreateClaimToAborted(principalKey, requestId);\n }\n const claim = getTopicCreateClaim(principalKey, requestId);\n if (!claim) throw new Error(\"topic create claim abort was not recorded\");\n return claim;\n })\n .immediate();\n}\n\nfunction topicRowExists(topicId: string | null): boolean {\n if (!topicId) return false;\n return Boolean(\n db\n .query<{ found: number }, [string]>(\"SELECT 1 AS found FROM api_topics WHERE id = ?\")\n .get(topicId),\n );\n}\n\n/** Whether a live claim-abort fence currently refuses messages into this topic. */\nexport function isTopicClaimAbortFenced(topicId: string): boolean {\n return Boolean(\n db\n .query<{ found: number }, [string]>(\n `SELECT 1 AS found FROM runtime_topic_state WHERE topic_id = ? AND ${CLAIM_ABORT_FENCE_PREDICATE}`,\n )\n .get(topicId),\n );\n}\n\n/** Whether an error is the message fence trigger's refusal. */\nexport function isTopicClaimAbortFenceError(error: unknown): boolean {\n return error instanceof Error && error.message.includes(TOPIC_CLAIM_ABORT_FENCE_ERROR);\n}\n\n/**\n * Whether the claimed topic's messages differ from what it was created with.\n *\n * Compared as an exact SET (count + hash of the sorted ids recorded at claim\n * time), not by rowid: a logical dump/import or a VACUUM that renumbers rowids\n * cannot make a post-create message look seeded. Any difference — a new\n * message, a hard-deleted one — counts, so an abort only ever deletes a topic\n * holding exactly its seeded history. Legacy claims without a recorded set fall\n * back to the rowid boundary.\n */\nexport function topicHasMessagesAfterClaim(claim: TopicCreateClaim): boolean {\n if (!claim.topicId) return false;\n if (claim.seedMessageCount !== null && claim.seedMessageIdsHash !== null) {\n const current = messageSetOf(claim.topicId);\n return current.count !== claim.seedMessageCount || current.hash !== claim.seedMessageIdsHash;\n }\n const row = db\n .query<{ found: number }, [string, number]>(\n \"SELECT 1 AS found FROM api_messages WHERE topic_id = ? AND rowid > ? LIMIT 1\",\n )\n .get(claim.topicId, claim.seedMaxMessageRowid);\n return Boolean(row);\n}\n\n/** Upper bound of claims one prune call removes (bounded work per request). */\nexport const TOPIC_CREATE_CLAIM_PRUNE_BATCH = 500;\n\n/**\n * Drop claims past the retention window. Returns the number removed.\n *\n * The retention anchor is the claim's LAST settlement: a committed claim is\n * kept from its `created_at`, an aborted one (fence) from its `settled_at` —\n * the moment it became aborted (rows settled before that column existed fall\n * back to `updated_at`). An old committed claim aborted today therefore\n * keeps refusing a late create with the same requestId for a full window.\n * Removes at most `batch` rows per call.\n */\nexport function pruneTopicCreateClaims(\n now: number = Date.now(),\n retentionMs: number = TOPIC_CREATE_CLAIM_RETENTION_MS,\n batch: number = TOPIC_CREATE_CLAIM_PRUNE_BATCH,\n): number {\n const cutoff = new Date(now - retentionMs).toISOString();\n const result = db\n .query(\n `DELETE FROM api_topic_create_claims WHERE rowid IN (\n SELECT rowid FROM api_topic_create_claims\n WHERE (state = 'committed' AND created_at < ?)\n OR (state = 'aborted' AND COALESCE(settled_at, updated_at) < ?)\n LIMIT ?)`,\n )\n .run(cutoff, cutoff, batch);\n return Number(result.changes ?? 0);\n}\n\n// ── tombstones ────────────────────────────────────────────────────────────\n\nfunction toTombstone(row: TombstoneRow): TopicTombstone {\n return {\n seq: Number(row.seq),\n topicId: row.topic_id,\n nodeId: row.node_id,\n reason: row.reason as TopicTombstoneReason,\n surface: row.surface,\n surfaceScope: row.surface_scope,\n deletedAt: row.deleted_at,\n };\n}\n\nexport function getTopicTombstone(topicId: string): TopicTombstone | null {\n const row = db\n .query<TombstoneRow, [string]>(\"SELECT * FROM api_topic_tombstones WHERE topic_id = ?\")\n .get(topicId);\n return row ? toTombstone(row) : null;\n}\n\n/** Tombstones after a cursor, oldest first. */\n/**\n * The tombstone feed after a cursor, oldest first: current tombstones merged\n * with scope moves (as `unshared` for the OLD scope, `scopeMoved: true`). Both\n * take their seq from the same never-decreasing counter.\n */\nexport function listTopicTombstonesAfter(after: number, limit: number): TopicTombstone[] {\n return db\n .query<TombstoneRow & { scope_moved: number }, [number, number, number]>(\n `SELECT seq, topic_id, node_id, reason, surface, surface_scope, deleted_at, 0 AS scope_moved\n FROM api_topic_tombstones WHERE seq > ?1\n UNION ALL\n SELECT seq, topic_id, node_id, 'unshared', 'otium', from_scope, moved_at, 1\n FROM api_topic_scope_moves WHERE seq > ?2\n ORDER BY seq ASC LIMIT ?3`,\n )\n .all(after, after, limit)\n .map((row) => ({\n ...toTombstone(row),\n ...(row.scope_moved ? { scopeMoved: true as const } : {}),\n }));\n}\n\n/** The latest admin scope move of a topic (the scope it was moved out of), if any. */\nexport function latestTopicScopeMove(topicId: string): TopicTombstone | null {\n const row = db\n .query<\n { seq: number | bigint; node_id: string | null; from_scope: string | null; moved_at: string },\n [string]\n >(\n `SELECT seq, node_id, from_scope, moved_at FROM api_topic_scope_moves\n WHERE topic_id = ? ORDER BY seq DESC LIMIT 1`,\n )\n .get(topicId);\n if (!row) return null;\n return {\n seq: Number(row.seq),\n topicId,\n nodeId: row.node_id,\n reason: \"unshared\",\n surface: \"otium\",\n surfaceScope: row.from_scope,\n deletedAt: row.moved_at,\n scopeMoved: true,\n };\n}\n\n// ── otium scope repair (review fix 6 / PR12 admin repair) ────────────────\n\nexport interface AdminRepairOtiumTopicScopeInput {\n topicId: string;\n /** Only an unscoped room can be repaired: must be `null`. */\n fromScope: null;\n /** Non-empty, no leading/trailing whitespace. */\n toScope: string;\n /**\n * The row the operator observed — compare-and-set. `surface`/`surfaceScope`\n * are required; `createdAt`/`title` pin the exact row when given.\n */\n expectedRow: { surface: \"otium\"; surfaceScope: null; createdAt?: string; title?: string };\n /** Who asked (operator/CLI user, `m9-stamp`). Recorded in the history row. */\n actor: string;\n reason: string;\n}\n\nexport type AdminRepairOtiumTopicScopeRefusal =\n | \"invalid_scope\"\n | \"not_found\"\n | \"not_otium\"\n | \"scope_not_null\"\n | \"row_changed\"\n | \"title_conflict\"\n | \"duplicate_manager\"\n | \"maintenance_in_progress\";\n\nexport type AdminRepairOtiumTopicScopeResult =\n | {\n ok: true;\n topicId: string;\n fromScope: null;\n toScope: string;\n /**\n * Committed create claims of the topic, left on their ORIGINAL principal\n * (never re-bound). A claim whose principal no longer covers the new\n * scope answers `409 claim_topic_moved` on replay/abort.\n */\n claimsLeft: number;\n /** seq of the scope-move entry in the tombstone feed (also the audit id). */\n moveSeq: number;\n }\n | { ok: false; topicId: string; reason: AdminRepairOtiumTopicScopeRefusal; detail?: string };\n\ninterface RepairTopicRow {\n id: string;\n title: string;\n kind: string;\n surface: string;\n surface_scope: string | null;\n created_at: string;\n}\n\nfunction repairOneTopicScope(\n input: AdminRepairOtiumTopicScopeInput,\n): AdminRepairOtiumTopicScopeResult {\n const { topicId } = input;\n const refuse = (reason: AdminRepairOtiumTopicScopeRefusal, detail?: string) =>\n ({ ok: false, topicId, reason, ...(detail ? { detail } : {}) }) as const;\n const toScope = typeof input.toScope === \"string\" ? input.toScope : \"\";\n if (!toScope || toScope !== toScope.trim() || input.fromScope !== null) {\n return refuse(\"invalid_scope\");\n }\n const row = db\n .query<RepairTopicRow, [string]>(\n \"SELECT id, title, kind, surface, surface_scope, created_at FROM api_topics WHERE id = ?\",\n )\n .get(topicId);\n if (!row) return refuse(\"not_found\");\n if (row.surface !== \"otium\" || input.expectedRow.surface !== \"otium\") return refuse(\"not_otium\");\n if (row.surface_scope !== null || input.expectedRow.surfaceScope !== null) {\n return refuse(\"scope_not_null\", row.surface_scope ?? undefined);\n }\n if (\n (input.expectedRow.createdAt !== undefined && input.expectedRow.createdAt !== row.created_at) ||\n (input.expectedRow.title !== undefined && input.expectedRow.title !== row.title)\n ) {\n return refuse(\"row_changed\");\n }\n // A claim abort (or any delete/reset/compact) holds the topic right now.\n const busy = db\n .query<{ found: number }, [string, number]>(\n `SELECT 1 AS found FROM runtime_topic_state\n WHERE topic_id = ? AND maintenance = 1 AND heartbeat_at >= ?`,\n )\n .get(topicId, Date.now() - CLAIM_ABORT_FENCE_STALE_MS);\n if (busy) return refuse(\"maintenance_in_progress\");\n if (row.kind === \"manager\") {\n // Manager rooms are one-per-user and all titled \"General\", so — exactly as\n // in `findTopicTitleConflict` — they take no part in title conflicts.\n // What must not happen is a SECOND manager room for the same owner in one\n // scope (the PR12 CLI and hub audit D7 enforce it too; this is the\n // primitive's own guard so no caller can create one silently).\n const duplicate = db\n .query<{ id: string }, [string, string, string, string]>(\n `SELECT t.id FROM api_topics t\n JOIN topic_members m ON m.topic_id = t.id AND m.role = 'owner'\n WHERE t.kind = 'manager' AND t.surface = 'otium' AND t.surface_scope IS ?\n AND t.id != ? AND t.id != ?\n AND m.user_id IN (\n SELECT user_id FROM topic_members WHERE topic_id = ? AND role = 'owner'\n )\n LIMIT 1`,\n )\n .get(toScope, topicId, GENERAL_TOPIC_ID, topicId);\n if (duplicate) return refuse(\"duplicate_manager\", duplicate.id);\n } else {\n // Same rule as `findTopicTitleConflict`: manager rooms are not title\n // peers, except the reserved shared `general` row.\n const conflict = db\n .query<{ id: string }, [string, string, string, string]>(\n `SELECT id FROM api_topics\n WHERE LOWER(TRIM(title)) = LOWER(TRIM(?)) AND surface = 'otium' AND surface_scope IS ?\n AND id != ? AND (kind != 'manager' OR id = ?) LIMIT 1`,\n )\n .get(row.title, toScope, topicId, GENERAL_TOPIC_ID);\n if (conflict) return refuse(\"title_conflict\", conflict.id);\n }\n\n const claimsLeft = Number(\n db\n .query<{ n: number }, [string]>(\n `SELECT COUNT(*) AS n FROM api_topic_create_claims\n WHERE topic_id = ? AND state = 'committed'`,\n )\n .get(topicId)?.n ?? 0,\n );\n db.query(\"INSERT INTO api_topic_scope_repair_grants (topic_id) VALUES (?)\").run(topicId);\n const updated = db\n .query(\n `UPDATE api_topics SET surface_scope = ?\n WHERE id = ? AND surface = 'otium' AND surface_scope IS NULL`,\n )\n .run(toScope, topicId);\n db.query(\"DELETE FROM api_topic_scope_repair_grants WHERE topic_id = ?\").run(topicId);\n if (Number(updated.changes ?? 0) !== 1) throw new Error(\"scope repair CAS lost the row\");\n db.query(BUMP_TOMBSTONE_SEQ_SQL).run();\n db.query(\n `INSERT INTO api_topic_scope_moves\n (seq, topic_id, node_id, from_scope, to_scope, actor, reason, claims_left, moved_at)\n VALUES (${TOMBSTONE_SEQ_SQL}, ?, ${NODE_IDENTITY_SQL}, NULL, ?, ?, ?, ?, ?)`,\n ).run(topicId, toScope, input.actor, input.reason, claimsLeft, new Date().toISOString());\n const moveSeq = Number(\n db.query<{ seq: number }, []>(`SELECT ${TOMBSTONE_SEQ_SQL} AS seq`).get()?.seq ?? 0,\n );\n return { ok: true, topicId, fromScope: null, toScope, claimsLeft, moveSeq };\n}\n\n/**\n * The ONLY sanctioned way to change an otium topic's `surface_scope` after\n * creation — the `api_topics_otium_scope_immutable` trigger refuses every other\n * writer. One-shot, audited, one `BEGIN IMMEDIATE` (joins the caller's\n * transaction when there is one):\n *\n * - only `NULL → <non-empty scope>` on a `surface='otium'` row, compare-and-set\n * against `expectedRow`; any refusal changes nothing;\n * - create claims are NOT re-bound: they stay on their original principal, and\n * replay/abort re-verify that the topic's current scope still belongs to the\n * claim's principal (else `409 claim_topic_moved`). Re-binding would let the\n * new scope's principal delete a room another caller created, and that\n * caller's retry would then create a duplicate;\n * - the move is recorded in `api_topic_scope_moves` (history + audit) with a\n * seq from the tombstone counter, and appears in the tombstone feed as an\n * `unshared` entry for the OLD scope (`scopeMoved: true`);\n * - tombstones are not rewritten.\n *\n * No HTTP route: storage / admin CLI only.\n */\nexport function adminRepairOtiumTopicScope(\n input: AdminRepairOtiumTopicScopeInput,\n): AdminRepairOtiumTopicScopeResult {\n return db.transaction(() => repairOneTopicScope(input)).immediate();\n}\n\n/**\n * M-9 bulk variant: stamp every unscoped otium room with `toScope` through the\n * same per-topic repair (history recorded, claims untouched). Rooms that are\n * refused (busy, title conflict, duplicate manager) are skipped and reported — the caller decides\n * whether that leaves its migration incomplete (it must, revision 5).\n *\n * `topicIds` narrows the pass to those rooms (the M-9 retry of its pending\n * set); ids that are no longer unscoped otium rooms are simply not selected.\n */\nexport function repairUnscopedOtiumTopicScopes(\n toScope: string,\n actor: string,\n reason: string,\n options: { topicIds?: readonly string[] } = {},\n): { stamped: number; skipped: AdminRepairOtiumTopicScopeResult[] } {\n const skipped: AdminRepairOtiumTopicScopeResult[] = [];\n let stamped = 0;\n const all = db\n .query<RepairTopicRow, []>(\n `SELECT id, title, kind, surface, surface_scope, created_at FROM api_topics\n WHERE surface = 'otium' AND surface_scope IS NULL`,\n )\n .all();\n const only = options.topicIds ? new Set(options.topicIds) : null;\n const rows = only ? all.filter((row) => only.has(row.id)) : all;\n for (const row of rows) {\n const result = repairOneTopicScope({\n topicId: row.id,\n fromScope: null,\n toScope,\n expectedRow: { surface: \"otium\", surfaceScope: null, createdAt: row.created_at },\n actor,\n reason,\n });\n if (result.ok) stamped += 1;\n else skipped.push(result);\n }\n return { stamped, skipped };\n}\n",
22
+ "// Persistent topic store backed by shared SQLite.\n\nimport { resolveFallbackAgent } from \"#platform/config-helpers\";\nimport { GENERAL_TOPIC_ID } from \"#platform/constants\";\nimport { logger } from \"#platform/logger\";\nimport { db } from \"#storage/forum-db\";\nimport { onRuntimeTopicMaintenanceReleased } from \"#storage/runtime-topic-state\";\nimport { registerStorageSchemaInitializer } from \"#storage/storage-host\";\n// Also registers the claim/tombstone schema and the api_topics tombstone and\n// scope-immutability triggers wherever topics can be written (topic-link PR7).\nimport { repairUnscopedOtiumTopicScopes } from \"#storage/topic-link-records\";\nimport type { AgentKind, EffortLevel } from \"#types\";\nimport type {\n AiMode,\n ParticipantDto,\n SubagentReportMode,\n TopicDto,\n TopicKind,\n TopicSurface,\n TopicVisibility,\n} from \"#types/api\";\n\n/**\n * Surface used when a caller does not name one — and the value every existing\n * row is backfilled with on first boot after the surface migration.\n *\n * Hosts that only ever serve one surface declare it once in their environment\n * (`NEGOTIUM_DEFAULT_SURFACE=otium` on the Otium hub and worker); a developer\n * Mac leaves it unset and gets `terminal`, with the telegram adapter\n * reclassifying its own mapped rooms afterwards.\n */\nexport function defaultTopicSurface(): TopicSurface {\n return normalizeTopicSurface(process.env.NEGOTIUM_DEFAULT_SURFACE);\n}\n\nexport function normalizeTopicSurface(value: unknown): TopicSurface {\n return value === \"telegram\" || value === \"otium\" || value === \"terminal\" ? value : \"terminal\";\n}\n\n/**\n * The surface instance new rooms are filed under when the caller names none.\n *\n * `surface` alone is not enough once a node may be attached to several Otium\n * workspaces (M-2): two workspaces are two independent namespaces on the same\n * surface. The adapter that owns the attachment installs the active scope at\n * mount time; `terminal` and `telegram` are singletons and stay null.\n *\n * Kept as process state rather than an argument threaded through every creation\n * path because the value is a property of *this process's attachment*, not of\n * any individual call — the same reason `defaultTopicSurface()` exists.\n */\nlet activeSurfaceScope: string | null = null;\n\nexport function normalizeSurfaceScope(value: unknown): string | null {\n if (typeof value !== \"string\") return null;\n const trimmed = value.trim();\n return trimmed ? trimmed : null;\n}\n\nexport function defaultSurfaceScope(): string | null {\n return activeSurfaceScope ?? normalizeSurfaceScope(process.env.NEGOTIUM_SURFACE_SCOPE);\n}\n\n/** Install (or clear) the scope new rooms inherit. Returns the previous value. */\nexport function setDefaultSurfaceScope(scope: string | null): string | null {\n const previous = activeSurfaceScope;\n activeSurfaceScope = normalizeSurfaceScope(scope);\n return previous;\n}\n\n/**\n * Whether an Otium room must name a workspace to be created at all (M-3).\n *\n * Off by default, and off for every single-workspace host: an unscoped room is\n * then legacy, reachable, and perfectly usable. The adapter turns it on only\n * while several workspaces are attached, because there an unscoped room is\n * reachable from none of them (M-10) — a room nobody can see is worse than a\n * refusal that says so.\n */\nlet surfaceScopeRequired = false;\n\nexport function setSurfaceScopeRequired(required: boolean): void {\n surfaceScopeRequired = required;\n}\n\nexport function isSurfaceScopeRequired(): boolean {\n return surfaceScopeRequired;\n}\n\n/**\n * How many Otium workspaces the adapter currently has mounted, or null when no\n * adapter ever reported (a node without the Otium adapter). Lets a loopback\n * caller tell \"one workspace, scope not resolved yet\" apart from \"no\n * workspace at all\" (topic-link design v2 §4.6, `GET /surface-scope`).\n */\nlet mountedSurfaceScopeCount: number | null = null;\n\nexport function setMountedSurfaceScopeCount(count: number | null): void {\n mountedSurfaceScopeCount = count === null ? null : Math.max(0, Math.floor(count));\n}\n\nexport interface LocalSurfaceScopeStatus {\n /** The workspace an unscoped (loopback) caller's otium rooms are filed under. */\n surfaceScope: string | null;\n /** False while the scope cannot be stated (several workspaces, or one not resolved yet). */\n resolved: boolean;\n /** True while several workspaces are mounted: a room must name one. */\n scopeRequired: boolean;\n /** Mounted Otium workspaces; 0 when no adapter reported. */\n joinsMounted: number;\n}\n\n/** The scope a loopback (no scope header) gateway caller gets. */\nexport function localSurfaceScopeStatus(): LocalSurfaceScopeStatus {\n const joinsMounted = mountedSurfaceScopeCount ?? 0;\n if (surfaceScopeRequired) {\n return { surfaceScope: null, resolved: false, scopeRequired: true, joinsMounted };\n }\n const surfaceScope = defaultSurfaceScope();\n return {\n surfaceScope,\n resolved: joinsMounted === 1 ? surfaceScope !== null : true,\n scopeRequired: false,\n joinsMounted,\n };\n}\n\nfunction tableColumns(table: string): Set<string> {\n const rows = db.query(`PRAGMA table_info(${table})`).all() as Array<{ name: string }>;\n return new Set(rows.map((row) => row.name));\n}\n\n/** Persist the authoritative agent and, when supplied, its normalized base defaults. */\nexport function setApiTopicAgent(\n topicId: string,\n agent: AgentKind,\n defaults?: { model: string; effort?: EffortLevel },\n): void {\n if (!defaults) {\n db.query(\"UPDATE api_topics SET agent = ? WHERE id = ?\").run(agent, topicId);\n return;\n }\n db.query(\"UPDATE api_topics SET agent = ?, base_model = ?, base_effort = ? WHERE id = ?\").run(\n agent,\n defaults.model,\n defaults.effort ?? null,\n topicId,\n );\n}\n\nfunction initializeApiTopicsSchema(): void {\n db.exec(`\n CREATE TABLE IF NOT EXISTS api_topics (\n id TEXT PRIMARY KEY,\n title TEXT NOT NULL,\n kind TEXT NOT NULL DEFAULT 'channel',\n description TEXT,\n agent TEXT,\n default_model TEXT,\n default_effort TEXT,\n participants TEXT,\n created_at TEXT NOT NULL,\n last_message_at TEXT,\n is_archived INTEGER NOT NULL DEFAULT 0,\n ai_mention INTEGER NOT NULL DEFAULT 0,\n ai_mode TEXT\n )\n`);\n\n const initialTopicColumns = tableColumns(\"api_topics\");\n const legacyTopicSchema = !initialTopicColumns.has(\"response_policy\");\n const needsCanonicalTopicRebuild = legacyTopicSchema || !initialTopicColumns.has(\"agent\");\n if (legacyTopicSchema) {\n // Rename the legacy column once; new databases are created with `agent`.\n try {\n db.exec(\"ALTER TABLE api_topics RENAME COLUMN default_agent TO agent\");\n } catch {\n // Already migrated or freshly created.\n }\n\n // Migrate existing DBs that predate the ai_mention column (team-mode topics).\n try {\n db.exec(\"ALTER TABLE api_topics ADD COLUMN ai_mention INTEGER NOT NULL DEFAULT 0\");\n } catch {\n // Column already exists — nothing to do.\n }\n\n // Migrate for spawn/fork tracking (R1).\n try {\n db.exec(\"ALTER TABLE api_topics ADD COLUMN parent_topic_id TEXT\");\n } catch {}\n try {\n db.exec(\"ALTER TABLE api_topics ADD COLUMN is_fork INTEGER NOT NULL DEFAULT 0\");\n } catch {}\n\n // Migrate for agent-spawned subagent worker rooms.\n try {\n db.exec(\"ALTER TABLE api_topics ADD COLUMN is_subagent INTEGER NOT NULL DEFAULT 0\");\n } catch {}\n\n // Migrate for session persistence.\n try {\n db.exec(\"ALTER TABLE api_topics ADD COLUMN session_id TEXT\");\n } catch {}\n\n try {\n db.exec(\"ALTER TABLE api_topics ADD COLUMN kind TEXT NOT NULL DEFAULT 'channel'\");\n } catch {}\n\n try {\n db.exec(\"ALTER TABLE api_topics ADD COLUMN ai_mode TEXT\");\n } catch {}\n\n db.exec(`\n CREATE TABLE IF NOT EXISTS api_schema_migrations (\n key TEXT PRIMARY KEY,\n applied_at TEXT NOT NULL\n )\n`);\n\n const ALWAYS_RESPOND_MIGRATION = \"api_topics_ai_invited_default_always_respond_20260623\";\n const alwaysRespondMigration = db\n .query(\"SELECT key FROM api_schema_migrations WHERE key = ?\")\n .get(ALWAYS_RESPOND_MIGRATION);\n if (!alwaysRespondMigration) {\n db.transaction(() => {\n db.query(\"UPDATE api_topics SET ai_mention = 0 WHERE agent IS NOT NULL\").run();\n db.query(\"INSERT INTO api_schema_migrations (key, applied_at) VALUES (?, ?)\").run(\n ALWAYS_RESPOND_MIGRATION,\n new Date().toISOString(),\n );\n })();\n }\n\n const GENERAL_AGENT_KIND_MIGRATION = \"api_topics_general_agent_kind_20260704\";\n const generalAgentKindMigration = db\n .query(\"SELECT key FROM api_schema_migrations WHERE key = ?\")\n .get(GENERAL_AGENT_KIND_MIGRATION);\n if (!generalAgentKindMigration) {\n db.transaction(() => {\n db.query(\"UPDATE api_topics SET kind = 'agent', ai_mention = 0 WHERE id = ?\").run(\n GENERAL_TOPIC_ID,\n );\n db.query(\"INSERT INTO api_schema_migrations (key, applied_at) VALUES (?, ?)\").run(\n GENERAL_AGENT_KIND_MIGRATION,\n new Date().toISOString(),\n );\n })();\n }\n\n const AI_MODE_MIGRATION = \"api_topics_ai_mode_20260704\";\n const aiModeMigration = db\n .query(\"SELECT key FROM api_schema_migrations WHERE key = ?\")\n .get(AI_MODE_MIGRATION);\n if (!aiModeMigration) {\n db.transaction(() => {\n db.query(\n `UPDATE api_topics\n SET\n kind = CASE\n WHEN id = ? THEN 'agent'\n WHEN kind = 'channel' AND agent IS NOT NULL AND ai_mention = 0 THEN 'agent'\n ELSE kind\n END,\n ai_mode = CASE\n WHEN id = ? THEN 'always'\n WHEN agent IS NULL THEN 'off'\n WHEN kind = 'agent' THEN 'always'\n WHEN kind = 'channel' AND ai_mention != 0 THEN 'mention'\n WHEN kind = 'channel' AND ai_mention = 0 THEN 'always'\n WHEN ai_mention != 0 THEN 'mention'\n ELSE 'always'\n END`,\n ).run(GENERAL_TOPIC_ID, GENERAL_TOPIC_ID);\n db.query(\"INSERT INTO api_schema_migrations (key, applied_at) VALUES (?, ?)\").run(\n AI_MODE_MIGRATION,\n new Date().toISOString(),\n );\n })();\n }\n\n const GENERAL_MANAGER_KIND_MIGRATION = \"api_topics_general_manager_kind_20260704\";\n const generalManagerKindMigration = db\n .query(\"SELECT key FROM api_schema_migrations WHERE key = ?\")\n .get(GENERAL_MANAGER_KIND_MIGRATION);\n if (!generalManagerKindMigration) {\n db.transaction(() => {\n db.query(\n \"UPDATE api_topics SET kind = 'manager', ai_mention = 0, ai_mode = 'always' WHERE id = ?\",\n ).run(GENERAL_TOPIC_ID);\n db.query(\"INSERT INTO api_schema_migrations (key, applied_at) VALUES (?, ?)\").run(\n GENERAL_MANAGER_KIND_MIGRATION,\n new Date().toISOString(),\n );\n })();\n }\n }\n\n function createCanonicalTopicsTable(name: string): void {\n db.exec(`\n CREATE TABLE IF NOT EXISTS ${name} (\n id TEXT PRIMARY KEY,\n title TEXT NOT NULL,\n kind TEXT NOT NULL CHECK (kind IN ('channel','agent','manager')),\n description TEXT,\n agent TEXT CHECK (agent IS NULL OR agent IN ('maestro','claude','codex')),\n base_model TEXT,\n base_effort TEXT CHECK (base_effort IS NULL OR base_effort IN ('low','medium','high','xhigh','max')),\n response_policy TEXT NOT NULL CHECK (response_policy IN ('off','mention','always')),\n created_at TEXT NOT NULL,\n last_message_at TEXT,\n parent_topic_id TEXT,\n memory_topic_id TEXT,\n memory_key TEXT,\n is_fork INTEGER NOT NULL DEFAULT 0 CHECK (is_fork IN (0,1)),\n is_subagent INTEGER NOT NULL DEFAULT 0 CHECK (is_subagent IN (0,1)),\n visibility TEXT NOT NULL DEFAULT 'visible' CHECK (visibility IN ('visible','hidden')),\n surface TEXT NOT NULL DEFAULT 'terminal' CHECK (surface IN ('terminal','telegram','otium')),\n surface_scope TEXT,\n browser_profile TEXT NOT NULL DEFAULT 'default',\n browser_profile_owner TEXT,\n browser_connect_port INTEGER,\n session_id TEXT,\n CHECK (\n (kind = 'channel' AND response_policy = 'off' AND agent IS NULL) OR\n (kind = 'channel' AND response_policy = 'mention' AND agent IS NOT NULL) OR\n (kind IN ('agent','manager') AND response_policy = 'always' AND agent IS NOT NULL)\n )\n )\n `);\n }\n\n function createTopicMembersTable(): void {\n db.exec(`\n CREATE TABLE IF NOT EXISTS topic_members (\n topic_id TEXT NOT NULL REFERENCES api_topics(id) ON DELETE CASCADE,\n user_id TEXT NOT NULL,\n role TEXT NOT NULL CHECK (role IN ('owner','member')),\n PRIMARY KEY (topic_id, user_id)\n )\n `);\n db.exec(\"CREATE INDEX IF NOT EXISTS idx_topic_members_user ON topic_members(user_id)\");\n }\n\n if (needsCanonicalTopicRebuild) {\n const legacyRows = db.query(\"SELECT * FROM api_topics\").all() as Array<Record<string, unknown>>;\n const existingMemberRows = tableColumns(\"topic_members\").has(\"topic_id\")\n ? (db.query(\"SELECT topic_id, user_id, role FROM topic_members\").all() as Array<{\n topic_id: string;\n user_id: string;\n role: string;\n }>)\n : [];\n const configColumns = tableColumns(\"api_topic_config\");\n const legacyAgentOverrides = configColumns.has(\"agent\")\n ? new Map(\n (\n db\n .query(\"SELECT topic_id, agent FROM api_topic_config WHERE agent IS NOT NULL\")\n .all() as Array<{ topic_id: string; agent: AgentKind }>\n ).map((row) => [row.topic_id, row.agent]),\n )\n : new Map<string, AgentKind>();\n const previousForeignKeys = db\n .query<{ foreign_keys: number }, []>(\"PRAGMA foreign_keys\")\n .get()?.foreign_keys;\n db.exec(\"PRAGMA foreign_keys = OFF\");\n try {\n db.transaction(() => {\n createCanonicalTopicsTable(\"api_topics_next\");\n for (const row of legacyRows) {\n const selectedAgent = (legacyAgentOverrides.get(String(row.id)) ??\n row.agent ??\n row.runtime_agent ??\n row.default_agent ??\n undefined) as AgentKind | undefined;\n const normalized = normalizeTopicState({\n id: String(row.id),\n kind: normalizeTopicKind(row.kind),\n agent: selectedAgent,\n aiMode: normalizeAiMode(row.response_policy ?? row.ai_mode),\n aiMention: Number(row.ai_mention ?? 0) !== 0,\n });\n const legacyBaseModel = row.base_model ?? row.default_model;\n const legacyBaseEffort = row.base_effort ?? row.default_effort;\n db.query(\n `INSERT INTO api_topics_next\n (id,title,kind,description,agent,base_model,base_effort,response_policy,\n created_at,last_message_at,parent_topic_id,memory_topic_id,memory_key,is_fork,is_subagent,visibility,surface,surface_scope,session_id)\n VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,\n ).run(\n String(row.id),\n String(row.title),\n normalized.kind,\n typeof row.description === \"string\" ? row.description : null,\n normalized.agent ?? null,\n typeof legacyBaseModel === \"string\" ? legacyBaseModel : null,\n typeof legacyBaseEffort === \"string\" ? legacyBaseEffort : null,\n normalized.aiMode,\n String(row.created_at),\n typeof row.last_message_at === \"string\" ? row.last_message_at : null,\n typeof row.parent_topic_id === \"string\" ? row.parent_topic_id : null,\n typeof row.memory_topic_id === \"string\" ? row.memory_topic_id : null,\n typeof row.memory_key === \"string\" ? row.memory_key : null,\n Number(row.is_fork ?? 0) !== 0 ? 1 : 0,\n Number(row.is_subagent ?? 0) !== 0 ? 1 : 0,\n row.visibility === \"hidden\" ? \"hidden\" : \"visible\",\n row.surface === undefined ? defaultTopicSurface() : normalizeTopicSurface(row.surface),\n normalizeSurfaceScope(row.surface_scope),\n typeof row.session_id === \"string\" ? row.session_id : null,\n );\n }\n db.exec(\"DROP TABLE IF EXISTS topic_members\");\n db.exec(\"DROP TABLE api_topics\");\n db.exec(\"ALTER TABLE api_topics_next RENAME TO api_topics\");\n createTopicMembersTable();\n if (existingMemberRows.length > 0) {\n for (const member of existingMemberRows) {\n db.query(\n \"INSERT OR REPLACE INTO topic_members (topic_id,user_id,role) VALUES (?,?,?)\",\n ).run(member.topic_id, member.user_id, member.role === \"owner\" ? \"owner\" : \"member\");\n }\n } else {\n for (const row of legacyRows) {\n let participants: ParticipantDto[] = [];\n try {\n const parsed = JSON.parse(String(row.participants ?? \"[]\"));\n if (Array.isArray(parsed)) participants = parsed as ParticipantDto[];\n } catch {\n participants = [];\n }\n for (const participant of participants) {\n if (!participant?.userId) continue;\n db.query(\n \"INSERT OR REPLACE INTO topic_members (topic_id,user_id,role) VALUES (?,?,?)\",\n ).run(\n String(row.id),\n participant.userId,\n participant.role === \"owner\" ? \"owner\" : \"member\",\n );\n }\n }\n }\n })();\n } finally {\n db.exec(`PRAGMA foreign_keys = ${previousForeignKeys ? \"ON\" : \"OFF\"}`);\n }\n } else {\n createCanonicalTopicsTable(\"api_topics\");\n createTopicMembersTable();\n }\n\n db.exec(`\n CREATE TABLE IF NOT EXISTS subagent_tell_grants (\n subagent_topic_id TEXT NOT NULL REFERENCES api_topics(id) ON DELETE CASCADE,\n target_topic_id TEXT NOT NULL REFERENCES api_topics(id) ON DELETE CASCADE,\n granted_by_topic_id TEXT NOT NULL REFERENCES api_topics(id) ON DELETE CASCADE,\n created_at TEXT NOT NULL,\n PRIMARY KEY (subagent_topic_id, target_topic_id)\n )\n `);\n db.exec(`\n DELETE FROM subagent_tell_grants\n WHERE subagent_topic_id NOT IN (SELECT id FROM api_topics)\n OR target_topic_id NOT IN (SELECT id FROM api_topics)\n OR granted_by_topic_id NOT IN (SELECT id FROM api_topics)\n `);\n db.exec(\"DELETE FROM topic_members WHERE topic_id NOT IN (SELECT id FROM api_topics)\");\n\n // Canonical databases created before explicit adapter visibility need a\n // lightweight additive migration; fresh/rebuilt databases already have it.\n if (!tableColumns(\"api_topics\").has(\"visibility\")) {\n db.exec(\"ALTER TABLE api_topics ADD COLUMN visibility TEXT NOT NULL DEFAULT 'visible'\");\n }\n if (!tableColumns(\"api_topics\").has(\"surface\")) {\n db.exec(\"ALTER TABLE api_topics ADD COLUMN surface TEXT NOT NULL DEFAULT 'terminal'\");\n }\n if (!tableColumns(\"api_topics\").has(\"surface_scope\")) {\n db.exec(\"ALTER TABLE api_topics ADD COLUMN surface_scope TEXT\");\n }\n // `access_mode` was replaced by `surface`: a topic is reachable from Otium\n // because it lives there, not because a flag was flipped (S-4). Dropping the\n // column removes the second, now-contradictory source of truth.\n if (tableColumns(\"api_topics\").has(\"access_mode\")) {\n try {\n db.exec(\"ALTER TABLE api_topics DROP COLUMN access_mode\");\n } catch (err) {\n logger.warn({ err }, \"api_topics: could not drop the retired access_mode column\");\n }\n }\n if (!tableColumns(\"api_topics\").has(\"browser_profile\")) {\n db.exec(\"ALTER TABLE api_topics ADD COLUMN browser_profile TEXT NOT NULL DEFAULT 'default'\");\n }\n if (!tableColumns(\"api_topics\").has(\"browser_profile_owner\")) {\n db.exec(\"ALTER TABLE api_topics ADD COLUMN browser_profile_owner TEXT\");\n }\n if (!tableColumns(\"api_topics\").has(\"browser_connect_port\")) {\n db.exec(\"ALTER TABLE api_topics ADD COLUMN browser_connect_port INTEGER\");\n }\n if (!tableColumns(\"api_topics\").has(\"subagent_report_mode\")) {\n db.exec(\"ALTER TABLE api_topics ADD COLUMN subagent_report_mode TEXT NOT NULL DEFAULT 'auto'\");\n }\n if (!tableColumns(\"api_topics\").has(\"derived_by_user_id\")) {\n db.exec(\"ALTER TABLE api_topics ADD COLUMN derived_by_user_id TEXT\");\n }\n if (!tableColumns(\"api_topics\").has(\"memory_topic_id\")) {\n db.exec(\"ALTER TABLE api_topics ADD COLUMN memory_topic_id TEXT\");\n }\n if (!tableColumns(\"api_topics\").has(\"memory_key\")) {\n db.exec(\"ALTER TABLE api_topics ADD COLUMN memory_key TEXT\");\n }\n db.exec(`\n UPDATE api_topics\n SET browser_profile_owner = (\n SELECT m.user_id FROM topic_members m\n WHERE m.topic_id = api_topics.id AND m.role = 'owner'\n ORDER BY m.rowid\n LIMIT 1\n )\n WHERE browser_profile_owner IS NULL\n`);\n backfillTopicSurfaces();\n ensureSurfaceScopeStampTables();\n db.exec(\n \"CREATE INDEX IF NOT EXISTS idx_api_topics_last_message ON api_topics(last_message_at DESC)\",\n );\n db.exec(\"CREATE INDEX IF NOT EXISTS idx_api_topics_surface ON api_topics(surface)\");\n db.exec(\n \"CREATE INDEX IF NOT EXISTS idx_api_topics_surface_scope ON api_topics(surface, surface_scope)\",\n );\n}\n\nconst SURFACE_SCOPE_STAMP_MIGRATION = \"api_topics_surface_scope_stamp_20260809\";\n\n/**\n * Minimum spacing between two unforced retries of an incomplete M-9 stamp.\n * The retry is driven by timers / scope refreshes, never by request traffic,\n * and this bound keeps even a tight caller from turning it into a hot path.\n */\nexport const SURFACE_SCOPE_STAMP_RETRY_INTERVAL_MS = 30_000;\n\n/**\n * Refusals that leave a room pending: the room is still an unscoped otium room\n * and the stamp may succeed later (maintenance ends, an operator renames the\n * conflicting room or resolves a duplicate manager room, the row settles).\n * Every other refusal (`not_found`, `not_otium`, `scope_not_null`) means there\n * is nothing left to stamp.\n */\nconst SURFACE_SCOPE_STAMP_RETRYABLE = new Set([\n \"maintenance_in_progress\",\n \"title_conflict\",\n \"duplicate_manager\",\n \"row_changed\",\n \"invalid_scope\",\n]);\n\nfunction ensureSurfaceScopeStampTables(): void {\n db.exec(`\n CREATE TABLE IF NOT EXISTS api_schema_migrations (\n key TEXT PRIMARY KEY,\n applied_at TEXT NOT NULL\n )\n`);\n // Rooms the M-9 stamp could not file yet (revision 5). `scope` is pinned at\n // the first attempt: a retry never re-reads the current workspace, so a\n // second workspace joined later cannot swallow the first one's rooms.\n db.exec(`\n CREATE TABLE IF NOT EXISTS api_surface_scope_stamp_pending (\n topic_id TEXT PRIMARY KEY,\n scope TEXT NOT NULL,\n reason TEXT NOT NULL,\n detail TEXT,\n attempts INTEGER NOT NULL DEFAULT 1,\n first_seen_at TEXT NOT NULL,\n last_attempt_at TEXT NOT NULL\n )\n`);\n}\n\nexport interface SurfaceScopeStampStatus {\n /** The completion marker is written: every pre-existing room was filed. */\n complete: boolean;\n /** Rooms the stamp skipped and will retry (maintenance, title conflict ...). */\n pending: number;\n /** Workspace the pending rooms will be filed under (pinned at first attempt). */\n scope: string | null;\n pendingTopics: Array<{\n topicId: string;\n reason: string;\n detail: string | null;\n attempts: number;\n }>;\n}\n\n/**\n * Operator view of the M-9 stamp (diagnostics; `unscopedPending` on\n * `GET /surface-scope`). Read-only: the tables exist from schema init.\n */\nexport function surfaceScopeStampStatus(): SurfaceScopeStampStatus {\n const complete = Boolean(\n db\n .query(\"SELECT key FROM api_schema_migrations WHERE key = ?\")\n .get(SURFACE_SCOPE_STAMP_MIGRATION),\n );\n const rows = db\n .query<\n { topic_id: string; scope: string; reason: string; detail: string | null; attempts: number },\n []\n >(\n \"SELECT topic_id, scope, reason, detail, attempts FROM api_surface_scope_stamp_pending ORDER BY topic_id\",\n )\n .all();\n return {\n complete,\n pending: rows.length,\n scope: rows[0]?.scope ?? null,\n pendingTopics: rows.map((row) => ({\n topicId: row.topic_id,\n reason: row.reason,\n detail: row.detail,\n attempts: Number(row.attempts),\n })),\n };\n}\n\n/**\n * M-9 — file every pre-existing Otium room under the workspace attached now.\n *\n * Deliberately *not* a schema-init step. The scope is only knowable after the\n * first successful Central contact (M-3), which happens long after the store\n * opens; a boot-time migration would see no scope, record itself as applied and\n * leave every room unstamped forever. The Otium runtime calls this instead, once,\n * as soon as it has resolved its workspace.\n *\n * Completes at most once per store: rooms created after this point are stamped\n * at creation, and a second workspace joined later must not swallow the first\n * one's rooms. Unlike the surface migration this can never rename anything —\n * the scope enters the uniqueness key in the same release, so nothing can start\n * colliding because of it.\n *\n * Revision 5: the completion marker is written only when NO room was skipped.\n * A room refused for a retryable reason (live maintenance, title conflict) is\n * recorded in `api_surface_scope_stamp_pending` with the first attempt's scope,\n * and later calls retry exactly those rooms under that pinned scope — never a\n * fresh sweep, never the caller's (possibly different) scope. Rooms already\n * stamped are no longer unscoped and drop out, so every pass is idempotent. The\n * whole pass is one `BEGIN IMMEDIATE`, so concurrent boots serialize: the\n * second sees the first one's marker or pending set and re-checks it.\n */\nexport function stampUnscopedOtiumTopics(scope: string): number {\n const normalized = normalizeSurfaceScope(scope);\n if (!normalized) return 0;\n ensureSurfaceScopeStampTables();\n // Cheap unlocked pre-check: a completed store never takes the write lock.\n if (\n db\n .query(\"SELECT key FROM api_schema_migrations WHERE key = ?\")\n .get(SURFACE_SCOPE_STAMP_MIGRATION)\n ) {\n return 0;\n }\n\n let stamped = 0;\n const stillPending: Array<{ topicId: string; reason: string; detail?: string }> = [];\n let effectiveScope = normalized;\n let ran = false;\n db.transaction(() => {\n // Re-check under the write lock: a concurrent boot may have finished.\n if (\n db\n .query(\"SELECT key FROM api_schema_migrations WHERE key = ?\")\n .get(SURFACE_SCOPE_STAMP_MIGRATION)\n ) {\n return;\n }\n ran = true;\n const pendingRows = db\n .query<{ topic_id: string; scope: string }, []>(\n \"SELECT topic_id, scope FROM api_surface_scope_stamp_pending ORDER BY topic_id\",\n )\n .all();\n const retry = pendingRows.length > 0;\n if (retry) effectiveScope = pendingRows[0]?.scope ?? normalized;\n // Through the audited scope repair: an otium room's scope is otherwise\n // immutable (topic-link review fix 6); the move is recorded and create\n // claims stay on their original principal.\n const result = repairUnscopedOtiumTopicScopes(\n effectiveScope,\n \"m9-stamp\",\n \"file pre-existing Otium rooms under the resolved workspace\",\n retry ? { topicIds: pendingRows.map((row) => row.topic_id) } : {},\n );\n stamped = result.stamped;\n for (const skip of result.skipped) {\n if (skip.ok || !SURFACE_SCOPE_STAMP_RETRYABLE.has(skip.reason)) continue;\n stillPending.push({ topicId: skip.topicId, reason: skip.reason, detail: skip.detail });\n }\n const now = new Date().toISOString();\n const keep = new Set(stillPending.map((row) => row.topicId));\n for (const row of pendingRows) {\n if (!keep.has(row.topic_id)) {\n db.query(\"DELETE FROM api_surface_scope_stamp_pending WHERE topic_id = ?\").run(\n row.topic_id,\n );\n }\n }\n for (const row of stillPending) {\n db.query(\n `INSERT INTO api_surface_scope_stamp_pending\n (topic_id, scope, reason, detail, attempts, first_seen_at, last_attempt_at)\n VALUES (?, ?, ?, ?, 1, ?, ?)\n ON CONFLICT(topic_id) DO UPDATE SET\n reason = excluded.reason,\n detail = excluded.detail,\n attempts = api_surface_scope_stamp_pending.attempts + 1,\n last_attempt_at = excluded.last_attempt_at`,\n ).run(row.topicId, effectiveScope, row.reason, row.detail ?? null, now, now);\n }\n if (stillPending.length === 0) {\n db.query(\"INSERT INTO api_schema_migrations (key, applied_at) VALUES (?, ?)\").run(\n SURFACE_SCOPE_STAMP_MIGRATION,\n now,\n );\n }\n }).immediate();\n if (!ran) return 0;\n if (effectiveScope !== normalized) {\n logger.info(\n { scope: normalized, pinnedScope: effectiveScope },\n \"api_topics: surface scope stamp retry keeps the workspace of its first attempt\",\n );\n }\n if (stamped > 0) {\n logger.info({ scope: effectiveScope, stamped }, \"api_topics: surface scope stamped\");\n }\n if (stillPending.length > 0) {\n // Operator-visible every attempt: a permanent title conflict never\n // completes the migration and needs a rename (or admin repair).\n logger.warn(\n {\n scope: effectiveScope,\n pending: stillPending.length,\n topicIds: stillPending.map((row) => row.topicId),\n skipped: stillPending,\n },\n \"api_topics: surface scope stamp incomplete; rooms stay pending and will be retried\",\n );\n } else {\n logger.info({ scope: effectiveScope }, \"api_topics: surface scope stamp complete\");\n }\n return stamped;\n}\n\nlet lastSurfaceScopeStampRetryAt = 0;\n\n/**\n * Retry an incomplete M-9 stamp under its pinned scope. No-op (no write lock)\n * when the stamp never started or already completed. Unforced calls run at most\n * once per {@link SURFACE_SCOPE_STAMP_RETRY_INTERVAL_MS} per process; `force`\n * is for discrete events (a pending room's maintenance released, a scope\n * refresh). Never throws: a busy database just waits for the next trigger.\n */\nexport function retryPendingSurfaceScopeStamp(\n options: { force?: boolean; now?: number } = {},\n): number {\n const now = options.now ?? Date.now();\n if (\n !options.force &&\n now - lastSurfaceScopeStampRetryAt < SURFACE_SCOPE_STAMP_RETRY_INTERVAL_MS\n ) {\n return 0;\n }\n lastSurfaceScopeStampRetryAt = now;\n try {\n ensureSurfaceScopeStampTables();\n const pinned = db\n .query<{ scope: string }, []>(\"SELECT scope FROM api_surface_scope_stamp_pending LIMIT 1\")\n .get();\n if (!pinned) return 0;\n return stampUnscopedOtiumTopics(pinned.scope);\n } catch (err) {\n logger.warn({ err }, \"api_topics: surface scope stamp retry failed (will retry)\");\n return 0;\n }\n}\n\n/** Whether `topicId` is waiting for the M-9 stamp (cheap point lookup). */\nexport function isSurfaceScopeStampPending(topicId: string): boolean {\n return Boolean(\n db.query(\"SELECT 1 FROM api_surface_scope_stamp_pending WHERE topic_id = ?\").get(topicId),\n );\n}\n\n// A pending room's maintenance fence was released: retry now instead of\n// waiting for the next timer tick. Deferred so the stamp never runs inside the\n// releasing caller's transaction.\nonRuntimeTopicMaintenanceReleased((topicId) => {\n const timer = setTimeout(() => {\n try {\n if (isSurfaceScopeStampPending(topicId)) retryPendingSurfaceScopeStamp({ force: true });\n } catch (err) {\n logger.warn({ err, topicId }, \"api_topics: surface scope stamp retry on release failed\");\n }\n }, 0);\n timer.unref?.();\n});\n\nconst SURFACE_BACKFILL_MIGRATION = \"api_topics_surface_backfill_20260808\";\n\n/**\n * One-time classification of pre-surface topics.\n *\n * Every row predates the column, so there is no per-row evidence in this store\n * to distinguish surfaces — the host declares it (`NEGOTIUM_DEFAULT_SURFACE`).\n * The telegram adapter owns the second pass: its chat↔topic mapping lives in a\n * different database file, so only it can reclassify the rooms it created.\n *\n * Names are unique per surface from now on, so collapsing three namespaces into\n * one can produce duplicates. Rather than failing the boot, the oldest room\n * keeps the name and the rest are suffixed — a rename is recoverable, a node\n * that refuses to start is not.\n */\nfunction backfillTopicSurfaces(): void {\n db.exec(`\n CREATE TABLE IF NOT EXISTS api_schema_migrations (\n key TEXT PRIMARY KEY,\n applied_at TEXT NOT NULL\n )\n`);\n const applied = db\n .query(\"SELECT key FROM api_schema_migrations WHERE key = ?\")\n .get(SURFACE_BACKFILL_MIGRATION);\n if (applied) return;\n\n const surface = defaultTopicSurface();\n db.transaction(() => {\n db.query(\"UPDATE api_topics SET surface = ?\").run(surface);\n renameSurfaceTitleCollisions();\n db.query(\"INSERT INTO api_schema_migrations (key, applied_at) VALUES (?, ?)\").run(\n SURFACE_BACKFILL_MIGRATION,\n new Date().toISOString(),\n );\n })();\n logger.info({ surface }, \"api_topics: surface backfilled\");\n}\n\n/**\n * Suffix duplicate `(surface, kind, title)` rows so the new uniqueness rule holds.\n *\n * Manager rooms are excluded: they are one per user, so on a multi-user host\n * every member has a personal room with the same title and none of them is a\n * duplicate. Renaming those relabels real rooms belonging to other people.\n */\nfunction renameSurfaceTitleCollisions(): void {\n const rows = db\n .query<{ id: string; title: string; kind: string; surface: string }, []>(\n \"SELECT id, title, kind, surface FROM api_topics WHERE kind != 'manager' ORDER BY created_at ASC, rowid ASC\",\n )\n .all();\n const keyOf = (surface: string, kind: string, title: string) =>\n [surface, kind, normalizedTitle(title)].join(\"\\u0000\");\n // Every original title is reserved up front. Allocating only against the\n // titles seen so far would let an earlier duplicate claim \"Foo (2)\" while a\n // real room already named \"Foo (2)\" sits later in the scan — that room would\n // then be pushed to \"Foo (2) (2)\" for no reason.\n const reserved = new Set(rows.map((row) => keyOf(row.surface, row.kind, row.title)));\n const used = new Set<string>();\n const update = db.query(\"UPDATE api_topics SET title = ? WHERE id = ?\");\n for (const row of rows) {\n const key = (title: string) => keyOf(row.surface, row.kind, title);\n if (!used.has(key(row.title))) {\n used.add(key(row.title));\n continue;\n }\n let suffix = 2;\n let candidate = `${row.title} (${suffix})`;\n while (reserved.has(key(candidate)) || used.has(key(candidate))) {\n suffix += 1;\n candidate = `${row.title} (${suffix})`;\n }\n used.add(key(candidate));\n update.run(candidate, row.id);\n logger.warn(\n { topicId: row.id, surface: row.surface, from: row.title, to: candidate },\n \"api_topics: renamed a duplicate title for surface-scoped uniqueness\",\n );\n }\n}\n\nregisterStorageSchemaInitializer(initializeApiTopicsSchema, 20);\n\nexport interface TopicRow {\n id: string;\n title: string;\n kind: string | null;\n description: string | null;\n agent: string | null;\n base_model: string | null;\n base_effort: string | null;\n response_policy: string;\n created_at: string;\n last_message_at: string | null;\n parent_topic_id: string | null;\n memory_topic_id: string | null;\n memory_key: string | null;\n is_fork: number;\n is_subagent: number;\n subagent_report_mode: string | null;\n derived_by_user_id: string | null;\n visibility: string | null;\n surface: string | null;\n surface_scope: string | null;\n browser_profile_owner: string | null;\n browser_connect_port: number | null;\n session_id: string | null;\n}\n\nexport interface TopicSessionLogContext {\n reason?: string;\n queryId?: string;\n agent?: AgentKind;\n}\n\nfunction shortSessionId(sessionId: string | null | undefined): string | null {\n return sessionId ? sessionId.slice(0, 8) : null;\n}\n\nfunction getTopicParticipants(topicId: string): ParticipantDto[] {\n return db\n .query<{ user_id: string; role: \"owner\" | \"member\" }, string>(\n \"SELECT user_id, role FROM topic_members WHERE topic_id = ? ORDER BY rowid\",\n )\n .all(topicId)\n .map((row) => ({ userId: row.user_id, role: row.role }));\n}\n\nfunction getAllTopicParticipants(): Map<string, ParticipantDto[]> {\n const grouped = new Map<string, ParticipantDto[]>();\n const rows = db\n .query<{ topic_id: string; user_id: string; role: \"owner\" | \"member\" }, []>(\n \"SELECT topic_id, user_id, role FROM topic_members ORDER BY rowid\",\n )\n .all();\n for (const row of rows) {\n const participants = grouped.get(row.topic_id) ?? [];\n participants.push({ userId: row.user_id, role: row.role });\n grouped.set(row.topic_id, participants);\n }\n return grouped;\n}\n\nfunction getAllSubagentTellTargets(): Map<string, string[]> {\n const rows = db\n .query(\n \"SELECT subagent_topic_id, target_topic_id FROM subagent_tell_grants ORDER BY created_at\",\n )\n .all() as Array<{ subagent_topic_id: string; target_topic_id: string }>;\n const grouped = new Map<string, string[]>();\n for (const row of rows) {\n const targets = grouped.get(row.subagent_topic_id) ?? [];\n targets.push(row.target_topic_id);\n grouped.set(row.subagent_topic_id, targets);\n }\n return grouped;\n}\n\nfunction rowToDto(\n r: TopicRow,\n participants = getTopicParticipants(r.id),\n tellTargets?: Map<string, string[]>,\n): TopicDto {\n const normalized = normalizeTopicState({\n id: r.id,\n kind: normalizeTopicKind(r.kind),\n agent: (r.agent as AgentKind | null) ?? undefined,\n aiMode: normalizeAiMode(r.response_policy),\n });\n return {\n id: r.id,\n title: r.title,\n kind: normalized.kind,\n description: r.description ?? undefined,\n agent: normalized.agent,\n defaultModel: r.base_model ?? \"deepseek-pro\",\n defaultEffort: (r.base_effort as EffortLevel) ?? undefined,\n aiMode: normalized.aiMode,\n aiMention: aiMentionFromMode(normalized.aiMode),\n participants,\n createdAt: r.created_at,\n lastMessageAt: r.last_message_at ?? new Date().toISOString(),\n parentTopicId: r.parent_topic_id ?? undefined,\n memoryTopicId: r.memory_topic_id ?? undefined,\n memoryKey: r.memory_key ?? undefined,\n isFork: r.is_fork !== 0,\n ...(r.derived_by_user_id ? { derivedByUserId: r.derived_by_user_id } : {}),\n ...(r.is_subagent !== 0 ? { isSubagent: true } : {}),\n ...(r.is_subagent !== 0\n ? {\n subagentTellTargetIds: tellTargets\n ? (tellTargets.get(r.id) ?? [])\n : listSubagentTellTargetIds(r.id),\n }\n : {}),\n ...(r.is_subagent !== 0\n ? {\n subagentReportMode: (r.subagent_report_mode === \"tell\" ||\n r.subagent_report_mode === \"status-only\"\n ? r.subagent_report_mode\n : \"auto\") as SubagentReportMode,\n }\n : {}),\n visibility: normalizeTopicVisibility(r.visibility),\n surface: normalizeTopicSurface(r.surface),\n surfaceScope: normalizeSurfaceScope(r.surface_scope),\n ...(r.browser_connect_port != null ? { browserConnectPort: r.browser_connect_port } : {}),\n };\n}\n\nexport function normalizeTopicVisibility(value: unknown): TopicVisibility {\n return value === \"hidden\" ? \"hidden\" : \"visible\";\n}\n\n/** Discovery boundary shared by user-facing adapters. */\nexport function isTopicVisible(topic: Pick<TopicDto, \"visibility\">): boolean {\n return topic.visibility !== \"hidden\";\n}\n\nexport function normalizeTopicKind(value: unknown): TopicKind | null {\n return value === \"channel\" || value === \"agent\" || value === \"manager\" ? value : null;\n}\n\nexport function normalizeAiMode(value: unknown): AiMode | null {\n return value === \"off\" || value === \"mention\" || value === \"always\" ? value : null;\n}\n\nexport function aiMentionFromMode(mode: AiMode): boolean {\n return mode === \"mention\";\n}\n\nexport function inferTopicKind(input: {\n agent?: string | null;\n aiMention?: boolean | null;\n}): TopicKind {\n return input.agent && input.aiMention !== true ? \"agent\" : \"channel\";\n}\n\nexport function inferAiMode(input: {\n kind?: TopicKind | null;\n agent?: string | null;\n aiMode?: AiMode | null;\n aiMention?: boolean | null;\n}): AiMode {\n if (input.kind === \"manager\") return \"always\";\n if (input.kind === \"agent\") return \"always\";\n if (input.kind === \"channel\") {\n if (!input.agent) return \"off\";\n if (input.aiMode === \"mention\") return \"mention\";\n if (input.aiMention === true) return \"mention\";\n return \"mention\";\n }\n if (!input.agent) return \"off\";\n if (input.aiMode) return input.aiMode;\n return input.aiMention === true ? \"mention\" : \"always\";\n}\n\nexport function normalizeTopicState(input: {\n id?: string;\n kind?: TopicKind | null;\n agent?: AgentKind | null;\n aiMode?: AiMode | null;\n aiMention?: boolean | null;\n}): { kind: TopicKind; aiMode: AiMode; agent?: AgentKind } {\n if (input.kind === \"manager\" || input.id === GENERAL_TOPIC_ID) {\n return {\n kind: \"manager\",\n aiMode: \"always\",\n agent: input.agent ?? resolveFallbackAgent(),\n };\n }\n\n const requestedKind = input.kind;\n const kind =\n requestedKind ??\n (input.aiMode === \"always\"\n ? \"agent\"\n : input.aiMode === \"mention\" || input.aiMode === \"off\"\n ? \"channel\"\n : input.agent && input.aiMention !== true\n ? \"agent\"\n : \"channel\");\n\n if (kind === \"agent\") {\n return {\n kind: \"agent\",\n aiMode: \"always\",\n agent: input.agent ?? resolveFallbackAgent(),\n };\n }\n\n const agent = input.aiMode === \"off\" ? undefined : (input.agent ?? undefined);\n return {\n kind: \"channel\",\n aiMode: agent ? \"mention\" : \"off\",\n agent,\n };\n}\n\nfunction normalizedTitle(title: string): string {\n return title.trim().toLowerCase();\n}\n\n/**\n * The workspace a written row belongs to.\n *\n * `surfaceScope` partitions one surface into independent namespaces. Otium\n * uses a workspace scope and Telegram uses a forum-group scope. Terminal is\n * normally unscoped. An explicit value always wins; only Otium has a\n * process-level default because its workspace attachment is host state.\n */\nfunction surfaceScopeForWrite(t: TopicDto): string | null {\n if (t.surfaceScope !== undefined) return normalizeSurfaceScope(t.surfaceScope);\n return normalizeTopicSurface(t.surface ?? defaultTopicSurface()) === \"otium\"\n ? defaultSurfaceScope()\n : null;\n}\n\nexport function upsertTopic(t: TopicDto): void {\n const normalized = normalizeTopicState({\n id: t.id,\n kind: normalizeTopicKind(t.kind),\n agent: t.agent ?? undefined,\n aiMode: normalizeAiMode(t.aiMode),\n aiMention: t.aiMention,\n });\n db.transaction(() => {\n db.query(\n `INSERT INTO api_topics\n (id,title,kind,description,agent,base_model,base_effort,response_policy,\n created_at,last_message_at,parent_topic_id,memory_topic_id,memory_key,is_fork,is_subagent,visibility,surface,\n surface_scope,subagent_report_mode,derived_by_user_id)\n VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)\n ON CONFLICT(id) DO UPDATE SET\n title = excluded.title,\n kind = excluded.kind,\n description = excluded.description,\n agent = excluded.agent,\n base_model = excluded.base_model,\n base_effort = excluded.base_effort,\n response_policy = excluded.response_policy,\n created_at = excluded.created_at,\n last_message_at = excluded.last_message_at,\n parent_topic_id = excluded.parent_topic_id,\n memory_topic_id = excluded.memory_topic_id,\n memory_key = excluded.memory_key,\n is_fork = excluded.is_fork,\n is_subagent = excluded.is_subagent,\n visibility = excluded.visibility,\n surface = excluded.surface,\n -- A room's workspace is fixed at creation (M-1). COALESCE, not\n -- assignment: an update may fill in a scope that was unknown when the\n -- room was created, but may never move a room to another workspace.\n -- An otium room is stricter (topic-link review fix 6): its scope never\n -- changes through an upsert, not even NULL -> scope; only the audited\n -- repair (adminRepairOtiumTopicScope / the M-9 stamp) may assign it.\n surface_scope = CASE\n WHEN excluded.surface = 'otium' OR api_topics.surface = 'otium'\n THEN api_topics.surface_scope\n ELSE COALESCE(api_topics.surface_scope, excluded.surface_scope)\n END,\n subagent_report_mode = excluded.subagent_report_mode,\n -- Who asked for the derive is a fact about creation; a later update\n -- that omits it must not erase it.\n derived_by_user_id = COALESCE(excluded.derived_by_user_id, api_topics.derived_by_user_id)`,\n ).run(\n t.id,\n t.title,\n normalized.kind,\n t.description ?? null,\n normalized.agent ?? null,\n t.defaultModel ?? null,\n t.defaultEffort ?? null,\n normalized.aiMode,\n t.createdAt,\n t.lastMessageAt ?? null,\n t.parentTopicId ?? null,\n t.memoryTopicId ?? null,\n t.memoryKey ?? null,\n t.isFork ? 1 : 0,\n t.isSubagent ? 1 : 0,\n normalizeTopicVisibility(t.visibility),\n // A DTO without a surface means \"wherever this host puts rooms\", not\n // \"terminal\": embedding hosts (Otium) build topic literals by hand and\n // never name one, so defaulting to the literal would file every hub room\n // on the wrong surface.\n normalizeTopicSurface(t.surface ?? defaultTopicSurface()),\n surfaceScopeForWrite(t),\n t.subagentReportMode ?? \"auto\",\n t.derivedByUserId ?? null,\n );\n db.query(\"DELETE FROM topic_members WHERE topic_id = ?\").run(t.id);\n for (const participant of t.participants) {\n db.query(\"INSERT INTO topic_members (topic_id,user_id,role) VALUES (?,?,?)\").run(\n t.id,\n participant.userId,\n participant.role,\n );\n }\n const initialBrowserProfileOwner = t.participants.find(\n (participant) => participant.role === \"owner\",\n )?.userId;\n if (initialBrowserProfileOwner) {\n db.query(\n `UPDATE api_topics\n SET browser_profile_owner = COALESCE(browser_profile_owner, ?)\n WHERE id = ?`,\n ).run(initialBrowserProfileOwner, t.id);\n }\n })();\n}\n\n/**\n * List topics, optionally restricted to one surface.\n *\n * The filter lives here rather than in each adapter so a forgotten call site\n * cannot leak a telegram room into the terminal picker; adapters pass their own\n * surface and get a closed world back.\n */\nexport function listTopics(\n opts: { surface?: TopicSurface; surfaceScope?: string | null } = {},\n): TopicDto[] {\n // `surfaceScope: null` is a real filter (\"the unscoped rooms\"), so presence —\n // not truthiness — decides whether the scope narrows the query at all.\n const scoped = Object.hasOwn(opts, \"surfaceScope\");\n const rows = (\n opts.surface\n ? db\n .query(\n `SELECT * FROM api_topics WHERE surface = ?${scoped ? \" AND surface_scope IS ?\" : \"\"} ORDER BY last_message_at DESC`,\n )\n .all(\n ...(scoped\n ? [normalizeTopicSurface(opts.surface), normalizeSurfaceScope(opts.surfaceScope)]\n : [normalizeTopicSurface(opts.surface)]),\n )\n : db.query(\"SELECT * FROM api_topics ORDER BY last_message_at DESC\").all()\n ) as TopicRow[];\n const participants = getAllTopicParticipants();\n // Batch-load tell grants once: per-row queries would make every listTopics()\n // call O(N) extra statements as subagent counts grow.\n const tellTargets = rows.some((row) => row.is_subagent !== 0)\n ? getAllSubagentTellTargets()\n : undefined;\n return rows.map((row) => rowToDto(row, participants.get(row.id) ?? [], tellTargets));\n}\n\nexport function getTopic(id: string): TopicDto | null {\n const r = db.query(\"SELECT * FROM api_topics WHERE id = ?\").get(id) as TopicRow | undefined;\n return r ? rowToDto(r) : null;\n}\n\n/** Return the private manager room owned by a user, excluding the retired shared General row. */\n/**\n * The user's own manager room, optionally on one surface.\n *\n * A manager room is one per user **per surface**: Terminal and Telegram each\n * give the same person their own personal room, and returning one surface's\n * room to the other adapter lets that adapter bind to — and reclassify — a room\n * belonging to a different surface. Callers that represent an adapter pass\n * theirs; unscoped lookups stay for maintenance paths that work by user alone.\n */\nexport function getManagerTopicForUser(\n userId: string,\n surface?: TopicSurface,\n opts: { surfaceScope?: string | null } = {},\n): TopicDto | null {\n const scoped = Object.hasOwn(opts, \"surfaceScope\");\n const sql = `SELECT t.* FROM api_topics t\n JOIN topic_members m ON m.topic_id = t.id\n WHERE t.kind = 'manager'\n AND t.id != ?\n AND m.user_id = ?\n AND m.role = 'owner'\n ${surface ? \"AND t.surface = ?\" : \"\"}\n ${scoped ? \"AND t.surface_scope IS ?\" : \"\"}\n ORDER BY t.created_at ASC\n LIMIT 1`;\n const params: Array<string | null> = [GENERAL_TOPIC_ID, userId];\n if (surface) params.push(surface);\n if (scoped) params.push(normalizeSurfaceScope(opts.surfaceScope));\n const row = db.query<TopicRow, Array<string | null>>(sql).get(...params);\n return row ? rowToDto(row) : null;\n}\n\n/**\n * Resolve the topic whose wiki memory should be used for this topic.\n *\n * Derived rooms keep `parentTopicId` as an immediate UI link. Memory normally\n * follows the chain to its original root, while `memoryTopicId` can redirect a\n * subagent to another accessible topic's accumulated knowledge.\n */\nexport function getTopicMemoryOrigin(id: string): TopicDto | null {\n let current = getTopic(id);\n if (!current) return null;\n\n const seen = new Set<string>([current.id]);\n while (true) {\n const nextId = current.memoryTopicId ?? current.parentTopicId;\n if (!nextId || seen.has(nextId)) break;\n const next = getTopic(nextId);\n if (!next) {\n // An explicitly selected memory topic that no longer resolves must not\n // silently fall back to the parent chain — that would leak the parent\n // room's memory to a subagent that asked for something else. Stop at the\n // current topic instead so the broken source is visible.\n if (current.memoryTopicId) {\n console.warn(\n `[topics] memory topic ${current.memoryTopicId} for ${current.id} is unresolvable; using the topic's own memory`,\n );\n }\n break;\n }\n current = next;\n seen.add(current.id);\n }\n\n return current;\n}\n\n/** Look up a topic by its user-visible title (case-insensitive exact match). */\nexport function getTopicByName(title: string): TopicDto | null {\n const r = db.query(\"SELECT * FROM api_topics WHERE LOWER(title) = LOWER(?)\").get(title) as\n | TopicRow\n | undefined;\n return r ? rowToDto(r) : null;\n}\n\nexport function getTopicByNameAndKind(title: string, kind: TopicKind): TopicDto | null {\n const r = db\n .query(\"SELECT * FROM api_topics WHERE LOWER(title) = LOWER(?) AND kind = ?\")\n .get(title, kind) as TopicRow | undefined;\n return r ? rowToDto(r) : null;\n}\n\n/**\n * Titles are unique **per surface namespace**, not per node: the same title may\n * exist on terminal, in multiple Telegram groups, and in each attached Otium\n * workspace. Independent namespaces never see each other, so a name taken in\n * one says nothing about another.\n */\nexport function findTopicTitleConflict(\n title: string,\n kind: TopicKind,\n opts: { excludeTopicId?: string; surface?: TopicSurface; surfaceScope?: string | null } = {},\n): TopicDto | null {\n const wanted = normalizedTitle(title);\n const surface = normalizeTopicSurface(opts.surface ?? defaultTopicSurface());\n const surfaceScope = Object.hasOwn(opts, \"surfaceScope\")\n ? normalizeSurfaceScope(opts.surfaceScope)\n : surface === \"otium\"\n ? defaultSurfaceScope()\n : null;\n const generalTitleRequested = wanted === normalizedTitle(GENERAL_TOPIC_ID);\n if (generalTitleRequested && opts.excludeTopicId !== GENERAL_TOPIC_ID) {\n const general = db.query(\"SELECT * FROM api_topics WHERE id = ?\").get(GENERAL_TOPIC_ID) as\n | TopicRow\n | undefined;\n if (general) return rowToDto(general);\n }\n\n // Manager rooms are one-per-user and system-created, so several of them\n // legitimately share a title (every member's personal \"General\"). Comparing\n // them against each other is not a conflict, it is the design — on a\n // multi-user host it renamed real rooms out from under their owners.\n if (kind === \"manager\") return null;\n\n const params: Array<string | null> = [wanted, surface, surfaceScope, kind, GENERAL_TOPIC_ID];\n let sql =\n \"SELECT * FROM api_topics WHERE LOWER(TRIM(title)) = ? AND surface = ? AND surface_scope IS ? AND (kind = ? OR id = ?)\";\n if (opts.excludeTopicId) {\n sql += \" AND id != ?\";\n params.push(opts.excludeTopicId);\n }\n sql += \" LIMIT 1\";\n const row = db.query<TopicRow, string[]>(sql).get(...params);\n return row ? rowToDto(row) : null;\n}\n\n/**\n * Move topics onto a surface. Used by adapters that own a classification the\n * canonical store cannot derive on its own (the telegram chat↔topic mapping\n * lives in that adapter's database, not this one).\n */\nexport function setTopicSurfaces(topicIds: readonly string[], surface: TopicSurface): number {\n if (topicIds.length === 0) return 0;\n const normalized = normalizeTopicSurface(surface);\n let changed = 0;\n db.transaction(() => {\n const update = db.query(\"UPDATE api_topics SET surface = ? WHERE id = ? AND surface != ?\");\n for (const topicId of topicIds) {\n changed += Number(update.run(normalized, topicId, normalized).changes ?? 0);\n }\n })();\n return changed;\n}\n\n/**\n * File an existing topic into one surface namespace without changing its id.\n * Adapter-owned migrations use this when their local mapping store is the only\n * authority capable of deriving the namespace (for example Telegram chat id).\n */\nexport function setTopicSurfaceScope(\n topicId: string,\n surface: TopicSurface,\n surfaceScope: string | null,\n): boolean {\n const normalizedSurface = normalizeTopicSurface(surface);\n const normalizedScope = normalizeSurfaceScope(surfaceScope);\n const result = db\n .query(\n `UPDATE api_topics SET surface = ?, surface_scope = ?\n WHERE id = ? AND (surface IS NOT ? OR surface_scope IS NOT ?)`,\n )\n .run(normalizedSurface, normalizedScope, topicId, normalizedSurface, normalizedScope);\n return Number(result.changes ?? 0) > 0;\n}\n\n/**\n * How wide a title lookup is allowed to reach.\n *\n * `surface` is required rather than optional. It used to default to \"search\n * every surface\", which contradicted S-6's promise that a missed call site\n * \"cannot leak a topic across surfaces\" — the guarantee only held where a\n * caller remembered to opt in, and four did not: Telegram's `/load` and `/del`\n * (the latter could delete a terminal room), the runtime MCP id path, the cron\n * id path, and the session inbox. Every one of those was a silent leak with a\n * correct-looking call. Making the parameter explicit turns each future\n * omission into a compile error instead.\n *\n * `{ scope: \"all\" }` is the deliberate way to search every surface. It exists\n * for operator tooling — the CLI manages jobs across surfaces on purpose — and\n * reads as a decision at the call site rather than as an oversight.\n */\nexport type TopicNameLookupScope =\n | { surface: TopicSurface; surfaceScope?: string | null }\n | { scope: \"all\" };\n\n/**\n * Look up a topic by title, restricted to topics where `userId` participates.\n *\n * Answers only on a single match: a title is unique per surface (S-3), so an\n * `{ scope: \"all\" }` lookup of a name used on two surfaces resolves to null\n * rather than picking one.\n */\nexport function getTopicByNameForUser(\n title: string,\n userId: string,\n lookupScope: TopicNameLookupScope,\n): TopicDto | null {\n const opts: { surface?: TopicSurface; surfaceScope?: string | null } =\n \"scope\" in lookupScope ? {} : lookupScope;\n const trimmed = title.trim();\n const qualified = /^(agent|channel|manager):(.+)$/i.exec(trimmed);\n const requestedKind = qualified ? normalizeTopicKind(qualified[1]?.toLowerCase()) : null;\n const requestedTitle = qualified ? qualified[2]!.trim() : trimmed;\n const scoped = Object.hasOwn(opts, \"surfaceScope\");\n const rows = db\n .query(\n `SELECT t.* FROM api_topics t\n WHERE LOWER(t.title) = LOWER(?)\n AND t.id != ?\n AND t.visibility != 'hidden'\n AND (? IS NULL OR t.surface = ?)\n ${scoped ? \"AND t.surface_scope IS ?\" : \"\"}\n AND EXISTS (\n SELECT 1 FROM topic_members m WHERE m.topic_id = t.id AND m.user_id = ?\n )`,\n )\n .all(\n requestedTitle,\n GENERAL_TOPIC_ID,\n opts.surface ?? null,\n opts.surface ?? null,\n ...(scoped ? [normalizeSurfaceScope(opts.surfaceScope)] : []),\n userId,\n ) as TopicRow[];\n const matches = requestedKind ? rows.filter((row) => row.kind === requestedKind) : rows;\n return matches.length === 1 ? rowToDto(matches[0]!) : null;\n}\n\n/** Persist the agent session ID for a topic after a successful turn. */\nexport function setTopicSessionId(\n topicId: string,\n sessionId: string,\n context: TopicSessionLogContext = {},\n): void {\n const previous = getTopicSessionId(topicId);\n const result = db\n .query(\"UPDATE api_topics SET session_id = ? WHERE id = ?\")\n .run(sessionId, topicId);\n const changes = Number(result.changes ?? 0);\n const logContext = {\n topicId,\n previousSessionId: shortSessionId(previous),\n sessionId: shortSessionId(sessionId),\n reason: context.reason,\n queryId: context.queryId,\n agent: context.agent,\n };\n if (changes === 0) {\n logger.warn(logContext, \"api-topic session_id update missed topic\");\n } else if (previous !== sessionId) {\n logger.debug(logContext, \"api-topic session_id updated\");\n } else {\n logger.debug(logContext, \"api-topic session_id unchanged\");\n }\n}\n\n/** Clear the session ID (e.g. on topic reset). */\nexport function clearTopicSessionId(topicId: string, reason = \"unspecified\"): void {\n const previous = getTopicSessionId(topicId);\n const result = db.query(\"UPDATE api_topics SET session_id = NULL WHERE id = ?\").run(topicId);\n const changes = Number(result.changes ?? 0);\n const logContext = { topicId, previousSessionId: shortSessionId(previous), reason };\n if (changes === 0) {\n logger.warn(logContext, \"api-topic session_id clear missed topic\");\n } else if (previous) {\n logger.info(logContext, \"api-topic session_id cleared\");\n } else {\n logger.debug(logContext, \"api-topic session_id already clear\");\n }\n}\n\n/** Read the persisted session ID for a topic, or null if none. */\nexport function getTopicSessionId(topicId: string): string | null {\n const r = db\n .query<{ session_id: string | null }, string>(\"SELECT session_id FROM api_topics WHERE id = ?\")\n .get(topicId);\n return r?.session_id ?? null;\n}\n\n/**\n * Hard-delete a topic row. Irreversible — the caller is responsible for also\n * deleting the topic's messages (see `deleteMessagesForTopic`). Returns false\n * if the topic didn't exist.\n */\nexport function deleteTopic(id: string, options: { allowManager?: boolean } = {}): boolean {\n const r = db\n .query<{ id: string; kind: string }, string>(\"SELECT id, kind FROM api_topics WHERE id = ?\")\n .get(id);\n if (!r) return false;\n if (id === GENERAL_TOPIC_ID || (r.kind === \"manager\" && !options.allowManager)) return false;\n db.query(\n `DELETE FROM subagent_tell_grants\n WHERE subagent_topic_id = ? OR target_topic_id = ? OR granted_by_topic_id = ?`,\n ).run(id, id, id);\n db.query(\"DELETE FROM topic_members WHERE topic_id = ?\").run(id);\n db.query(\"DELETE FROM api_topics WHERE id = ?\").run(id);\n return true;\n}\n\nexport function listSubagentTellTargetIds(subagentTopicId: string): string[] {\n return db\n .query<{ target_topic_id: string }, string>(\n \"SELECT target_topic_id FROM subagent_tell_grants WHERE subagent_topic_id = ? ORDER BY created_at\",\n )\n .all(subagentTopicId)\n .map((row) => row.target_topic_id);\n}\n\nexport function grantSubagentTellTarget(\n subagentTopicId: string,\n targetTopicId: string,\n grantedByTopicId: string,\n): void {\n db.query(\n `INSERT INTO subagent_tell_grants\n (subagent_topic_id,target_topic_id,granted_by_topic_id,created_at)\n VALUES (?,?,?,?)\n ON CONFLICT(subagent_topic_id,target_topic_id) DO UPDATE SET\n granted_by_topic_id = excluded.granted_by_topic_id`,\n ).run(subagentTopicId, targetTopicId, grantedByTopicId, new Date().toISOString());\n}\n\nexport function revokeSubagentTellTarget(subagentTopicId: string, targetTopicId: string): boolean {\n return (\n db\n .query(\"DELETE FROM subagent_tell_grants WHERE subagent_topic_id = ? AND target_topic_id = ?\")\n .run(subagentTopicId, targetTopicId).changes > 0\n );\n}\n\n/**\n * Preserve a derived-topic chain when an intermediate parent is deleted.\n * Direct children move to the deleted topic's parent (or become roots) rather\n * than retaining a dangling parent id that would break memory-origin lookup.\n */\n/** Ids of the subagent worker rooms spawned directly from `parentTopicId`. */\nexport function listSubagentChildTopicIds(parentTopicId: string): string[] {\n return db\n .query<{ id: string }, string>(\n \"SELECT id FROM api_topics WHERE parent_topic_id = ? AND is_subagent = 1 ORDER BY created_at\",\n )\n .all(parentTopicId)\n .map((row) => row.id);\n}\n\nexport function reparentTopicChildren(\n deletedTopicId: string,\n replacementParentTopicId: string | null,\n): string[] {\n const rows = db\n .query<{ id: string }, string>(\"SELECT id FROM api_topics WHERE parent_topic_id = ?\")\n .all(deletedTopicId);\n if (rows.length === 0) return [];\n db.query(\"UPDATE api_topics SET parent_topic_id = ? WHERE parent_topic_id = ?\").run(\n replacementParentTopicId,\n deletedTopicId,\n );\n // Reparenting can move a topic out of the subtree whose manager granted its\n // tell edges; purge involved grants (fail closed) — an ancestor can re-grant.\n for (const row of rows) {\n db.query(\n \"DELETE FROM subagent_tell_grants WHERE subagent_topic_id = ? OR target_topic_id = ?\",\n ).run(row.id, row.id);\n }\n return rows.map((row) => row.id);\n}\n\nexport function addParticipantToDB(\n topicId: string,\n userId: string,\n role: \"member\" | \"owner\",\n): boolean {\n if (!db.query(\"SELECT 1 FROM api_topics WHERE id = ?\").get(topicId)) return false;\n db.query(\"INSERT OR IGNORE INTO topic_members (topic_id,user_id,role) VALUES (?,?,?)\").run(\n topicId,\n userId,\n role,\n );\n return true;\n}\n\nexport function removeParticipantFromDB(topicId: string, userId: string): boolean {\n if (!db.query(\"SELECT 1 FROM api_topics WHERE id = ?\").get(topicId)) return false;\n db.query(\"DELETE FROM topic_members WHERE topic_id = ? AND user_id = ?\").run(topicId, userId);\n return true;\n}\n",
23
+ "/**\n * Global (workspace-wide) application settings — a single shared record, not\n * per-user and not per-topic.\n *\n * Currently holds the global AI name (default \"Otium\"): one name for this\n * node. Read fresh from disk on every call, deliberately uncached — the\n * long-running node process (turn-runner, `/health`) and the short-lived\n * `negotium name` CLI process are different processes that must agree\n * immediately. A cached in-memory copy here previously meant `negotium name\n * <x>` against an already-running node silently did nothing until the node\n * was restarted. The file is tiny and this is called at most once per turn or\n * health check, so the extra read costs nothing worth caching for.\n */\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { resolveStorageDataDir } from \"#storage/storage-host\";\n\nexport const DEFAULT_AI_NAME = \"Otium\";\n\nfunction settingsFile(): string {\n return join(resolveStorageDataDir(), \"otium-settings.json\");\n}\n\nexport function getGlobalAiName(): string {\n const path = settingsFile();\n try {\n if (existsSync(path)) {\n const data = JSON.parse(readFileSync(path, \"utf8\")) as { aiName?: unknown };\n if (typeof data.aiName === \"string\" && data.aiName.trim()) {\n return data.aiName.trim();\n }\n }\n } catch {\n // Corrupt/missing file → fall through to the default.\n }\n return DEFAULT_AI_NAME;\n}\n\n/** Set the global AI name (empty → reset to default). Persists to disk. */\nexport function setGlobalAiName(name: string): string {\n const path = settingsFile();\n const aiName = name.trim() || DEFAULT_AI_NAME;\n try {\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(path, JSON.stringify({ aiName }, null, 2));\n } catch {\n // Best-effort persistence; callers still get the resolved value back.\n }\n return aiName;\n}\n",
24
+ "import { db } from \"#storage/forum-db\";\nimport { registerStorageSchemaInitializer } from \"#storage/storage-host\";\nimport type { AskUserQuestionDto } from \"#types/api\";\n\nexport type AskUserGateState = \"pending\" | \"claimed\" | \"answered\" | \"cancelled\" | \"quarantined\";\n\nexport interface AskUserGateRecord {\n gateId: string;\n topicId: string;\n queryId?: string;\n idempotencyKey: string;\n bodyHash: string;\n messageId: string;\n ownerId: string;\n state: AskUserGateState;\n selectedLabel?: string;\n answeredBy?: string;\n}\n\ninterface AskUserGateRow {\n gate_id: string;\n topic_id: string;\n query_id: string | null;\n idempotency_key: string;\n body_hash: string;\n message_id: string;\n owner_id: string;\n state: AskUserGateState;\n selected_label: string | null;\n answered_by: string | null;\n}\n\nexport interface AskUserGateCardUpdate {\n topicId: string;\n messageId: string;\n askUserQuestion: AskUserQuestionDto;\n editedAt: string;\n}\n\nfunction initializeAskUserGateSchema(): void {\n db.exec(`\n CREATE TABLE IF NOT EXISTS ask_user_gates (\n gate_id TEXT PRIMARY KEY,\n topic_id TEXT NOT NULL REFERENCES api_topics(id) ON DELETE CASCADE,\n query_id TEXT,\n idempotency_key TEXT NOT NULL,\n body_hash TEXT NOT NULL,\n message_id TEXT NOT NULL UNIQUE,\n owner_id TEXT NOT NULL,\n state TEXT NOT NULL,\n selected_label TEXT,\n answered_by TEXT,\n claim_source TEXT,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL\n );\n CREATE INDEX IF NOT EXISTS idx_ask_user_gates_idempotency\n ON ask_user_gates(topic_id, idempotency_key, created_at);\n CREATE UNIQUE INDEX IF NOT EXISTS idx_ask_user_gates_active_key\n ON ask_user_gates(topic_id, idempotency_key)\n WHERE state IN ('pending', 'claimed');\n `);\n}\n\nregisterStorageSchemaInitializer(initializeAskUserGateSchema, 31);\n\nfunction fromRow(row: AskUserGateRow): AskUserGateRecord {\n return {\n gateId: row.gate_id,\n topicId: row.topic_id,\n queryId: row.query_id ?? undefined,\n idempotencyKey: row.idempotency_key,\n bodyHash: row.body_hash,\n messageId: row.message_id,\n ownerId: row.owner_id,\n state: row.state,\n selectedLabel: row.selected_label ?? undefined,\n answeredBy: row.answered_by ?? undefined,\n };\n}\n\nfunction latestGate(topicId: string, idempotencyKey: string): AskUserGateRecord | null {\n const row = db\n .query(\n `SELECT * FROM ask_user_gates\n WHERE topic_id = ? AND idempotency_key = ?\n ORDER BY rowid DESC LIMIT 1`,\n )\n .get(topicId, idempotencyKey) as AskUserGateRow | undefined;\n return row ? fromRow(row) : null;\n}\n\nfunction expireAskCard(\n topicId: string,\n messageId: string,\n editedAt: string,\n): AskUserGateCardUpdate | null {\n const row = db\n .query(\n `SELECT ask_user_question FROM api_messages\n WHERE topic_id = ? AND id = ? AND deleted = 0 AND kind = 'ask_user_question'`,\n )\n .get(topicId, messageId) as { ask_user_question: string | null } | undefined;\n if (!row?.ask_user_question) return null;\n const ask = JSON.parse(row.ask_user_question) as AskUserQuestionDto;\n if (ask.selectedLabel || ask.expired) return null;\n const expired = { ...ask, expired: true };\n db.query(\n `UPDATE api_messages SET ask_user_question = ?, edited_at = ?\n WHERE topic_id = ? AND id = ? AND deleted = 0 AND kind = 'ask_user_question'`,\n ).run(JSON.stringify(expired), editedAt, topicId, messageId);\n return { topicId, messageId, askUserQuestion: expired, editedAt };\n}\n\nexport type PrepareAskUserGateResult =\n | { outcome: \"created\"; gate: AskUserGateRecord }\n | { outcome: \"pending\"; gate: AskUserGateRecord }\n | { outcome: \"replay\"; gate: AskUserGateRecord }\n | { outcome: \"conflict\"; gate: AskUserGateRecord };\n\nexport function prepareAskUserGate(args: {\n gateId: string;\n topicId: string;\n queryId?: string;\n idempotencyKey: string;\n bodyHash: string;\n messageId: string;\n ownerId: string;\n now: string;\n}): PrepareAskUserGateResult {\n return db\n .transaction(() => {\n const latest = latestGate(args.topicId, args.idempotencyKey);\n if (latest?.bodyHash !== undefined && latest.bodyHash !== args.bodyHash) {\n return { outcome: \"conflict\", gate: latest } as const;\n }\n if (latest?.state === \"answered\") return { outcome: \"replay\", gate: latest } as const;\n if (\n latest &&\n (latest.state === \"pending\" || latest.state === \"claimed\") &&\n latest.ownerId === args.ownerId\n ) {\n return { outcome: \"pending\", gate: latest } as const;\n }\n if (latest && (latest.state === \"pending\" || latest.state === \"claimed\")) {\n return { outcome: \"pending\", gate: latest } as const;\n }\n\n db.query(\n `INSERT INTO ask_user_gates\n (gate_id, topic_id, query_id, idempotency_key, body_hash, message_id, owner_id, state, created_at, updated_at)\n VALUES (?, ?, ?, ?, ?, ?, ?, 'pending', ?, ?)`,\n ).run(\n args.gateId,\n args.topicId,\n args.queryId ?? null,\n args.idempotencyKey,\n args.bodyHash,\n args.messageId,\n args.ownerId,\n args.now,\n args.now,\n );\n return {\n outcome: \"created\",\n gate: {\n gateId: args.gateId,\n topicId: args.topicId,\n queryId: args.queryId,\n idempotencyKey: args.idempotencyKey,\n bodyHash: args.bodyHash,\n messageId: args.messageId,\n ownerId: args.ownerId,\n state: \"pending\",\n },\n } as const;\n })\n .immediate();\n}\n\nexport function quarantineAskUserGate(\n gateId: string,\n ownerId: string,\n now = new Date().toISOString(),\n): AskUserGateCardUpdate | null {\n return db\n .transaction(() => {\n const row = db.query(\"SELECT * FROM ask_user_gates WHERE gate_id = ?\").get(gateId) as\n | AskUserGateRow\n | undefined;\n if (!row || row.owner_id !== ownerId || ![\"pending\", \"claimed\"].includes(row.state)) {\n return null;\n }\n const result = db\n .query(\n `UPDATE ask_user_gates SET state = 'quarantined', updated_at = ?\n WHERE gate_id = ? AND owner_id = ? AND state IN ('pending', 'claimed')`,\n )\n .run(now, gateId, ownerId);\n if (Number(result.changes ?? 0) === 0) return null;\n return expireAskCard(row.topic_id, row.message_id, now);\n })\n .immediate();\n}\n\nexport function quarantineForeignAskUserGates(\n liveOwnerIds: ReadonlySet<string>,\n now = new Date().toISOString(),\n): AskUserGateCardUpdate[] {\n return db\n .transaction(() => {\n const rows = db\n .query(\n `SELECT * FROM ask_user_gates\n WHERE state IN ('pending', 'claimed')`,\n )\n .all() as AskUserGateRow[];\n const updates: AskUserGateCardUpdate[] = [];\n for (const row of rows) {\n if (liveOwnerIds.has(row.owner_id)) continue;\n if (row.state === \"claimed\" && row.selected_label && row.answered_by) {\n db.query(\n `UPDATE ask_user_gates SET state = 'answered', updated_at = ?\n WHERE gate_id = ? AND state = 'claimed'`,\n ).run(now, row.gate_id);\n continue;\n }\n const result = db\n .query(\n `UPDATE ask_user_gates SET state = 'quarantined', updated_at = ?\n WHERE gate_id = ? AND state IN ('pending', 'claimed')`,\n )\n .run(now, row.gate_id);\n if (Number(result.changes ?? 0) === 0) continue;\n const update = expireAskCard(row.topic_id, row.message_id, now);\n if (update) updates.push(update);\n }\n const legacyCards = db\n .query(\n `SELECT m.topic_id, m.id\n FROM api_messages m\n LEFT JOIN ask_user_gates g ON g.message_id = m.id\n WHERE m.kind = 'ask_user_question'\n AND m.deleted = 0\n AND g.gate_id IS NULL`,\n )\n .all() as { topic_id: string; id: string }[];\n for (const card of legacyCards) {\n const update = expireAskCard(card.topic_id, card.id, now);\n if (update) updates.push(update);\n }\n return updates;\n })\n .immediate();\n}\n\nexport type ClaimAskUserGateResult =\n | {\n outcome: \"claimed\";\n gate: AskUserGateRecord;\n askUserQuestion: AskUserQuestionDto;\n editedAt: string;\n }\n | { outcome: \"unavailable\" };\n\nexport function claimAskUserGateAndSelect(args: {\n topicId: string;\n messageId: string;\n label: string;\n /** Accept a label that is not one of the card's choices (free-text answer or skip). */\n allowAnyLabel?: boolean;\n userId: string;\n ownerId: string;\n source: string;\n now: string;\n}): ClaimAskUserGateResult {\n return db\n .transaction(() => {\n const row = db\n .query(\n `SELECT * FROM ask_user_gates\n WHERE topic_id = ? AND message_id = ?\n ORDER BY rowid DESC LIMIT 1`,\n )\n .get(args.topicId, args.messageId) as AskUserGateRow | undefined;\n if (!row || row.owner_id !== args.ownerId || row.state !== \"pending\") {\n return { outcome: \"unavailable\" } as const;\n }\n const message = db\n .query(\n `SELECT ask_user_question FROM api_messages\n WHERE topic_id = ? AND id = ? AND deleted = 0 AND kind = 'ask_user_question'`,\n )\n .get(args.topicId, args.messageId) as { ask_user_question: string | null } | undefined;\n if (!message?.ask_user_question) return { outcome: \"unavailable\" } as const;\n const ask = JSON.parse(message.ask_user_question) as AskUserQuestionDto;\n if (\n ask.expired ||\n ask.selectedLabel ||\n (!args.allowAnyLabel && !ask.choices.some((choice) => choice.label === args.label))\n ) {\n return { outcome: \"unavailable\" } as const;\n }\n\n const claimed = db\n .query(\n `UPDATE ask_user_gates\n SET state = 'answered', selected_label = ?, answered_by = ?, claim_source = ?, updated_at = ?\n WHERE gate_id = ? AND owner_id = ? AND state = 'pending'`,\n )\n .run(args.label, args.userId, args.source, args.now, row.gate_id, args.ownerId);\n if (Number(claimed.changes ?? 0) === 0) return { outcome: \"unavailable\" } as const;\n\n const selected = { ...ask, selectedLabel: args.label };\n db.query(\n `UPDATE api_messages SET ask_user_question = ?, edited_at = ?\n WHERE topic_id = ? AND id = ? AND deleted = 0 AND kind = 'ask_user_question'`,\n ).run(JSON.stringify(selected), args.now, args.topicId, args.messageId);\n return {\n outcome: \"claimed\",\n gate: fromRow({\n ...row,\n state: \"answered\",\n selected_label: args.label,\n answered_by: args.userId,\n }),\n askUserQuestion: selected,\n editedAt: args.now,\n } as const;\n })\n .immediate();\n}\n\nexport function cancelAskUserGate(\n topicId: string,\n messageId: string,\n ownerId: string,\n now = new Date().toISOString(),\n): AskUserGateCardUpdate | null {\n return db\n .transaction(() => {\n const row = db\n .query(\n `SELECT * FROM ask_user_gates\n WHERE topic_id = ? AND message_id = ? ORDER BY rowid DESC LIMIT 1`,\n )\n .get(topicId, messageId) as AskUserGateRow | undefined;\n if (!row || row.owner_id !== ownerId || row.state !== \"pending\") return null;\n const result = db\n .query(\n `UPDATE ask_user_gates SET state = 'cancelled', updated_at = ?\n WHERE gate_id = ? AND owner_id = ? AND state = 'pending'`,\n )\n .run(now, row.gate_id, ownerId);\n if (Number(result.changes ?? 0) === 0) return null;\n return expireAskCard(topicId, messageId, now);\n })\n .immediate();\n}\n",
25
+ "import {\n existsSync,\n mkdirSync,\n readFileSync,\n renameSync,\n unlinkSync,\n writeFileSync,\n} from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { MANAGER_TOPIC_LOG_NAME, NODE_LOCAL_USER_ID } from \"#platform/constants\";\nimport { appendJsonlLine } from \"#platform/jsonl\";\nimport { logger } from \"#platform/logger\";\nimport { sanitizeId, sanitizeTopicName } from \"#security/sanitize\";\nimport { resolveStorageDataDir } from \"#storage/storage-host\";\nimport type { AgentKind, UnifiedEvent } from \"#types\";\n\n/**\n * Per-topic conversation log (UnifiedEvent stream) used as the\n * **provider-agnostic source of truth** for cross-agent portability.\n *\n * Storage layout:\n * {DATA_DIR}/conversations/{sanitizedTopicName}.jsonl\n * {DATA_DIR}/conversations/{sanitizedTopicName}.active.jsonl\n *\n * A private General is the one room several users may hold at once, so its\n * pair is qualified with the owner — see {@link topicFilename}.\n *\n * The first file is append-only and retains every yielded UnifiedEvent for\n * archive and teardown. The optional active file is a replaceable provider\n * projection: compaction writes its summary there and later turns append to\n * both streams. Agent switches and rollout repair read the active projection.\n *\n * The Claude/Codex SDK rollouts (~/.claude/projects/, ~/.codex/sessions/) are\n * intentionally treated as opaque side-effects of the SDKs. The raw stream\n * remains the forensic source of truth.\n */\nexport interface ConversationEntry {\n ts: string;\n /**\n * Agent that produced this event, frozen at write time. A topic that has\n * been switched (via `set_agent`) will have a mixed-agent log: earlier\n * entries keep the agent that originally generated them. Replay code\n * (rollout-codec `extractChatPairs`) intentionally ignores this field —\n * the cross-agent rollout's whole point is to feed past dialogue, no\n * matter who produced it, into the *new* SDK as if it were native.\n */\n agent: AgentKind;\n event: UnifiedEvent;\n}\n\n/** Public userId remains in the API, but standalone storage has one flat local namespace. */\nfunction conversationDir(_userId: number | string): string {\n return join(resolveStorageDataDir(), \"conversations\");\n}\n\n/**\n * One flat namespace is safe because a room title is unique per surface (S-3)\n * — with exactly one exception. A manager room is deliberately exempt from\n * title conflicts, since every person gets a private \"General\" per workspace,\n * and `general` is a reserved name no other room can take. Keying the log on\n * the title alone therefore pointed every user's private General at the same\n * `general.jsonl`: two people's transcripts interleaved in one append-only\n * file, and whatever reads it back by name (rollout reconstruction, archive,\n * teardown) hands one person the other's private history.\n *\n * Only that room is qualified with its owner, so nothing else moves, and the\n * standalone node's own principal keeps the unqualified path it has always\n * written — an existing install needs no migration.\n */\nfunction topicFilename(userId: number | string, topicName: string): string {\n const t = sanitizeTopicName(topicName, true);\n const owner = String(userId);\n if (t !== MANAGER_TOPIC_LOG_NAME || owner === NODE_LOCAL_USER_ID) return `${t}.jsonl`;\n return `${t}.${sanitizeId(owner)}.jsonl`;\n}\n\n/** Compute the absolute path for a given user/topic conversation log. */\nexport function getConversationPath(userId: number | string, topicName: string): string {\n return join(conversationDir(userId), topicFilename(userId, topicName));\n}\n\n/** Replaceable provider context derived from the append-only raw conversation log. */\nexport function getActiveConversationPath(userId: number | string, topicName: string): string {\n const rawPath = getConversationPath(userId, topicName);\n return rawPath.endsWith(\".jsonl\")\n ? `${rawPath.slice(0, -\".jsonl\".length)}.active.jsonl`\n : `${rawPath}.active`;\n}\n\nexport function hasActiveConversation(userId: number | string, topicName: string): boolean {\n return existsSync(getActiveConversationPath(userId, topicName));\n}\n\n/**\n * Append a single UnifiedEvent for the given topic. Creates the parent\n * directory and the file as needed. Best-effort: I/O failures are logged but\n * never throw, since recording must not break the live stream to Telegram.\n *\n * **Concurrency note (review item M2, revised):** within the bot process the\n * single-threaded event loop already serializes writes — but this module is\n * NOT single-process: the self-config MCP server (a separate stdio process,\n * via `topic-agent-switch`) and provider bridge helpers append to the same\n * topic logs.\n * Cross-process interleaving on macOS is real for lines beyond PIPE_BUF\n * (512B), and a torn line is silently dropped by `readConversation` —\n * corrupting the canonical source for cross-agent rollout reconstruction.\n * Writes therefore go through `appendJsonlLine` (sidecar `.lock` via O_EXCL,\n * stale-lock reclaim, and a `JsonlLockTimeoutError` when the lock stays busy —\n * nothing is written unlocked, so a contended append fails instead of risking\n * an interleaved line that `readConversationPath` would later discard).\n *\n * The append stays SYNCHRONOUS on purpose: a previous attempt at a\n * Promise-chained per-topic queue made writes async (durability gap before a\n * synchronous `readConversation`) and broke `set_agent` in the bridge tests.\n */\nexport function appendConversationEvent(\n userId: number | string,\n topicName: string,\n agent: AgentKind,\n event: UnifiedEvent,\n): boolean {\n try {\n appendConversationEventStrict(userId, topicName, agent, event);\n return true;\n } catch (err) {\n logger.warn(\n { err, userId, topicName, eventType: event.type },\n \"appendConversationEvent: write failed\",\n );\n return false;\n }\n}\n\n/**\n * The raw manifest accepted an entry that the active projection rejected.\n *\n * Distinct from a plain write failure because the two logs are now out of sync\n * rather than merely un-updated: `raw` records the event, `active` — the log\n * replayed to the provider — does not.\n */\nexport class ConversationLogDivergedError extends Error {\n constructor(\n readonly rawPath: string,\n readonly activePath: string,\n override readonly cause: unknown,\n ) {\n super(\n `conversation logs diverged: the entry is in the raw manifest (${rawPath}) ` +\n `but the active projection (${activePath}) rejected it`,\n );\n this.name = \"ConversationLogDivergedError\";\n }\n}\n\n/**\n * Strict variant for state transitions where the conversation log is a manifest\n * rather than telemetry. Throws on I/O failure so callers can avoid committing\n * DB state that points at an unmanifested SDK session.\n */\nexport function appendConversationEventStrict(\n userId: number | string,\n topicName: string,\n agent: AgentKind,\n event: UnifiedEvent,\n): void {\n const path = getConversationPath(userId, topicName);\n const entry: ConversationEntry = {\n ts: new Date().toISOString(),\n agent,\n event,\n };\n const line = JSON.stringify(entry);\n mkdirSync(dirname(path), { recursive: true });\n appendJsonlLine(path, line);\n const activePath = getActiveConversationPath(userId, topicName);\n if (existsSync(activePath)) {\n try {\n appendJsonlLine(activePath, line);\n } catch (cause) {\n // The two appends are not atomic. Raw already has the entry, so failing\n // here leaves the logs permanently split: the provider replays `active`\n // and will never see this event, while the raw manifest says it happened.\n // We cannot un-append, so at least name the inconsistency instead of\n // surfacing a generic write error that hides which side is wrong.\n throw new ConversationLogDivergedError(path, activePath, cause);\n }\n }\n}\n\n/** Append lifecycle metadata to the raw manifest without changing active context. */\nexport function appendRawConversationEventStrict(\n userId: number | string,\n topicName: string,\n agent: AgentKind,\n event: UnifiedEvent,\n): void {\n const path = getConversationPath(userId, topicName);\n const entry: ConversationEntry = {\n ts: new Date().toISOString(),\n agent,\n event,\n };\n mkdirSync(dirname(path), { recursive: true });\n appendJsonlLine(path, JSON.stringify(entry));\n}\n\n/**\n * Read one JSONL conversation stream. Malformed lines are skipped so one\n * damaged event does not poison the remaining history.\n */\nfunction readConversationPath(path: string): ConversationEntry[] {\n const out: ConversationEntry[] = [];\n if (!existsSync(path)) return out;\n let raw: string;\n try {\n raw = readFileSync(path, \"utf8\");\n } catch (err) {\n logger.warn({ err, path }, \"readConversation: read failed\");\n return out;\n }\n for (const line of raw.split(\"\\n\")) {\n if (!line.trim()) continue;\n try {\n out.push(JSON.parse(line) as ConversationEntry);\n } catch (err) {\n logger.warn(\n { err, line: line.slice(0, 200) },\n \"readConversation: malformed JSONL line skipped\",\n );\n }\n }\n return out;\n}\n\n/**\n * Read the context the next provider turn should receive. Before the first\n * compaction this is the raw stream. Afterwards the replaceable active stream\n * contains the compacted summary plus every subsequently recorded event.\n *\n * NOTE(perf): reads the whole file each call. Topics in the kilobyte range\n * are fine; if a single topic ever grows into multi-megabyte territory,\n * consider a streaming reader (`readline`/`Bun.file().stream()`) and a\n * size-bounded tail.\n */\nexport function readConversation(userId: number | string, topicName: string): ConversationEntry[] {\n const activePath = getActiveConversationPath(userId, topicName);\n return readConversationPath(\n existsSync(activePath) ? activePath : getConversationPath(userId, topicName),\n );\n}\n\n/** Read the immutable full-fidelity stream used for archive and teardown. */\nexport function readRawConversation(\n userId: number | string,\n topicName: string,\n): ConversationEntry[] {\n return readConversationPath(getConversationPath(userId, topicName));\n}\n\n/** Atomically replace only the provider's active context projection. */\nexport function replaceConversationStrict(\n userId: number | string,\n topicName: string,\n entries: ConversationEntry[],\n): void {\n replaceConversationPathStrict(getActiveConversationPath(userId, topicName), entries);\n}\n\n/** Atomically seed or restore the append-only stream before it becomes live. */\nexport function replaceRawConversationStrict(\n userId: number | string,\n topicName: string,\n entries: ConversationEntry[],\n): void {\n replaceConversationPathStrict(getConversationPath(userId, topicName), entries);\n}\n\nfunction replaceConversationPathStrict(path: string, entries: ConversationEntry[]): void {\n const tempPath = `${path}.${process.pid}.${Date.now()}.tmp`;\n mkdirSync(dirname(path), { recursive: true });\n try {\n writeFileSync(\n tempPath,\n entries.length > 0 ? `${entries.map((entry) => JSON.stringify(entry)).join(\"\\n\")}\\n` : \"\",\n { flag: \"wx\" },\n );\n renameSync(tempPath, path);\n } catch (error) {\n try {\n unlinkSync(tempPath);\n } catch {}\n throw error;\n }\n}\n\n/**\n * Copy the unified conversation log of `srcTopic` into the file path that\n * `dstTopic` will read from. Used by `/fork` so a forked child topic inherits\n * the parent's full cross-agent history, not just the agent's native SDK\n * rollout. `/spawn` intentionally does not call this; it starts with no\n * conversation history. Without this copy, a fork followed immediately by\n * `/agent <other>` would feed the empty child log to `switchTopicAgent` and\n * the new agent would start from zero — see the bug report from 2026-05-24.\n *\n * Semantics:\n * - Copies the parent's raw stream and its active projection when present.\n * - Writes independent files so parent and child can diverge after the fork.\n * - Refuses to overwrite a non-empty destination (returns `{copied:false}`).\n * `/fork`'s only caller runs this immediately after topic creation when\n * the dst file is guaranteed empty, so a non-empty dst means a programmer\n * error somewhere upstream — fail loud rather than silently merging.\n * - On any I/O error: throws. The caller (`createChildTopic`) already has\n * a rollback path that wraps this call.\n */\nexport function cloneConversationLog(opts: {\n userId: number | string;\n srcTopic: string;\n dstTopic: string;\n}): { copied: boolean; entries: number } {\n const { userId, srcTopic, dstTopic } = opts;\n const dstPath = getConversationPath(userId, dstTopic);\n if (existsSync(dstPath) && readFileSync(dstPath, \"utf8\").trim().length > 0) {\n logger.warn(\n { userId, srcTopic, dstTopic, dstPath },\n \"cloneConversationLog: dst already non-empty — refusing to overwrite\",\n );\n return { copied: false, entries: 0 };\n }\n const entries = readRawConversation(userId, srcTopic);\n if (entries.length === 0) {\n return { copied: false, entries: 0 };\n }\n const body = `${entries.map((e) => JSON.stringify(e)).join(\"\\n\")}\\n`;\n mkdirSync(dirname(dstPath), { recursive: true });\n writeFileSync(dstPath, body);\n const srcActivePath = getActiveConversationPath(userId, srcTopic);\n if (existsSync(srcActivePath)) {\n const dstActivePath = getActiveConversationPath(userId, dstTopic);\n writeFileSync(dstActivePath, readFileSync(srcActivePath));\n }\n return { copied: true, entries: entries.length };\n}\n\n/**\n * Walk the unified log backwards and return the most recent SDK-emitted\n * session id for the given agent — or null if that agent has never run on\n * this topic.\n *\n * Used by `set_agent` to round-trip the SAME native rollout file across\n * agent switches: when the user does claude → codex → claude, we reuse\n * the original claude sessionId so the synthetic rollout lands at the\n * same path the SDK already manages, preserving prompt-cache continuity\n * and avoiding orphan `~/.claude/projects/<dir>/<id>.jsonl` files.\n *\n * Behavior:\n * - First-ever switch to an agent (no prior session events) → null,\n * caller falls back to a fresh randomUUID/uuidv7. Same as before.\n * - Roundtrip switch (prior session exists) → that sessionId.\n *\n * `session` events are emitted on every turn by claude-/codex-provider and\n * captured into the unified log by runAgent's append wrapper. The most\n * recent one for the target agent is by definition the current SDK-side\n * resume key for that agent.\n */\nexport function findLastSessionIdForAgent(\n entries: ConversationEntry[],\n agent: AgentKind,\n): string | null {\n for (let i = entries.length - 1; i >= 0; i--) {\n const entry = entries[i];\n if (entry.agent !== agent) continue;\n if (entry.event.type === \"session\") {\n return entry.event.sessionId;\n }\n }\n return null;\n}\n",
26
+ "import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { logger } from \"#platform/logger\";\nimport { sanitizeFileName } from \"#security/sanitize\";\nimport { resolveStorageDataDir } from \"#storage/storage-host\";\nimport type { AgentKind, DecisionSnapshot } from \"#types\";\n\nexport type StoredDecision = DecisionSnapshot;\n\nexport const DECISION_STATUS_VALUES = [\n \"proposed\",\n \"accepted\",\n \"executed\",\n \"rejected\",\n \"superseded\",\n] as const;\n\ninterface DecisionFileShape {\n version: 1;\n decisions: StoredDecision[];\n}\n\nfunction safeDecisionScopeKey(scopeKey: string): string {\n const safe = sanitizeFileName(scopeKey);\n if (!safe || safe === \".\" || safe === \"..\") {\n throw new Error(`decisions: refusing unsafe scope key: ${scopeKey}`);\n }\n return safe;\n}\n\nexport function decisionScopeKey(opts: { topicId?: string; session: string }): string {\n return opts.topicId?.trim() || opts.session || \"default\";\n}\n\nexport function getDecisionFilePath(userId: number | string, scopeKey: string): string {\n void userId;\n return join(resolveStorageDataDir(), \"decisions\", `${safeDecisionScopeKey(scopeKey)}.json`);\n}\n\nexport function getDecisionGraphSvgPath(userId: number | string, scopeKey: string): string {\n void userId;\n return join(\n resolveStorageDataDir(),\n \"decision-renders\",\n safeDecisionScopeKey(scopeKey),\n \"latest.svg\",\n );\n}\n\nexport function writeDecisionGraphSvg(\n userId: number | string,\n scopeKey: string,\n svg: string,\n): string {\n const path = getDecisionGraphSvgPath(userId, scopeKey);\n mkdirSync(dirname(path), { recursive: true });\n const tmp = `${path}.${process.pid}.tmp`;\n writeFileSync(tmp, svg, \"utf-8\");\n renameSync(tmp, path);\n return path;\n}\n\nexport function readDecisions(userId: number | string, scopeKey: string): StoredDecision[] {\n const path = getDecisionFilePath(userId, scopeKey);\n if (!existsSync(path)) return [];\n try {\n const parsed = JSON.parse(readFileSync(path, \"utf-8\")) as DecisionFileShape;\n return Array.isArray(parsed?.decisions) ? parsed.decisions : [];\n } catch (error) {\n logger.warn({ err: error, path }, \"decisions: failed to read decision store\");\n return [];\n }\n}\n\nexport function writeDecisions(\n userId: number | string,\n scopeKey: string,\n decisions: StoredDecision[],\n): void {\n const path = getDecisionFilePath(userId, scopeKey);\n mkdirSync(dirname(path), { recursive: true });\n const payload: DecisionFileShape = { version: 1, decisions };\n const tmp = `${path}.${process.pid}.tmp`;\n writeFileSync(tmp, JSON.stringify(payload, null, 2), \"utf-8\");\n renameSync(tmp, path);\n}\n\nexport interface DecisionCreateInput {\n action: string;\n reasoning: string;\n agent: AgentKind;\n model?: string;\n status?: StoredDecision[\"status\"];\n causedBy?: string[];\n timestamp?: number;\n}\n\nexport interface DecisionUpdateInput {\n id: string;\n action?: string;\n reasoning?: string;\n status?: StoredDecision[\"status\"];\n causedBy?: string[];\n}\n\nfunction nextDecisionId(decisions: StoredDecision[]): number {\n let max = 0;\n for (const decision of decisions) {\n const id = Number(decision.id);\n if (Number.isInteger(id) && id > max) max = id;\n }\n return max + 1;\n}\n\nfunction normalizedIds(ids: string[] | undefined): string[] | undefined {\n if (!ids) return undefined;\n const unique = [...new Set(ids.map((id) => id.trim()).filter(Boolean))];\n return unique.length > 0 ? unique : undefined;\n}\n\nexport function validateDecisionGraph(decisions: StoredDecision[]): void {\n const ids = new Set(decisions.map((decision) => decision.id));\n for (const decision of decisions) {\n for (const upstream of decision.causedBy ?? []) {\n if (!ids.has(upstream)) {\n throw new Error(`Decision #${decision.id} references missing decision #${upstream}.`);\n }\n if (upstream === decision.id) {\n throw new Error(`Decision #${decision.id} cannot cause itself.`);\n }\n }\n }\n\n const visiting = new Set<string>();\n const visited = new Set<string>();\n const byId = new Map(decisions.map((decision) => [decision.id, decision]));\n const visit = (id: string): void => {\n if (visited.has(id)) return;\n if (visiting.has(id)) throw new Error(`Decision graph contains a cycle at #${id}.`);\n visiting.add(id);\n for (const upstream of byId.get(id)?.causedBy ?? []) visit(upstream);\n visiting.delete(id);\n visited.add(id);\n };\n for (const id of ids) visit(id);\n}\n\nexport function createDecisions(\n decisions: StoredDecision[],\n inputs: DecisionCreateInput[],\n): { decisions: StoredDecision[]; created: StoredDecision[] } {\n const out = [...decisions];\n const created: StoredDecision[] = [];\n let id = nextDecisionId(out);\n for (const input of inputs) {\n const decision: StoredDecision = {\n id: String(id++),\n action: input.action.trim(),\n reasoning: input.reasoning.trim(),\n agent: input.agent,\n status: input.status ?? \"accepted\",\n timestamp: input.timestamp ?? Date.now(),\n ...(input.model ? { model: input.model } : {}),\n ...(normalizedIds(input.causedBy) ? { causedBy: normalizedIds(input.causedBy) } : {}),\n };\n out.push(decision);\n created.push(decision);\n }\n validateDecisionGraph(out);\n return { decisions: out, created };\n}\n\nexport function updateDecisions(\n decisions: StoredDecision[],\n updates: DecisionUpdateInput[],\n): { decisions: StoredDecision[]; missing: string[] } {\n const out = decisions.map((decision) => ({\n ...decision,\n ...(decision.causedBy ? { causedBy: [...decision.causedBy] } : {}),\n }));\n const byId = new Map(out.map((decision) => [decision.id, decision]));\n const missing: string[] = [];\n for (const update of updates) {\n const decision = byId.get(update.id);\n if (!decision) {\n missing.push(update.id);\n continue;\n }\n if (update.action !== undefined) decision.action = update.action.trim();\n if (update.reasoning !== undefined) decision.reasoning = update.reasoning.trim();\n if (update.status !== undefined) decision.status = update.status;\n if (update.causedBy !== undefined) {\n const ids = normalizedIds(update.causedBy);\n if (ids) decision.causedBy = ids;\n else delete decision.causedBy;\n }\n }\n validateDecisionGraph(out);\n return { decisions: out, missing };\n}\n\nexport function deleteDecisions(\n decisions: StoredDecision[],\n opts: { ids?: string[]; all?: boolean },\n): { decisions: StoredDecision[]; removed: number } {\n if (opts.all) return { decisions: [], removed: decisions.length };\n const ids = new Set(opts.ids ?? []);\n const kept = decisions\n .filter((decision) => !ids.has(decision.id))\n .map((decision) => {\n const causedBy = decision.causedBy?.filter((id) => !ids.has(id));\n const next = { ...decision };\n if (causedBy && causedBy.length > 0) next.causedBy = causedBy;\n else delete next.causedBy;\n return next;\n });\n return { decisions: kept, removed: decisions.length - kept.length };\n}\n\nexport function renderDecisionList(decisions: StoredDecision[]): string {\n if (decisions.length === 0) return \"Decisions (0 recorded)\";\n return [\n `Decisions (${decisions.length} recorded)`,\n ...decisions.map((decision) => {\n const causes = decision.causedBy?.length\n ? ` <- ${decision.causedBy.map((id) => `#${id}`).join(\", \")}`\n : \"\";\n return `[${decision.status}] #${decision.id} ${decision.action}${causes}\\n ${decision.reasoning}`;\n }),\n ].join(\"\\n\");\n}\n",
27
+ "/**\n * Stringify an unknown thrown value for logging or user-visible messages.\n * Default fallback is `String(e)`. Pass an explicit fallback (e.g. \"unknown\")\n * to override what non-Error throws turn into.\n */\nexport function errMsg(e: unknown, fallback?: string): string {\n if (e instanceof Error) return e.message;\n return fallback ?? String(e);\n}\n",
28
+ "import { resolveFallbackAgent } from \"#platform/config-helpers\";\nimport { errMsg } from \"#platform/error\";\nimport { logger } from \"#platform/logger\";\nimport { db } from \"#storage/forum-db\";\nimport { closeStorageDatabase, registerStorageSchemaInitializer } from \"#storage/storage-host\";\nimport { type AgentKind, isAgentKind } from \"#types\";\n\nexport { db };\n\nexport interface ForumTopicInfo {\n messageThreadId: number;\n sessionId: string;\n createdAt: string;\n name: string;\n description?: string;\n forkOrigin?: string;\n agent: AgentKind;\n}\n\nexport interface UserForumConfig {\n communicateThreadId?: number;\n dmSessionId?: string;\n topics: { [topicName: string]: ForumTopicInfo };\n}\n\nexport type TopicRow = {\n user_id: string;\n name: string;\n message_thread_id: number;\n session_id: string | null;\n created_at: string;\n description: string | null;\n fork_origin: string | null;\n agent: string | null;\n};\n\nexport type UserRow = {\n id: string;\n dm_session_id: string | null;\n communicate_thread_id: number | null;\n};\n\nfunction initializeForumSchema(): void {\n // SQLite column defaults must be fixed literals, not runtime expressions —\n // interpolate the node's actual default agent once here rather than\n // hardcoding \"claude\" (which only matched FALLBACK_AGENT's own old\n // default). Only takes effect for a row inserted without naming `agent`\n // explicitly; every real insert path names it.\n const fallbackAgent = resolveFallbackAgent();\n db.exec(`\n CREATE TABLE IF NOT EXISTS users (\n id TEXT PRIMARY KEY,\n dm_session_id TEXT,\n communicate_thread_id INTEGER\n );\n\n CREATE TABLE IF NOT EXISTS topics (\n user_id TEXT NOT NULL REFERENCES users(id),\n name TEXT NOT NULL,\n message_thread_id INTEGER NOT NULL,\n session_id TEXT,\n created_at TEXT NOT NULL,\n description TEXT,\n fork_origin TEXT,\n agent TEXT NOT NULL DEFAULT '${fallbackAgent}',\n mcp_enabled TEXT,\n mcp_extra TEXT,\n last_shown_model TEXT,\n last_shown_effort TEXT,\n last_shown_agent TEXT,\n PRIMARY KEY (user_id, name),\n UNIQUE (user_id, message_thread_id)\n );\n\n CREATE INDEX IF NOT EXISTS idx_topics_lookup ON topics(user_id, message_thread_id);\n`);\n\n function tryMigrate(sql: string, expectedMsg?: string): void {\n try {\n db.exec(sql);\n } catch (e) {\n if (expectedMsg && errMsg(e).includes(expectedMsg)) return;\n logger.error({ err: e, sql }, \"DB migration failed\");\n throw e;\n }\n }\n\n type SqlValue = string | number | bigint | boolean | null | Uint8Array;\n\n function sqlValue(value: unknown): SqlValue {\n if (value === undefined || value === null) return null;\n if (\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"bigint\" ||\n typeof value === \"boolean\"\n ) {\n return value;\n }\n if (value instanceof Uint8Array) return value;\n return String(value);\n }\n\n function columnExists(table: string, column: string): boolean {\n return db\n .query<{ name: string }, []>(`PRAGMA table_info(${table})`)\n .all()\n .some((c) => c.name === column);\n }\n\n function tableSql(table: string): string | null {\n return (\n db\n .query<{ sql: string }, string>(\n \"SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?\",\n )\n .get(table)?.sql ?? null\n );\n }\n\n function dropColumnIfExists(table: string, column: string): void {\n if (columnExists(table, column)) {\n tryMigrate(`ALTER TABLE ${table} DROP COLUMN ${column}`);\n }\n }\n\n function topicTableNeedsRebuild(): boolean {\n const sql = tableSql(\"topics\");\n if (!sql) return false;\n const cols = db.query<{ name: string }, []>(\"PRAGMA table_info(topics)\").all();\n const names = new Set(cols.map((c) => c.name));\n return (\n names.has(\"forum_group_id\") ||\n names.has(\"system_prompt_extra\") ||\n names.has(\"model\") ||\n names.has(\"effort\") ||\n names.has(\"model_pinned\") ||\n names.has(\"effort_pinned\") ||\n names.has(\"memory_files\") ||\n names.has(\"memory_summary\") ||\n names.has(\"privacy_mode\") ||\n names.has(\"advisor_enabled\") ||\n names.has(\"agent_settings\") ||\n !/PRIMARY KEY \\(\\s*user_id\\s*,\\s*name\\s*\\)/i.test(sql)\n );\n }\n\n function normalizeStoredAgent(value: unknown): AgentKind {\n if (isAgentKind(value)) return value;\n if (value === \"hermes\" || value === \"alpha\") return \"maestro\";\n return fallbackAgent;\n }\n\n function rebuildTopicsTableIfNeeded(): void {\n if (!topicTableNeedsRebuild()) return;\n\n const cols = db.query<{ name: string }, []>(\"PRAGMA table_info(topics)\").all();\n const has = new Set(cols.map((c) => c.name));\n const pick = (row: Record<string, unknown>, column: string, fallback: unknown = null) =>\n has.has(column) ? (row[column] ?? fallback) : fallback;\n const descriptionFor = (row: Record<string, unknown>) =>\n pick(row, \"description\", pick(row, \"system_prompt_extra\", null));\n\n const rows = db\n .query<Record<string, unknown>, []>(\"SELECT rowid AS __rowid, * FROM topics\")\n .all()\n .sort((a, b) => {\n const aCreated = String(pick(a, \"created_at\", \"\"));\n const bCreated = String(pick(b, \"created_at\", \"\"));\n const byDate = bCreated.localeCompare(aCreated);\n if (byDate !== 0) return byDate;\n return Number(b.__rowid ?? 0) - Number(a.__rowid ?? 0);\n });\n\n const previousForeignKeys = db\n .query<{ foreign_keys: number }, []>(\"PRAGMA foreign_keys\")\n .get()?.foreign_keys;\n db.exec(\"PRAGMA foreign_keys = OFF\");\n try {\n db.transaction(() => {\n db.exec(\"DROP TABLE IF EXISTS topics_new\");\n db.exec(`\n CREATE TABLE topics_new (\n user_id TEXT NOT NULL REFERENCES users(id),\n name TEXT NOT NULL,\n message_thread_id INTEGER NOT NULL,\n session_id TEXT,\n created_at TEXT NOT NULL,\n description TEXT,\n fork_origin TEXT,\n agent TEXT NOT NULL DEFAULT '${fallbackAgent}',\n mcp_enabled TEXT,\n mcp_extra TEXT,\n last_shown_model TEXT,\n last_shown_effort TEXT,\n last_shown_agent TEXT,\n PRIMARY KEY (user_id, name),\n UNIQUE (user_id, message_thread_id)\n )\n `);\n\n const insert = db.query(`\n INSERT OR IGNORE INTO topics_new\n (user_id, name, message_thread_id, session_id, created_at, description,\n fork_origin, agent, mcp_enabled, mcp_extra, last_shown_model,\n last_shown_effort, last_shown_agent)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n `);\n let inserted = 0;\n const fallbackCreatedAt = new Date().toISOString();\n for (const row of rows) {\n const result = insert.run(\n String(pick(row, \"user_id\", \"\")),\n String(pick(row, \"name\", \"\")),\n Number(pick(row, \"message_thread_id\", 0)),\n sqlValue(pick(row, \"session_id\", null)),\n String(pick(row, \"created_at\", fallbackCreatedAt)),\n sqlValue(descriptionFor(row)),\n sqlValue(pick(row, \"fork_origin\", null)),\n normalizeStoredAgent(pick(row, \"agent\", fallbackAgent)),\n sqlValue(pick(row, \"mcp_enabled\", null)),\n sqlValue(pick(row, \"mcp_extra\", null)),\n sqlValue(pick(row, \"last_shown_model\", null)),\n sqlValue(pick(row, \"last_shown_effort\", null)),\n sqlValue(pick(row, \"last_shown_agent\", null)),\n );\n if (Number(result.changes ?? 0) > 0) inserted += 1;\n }\n\n db.exec(\"DROP TABLE topics\");\n db.exec(\"ALTER TABLE topics_new RENAME TO topics\");\n db.exec(\n \"CREATE INDEX IF NOT EXISTS idx_topics_lookup ON topics(user_id, message_thread_id)\",\n );\n logger.info(\n { migrated: inserted, skippedConflicts: rows.length - inserted },\n \"topics schema migrated to current user-scoped schema\",\n );\n })();\n } finally {\n db.exec(`PRAGMA foreign_keys = ${previousForeignKeys ? \"ON\" : \"OFF\"}`);\n }\n }\n\n rebuildTopicsTableIfNeeded();\n\n tryMigrate(\"ALTER TABLE topics ADD COLUMN fork_origin TEXT\", \"duplicate column\");\n tryMigrate(\n `ALTER TABLE topics ADD COLUMN agent TEXT NOT NULL DEFAULT '${fallbackAgent}'`,\n \"duplicate column\",\n );\n tryMigrate(\"ALTER TABLE topics ADD COLUMN mcp_enabled TEXT\", \"duplicate column\");\n tryMigrate(\"ALTER TABLE topics ADD COLUMN mcp_extra TEXT\", \"duplicate column\");\n tryMigrate(\"ALTER TABLE topics ADD COLUMN last_shown_model TEXT\", \"duplicate column\");\n tryMigrate(\"ALTER TABLE topics ADD COLUMN last_shown_effort TEXT\", \"duplicate column\");\n tryMigrate(\"ALTER TABLE topics ADD COLUMN last_shown_agent TEXT\", \"duplicate column\");\n\n for (const column of [\"privacy_mode\", \"advisor_enabled\", \"agent_settings\"]) {\n dropColumnIfExists(\"topics\", column);\n }\n dropColumnIfExists(\"users\", \"manager_session_id\");\n\n tryMigrate(\"DROP INDEX idx_topics_lookup\", \"no such index\");\n tryMigrate(\"CREATE INDEX IF NOT EXISTS idx_topics_lookup ON topics(user_id, message_thread_id)\");\n\n function assertColumn(table: string, column: string): void {\n if (!columnExists(table, column)) {\n throw new Error(`Schema migration failed: ${table}.${column} is missing`);\n }\n }\n\n for (const column of [\"id\", \"dm_session_id\", \"communicate_thread_id\"]) {\n assertColumn(\"users\", column);\n }\n for (const column of [\n \"user_id\",\n \"name\",\n \"message_thread_id\",\n \"session_id\",\n \"created_at\",\n \"description\",\n \"fork_origin\",\n \"agent\",\n \"mcp_enabled\",\n \"mcp_extra\",\n \"last_shown_model\",\n \"last_shown_effort\",\n \"last_shown_agent\",\n ]) {\n assertColumn(\"topics\", column);\n }\n}\n\nregisterStorageSchemaInitializer(initializeForumSchema, 10);\n\nexport function rowToTopic(row: TopicRow): ForumTopicInfo {\n if (!isAgentKind(row.agent)) throw new Error(`Invalid agent in DB: ${row.agent}`);\n const agent: AgentKind = row.agent;\n return {\n messageThreadId: row.message_thread_id,\n sessionId: row.session_id ?? \"\",\n createdAt: row.created_at,\n name: row.name,\n agent,\n ...(row.description && { description: row.description }),\n ...(row.fork_origin && { forkOrigin: row.fork_origin }),\n };\n}\n\nexport function flushSessionCache() {\n closeStorageDatabase();\n}\n\nexport { logger };\n",
29
+ "import { type AgentKind, isAgentKind } from \"#types\";\nimport { db } from \"./schema\";\n\nexport function getTopicAgent(userId: number, topicName: string): AgentKind {\n const row = db\n .query<{ agent: string | null }, [string, string]>(\n \"SELECT agent FROM topics WHERE user_id = ? AND name = ?\",\n )\n .get(String(userId), topicName);\n const value = row?.agent;\n if (!isAgentKind(value)) throw new Error(`Invalid agent in DB: ${value}`);\n return value;\n}\n\nexport function setTopicAgent(userId: number, topicName: string, agent: AgentKind): boolean {\n const result = db\n .query(\"UPDATE topics SET agent = ? WHERE user_id = ? AND name = ?\")\n .run(agent, String(userId), topicName);\n return result.changes > 0;\n}\n",
30
+ "import { resolveFallbackAgent } from \"#platform/config-helpers\";\nimport { type AgentKind, isAgentKind } from \"#types\";\nimport {\n db,\n type ForumTopicInfo,\n logger,\n rowToTopic,\n type TopicRow,\n type UserForumConfig,\n type UserRow,\n} from \"./schema\";\n\nexport function getUserConfig(userId: number): UserForumConfig | null {\n const user = db.query<UserRow, string>(\"SELECT * FROM users WHERE id = ?\").get(String(userId));\n if (!user) return null;\n\n const topicRows = db\n .query<TopicRow, string>(\"SELECT * FROM topics WHERE user_id = ?\")\n .all(String(userId));\n const topics: { [name: string]: ForumTopicInfo } = {};\n for (const row of topicRows) topics[row.name] = rowToTopic(row);\n\n return {\n ...(user.dm_session_id && { dmSessionId: user.dm_session_id }),\n ...(user.communicate_thread_id != null && { communicateThreadId: user.communicate_thread_id }),\n topics,\n };\n}\n\nexport function getTopicByName(userId: number, name: string): ForumTopicInfo | null {\n const row = db\n .query<TopicRow, [string, string]>(\"SELECT * FROM topics WHERE user_id = ? AND name = ?\")\n .get(String(userId), name);\n return row ? rowToTopic(row) : null;\n}\n\nexport function findUserByThread(\n threadId: number,\n): { userId: number; topic: ForumTopicInfo } | null {\n const row = db\n .query<TopicRow, number>(\"SELECT * FROM topics WHERE message_thread_id = ?\")\n .get(threadId);\n if (!row) return null;\n return { userId: Number(row.user_id), topic: rowToTopic(row) };\n}\n\nexport function getSessionForTopic(userId: number, topicName: string): string | null {\n const row = db\n .query<{ session_id: string | null }, [string, string]>(\n \"SELECT session_id FROM topics WHERE user_id = ? AND name = ?\",\n )\n .get(String(userId), topicName);\n return row?.session_id || null;\n}\n\nexport function getTopicNames(userId: number): string[] {\n const rows = db\n .query<{ name: string }, string>(\"SELECT name FROM topics WHERE user_id = ?\")\n .all(String(userId));\n return rows.map((r) => r.name);\n}\n\nexport function getAllTopics(userId: number): ForumTopicInfo[] {\n const rows = db\n .query<TopicRow, string>(\"SELECT * FROM topics WHERE user_id = ?\")\n .all(String(userId));\n return rows.map(rowToTopic);\n}\n\nexport function getAllUserIds(): number[] {\n const rows = db.query<{ id: string }, []>(\"SELECT id FROM users\").all();\n return rows.map((r) => Number(r.id)).filter((n) => !Number.isNaN(n));\n}\n\nexport function getCommunicateThreadId(userId: number): number | null {\n const row = db\n .query<{ communicate_thread_id: number | null }, string>(\n \"SELECT communicate_thread_id FROM users WHERE id = ?\",\n )\n .get(String(userId));\n return row?.communicate_thread_id ?? null;\n}\n\nexport function getDmSessionId(userId: number): string | null {\n const row = db\n .query<{ dm_session_id: string | null }, string>(\"SELECT dm_session_id FROM users WHERE id = ?\")\n .get(String(userId));\n return row?.dm_session_id ?? null;\n}\n\nexport function getTopicDescription(userId: number, topicName: string): string | null {\n const row = db\n .query<{ description: string | null }, [string, string]>(\n \"SELECT description FROM topics WHERE user_id = ? AND name = ?\",\n )\n .get(String(userId), topicName);\n return row?.description || null;\n}\n\nexport function getTopicMcpConfig(\n userId: number,\n topicName: string,\n): { enabled: string[] | null; extra: Record<string, unknown> } {\n const row = db\n .query<{ mcp_enabled: string | null; mcp_extra: string | null }, [string, string]>(\n \"SELECT mcp_enabled, mcp_extra FROM topics WHERE user_id = ? AND name = ?\",\n )\n .get(String(userId), topicName);\n let enabled: string[] | null = null;\n let extra: Record<string, unknown> = {};\n try {\n if (row?.mcp_enabled) enabled = JSON.parse(row.mcp_enabled);\n } catch (e) {\n logger.warn({ err: e }, \"getTopicMcpConfig: failed to parse mcp_enabled\");\n }\n try {\n if (row?.mcp_extra) extra = JSON.parse(row.mcp_extra);\n } catch (e) {\n logger.warn({ err: e }, \"getTopicMcpConfig: failed to parse mcp_extra\");\n }\n return { enabled, extra };\n}\n\nexport function addTopic(\n userId: number,\n name: string,\n messageThreadId: number,\n sessionId?: string,\n createdAt?: string,\n): boolean {\n if (name.startsWith(\"__\")) {\n logger.warn({ name }, \"addTopic: refusing reserved __ prefix\");\n return false;\n }\n db.query(\"INSERT OR IGNORE INTO users (id) VALUES (?)\").run(String(userId));\n db.query(`\n INSERT INTO topics (user_id, name, message_thread_id, session_id, created_at, agent)\n VALUES (?, ?, ?, ?, ?, ?)\n ON CONFLICT(user_id, name) DO UPDATE SET\n message_thread_id = excluded.message_thread_id,\n session_id = COALESCE(excluded.session_id, topics.session_id),\n created_at = excluded.created_at\n `).run(\n String(userId),\n name,\n messageThreadId,\n sessionId ?? null,\n createdAt ?? new Date().toISOString(),\n resolveFallbackAgent(),\n );\n return true;\n}\n\nexport function renameTopic(\n userId: number,\n oldName: string,\n newName: string,\n): { ok: true } | { ok: false; reason: \"not_found\" | \"name_taken\" } {\n if (oldName === newName) return { ok: true };\n if (getTopicByName(userId, newName)) return { ok: false, reason: \"name_taken\" };\n const result = db\n .prepare(\"UPDATE topics SET name = ? WHERE user_id = ? AND name = ?\")\n .run(newName, String(userId), oldName);\n if (result.changes === 0) return { ok: false, reason: \"not_found\" };\n return { ok: true };\n}\n\nexport function removeTopic(userId: number, name: string) {\n db.query(\"DELETE FROM topics WHERE user_id = ? AND name = ?\").run(String(userId), name);\n}\n\nexport function setSessionForTopic(userId: number, topicName: string, sessionId: string) {\n db.query(\"UPDATE topics SET session_id = ? WHERE user_id = ? AND name = ?\").run(\n sessionId,\n String(userId),\n topicName,\n );\n}\n\nexport function clearSessionForTopic(userId: number, topicName: string) {\n db.query(\"UPDATE topics SET session_id = NULL WHERE user_id = ? AND name = ?\").run(\n String(userId),\n topicName,\n );\n}\n\nexport function setDmSessionId(userId: number, sessionId: string) {\n db.query(`\n INSERT INTO users (id, dm_session_id) VALUES (?, ?)\n ON CONFLICT(id) DO UPDATE SET dm_session_id = excluded.dm_session_id\n `).run(String(userId), sessionId);\n}\n\nexport function clearDmSessionId(userId: number) {\n db.query(\"UPDATE users SET dm_session_id = NULL WHERE id = ?\").run(String(userId));\n}\n\nexport function setTopicDescription(\n userId: number,\n topicName: string,\n description: string,\n): boolean {\n const result = db\n .query(\"UPDATE topics SET description = ? WHERE user_id = ? AND name = ?\")\n .run(description, String(userId), topicName);\n return result.changes > 0;\n}\n\nexport function getLastShownConfig(\n userId: number,\n topicName: string,\n): { agent: AgentKind | null; model: string | null; effort: string | null } | null {\n type LastShownRow = {\n last_shown_agent: string | null;\n last_shown_model: string | null;\n last_shown_effort: string | null;\n };\n const row = db\n .query<LastShownRow, [string, string]>(\n \"SELECT last_shown_agent, last_shown_model, last_shown_effort FROM topics WHERE user_id = ? AND name = ?\",\n )\n .get(String(userId), topicName);\n if (!row) return null;\n const agent =\n row.last_shown_agent && isAgentKind(row.last_shown_agent) ? row.last_shown_agent : null;\n return { agent, model: row.last_shown_model, effort: row.last_shown_effort };\n}\n\nexport function setLastShownConfig(\n userId: number,\n topicName: string,\n agent: AgentKind,\n model: string,\n effort: string | undefined,\n): boolean {\n const result = db\n .query(\n \"UPDATE topics SET last_shown_agent = ?, last_shown_model = ?, last_shown_effort = ? WHERE user_id = ? AND name = ?\",\n )\n .run(agent, model, effort ?? null, String(userId), topicName);\n return result.changes > 0;\n}\n\nexport function setTopicForkOrigin(userId: number, topicName: string, origin: string): boolean {\n const result = db\n .query(\"UPDATE topics SET fork_origin = ? WHERE user_id = ? AND name = ?\")\n .run(origin, String(userId), topicName);\n return result.changes > 0;\n}\n\nexport function updateTopicThreadId(\n userId: number,\n topicName: string,\n newThreadId: number,\n): boolean {\n const result = db\n .query(\"UPDATE topics SET message_thread_id = ? WHERE user_id = ? AND name = ?\")\n .run(newThreadId, String(userId), topicName);\n return result.changes > 0;\n}\n\nexport function setTopicMcpEnabled(\n userId: number,\n topicName: string,\n enabled: string[] | null,\n): boolean {\n const value = enabled !== null ? JSON.stringify(enabled) : null;\n const result = db\n .query(\"UPDATE topics SET mcp_enabled = ? WHERE user_id = ? AND name = ?\")\n .run(value, String(userId), topicName);\n return result.changes > 0;\n}\n\nexport function setTopicMcpExtra(\n userId: number,\n topicName: string,\n extra: Record<string, unknown>,\n): boolean {\n const result = db\n .query(\"UPDATE topics SET mcp_extra = ? WHERE user_id = ? AND name = ?\")\n .run(JSON.stringify(extra), String(userId), topicName);\n return result.changes > 0;\n}\n",
31
+ "import { randomUUID } from \"node:crypto\";\nimport { db } from \"#storage/forum-db\";\nimport { TOPIC_MAINTENANCE_STALE_MS } from \"#storage/runtime-topic-state\";\nimport { registerStorageSchemaInitializer } from \"#storage/storage-host\";\n\nexport const RUNTIME_INSTANCE_ID = `${process.pid}-${randomUUID()}`;\nexport const TURN_LEASE_STALE_MS = 10_000;\n\nexport interface RuntimeTurnLease {\n topicId: string;\n queryId: string;\n ownerId: string;\n origin: string;\n startedAt: number;\n heartbeatAt: number;\n abortRequested: boolean;\n abortReason?: \"internal\" | \"external\";\n}\n\ninterface RuntimeTurnLeaseRow {\n topic_id: string;\n query_id: string;\n owner_id: string;\n origin: string;\n started_at: number | bigint;\n heartbeat_at: number | bigint;\n abort_requested: number;\n abort_reason: string | null;\n}\n\nregisterStorageSchemaInitializer((database) => {\n database.exec(`\n CREATE TABLE IF NOT EXISTS runtime_turn_leases (\n topic_id TEXT PRIMARY KEY,\n query_id TEXT NOT NULL UNIQUE,\n owner_id TEXT NOT NULL,\n origin TEXT NOT NULL,\n started_at INTEGER NOT NULL,\n heartbeat_at INTEGER NOT NULL,\n abort_requested INTEGER NOT NULL DEFAULT 0 CHECK (abort_requested IN (0, 1)),\n abort_reason TEXT CHECK (abort_reason IS NULL OR abort_reason IN ('internal', 'external'))\n );\n CREATE INDEX IF NOT EXISTS idx_runtime_turn_leases_heartbeat ON runtime_turn_leases(heartbeat_at);\n `);\n}, 33);\n\nfunction rowToLease(row: RuntimeTurnLeaseRow): RuntimeTurnLease {\n const abortReason =\n row.abort_reason === \"internal\" || row.abort_reason === \"external\"\n ? row.abort_reason\n : undefined;\n return {\n topicId: row.topic_id,\n queryId: row.query_id,\n ownerId: row.owner_id,\n origin: row.origin,\n startedAt: Number(row.started_at),\n heartbeatAt: Number(row.heartbeat_at),\n abortRequested: row.abort_requested !== 0,\n abortReason,\n };\n}\n\nexport function getRuntimeTurnLease(topicId: string, now = Date.now()): RuntimeTurnLease | null {\n const row = db\n .query<RuntimeTurnLeaseRow, [string]>(\"SELECT * FROM runtime_turn_leases WHERE topic_id = ?\")\n .get(topicId);\n if (!row) return null;\n const lease = rowToLease(row);\n return now - lease.heartbeatAt <= TURN_LEASE_STALE_MS ? lease : null;\n}\n\nexport function listRuntimeTurnLeases(now = Date.now()): RuntimeTurnLease[] {\n return db\n .query<RuntimeTurnLeaseRow, []>(\"SELECT * FROM runtime_turn_leases ORDER BY started_at ASC\")\n .all()\n .map(rowToLease)\n .filter((lease) => now - lease.heartbeatAt <= TURN_LEASE_STALE_MS);\n}\n\nexport function claimRuntimeTurnLease(\n input: {\n topicId: string;\n queryId: string;\n origin: string;\n ownerId?: string;\n },\n now = Date.now(),\n): boolean {\n const ownerId = input.ownerId ?? RUNTIME_INSTANCE_ID;\n const result = db\n .query(\n `INSERT INTO runtime_turn_leases\n (topic_id, query_id, owner_id, origin, started_at, heartbeat_at, abort_requested, abort_reason)\n SELECT ?, ?, ?, ?, ?, ?, 0, NULL\n WHERE NOT EXISTS (\n SELECT 1 FROM runtime_topic_state\n WHERE topic_id = ? AND maintenance = 1 AND heartbeat_at >= ?\n )\n ON CONFLICT(topic_id) DO UPDATE SET\n query_id = excluded.query_id,\n owner_id = excluded.owner_id,\n origin = excluded.origin,\n started_at = excluded.started_at,\n heartbeat_at = excluded.heartbeat_at,\n abort_requested = 0,\n abort_reason = NULL\n WHERE (runtime_turn_leases.owner_id = excluded.owner_id\n OR runtime_turn_leases.heartbeat_at < ?)\n AND NOT EXISTS (\n SELECT 1 FROM runtime_topic_state\n WHERE topic_id = excluded.topic_id AND maintenance = 1 AND heartbeat_at >= ?\n )`,\n )\n .run(\n input.topicId,\n input.queryId,\n ownerId,\n input.origin,\n now,\n now,\n input.topicId,\n now - TOPIC_MAINTENANCE_STALE_MS,\n now - TURN_LEASE_STALE_MS,\n now - TOPIC_MAINTENANCE_STALE_MS,\n );\n return Number(result.changes ?? 0) > 0;\n}\n\nexport function heartbeatRuntimeTurnLease(\n topicId: string,\n queryId: string,\n ownerId = RUNTIME_INSTANCE_ID,\n now = Date.now(),\n): { owned: boolean; abortRequested: boolean; abortReason?: \"internal\" | \"external\" } {\n const updated = db\n .query(\n `UPDATE runtime_turn_leases\n SET heartbeat_at = ?\n WHERE topic_id = ? AND query_id = ? AND owner_id = ?`,\n )\n .run(now, topicId, queryId, ownerId);\n if (Number(updated.changes ?? 0) === 0) return { owned: false, abortRequested: false };\n\n const row = db\n .query<{ abort_requested: number; abort_reason: string | null }, [string, string, string]>(\n `SELECT abort_requested, abort_reason\n FROM runtime_turn_leases\n WHERE topic_id = ? AND query_id = ? AND owner_id = ?`,\n )\n .get(topicId, queryId, ownerId);\n const abortReason =\n row?.abort_reason === \"internal\" || row?.abort_reason === \"external\"\n ? row.abort_reason\n : undefined;\n return {\n owned: Boolean(row),\n abortRequested: row?.abort_requested !== 0,\n abortReason,\n };\n}\n\nexport function requestRuntimeTurnAbort(topicId: string, reason: \"internal\" | \"external\"): boolean {\n const result = db\n .query(\n `UPDATE runtime_turn_leases\n SET abort_requested = 1,\n abort_reason = CASE\n WHEN abort_reason = 'external' THEN abort_reason\n ELSE ?\n END\n WHERE topic_id = ? AND heartbeat_at >= ?`,\n )\n .run(reason, topicId, Date.now() - TURN_LEASE_STALE_MS);\n return Number(result.changes ?? 0) > 0;\n}\n\nexport function releaseRuntimeTurnLease(\n topicId: string,\n queryId: string,\n ownerId = RUNTIME_INSTANCE_ID,\n): boolean {\n const result = db\n .query(\n `DELETE FROM runtime_turn_leases\n WHERE topic_id = ? AND query_id = ? AND owner_id = ?`,\n )\n .run(topicId, queryId, ownerId);\n return Number(result.changes ?? 0) > 0;\n}\n",
32
+ "import { logger } from \"#platform/logger\";\nimport { db } from \"#storage/forum-db\";\nimport { RUNTIME_INSTANCE_ID } from \"#storage/runtime-leases\";\nimport { registerStorageSchemaInitializer } from \"#storage/storage-host\";\n\nexport const PROCESS_LEASE_STALE_MS = 5_000;\nexport const PROCESS_LEASE_HEARTBEAT_MS = 1_000;\n\nexport interface RuntimeProcessLease {\n role: string;\n ownerId: string;\n pid: number;\n startedAt: number;\n heartbeatAt: number;\n}\n\nexport interface RuntimeProcessLeaseHandle extends RuntimeProcessLease {\n stop(): void;\n}\n\nexport interface AcquireRuntimeProcessLeaseOptions {\n ownerId?: string;\n pid?: number;\n now?: number;\n staleMs?: number;\n heartbeatMs?: number;\n onLost?: () => void;\n}\n\nexport interface WaitForRuntimeProcessLeaseOptions extends AcquireRuntimeProcessLeaseOptions {\n waitMs?: number;\n retryMs?: number;\n}\n\nexport interface WaitForRequiredRuntimeProcessLeaseOptions\n extends WaitForRuntimeProcessLeaseOptions {\n workloadName?: string;\n}\n\ninterface RuntimeProcessLeaseRow {\n role: string;\n owner_id: string;\n pid: number | bigint;\n started_at: number | bigint;\n heartbeat_at: number | bigint;\n}\n\nregisterStorageSchemaInitializer((database) => {\n database.exec(`\n CREATE TABLE IF NOT EXISTS runtime_process_leases (\n role TEXT PRIMARY KEY,\n owner_id TEXT NOT NULL UNIQUE,\n pid INTEGER NOT NULL,\n started_at INTEGER NOT NULL,\n heartbeat_at INTEGER NOT NULL\n );\n CREATE INDEX IF NOT EXISTS idx_runtime_process_leases_heartbeat ON runtime_process_leases(heartbeat_at);\n `);\n}, 34);\n\nfunction rowToLease(row: RuntimeProcessLeaseRow): RuntimeProcessLease {\n return {\n role: row.role,\n ownerId: row.owner_id,\n pid: Number(row.pid),\n startedAt: Number(row.started_at),\n heartbeatAt: Number(row.heartbeat_at),\n };\n}\n\nfunction isProcessAlive(pid: number): boolean {\n if (!Number.isSafeInteger(pid) || pid <= 0) return false;\n try {\n process.kill(pid, 0);\n return true;\n } catch (error) {\n return (error as NodeJS.ErrnoException).code !== \"ESRCH\";\n }\n}\n\nexport function isRuntimeProcessLeaseAlive(lease: RuntimeProcessLease): boolean {\n return Date.now() - lease.heartbeatAt <= PROCESS_LEASE_STALE_MS && isProcessAlive(lease.pid);\n}\n\nfunction removeDeadRuntimeProcessLease(role: string): void {\n const row = db\n .query<RuntimeProcessLeaseRow, [string]>(\"SELECT * FROM runtime_process_leases WHERE role = ?\")\n .get(role);\n if (!row) return;\n const lease = rowToLease(row);\n if (isProcessAlive(lease.pid)) return;\n db.query(\n `DELETE FROM runtime_process_leases\n WHERE role = ? AND owner_id = ? AND pid = ? AND heartbeat_at = ?`,\n ).run(lease.role, lease.ownerId, lease.pid, lease.heartbeatAt);\n}\n\nexport function getRuntimeProcessLease(\n role: string,\n now = Date.now(),\n staleMs = PROCESS_LEASE_STALE_MS,\n): RuntimeProcessLease | null {\n const row = db\n .query<RuntimeProcessLeaseRow, [string]>(\"SELECT * FROM runtime_process_leases WHERE role = ?\")\n .get(role);\n if (!row) return null;\n const lease = rowToLease(row);\n return now - lease.heartbeatAt <= staleMs ? lease : null;\n}\n\n/** List healthy process leases, optionally restricted to one role prefix. */\nexport function listRuntimeProcessLeases(\n rolePrefix = \"\",\n now = Date.now(),\n staleMs = PROCESS_LEASE_STALE_MS,\n): RuntimeProcessLease[] {\n const rows = rolePrefix\n ? db\n .query<RuntimeProcessLeaseRow, [string]>(\n \"SELECT * FROM runtime_process_leases WHERE role LIKE ? ORDER BY role\",\n )\n .all(`${rolePrefix}%`)\n : db\n .query<RuntimeProcessLeaseRow, []>(\"SELECT * FROM runtime_process_leases ORDER BY role\")\n .all();\n return rows.map(rowToLease).filter((lease) => now - lease.heartbeatAt <= staleMs);\n}\n\n/** Remove crash leftovers without evicting a live process whose heartbeat is delayed. */\nexport function removeDeadRuntimeProcessLeases(rolePrefix = \"\"): number {\n const rows = rolePrefix\n ? db\n .query<RuntimeProcessLeaseRow, [string]>(\n \"SELECT * FROM runtime_process_leases WHERE role LIKE ?\",\n )\n .all(`${rolePrefix}%`)\n : db.query<RuntimeProcessLeaseRow, []>(\"SELECT * FROM runtime_process_leases\").all();\n let removed = 0;\n for (const row of rows) {\n const lease = rowToLease(row);\n if (isProcessAlive(lease.pid)) continue;\n const result = db\n .query(\n `DELETE FROM runtime_process_leases\n WHERE role = ? AND owner_id = ? AND pid = ? AND heartbeat_at = ?`,\n )\n .run(lease.role, lease.ownerId, lease.pid, lease.heartbeatAt);\n removed += Number(result.changes ?? 0);\n }\n return removed;\n}\n\nexport function heartbeatRuntimeProcessLease(\n role: string,\n ownerId: string,\n now = Date.now(),\n): boolean {\n const result = db\n .query(\n `UPDATE runtime_process_leases\n SET heartbeat_at = ?\n WHERE role = ? AND owner_id = ?`,\n )\n .run(now, role, ownerId);\n return Number(result.changes ?? 0) > 0;\n}\n\nexport function releaseRuntimeProcessLease(role: string, ownerId: string): boolean {\n const result = db\n .query(\"DELETE FROM runtime_process_leases WHERE role = ? AND owner_id = ?\")\n .run(role, ownerId);\n return Number(result.changes ?? 0) > 0;\n}\n\n/**\n * Claim one cross-process role and keep it alive with a SQLite heartbeat.\n * A process that exits without cleanup is replaceable after `staleMs`.\n */\nexport function acquireRuntimeProcessLease(\n role: string,\n options: AcquireRuntimeProcessLeaseOptions = {},\n): RuntimeProcessLeaseHandle | null {\n const normalizedRole = role.trim();\n if (!normalizedRole) throw new Error(\"runtime process lease role must not be empty\");\n removeDeadRuntimeProcessLease(normalizedRole);\n const ownerId = options.ownerId ?? `${RUNTIME_INSTANCE_ID}:${normalizedRole}`;\n const pid = options.pid ?? process.pid;\n const now = options.now ?? Date.now();\n const staleMs = options.staleMs ?? PROCESS_LEASE_STALE_MS;\n const result = db\n .query(\n `INSERT INTO runtime_process_leases (role, owner_id, pid, started_at, heartbeat_at)\n VALUES (?, ?, ?, ?, ?)\n ON CONFLICT(role) DO UPDATE SET\n owner_id = excluded.owner_id,\n pid = excluded.pid,\n started_at = excluded.started_at,\n heartbeat_at = excluded.heartbeat_at\n WHERE runtime_process_leases.heartbeat_at < ?`,\n )\n .run(normalizedRole, ownerId, pid, now, now, now - staleMs);\n if (Number(result.changes ?? 0) === 0) return null;\n\n let stopped = false;\n const heartbeatMs = options.heartbeatMs ?? PROCESS_LEASE_HEARTBEAT_MS;\n let lastHeartbeatAt = now;\n const lose = () => {\n stopped = true;\n clearInterval(timer);\n try {\n options.onLost?.();\n } catch (error) {\n logger.error({ err: error, role: normalizedRole }, \"process lease: onLost handler failed\");\n }\n };\n // A timer callback must never throw: an uncaught exception there kills a\n // daemon (and hangs `bun test` on Bun 1.2.x). A failed heartbeat write (busy\n // past the timeout, I/O error) is retried on the next tick; once no heartbeat\n // has succeeded for `staleMs`, another process may legitimately have taken\n // the role, so the lease is treated as lost.\n const timer = setInterval(() => {\n if (stopped) return;\n let alive: boolean;\n try {\n alive = heartbeatRuntimeProcessLease(normalizedRole, ownerId);\n } catch (error) {\n logger.warn({ err: error, role: normalizedRole }, \"process lease: heartbeat failed\");\n if (Date.now() - lastHeartbeatAt >= staleMs) lose();\n return;\n }\n if (alive) {\n lastHeartbeatAt = Date.now();\n return;\n }\n lose();\n }, heartbeatMs);\n timer.unref?.();\n\n return {\n role: normalizedRole,\n ownerId,\n pid,\n startedAt: now,\n heartbeatAt: now,\n stop() {\n if (stopped) return;\n stopped = true;\n clearInterval(timer);\n releaseRuntimeProcessLease(normalizedRole, ownerId);\n },\n };\n}\n\n/**\n * Wait through a graceful handoff or stale-heartbeat window instead of making\n * process supervisors burn through their restart budget on a transient clash.\n */\nexport async function waitForRuntimeProcessLease(\n role: string,\n options: WaitForRuntimeProcessLeaseOptions = {},\n): Promise<RuntimeProcessLeaseHandle | null> {\n const {\n waitMs = PROCESS_LEASE_STALE_MS + PROCESS_LEASE_HEARTBEAT_MS,\n retryMs = 100,\n ...acquireOptions\n } = options;\n const deadline = Date.now() + Math.max(0, waitMs);\n const interval = Math.max(1, retryMs);\n while (true) {\n const lease = acquireRuntimeProcessLease(role, acquireOptions);\n if (lease) return lease;\n const remaining = deadline - Date.now();\n if (remaining <= 0) return null;\n await new Promise<void>((resolve) => setTimeout(resolve, Math.min(interval, remaining)));\n }\n}\n\n/** Claim a process role or report the live owner in a user-facing error. */\nexport async function waitForRequiredRuntimeProcessLease(\n role: string,\n options: WaitForRequiredRuntimeProcessLeaseOptions = {},\n): Promise<RuntimeProcessLeaseHandle> {\n const { workloadName = role, ...leaseOptions } = options;\n const lease = await waitForRuntimeProcessLease(role, leaseOptions);\n if (lease) return lease;\n const current = getRuntimeProcessLease(role);\n throw new Error(`${workloadName} is already running${current ? ` (pid ${current.pid})` : \"\"}`);\n}\n",
33
+ "import { createHash } from \"node:crypto\";\nimport {\n closeSync,\n mkdirSync,\n openSync,\n readdirSync,\n readFileSync,\n statSync,\n unlinkSync,\n writeFileSync,\n} from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { resolveStorageSessionAsksDir } from \"#storage/storage-host\";\n\nexport const PENDING_ASK_TTL_MS = 15 * 60 * 1000;\n\nexport type PendingAskState =\n | \"requested\"\n | \"reply_ready\"\n | \"queued_for_caller\"\n | \"injecting_to_caller\";\n\nexport type PendingAskUserId = number | string;\n\nexport interface PendingAskRecord {\n userId: PendingAskUserId;\n from: string;\n to: string;\n requestId: string;\n contextId?: string;\n state: PendingAskState;\n createdAt: string;\n updatedAt: string;\n}\n\nexport interface AskReplySource {\n from?: string;\n requestId?: string;\n contextId?: string;\n}\n\nexport interface PendingAskKey {\n userId: PendingAskUserId;\n from: string;\n to: string;\n}\n\nexport interface PendingAskIdentity extends PendingAskKey {\n requestId?: string;\n}\n\ntype AskKey = PendingAskKey;\ntype AskIdentity = PendingAskIdentity;\n\nfunction pendingAskDir(userId: PendingAskUserId): string {\n const rawUserId = String(userId);\n const safeUserId =\n /^[A-Za-z0-9][A-Za-z0-9_.@-]{0,255}$/.test(rawUserId) && !rawUserId.includes(\"..\")\n ? rawUserId\n : `sha256-${createHash(\"sha256\").update(rawUserId).digest(\"hex\")}`;\n return join(resolveStorageSessionAsksDir(), safeUserId);\n}\n\nconst ASK_FILENAME_PREFIX = \"v3-\";\nconst V2_ASK_FILENAME_PREFIX = \"v2-\";\n\nfunction encodeAskKey(key: Pick<AskKey, \"from\" | \"to\">): string {\n return JSON.stringify([key.from, key.to]);\n}\n\nfunction pendingAskPath(key: AskKey): string {\n const digest = createHash(\"sha256\").update(encodeAskKey(key)).digest(\"hex\");\n return join(pendingAskDir(key.userId), `${ASK_FILENAME_PREFIX}${digest}.pending`);\n}\n\nfunction v2PendingAskPath(key: AskKey): string {\n const encoded = Buffer.from(encodeAskKey(key), \"utf8\").toString(\"base64url\");\n return join(pendingAskDir(key.userId), `${V2_ASK_FILENAME_PREFIX}${encoded}.pending`);\n}\n\nfunction legacyPendingAskPath(key: AskKey): string | null {\n if (\n key.from.includes(\"/\") ||\n key.from.includes(\"\\\\\") ||\n key.to.includes(\"/\") ||\n key.to.includes(\"\\\\\") ||\n key.from.includes(\"\\0\") ||\n key.to.includes(\"\\0\")\n ) {\n return null;\n }\n const dir = pendingAskDir(key.userId);\n const candidate = join(dir, `${key.from}___${key.to}.pending`);\n return dirname(candidate) === dir ? candidate : null;\n}\n\nfunction parsePendingAskFilename(fileName: string): { from: string; to: string } | null {\n if (!fileName.endsWith(\".pending\")) return null;\n const raw = fileName.slice(0, -\".pending\".length);\n if (raw.startsWith(V2_ASK_FILENAME_PREFIX)) {\n try {\n const decoded = JSON.parse(\n Buffer.from(raw.slice(V2_ASK_FILENAME_PREFIX.length), \"base64url\").toString(\"utf8\"),\n ) as unknown;\n if (\n Array.isArray(decoded) &&\n decoded.length === 2 &&\n decoded.every((part) => typeof part === \"string\")\n ) {\n return { from: decoded[0], to: decoded[1] };\n }\n } catch {\n // A legacy caller key may itself start with \"v2-\". Fall through to the\n // delimiter parser when the suffix is not a valid v2 payload.\n }\n }\n\n // Read files created before the opaque v2 key was introduced.\n const sep = raw.indexOf(\"___\");\n if (sep < 0) return null;\n return { from: raw.slice(0, sep), to: raw.slice(sep + 3) };\n}\n\nfunction readPendingAskFile(path: string, fallback: AskKey): PendingAskRecord | null {\n try {\n const raw = readFileSync(path, \"utf8\").trim();\n if (!raw) return null;\n if (!raw.startsWith(\"{\")) {\n const ts = new Date(statSync(path).mtimeMs).toISOString();\n return {\n userId: fallback.userId,\n from: fallback.from,\n to: fallback.to,\n requestId: raw,\n state: \"requested\",\n createdAt: ts,\n updatedAt: ts,\n };\n }\n const parsed = JSON.parse(raw) as Partial<PendingAskRecord>;\n if (!parsed.requestId || !parsed.from || !parsed.to) return null;\n if (parsed.userId !== undefined && String(parsed.userId) !== String(fallback.userId))\n return null;\n if (fallback.from && parsed.from !== fallback.from) return null;\n if (fallback.to && parsed.to !== fallback.to) return null;\n const now = new Date().toISOString();\n return {\n // The directory selected by the caller is authoritative. Never let a\n // tampered record redirect a later migration/update into another user root.\n userId: fallback.userId,\n from: parsed.from,\n to: parsed.to,\n requestId: parsed.requestId,\n contextId: parsed.contextId,\n state: parsed.state ?? \"requested\",\n createdAt: parsed.createdAt ?? now,\n updatedAt: parsed.updatedAt ?? parsed.createdAt ?? now,\n };\n } catch {\n return null;\n }\n}\n\nfunction isStale(record: PendingAskRecord | null, path: string): boolean {\n const ts = record ? Date.parse(record.updatedAt || record.createdAt) : Number.NaN;\n if (Number.isFinite(ts)) return Date.now() - ts > PENDING_ASK_TTL_MS;\n try {\n return Date.now() - statSync(path).mtimeMs > PENDING_ASK_TTL_MS;\n } catch {\n return false;\n }\n}\n\nfunction writePendingAsk(record: PendingAskRecord): void {\n const path = pendingAskPath(record);\n mkdirSync(pendingAskDir(record.userId), { recursive: true });\n writeFileSync(path, `${JSON.stringify(record)}\\n`);\n}\n\nfunction writePendingAskIfAbsent(record: PendingAskRecord): boolean {\n const path = pendingAskPath(record);\n mkdirSync(pendingAskDir(record.userId), { recursive: true });\n let fd: number | null = null;\n try {\n fd = openSync(path, \"wx\");\n writeFileSync(fd, `${JSON.stringify(record)}\\n`);\n return true;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"EEXIST\") return false;\n throw error;\n } finally {\n if (fd !== null) closeSync(fd);\n }\n}\n\nfunction readPendingAsk(key: AskKey): { path: string; record: PendingAskRecord } | null {\n const canonicalPath = pendingAskPath(key);\n const canonical = readPendingAskFile(canonicalPath, key);\n if (canonical && canonical.from === key.from && canonical.to === key.to) {\n return { path: canonicalPath, record: canonical };\n }\n\n for (const compatibilityPath of [v2PendingAskPath(key), legacyPendingAskPath(key)]) {\n if (!compatibilityPath) continue;\n const legacy = readPendingAskFile(compatibilityPath, key);\n if (!legacy || legacy.from !== key.from || legacy.to !== key.to) continue;\n\n const migrated = writePendingAskIfAbsent(legacy);\n const next = migrated ? legacy : readPendingAskFile(canonicalPath, key);\n if (next && next.from === key.from && next.to === key.to) {\n try {\n unlinkSync(compatibilityPath);\n } catch {\n // The canonical record is durable; concurrent cleanup may win.\n }\n return { path: canonicalPath, record: next };\n }\n\n // Never discard a valid compatibility record when a corrupt or racing\n // canonical file cannot be trusted.\n return { path: compatibilityPath, record: legacy };\n }\n\n return null;\n}\n\nexport function createPendingAsk(args: {\n userId: PendingAskUserId;\n from: string;\n to: string;\n requestId: string;\n contextId?: string;\n}):\n | { ok: true; record: PendingAskRecord }\n | { ok: false; existing: PendingAskRecord | null; stale: boolean } {\n const migrated = readPendingAsk(args);\n if (migrated && !isStale(migrated.record, migrated.path)) {\n return { ok: false, existing: migrated.record, stale: false };\n }\n if (migrated) {\n try {\n unlinkSync(migrated.path);\n } catch {\n return { ok: false, existing: migrated.record, stale: true };\n }\n }\n const path = pendingAskPath(args);\n const now = new Date().toISOString();\n const record: PendingAskRecord = {\n userId: args.userId,\n from: args.from,\n to: args.to,\n requestId: args.requestId,\n contextId: args.contextId,\n state: \"requested\",\n createdAt: now,\n updatedAt: now,\n };\n\n mkdirSync(pendingAskDir(args.userId), { recursive: true });\n for (let attempt = 0; attempt < 2; attempt++) {\n let fd: number | null = null;\n try {\n fd = openSync(path, \"wx\");\n writeFileSync(fd, `${JSON.stringify(record)}\\n`);\n return { ok: true, record };\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== \"EEXIST\") throw err;\n const existing = readPendingAskFile(path, args);\n if (!isStale(existing, path)) return { ok: false, existing, stale: false };\n try {\n unlinkSync(path);\n } catch {\n return { ok: false, existing, stale: true };\n }\n } finally {\n if (fd !== null) closeSync(fd);\n }\n }\n\n return { ok: false, existing: readPendingAskFile(path, args), stale: true };\n}\n\nexport function markPendingAskState(\n args: AskIdentity & { state: PendingAskState },\n): PendingAskRecord | null {\n const pending = readPendingAsk(args);\n if (!pending) return null;\n const record = pending.record;\n if (args.requestId && record.requestId !== args.requestId) return record;\n const next = {\n ...record,\n state: args.state,\n updatedAt: new Date().toISOString(),\n };\n writePendingAsk(next);\n if (pending.path !== pendingAskPath(next)) {\n try {\n unlinkSync(pending.path);\n } catch {\n // The canonical v3 record already contains the update.\n }\n }\n return next;\n}\n\nexport function clearPendingAsk(args: AskIdentity): boolean {\n const pending = readPendingAsk(args);\n const path = pending?.path ?? pendingAskPath(args);\n const record = pending?.record ?? null;\n if (args.requestId && record && record.requestId !== args.requestId) return false;\n try {\n unlinkSync(path);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Retry-safe, requestId-scoped release of one ask's pending marker: `true`\n * once no marker of *this* ask remains (it was removed now, was already gone,\n * or the slot now belongs to a different — newer — ask, which is never\n * touched). `false` means our marker is still there (the unlink failed), so\n * whoever holds the ask's durable row must keep it and try again. Idempotent.\n * May throw on unexpected I/O errors; callers treat that as `false`.\n */\nexport function releasePendingAsk(args: PendingAskKey & { requestId: string }): boolean {\n if (clearPendingAsk(args)) return true;\n const still = readPendingAsk(args);\n return !still || still.record.requestId !== args.requestId;\n}\n\nexport function markPendingAskSources(args: {\n userId: PendingAskUserId;\n callerTopic: string;\n sources?: AskReplySource[];\n state: PendingAskState;\n}): void {\n for (const source of args.sources ?? []) {\n if (!source.from) continue;\n markPendingAskState({\n userId: args.userId,\n from: args.callerTopic,\n to: source.from,\n requestId: source.requestId,\n state: args.state,\n });\n }\n}\n\nexport function clearPendingAskSources(args: {\n userId: PendingAskUserId;\n callerTopic: string;\n sources?: AskReplySource[];\n}): void {\n for (const source of args.sources ?? []) {\n if (!source.from) continue;\n clearPendingAsk({\n userId: args.userId,\n from: args.callerTopic,\n to: source.from,\n requestId: source.requestId,\n });\n }\n}\n\nexport function listPendingAsksForCaller(args: {\n userId: PendingAskUserId;\n from: string;\n}): PendingAskRecord[] {\n const dir = pendingAskDir(args.userId);\n let files: string[];\n try {\n files = readdirSync(dir);\n } catch {\n return [];\n }\n\n const records = new Map<string, PendingAskRecord>();\n for (const fileName of files) {\n const isV3 = fileName.startsWith(ASK_FILENAME_PREFIX);\n const parsed = isV3 ? { from: args.from, to: \"\" } : parsePendingAskFilename(fileName);\n if (!parsed) continue;\n const path = join(dir, fileName);\n const record = readPendingAskFile(path, {\n userId: args.userId,\n from: parsed.from,\n to: parsed.to,\n });\n if (!record || record.from !== args.from) continue;\n if (isStale(record, path)) {\n try {\n unlinkSync(path);\n } catch {\n // Best-effort stale cleanup only.\n }\n continue;\n }\n const canonical = readPendingAsk(record);\n if (!canonical || canonical.record.from !== args.from) continue;\n if (path !== canonical.path) {\n try {\n unlinkSync(path);\n } catch {\n // Canonical record wins; duplicate compatibility cleanup is best effort.\n }\n }\n if (isStale(canonical.record, canonical.path)) {\n try {\n unlinkSync(canonical.path);\n } catch {\n // Best-effort stale cleanup only.\n }\n continue;\n }\n records.set(encodeAskKey(canonical.record), canonical.record);\n }\n return [...records.values()];\n}\n\n/** Remove durable ask edges to or from a topic that no longer exists. */\nexport function deletePendingAsksForTopic(args: {\n userId: PendingAskUserId;\n topicName: string;\n}): number {\n const dir = pendingAskDir(args.userId);\n let files: string[];\n try {\n files = readdirSync(dir);\n } catch {\n return 0;\n }\n\n let deleted = 0;\n for (const fileName of files) {\n const path = join(dir, fileName);\n const parsed = parsePendingAskFilename(fileName);\n const record = readPendingAskFile(path, {\n userId: args.userId,\n from: parsed?.from ?? \"\",\n to: parsed?.to ?? \"\",\n });\n const from = record?.from ?? parsed?.from;\n const to = record?.to ?? parsed?.to;\n if (from !== args.topicName && to !== args.topicName) continue;\n try {\n unlinkSync(path);\n deleted++;\n } catch {\n // Best-effort teardown; stale cleanup will retry any file that survives.\n }\n }\n return deleted;\n}\n\nexport function describePendingAskState(state: PendingAskState): string {\n switch (state) {\n case \"requested\":\n return \"대상 세션 처리 중\";\n case \"reply_ready\":\n return \"응답 생성 완료, 이 세션 주입 준비 중\";\n case \"queued_for_caller\":\n return \"응답 생성 완료, 이 세션 실행 종료 후 주입 대기 중\";\n case \"injecting_to_caller\":\n return \"응답을 이 세션에 주입 중\";\n }\n}\n",
34
+ "import type { StorageDatabase, StorageHostConfig } from \"#storage/storage-contract\";\nimport {\n configureStorageHost as configureInternalStorageHost,\n resetStorageHost as resetInternalStorageHost,\n storageDatabase,\n} from \"#storage/storage-host\";\n\n/** Configure the lazy process-local storage boundary and return an idempotent disposer. */\nexport const configureStorageHost: (options: StorageHostConfig) => () => void =\n configureInternalStorageHost;\n\n/** Remove every configured host layer and restore standalone fallbacks. */\nexport const resetStorageHost: () => void = resetInternalStorageHost;\n\n/** Stable structurally typed proxy over the currently active database. */\nexport const db: StorageDatabase = storageDatabase;\n",
35
+ "import { existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { logger } from \"#platform/logger\";\nimport { sanitizeFileName } from \"#security/sanitize\";\nimport { resolveStorageDataDir } from \"#storage/storage-host\";\nimport type { TaskSnapshot } from \"#types\";\n\n/**\n * Otium-owned task store, shared by every agent backend.\n *\n * Provider-native task/todo stores are not authoritative because they live\n * inside one SDK session. This store is keyed by Otium topic context so task\n * state survives agent switches and feeds the same live task panel for\n * claude/codex/maestro.\n */\nexport type StoredTask = TaskSnapshot;\n\nexport const TASK_STATUS_VALUES = [\"pending\", \"in_progress\", \"completed\"] as const;\n\ninterface TaskFileShape {\n version: 1;\n tasks: StoredTask[];\n}\n\nfunction safeTaskScopeKey(scopeKey: string): string {\n const safe = sanitizeFileName(scopeKey);\n if (!safe || safe === \".\" || safe === \"..\") {\n throw new Error(`tasks: refusing unsafe scope key: ${scopeKey}`);\n }\n return safe;\n}\n\nexport function taskScopeKey(opts: { topicId?: string; session: string }): string {\n return opts.topicId?.trim() || opts.session || \"default\";\n}\n\nexport function getTaskFilePath(userId: number | string, scopeKey: string): string {\n void userId;\n return join(resolveStorageDataDir(), \"tasks\", `${safeTaskScopeKey(scopeKey)}.json`);\n}\n\nexport function readTasks(userId: number | string, scopeKey: string): StoredTask[] {\n const path = getTaskFilePath(userId, scopeKey);\n if (!existsSync(path)) return [];\n try {\n const parsed = JSON.parse(readFileSync(path, \"utf-8\")) as TaskFileShape;\n return Array.isArray(parsed?.tasks) ? parsed.tasks : [];\n } catch (e) {\n logger.warn({ err: e, path }, \"tasks: failed to read task store\");\n return [];\n }\n}\n\nexport function writeTasks(userId: number | string, scopeKey: string, tasks: StoredTask[]): void {\n const path = getTaskFilePath(userId, scopeKey);\n mkdirSync(dirname(path), { recursive: true });\n const payload: TaskFileShape = { version: 1, tasks };\n const tmp = `${path}.${process.pid}.tmp`;\n writeFileSync(tmp, JSON.stringify(payload, null, 2), \"utf-8\");\n renameSync(tmp, path);\n}\n\nexport function taskFileMtimeNs(userId: number | string, scopeKey: string): bigint | null {\n try {\n return statSync(getTaskFilePath(userId, scopeKey), { bigint: true }).mtimeNs;\n } catch {\n return null;\n }\n}\n\nexport interface TaskCreateInput {\n subject: string;\n activeForm?: string;\n blockedBy?: string[];\n owner?: string;\n}\n\nexport interface TaskUpdateInput {\n id: string;\n status?: StoredTask[\"status\"];\n subject?: string;\n activeForm?: string;\n blockedBy?: string[];\n owner?: string;\n}\n\nfunction nextTaskId(tasks: StoredTask[]): number {\n let max = 0;\n for (const task of tasks) {\n const n = Number(task.id);\n if (Number.isInteger(n) && n > max) max = n;\n }\n return max + 1;\n}\n\nexport function createTasks(\n tasks: StoredTask[],\n inputs: TaskCreateInput[],\n): { tasks: StoredTask[]; created: StoredTask[] } {\n const out = [...tasks];\n const created: StoredTask[] = [];\n let id = nextTaskId(out);\n for (const input of inputs) {\n const task: StoredTask = {\n id: String(id++),\n subject: input.subject,\n status: \"pending\",\n ...(input.blockedBy && input.blockedBy.length > 0 ? { blockedBy: input.blockedBy } : {}),\n ...(input.activeForm ? { activeForm: input.activeForm } : {}),\n ...(input.owner ? { owner: input.owner } : {}),\n };\n out.push(task);\n created.push(task);\n }\n return { tasks: out, created };\n}\n\nexport function updateTasks(\n tasks: StoredTask[],\n updates: TaskUpdateInput[],\n): { tasks: StoredTask[]; missing: string[] } {\n const out = tasks.map((task) => ({ ...task }));\n const byId = new Map(out.map((task) => [task.id, task]));\n const missing: string[] = [];\n for (const update of updates) {\n const task = byId.get(update.id);\n if (!task) {\n missing.push(update.id);\n continue;\n }\n if (update.status !== undefined) task.status = update.status;\n if (update.subject !== undefined) task.subject = update.subject;\n if (update.activeForm !== undefined) {\n if (update.activeForm) task.activeForm = update.activeForm;\n else delete task.activeForm;\n }\n if (update.owner !== undefined) {\n if (update.owner) task.owner = update.owner;\n else delete task.owner;\n }\n if (update.blockedBy !== undefined) {\n if (update.blockedBy.length > 0) task.blockedBy = update.blockedBy;\n else delete task.blockedBy;\n }\n }\n return { tasks: out, missing };\n}\n\nexport function deleteTasks(\n tasks: StoredTask[],\n opts: { ids?: string[]; all?: boolean },\n): { tasks: StoredTask[]; removed: number } {\n if (opts.all) return { tasks: [], removed: tasks.length };\n const ids = new Set(opts.ids ?? []);\n const kept = tasks.filter((task) => !ids.has(task.id));\n return { tasks: kept, removed: tasks.length - kept.length };\n}\n\nexport function renderTaskList(tasks: StoredTask[]): string {\n if (tasks.length === 0) return \"작업 목록이 비어 있습니다.\";\n const mark = { pending: \"[ ]\", in_progress: \"[->]\", completed: \"[x]\" } as const;\n const lines = tasks.map((task) => {\n const deps =\n task.blockedBy && task.blockedBy.length > 0\n ? ` (blocked by #${task.blockedBy.join(\", #\")})`\n : \"\";\n const owner = task.owner ? ` @${task.owner}` : \"\";\n return `${mark[task.status]} #${task.id} ${task.subject}${deps}${owner}`;\n });\n const done = tasks.filter((task) => task.status === \"completed\").length;\n return [`Tasks (${done}/${tasks.length} 완료)`, ...lines].join(\"\\n\");\n}\n",
36
+ "import { createHash } from \"node:crypto\";\nimport { mkdirSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { appendJsonlEntry, readJsonlLines } from \"#platform/jsonl\";\nimport { logger } from \"#platform/logger\";\nimport { getTopicSessionId } from \"#storage/api-topics\";\nimport { resolveStorageLogDir } from \"#storage/storage-host\";\nimport type { AgentKind, TokenUsage } from \"#types\";\n\nexport interface QueryRecord {\n schemaVersion: 2;\n timestamp: string; // ISO 8601 UTC\n session: string; // topic title (legacy output name)\n topicId: string;\n providerSessionId?: string;\n agent: AgentKind;\n model: string;\n /** Cache-miss input only. */\n inputTokens: number;\n outputTokens: number;\n cacheCreationInputTokens: number;\n cacheReadInputTokens: number;\n contextTokens?: number;\n contextWindow?: number;\n estimatedCostUsd: number;\n /**\n * The provider's own raw cost figure for this query, when it reported one\n * (currently only `claude`, via the Agent SDK's `total_cost_usd`). That\n * figure is the *session's running total so far*, not this query's own\n * cost -- `estimatedCostUsd` above is already the marginal delta derived\n * from it (see `recordUsage`). Kept so the *next* query in the same\n * provider session has something to diff against; never summed itself.\n */\n cumulativeCostUsd?: number;\n}\n\nexport interface Bucket {\n inputTokens: number;\n outputTokens: number;\n cacheCreationInputTokens: number;\n cacheReadInputTokens: number;\n queries: number;\n estimatedCostUsd: number;\n}\n\nexport interface CurrentSessionUsage {\n timestamp: string;\n topicId: string;\n topicTitle: string;\n providerSessionId?: string;\n agent: AgentKind;\n model: string;\n contextTokens: number;\n contextWindow: number;\n}\n\nexport interface TopicUsageSummary extends Bucket {\n topicId: string;\n currentSession?: CurrentSessionUsage;\n}\n\nfunction emptyBucket(): Bucket {\n return {\n inputTokens: 0,\n outputTokens: 0,\n cacheCreationInputTokens: 0,\n cacheReadInputTokens: 0,\n queries: 0,\n estimatedCostUsd: 0,\n };\n}\n\nexport function tokenStatsFileId(userId: number | string): string {\n const rawUserId = String(userId);\n // Preserve existing filenames for ordinary IDs, but never let an external\n // identity introduce path separators or unbounded filename length.\n return /^[A-Za-z0-9][A-Za-z0-9_.@-]{0,255}$/.test(rawUserId) && !rawUserId.includes(\"..\")\n ? rawUserId\n : `sha256-${createHash(\"sha256\").update(rawUserId).digest(\"hex\")}`;\n}\n\nfunction queriesPath(userId: number | string): string {\n const fileId = tokenStatsFileId(userId);\n const logDir = resolveStorageLogDir();\n mkdirSync(logDir, { recursive: true });\n return join(logDir, `token-queries-${fileId}.jsonl`);\n}\n\nfunction loadRecords(userId: number | string): unknown[] {\n try {\n return readJsonlLines(queriesPath(userId)).flatMap((line) => {\n try {\n return [JSON.parse(line) as unknown];\n } catch {\n return [];\n }\n });\n } catch {\n return [];\n }\n}\n\nexport function calcCost(\n b: Pick<\n Bucket,\n | \"inputTokens\"\n | \"outputTokens\"\n | \"cacheCreationInputTokens\"\n | \"cacheReadInputTokens\"\n | \"estimatedCostUsd\"\n >,\n): number {\n return b.estimatedCostUsd;\n}\n\ntype TokenPrices = {\n input: number;\n output: number;\n cacheWrite?: number;\n cacheRead: number;\n};\n\nconst TOKEN_PRICES: Record<string, TokenPrices> = {\n \"codex:gpt-6-astra\": { input: 10, cacheWrite: 12.5, cacheRead: 1, output: 50 },\n \"codex:gpt-6-sol\": { input: 2, cacheRead: 0.2, output: 10 },\n \"codex:gpt-6-luna\": { input: 0.1, cacheRead: 0.01, output: 0.5 },\n \"codex:gpt-6.1-terra\": { input: 1, cacheRead: 0.05, output: 5 },\n // GPT-5.6 Sol/Luna/Terra are retired aliases, but historical usage rows still\n // carry the old ids, so their prices stay for cost accounting.\n \"codex:gpt-5.6-sol\": { input: 5, cacheRead: 0.5, output: 30 },\n \"codex:gpt-5.6-terra\": { input: 2.5, cacheRead: 0.25, output: 15 },\n \"codex:gpt-5.6-luna\": { input: 1, cacheRead: 0.1, output: 6 },\n // Fable 5.1 (2026-09-01) cut cache-read pricing 75% from $1/M to $0.25/M.\n \"claude:fable\": { input: 10, cacheWrite: 12.5, cacheRead: 0.25, output: 50 },\n \"claude:opus\": { input: 4, cacheWrite: 5, cacheRead: 0.4, output: 20 },\n \"claude:claude-opus-5-5\": { input: 4, cacheWrite: 5, cacheRead: 0.4, output: 20 },\n \"claude:sonnet\": { input: 2, cacheWrite: 2.5, cacheRead: 0.2, output: 10 },\n \"maestro:kimi-k3\": { input: 3, cacheRead: 0.3, output: 15 },\n \"maestro:kimi-k2.7-code\": { input: 0.95, cacheRead: 0.19, output: 4 },\n // Approximate published GLM rates; no separate cache-read rate is published,\n // so cache reads conservatively use the ordinary input price.\n \"maestro:glm-5.3\": { input: 1.4, cacheRead: 1.4, output: 4.4 },\n // glm-5.2 removed from the selectable catalog (2026-09-12): confirmed priced\n // identically to glm-5.3, so it no longer needs a separate route. Rate kept\n // here (corrected to match reality) only so historical query records still\n // logged under \"glm-5.2\" can be cost-estimated.\n \"maestro:glm-5.2\": { input: 1.4, cacheRead: 1.4, output: 4.4 },\n \"maestro:glm-5.3-flash\": { input: 0.15, cacheRead: 0.15, output: 0.5 },\n \"maestro:deepseek-pro\": { input: 0.435, cacheRead: 0.003625, output: 0.87 },\n \"maestro:deepseek-flash\": { input: 0.14, cacheRead: 0.0028, output: 0.28 },\n};\n\nfunction estimateUsageCost(\n agent: AgentKind,\n model: string,\n usage: Pick<\n QueryRecord,\n \"inputTokens\" | \"outputTokens\" | \"cacheCreationInputTokens\" | \"cacheReadInputTokens\"\n >,\n): number {\n const prices = TOKEN_PRICES[`${agent}:${model}`];\n if (!prices) return 0;\n return (\n (usage.inputTokens * prices.input +\n usage.outputTokens * prices.output +\n (agent === \"claude\"\n ? usage.cacheCreationInputTokens * (prices.cacheWrite ?? prices.input)\n : 0) +\n usage.cacheReadInputTokens * prices.cacheRead) /\n 1_000_000\n );\n}\n\nfunction isQueryRecord(value: unknown): value is QueryRecord {\n if (!value || typeof value !== \"object\") return false;\n const record = value as Partial<QueryRecord>;\n return (\n record.schemaVersion === 2 &&\n typeof record.timestamp === \"string\" &&\n typeof record.session === \"string\" &&\n typeof record.topicId === \"string\" &&\n typeof record.agent === \"string\" &&\n typeof record.model === \"string\" &&\n typeof record.inputTokens === \"number\" &&\n typeof record.outputTokens === \"number\" &&\n typeof record.cacheCreationInputTokens === \"number\" &&\n typeof record.cacheReadInputTokens === \"number\" &&\n typeof record.estimatedCostUsd === \"number\"\n );\n}\n\n/**\n * The previous query's raw cumulative cost for this same provider session\n * (`cumulativeCostUsd`, or its `estimatedCostUsd` for a pre-fix row logged\n * before that field existed -- conservative, since on that older code path\n * the two were the same number). `0` when this is the session's first\n * recorded query, or the provider never reports a running total at all.\n *\n * Scans the user's whole log backwards; `recordUsage` calls this at most\n * once per completed query, so it trades a bit of I/O for not having to\n * keep cross-process session state in memory.\n */\nfunction previousCumulativeCost(userId: number | string, providerSessionId: string): number {\n let lines: string[];\n try {\n lines = readJsonlLines(queriesPath(userId));\n } catch {\n return 0;\n }\n for (let i = lines.length - 1; i >= 0; i--) {\n let parsed: Partial<QueryRecord>;\n try {\n parsed = JSON.parse(lines[i]) as Partial<QueryRecord>;\n } catch {\n continue;\n }\n if (parsed.providerSessionId !== providerSessionId) continue;\n if (typeof parsed.cumulativeCostUsd === \"number\") return parsed.cumulativeCostUsd;\n if (typeof parsed.estimatedCostUsd === \"number\") return parsed.estimatedCostUsd;\n return 0;\n }\n return 0;\n}\n\n/** 쿼리 완료 시 호출 — JSONL에 한 줄 추가 */\nexport function recordUsage(\n userId: number | string,\n session: string,\n usage: TokenUsage,\n context: {\n topicId: string;\n providerSessionId?: string;\n agent: AgentKind;\n model: string;\n },\n) {\n const cacheReadInputTokens = usage.cacheReadInputTokens ?? 0;\n // Claude reports cache buckets separately; Codex and Maestro include cache\n // hits in their provider input total.\n const inputTokens =\n context.agent === \"claude\"\n ? usage.inputTokens\n : Math.max(0, usage.inputTokens - cacheReadInputTokens);\n const normalized = {\n inputTokens,\n outputTokens: usage.outputTokens,\n cacheCreationInputTokens: usage.cacheCreationInputTokens ?? 0,\n cacheReadInputTokens,\n };\n // `usage.costUsd` (currently claude-only, the Agent SDK's `total_cost_usd`)\n // is the *session's cost so far*, not this one query's -- summed as-is\n // across a session's queries (as every other field here is), it inflates\n // the total roughly `queries / 2`-fold. Store the marginal delta against\n // the previous query's own cumulative figure instead, so `estimatedCostUsd`\n // stays what the rest of this module assumes every record's is: this\n // query's own cost, safe to add up.\n let estimatedCostUsd: number;\n let cumulativeCostUsd: number | undefined;\n if (usage.costUsd !== undefined) {\n const previous = context.providerSessionId\n ? previousCumulativeCost(userId, context.providerSessionId)\n : 0;\n estimatedCostUsd = Math.max(0, usage.costUsd - previous);\n cumulativeCostUsd = usage.costUsd;\n } else {\n estimatedCostUsd = estimateUsageCost(context.agent, context.model, normalized);\n }\n const record: QueryRecord = {\n schemaVersion: 2,\n timestamp: new Date().toISOString(),\n session,\n topicId: context.topicId,\n ...(context.providerSessionId ? { providerSessionId: context.providerSessionId } : {}),\n agent: context.agent,\n model: context.model,\n ...normalized,\n ...(usage.contextTokens !== undefined ? { contextTokens: usage.contextTokens } : {}),\n ...(usage.contextWindow !== undefined ? { contextWindow: usage.contextWindow } : {}),\n estimatedCostUsd,\n ...(cumulativeCostUsd !== undefined ? { cumulativeCostUsd } : {}),\n };\n try {\n appendJsonlEntry(queriesPath(userId), record);\n } catch (e) {\n logger.warn({ err: e, userId }, \"token-stats: Failed to record\");\n }\n}\n\nexport function deleteTopicStats(userId: number | string, topicId: string): void {\n const path = queriesPath(userId);\n try {\n const kept = readJsonlLines(path).filter((line) => {\n try {\n const record = JSON.parse(line) as { topicId?: unknown };\n return record.topicId !== topicId;\n } catch {\n return true;\n }\n });\n writeFileSync(path, kept.length > 0 ? `${kept.join(\"\\n\")}\\n` : \"\", \"utf-8\");\n } catch (e) {\n if ((e as NodeJS.ErrnoException).code === \"ENOENT\") return;\n logger.warn({ err: e, userId, topicId }, \"token-stats: Failed to delete topic stats\");\n }\n}\n\nexport function getStats(\n userId: number | string,\n from?: string,\n to?: string,\n): {\n total: Bucket;\n byHour: Record<string, Bucket>;\n bySession: Record<string, Bucket>;\n currentSessions: CurrentSessionUsage[];\n ignoredLegacyRecords: number;\n estimatedCostUsd: number;\n} {\n const records = loadRecords(userId);\n\n const fromTs = from ? new Date(from).getTime() : 0;\n const toTs = to ? new Date(to).getTime() : Infinity;\n\n if ((from && Number.isNaN(fromTs)) || (to && Number.isNaN(toTs))) {\n logger.warn({ from, to }, \"token-stats: Invalid date range, returning empty\");\n return {\n total: emptyBucket(),\n byHour: {},\n bySession: {},\n currentSessions: [],\n ignoredLegacyRecords: 0,\n estimatedCostUsd: 0,\n };\n }\n\n const total = emptyBucket();\n const byHour: Record<string, Bucket> = {};\n const bySession: Record<string, Bucket> = {};\n const currentSessions = new Map<string, CurrentSessionUsage>();\n let ignoredLegacyRecords = 0;\n\n for (const raw of records) {\n if (!isQueryRecord(raw)) {\n ignoredLegacyRecords += 1;\n continue;\n }\n const r = raw;\n const ts = new Date(r.timestamp).getTime();\n if (ts < fromTs || ts > toTs) continue;\n\n const hourKey = r.timestamp.slice(0, 13); // \"2026-03-28T14\"\n\n if (!byHour[hourKey]) byHour[hourKey] = emptyBucket();\n if (!bySession[r.session]) bySession[r.session] = emptyBucket();\n\n for (const bucket of [total, byHour[hourKey], bySession[r.session]]) {\n bucket.inputTokens += r.inputTokens;\n bucket.outputTokens += r.outputTokens;\n bucket.cacheCreationInputTokens += r.cacheCreationInputTokens;\n bucket.cacheReadInputTokens += r.cacheReadInputTokens;\n bucket.queries += 1;\n bucket.estimatedCostUsd += r.estimatedCostUsd;\n }\n\n if (r.contextTokens !== undefined && r.contextWindow !== undefined && r.contextWindow > 0) {\n currentSessions.set(r.topicId, {\n timestamp: r.timestamp,\n topicId: r.topicId,\n topicTitle: r.session,\n ...(r.providerSessionId ? { providerSessionId: r.providerSessionId } : {}),\n agent: r.agent,\n model: r.model,\n contextTokens: r.contextTokens,\n contextWindow: r.contextWindow,\n });\n }\n }\n\n return {\n total,\n byHour,\n bySession,\n currentSessions: [...currentSessions.values()].sort((a, b) =>\n b.timestamp.localeCompare(a.timestamp),\n ),\n ignoredLegacyRecords,\n estimatedCostUsd: calcCost(total),\n };\n}\n\n/** Exact all-time usage for one topic, independent of transcript pagination. */\nexport function getTopicStats(\n userId: number | string,\n topicId: string,\n activeProviderSessionId = getTopicSessionId(topicId) ?? undefined,\n): TopicUsageSummary {\n const total = emptyBucket();\n let currentSession: CurrentSessionUsage | undefined;\n\n for (const raw of loadRecords(userId)) {\n if (!isQueryRecord(raw) || raw.topicId !== topicId) continue;\n\n total.inputTokens += raw.inputTokens;\n total.outputTokens += raw.outputTokens;\n total.cacheCreationInputTokens += raw.cacheCreationInputTokens;\n total.cacheReadInputTokens += raw.cacheReadInputTokens;\n total.queries += 1;\n total.estimatedCostUsd += raw.estimatedCostUsd;\n\n if (\n raw.contextTokens !== undefined &&\n raw.contextWindow !== undefined &&\n raw.contextWindow > 0 &&\n activeProviderSessionId !== undefined &&\n raw.providerSessionId === activeProviderSessionId &&\n (!currentSession || raw.timestamp > currentSession.timestamp)\n ) {\n currentSession = {\n timestamp: raw.timestamp,\n topicId: raw.topicId,\n topicTitle: raw.session,\n ...(raw.providerSessionId ? { providerSessionId: raw.providerSessionId } : {}),\n agent: raw.agent,\n model: raw.model,\n contextTokens: raw.contextTokens,\n contextWindow: raw.contextWindow,\n };\n }\n }\n\n return { topicId, ...total, ...(currentSession ? { currentSession } : {}) };\n}\n",
37
+ "import { mkdirSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { countMemoryArchiveExchanges } from \"#agents/memory-archive-policy\";\nimport { logger } from \"#platform/logger\";\nimport { sanitizeTopicName } from \"#security/sanitize\";\nimport { getAllMessagesForTopic, getMessagesForTopicAfterRowid } from \"#storage/api-messages\";\nimport { readRawConversation } from \"#storage/conversations\";\nimport { formatTopicArchiveTranscriptRecord } from \"#storage/topic-transcript\";\nimport { getSharedWikiDir } from \"#storage/wiki\";\nimport type { UnifiedEvent } from \"#types\";\n\nexport interface TopicArchiveResult {\n path: string;\n messageCount: number;\n exchangeCount: number;\n lastRowid: number;\n}\n\nexport interface ConversationEventArchiveResult {\n path: string;\n eventCount: number;\n}\n\nexport interface TopicArchiveOptions {\n afterRowid?: number;\n reason?: \"delete\" | \"idle\" | \"reset\";\n}\n\n/**\n * Forensic-archive a topic's SQLite-backed messages into the shared\n * `wiki/archive/` as JSONL transcript records.\n *\n * Otium keeps conversations in the `api_messages` table (SQLite), not in the\n * `PROJECT_ROOT/logs` activity-log files that Otium's `archiveSessionLogs`\n * scans — so this is Otium's native equivalent. Each JSONL record keeps the raw\n * DB message under `message`, plus a human-readable `line`/`role`/`speaker` for\n * the background wiki-archiver turn.\n *\n * Output lands in the **shared** wiki root (see `getSharedWikiDir`) because\n * that is the root the wiki MCP serves in topic-id mode; writing it elsewhere\n * would make the archive invisible to later `wiki_query` calls.\n *\n * Returns `null` when the selected range has no messages.\n */\nexport function archiveTopicMessages(\n topicId: string,\n topicTitle: string,\n options: TopicArchiveOptions = {},\n): TopicArchiveResult | null {\n const rows =\n options.afterRowid !== undefined\n ? getMessagesForTopicAfterRowid(topicId, options.afterRowid)\n : getAllMessagesForTopic(topicId);\n if (rows.length === 0) return null;\n\n const safeTopic = sanitizeTopicName(topicTitle, true);\n const archiveDir = join(getSharedWikiDir(), \"archive\");\n mkdirSync(archiveDir, { recursive: true });\n\n // Collision-proof file name: a topic deleted twice on the same day (e.g.\n // recreated then deleted again) must not clobber the earlier archive.\n const date = new Date().toISOString().slice(0, 10);\n const reasonSuffix = options.reason && options.reason !== \"delete\" ? `_${options.reason}` : \"\";\n let filename: string;\n let counter = 1;\n const lastRowid = rows.reduce((max, row) => Math.max(max, row.rowid ?? 0), 0);\n const body = `${rows\n .map((r, index) => JSON.stringify(formatTopicArchiveTranscriptRecord(r, topicTitle, index + 1)))\n .join(\"\\n\")}\\n`;\n let path: string;\n while (true) {\n filename = `${safeTopic}_${date}${reasonSuffix}${counter === 1 ? \"\" : `_${counter}`}.jsonl`;\n path = join(archiveDir, filename);\n try {\n writeFileSync(path, body, { flag: \"wx\" });\n break;\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== \"EEXIST\") throw err;\n counter++;\n }\n }\n\n const exchangeCount = countMemoryArchiveExchanges(rows);\n logger.info(\n { topicId, topicTitle, archive: path, messageCount: rows.length, exchangeCount, lastRowid },\n \"archiveTopicMessages: archived topic messages\",\n );\n return { path, messageCount: rows.length, exchangeCount, lastRowid };\n}\n\n/** Render one UnifiedEvent's primary text. Shared with session-history's read/search tools. */\nexport function eventText(event: UnifiedEvent): string {\n if (\"content\" in event && typeof event.content === \"string\") return event.content;\n if (event.type === \"session\") return `sessionId: ${event.sessionId}`;\n if (event.type === \"tool_use\") {\n return `${event.name}(${JSON.stringify(event.input)})`;\n }\n if (event.type === \"tool_progress\") return `${event.toolName} · ${event.elapsed}s`;\n if (event.type === \"tool_use_summary\") return event.summary;\n if (event.type === \"file\") return `${event.path} (${event.source})`;\n return JSON.stringify(event);\n}\n\n/** Render one UnifiedEvent's speaker label. Shared with session-history's read/search tools. */\nexport function eventSpeaker(event: UnifiedEvent, agent: string): string {\n if (event.type === \"user_message\") return \"user\";\n if (event.type === \"tool_use\" || event.type === \"tool_result\") return `tool:${agent}`;\n if (event.type === \"reasoning\") return `reasoning:${agent}`;\n if (event.type === \"session\") return `session:${agent}`;\n return `assistant:${agent}`;\n}\n\n/**\n * Preserve the append-only provider-neutral event stream before topic teardown.\n * Unlike the visible transcript this includes tools, reasoning, errors, and\n * every provider session id across agent switches and compactions.\n */\nexport function archiveConversationEvents(\n topicId: string,\n topicTitle: string,\n userId: string,\n options: Pick<TopicArchiveOptions, \"reason\"> = {},\n): ConversationEventArchiveResult | null {\n const entries = readRawConversation(userId, topicTitle);\n if (entries.length === 0) return null;\n\n const archiveDir = join(getSharedWikiDir(), \"archive\");\n mkdirSync(archiveDir, { recursive: true });\n const safeTopic = sanitizeTopicName(topicTitle, true);\n const date = new Date().toISOString().slice(0, 10);\n const reasonSuffix = options.reason && options.reason !== \"delete\" ? `_${options.reason}` : \"\";\n const body = `${entries\n .map((entry, index) => {\n const text = eventText(entry.event);\n const speaker = eventSpeaker(entry.event, entry.agent);\n return JSON.stringify({\n type: \"event\",\n index: index + 1,\n topicId,\n topicTitle,\n createdAt: entry.ts,\n role: entry.event.type === \"user_message\" ? \"user\" : \"assistant\",\n speaker,\n line: `[${entry.ts}] ${speaker}: ${text.replace(/\\s+/g, \" \").trim().slice(0, 2000)}`,\n text,\n agent: entry.agent,\n eventType: entry.event.type,\n event: entry.event,\n });\n })\n .join(\"\\n\")}\\n`;\n\n let counter = 1;\n while (true) {\n const suffix = counter === 1 ? \"\" : `_${counter}`;\n const path = join(archiveDir, `${safeTopic}_${date}${reasonSuffix}_events${suffix}.jsonl`);\n try {\n writeFileSync(path, body, { flag: \"wx\" });\n logger.info(\n { topicId, topicTitle, archive: path, eventCount: entries.length },\n \"archiveConversationEvents: archived raw conversation events\",\n );\n return { path, eventCount: entries.length };\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"EEXIST\") throw error;\n counter++;\n }\n }\n}\n",
38
+ "export interface MemoryArchiveMessage {\n author_id: string;\n agent_type?: string | null;\n kind?: string | null;\n}\n\n/**\n * Shared lifecycle gate for reset/delete memory distillation. Keep the raw\n * forensic archive even below this threshold, but do not spend an agent turn\n * on a session with five or fewer completed user/assistant exchanges. This\n * mirrors Clawgram's lifecycle-level MIN_EXCHANGE_COUNT policy.\n */\nexport const MIN_MEMORY_ARCHIVE_EXCHANGES = 6;\n\nexport interface MemoryArchiveTopicContext {\n isSubagent?: boolean;\n memoryTopicId?: string;\n}\n\n/**\n * Explicit-memory subagents are usually short, focused turns. Persist one\n * completed exchange back to their selected memory topic, while retaining the\n * normal threshold for regular topics and incomplete/failed turns.\n */\nexport function meetsMemoryArchiveExchangeThreshold(\n exchangeCount: number,\n minExchanges: number,\n topic: MemoryArchiveTopicContext,\n): boolean {\n if (exchangeCount <= 0) return false;\n if (topic.isSubagent && topic.memoryTopicId) return true;\n return exchangeCount >= minExchanges;\n}\n\n/** Count completed conversational exchanges while ignoring system/tool/card noise. */\nexport function countMemoryArchiveExchanges(rows: readonly MemoryArchiveMessage[]): number {\n let waitingForAssistant = false;\n let completed = 0;\n\n for (const row of rows) {\n const assistant = row.author_id === \"ai\" || Boolean(row.agent_type);\n const conversational = row.kind == null || row.kind === \"message\";\n if (!assistant && row.author_id !== \"system\" && conversational) {\n waitingForAssistant = true;\n continue;\n }\n if (assistant && conversational && waitingForAssistant) {\n completed++;\n waitingForAssistant = false;\n }\n }\n\n return completed;\n}\n",
39
+ "export interface TopicArchiveMessageRow {\n id: string;\n topic_id: string;\n parent_id: string | null;\n author_id: string;\n text: string;\n query_id: string | null;\n agent_type: string | null;\n model: string | null;\n attachments: string | null;\n usage: string | null;\n deleted: number;\n created_at: string;\n rowid?: number;\n}\n\nexport type TopicArchiveRole = \"user\" | \"assistant\" | \"system\";\n\nexport interface TopicArchiveTranscriptRecord {\n type: \"message\";\n index: number;\n topicId: string;\n topicTitle: string;\n id: string;\n createdAt: string;\n rowid?: number;\n role: TopicArchiveRole;\n speaker: string;\n line: string;\n text: string;\n authorId: string;\n parentId?: string;\n queryId?: string;\n agentType?: string;\n model?: string;\n attachments?: unknown;\n usage?: unknown;\n message: TopicArchiveMessageRow;\n}\n\nfunction parseJsonField(value: string | null): unknown | undefined {\n if (!value) return undefined;\n try {\n return JSON.parse(value);\n } catch {\n return value;\n }\n}\n\nfunction transcriptRole(row: TopicArchiveMessageRow): TopicArchiveRole {\n if (row.author_id === \"system\") return \"system\";\n if (row.author_id === \"ai\" || row.agent_type) return \"assistant\";\n return \"user\";\n}\n\nfunction transcriptSpeaker(row: TopicArchiveMessageRow, role: TopicArchiveRole): string {\n if (role === \"assistant\") return row.agent_type ? `assistant:${row.agent_type}` : \"assistant\";\n if (role === \"system\") return \"system\";\n return `user:${row.author_id}`;\n}\n\nfunction oneLine(text: string): string {\n const compact = text.replace(/\\s+/g, \" \").trim();\n return compact.length > 2000 ? `${compact.slice(0, 2000)}...` : compact;\n}\n\nexport function formatTopicArchiveTranscriptRecord(\n row: TopicArchiveMessageRow,\n topicTitle: string,\n index: number,\n): TopicArchiveTranscriptRecord {\n const role = transcriptRole(row);\n const speaker = transcriptSpeaker(row, role);\n const attachments = parseJsonField(row.attachments);\n const usage = parseJsonField(row.usage);\n\n return {\n type: \"message\",\n index,\n topicId: row.topic_id,\n topicTitle,\n id: row.id,\n createdAt: row.created_at,\n ...(row.rowid !== undefined ? { rowid: row.rowid } : {}),\n role,\n speaker,\n line: `[${row.created_at}] ${speaker}: ${oneLine(row.text)}`,\n text: row.text,\n authorId: row.author_id,\n ...(row.parent_id ? { parentId: row.parent_id } : {}),\n ...(row.query_id ? { queryId: row.query_id } : {}),\n ...(row.agent_type ? { agentType: row.agent_type } : {}),\n ...(row.model ? { model: row.model } : {}),\n ...(attachments !== undefined ? { attachments } : {}),\n ...(usage !== undefined ? { usage } : {}),\n message: row,\n };\n}\n",
40
+ "import { existsSync, readdirSync, statSync } from \"node:fs\";\nimport { basename, dirname, join } from \"node:path\";\nimport { sanitizeTopicName } from \"#security/sanitize\";\nimport { resolveStorageSharedWikiDir, resolveStorageWorkspaceDir } from \"#storage/storage-host\";\n\nexport function getWikiDir(_userId: number, workspaceDir = resolveStorageWorkspaceDir()): string {\n return join(workspaceDir, \"wiki\");\n}\n\n/**\n * Shared wiki root. Otium keeps one workspace wiki for every topic and member;\n * filesystem wiki state is not partitioned by user.\n */\nexport function getSharedWikiDir(workspaceDir = resolveStorageWorkspaceDir()): string {\n return workspaceDir === resolveStorageWorkspaceDir()\n ? resolveStorageSharedWikiDir()\n : join(workspaceDir, \"wiki\");\n}\n\n/** Find the most recent wiki/summaries/ file for a given topic. */\nfunction findLatestSummaryFile(wikiDir: string, safeTopic: string): string | null {\n const summariesDir = join(wikiDir, \"summaries\");\n if (!existsSync(summariesDir)) return null;\n const files = readdirSync(summariesDir)\n .filter(\n (f) =>\n f.endsWith(\".md\") &&\n f.match(new RegExp(`^\\\\d{4}-\\\\d{2}-\\\\d{2}-${safeTopic}(\\\\.md|~\\\\d+\\\\.md)$`)) &&\n !f.endsWith(\"-sent-files.md\"),\n )\n .sort((left, right) => {\n const mtimeDelta =\n statSync(join(summariesDir, right)).mtimeMs - statSync(join(summariesDir, left)).mtimeMs;\n return mtimeDelta || right.localeCompare(left, undefined, { numeric: true });\n });\n return files.length > 0 ? join(summariesDir, files[0]) : null;\n}\n\n/** Return wiki/topic/<name>.md brief path and latest summary file for system prompt injection.\n * Falls back to forkOrigin's brief when the topic's own brief doesn't exist yet.\n * Returns empty memoryFiles if neither brief exists. */\nexport function getTopicMemoryFilePaths(\n _userId: number,\n topicName: string,\n forkOrigin?: string,\n workspaceDir = resolveStorageWorkspaceDir(),\n): {\n memoryDir: string;\n memoryFiles: string[];\n latestSummaryFile?: string;\n hasArchive?: boolean;\n} {\n const wikiDir = getSharedWikiDir(workspaceDir);\n\n const resolveBrief = (name: string) => {\n const safe = sanitizeTopicName(name, true);\n const brief = join(wikiDir, \"topic\", `${safe}.md`);\n const latestSummary = findLatestSummaryFile(wikiDir, safe);\n return { brief, latestSummary };\n };\n\n const archiveDir = join(wikiDir, \"archive\");\n const archiveExistsFor = (name: string) => {\n const safe = sanitizeTopicName(name);\n return (\n existsSync(archiveDir) &&\n readdirSync(archiveDir).some((f) => f.endsWith(\".jsonl\") && f.startsWith(`${safe}_`))\n );\n };\n\n const sourceTopic = forkOrigin ?? topicName;\n const hasArchive =\n archiveExistsFor(sourceTopic) || (forkOrigin ? archiveExistsFor(topicName) : false);\n const target = resolveBrief(sourceTopic);\n if (existsSync(target.brief)) {\n return {\n memoryDir: dirname(target.brief),\n memoryFiles: [basename(target.brief)],\n ...(target.latestSummary ? { latestSummaryFile: target.latestSummary } : {}),\n ...(hasArchive ? { hasArchive: true } : {}),\n };\n }\n\n return {\n memoryDir: join(wikiDir, \"topic\"),\n memoryFiles: [],\n ...(target.latestSummary ? { latestSummaryFile: target.latestSummary } : {}),\n ...(hasArchive ? { hasArchive: true } : {}),\n };\n}\n",
41
+ "import { rmSync } from \"node:fs\";\nimport { db } from \"#storage/forum-db\";\nimport { registerStorageSchemaInitializer } from \"#storage/storage-host\";\n\nregisterStorageSchemaInitializer((database) => {\n database.exec(`\n CREATE TABLE IF NOT EXISTS api_topic_archive_state (\n topic_id TEXT PRIMARY KEY,\n last_archived_rowid INTEGER NOT NULL DEFAULT 0,\n last_archive_path TEXT,\n updated_at TEXT NOT NULL\n );\n CREATE TABLE IF NOT EXISTS api_topic_archive_jobs (\n topic_id TEXT PRIMARY KEY,\n after_rowid INTEGER NOT NULL,\n last_rowid INTEGER NOT NULL,\n archive_path TEXT NOT NULL,\n message_count INTEGER NOT NULL,\n status TEXT NOT NULL CHECK (status IN ('running', 'pending')),\n updated_at TEXT NOT NULL\n );\n `);\n}, 30);\n\nconst ARCHIVE_JOB_STALE_MS = 30 * 60 * 1000;\n\nexport interface TopicArchiveState {\n topicId: string;\n lastArchivedRowid: number;\n lastArchivePath?: string;\n updatedAt: string;\n}\n\nexport interface TopicArchiveJob {\n topicId: string;\n afterRowid: number;\n lastRowid: number;\n archivePath: string;\n messageCount: number;\n status: \"running\" | \"pending\";\n updatedAt: string;\n}\n\nexport interface TopicArchiveJobCandidate {\n lastRowid: number;\n archivePath: string;\n messageCount: number;\n}\n\ninterface TopicArchiveStateRow {\n topic_id: string;\n last_archived_rowid: number;\n last_archive_path: string | null;\n updated_at: string;\n}\n\ninterface TopicArchiveJobRow {\n topic_id: string;\n after_rowid: number;\n last_rowid: number;\n archive_path: string;\n message_count: number;\n status: \"running\" | \"pending\";\n updated_at: string;\n}\n\nfunction rowToJob(row: TopicArchiveJobRow): TopicArchiveJob {\n return {\n topicId: row.topic_id,\n afterRowid: row.after_rowid,\n lastRowid: row.last_rowid,\n archivePath: row.archive_path,\n messageCount: row.message_count,\n status: row.status,\n updatedAt: row.updated_at,\n };\n}\n\nexport function getTopicArchiveState(topicId: string): TopicArchiveState | null {\n const row = db.query(\"SELECT * FROM api_topic_archive_state WHERE topic_id = ?\").get(topicId) as\n | TopicArchiveStateRow\n | undefined;\n if (!row) return null;\n return {\n topicId: row.topic_id,\n lastArchivedRowid: row.last_archived_rowid,\n lastArchivePath: row.last_archive_path ?? undefined,\n updatedAt: row.updated_at,\n };\n}\n\nexport function setTopicArchiveState(\n topicId: string,\n lastArchivedRowid: number,\n lastArchivePath?: string,\n): void {\n db.query(\n `INSERT INTO api_topic_archive_state (topic_id, last_archived_rowid, last_archive_path, updated_at)\n VALUES (?, ?, ?, ?)\n ON CONFLICT(topic_id) DO UPDATE SET\n last_archived_rowid = excluded.last_archived_rowid,\n last_archive_path = excluded.last_archive_path,\n updated_at = excluded.updated_at`,\n ).run(topicId, lastArchivedRowid, lastArchivePath ?? null, new Date().toISOString());\n}\n\n/** Atomically reserve one active-topic archive job across runtime processes. */\nexport function claimTopicArchiveJob(\n topicId: string,\n create: (afterRowid: number) => TopicArchiveJobCandidate | null,\n now = Date.now(),\n): { kind: \"claimed\"; job: TopicArchiveJob } | { kind: \"busy\" } | null {\n const claimExisting = () =>\n db.transaction(() => {\n const existing = db\n .query<TopicArchiveJobRow, [string]>(\n \"SELECT * FROM api_topic_archive_jobs WHERE topic_id = ?\",\n )\n .get(topicId);\n if (!existing) return null;\n const updatedAt = Date.parse(existing.updated_at);\n if (\n existing.status === \"running\" &&\n Number.isFinite(updatedAt) &&\n now - updatedAt < ARCHIVE_JOB_STALE_MS\n ) {\n return { kind: \"busy\" } as const;\n }\n const timestamp = new Date(now).toISOString();\n db.query(\n \"UPDATE api_topic_archive_jobs SET status = 'running', updated_at = ? WHERE topic_id = ?\",\n ).run(timestamp, topicId);\n return {\n kind: \"claimed\",\n job: rowToJob({ ...existing, status: \"running\", updated_at: timestamp }),\n } as const;\n })();\n\n const existingClaim = claimExisting();\n if (existingClaim) return existingClaim;\n\n // File serialization stays outside the SQLite write transaction. Only the\n // short compare-and-insert below is serialized across runtime processes.\n for (let attempt = 0; attempt < 2; attempt++) {\n const afterRowid = getTopicArchiveState(topicId)?.lastArchivedRowid ?? 0;\n const candidate = create(afterRowid);\n if (!candidate) return null;\n const result = db.transaction(() => {\n const existing = db\n .query<TopicArchiveJobRow, [string]>(\n \"SELECT * FROM api_topic_archive_jobs WHERE topic_id = ?\",\n )\n .get(topicId);\n if (existing) return { kind: \"busy\" } as const;\n const currentRowid = getTopicArchiveState(topicId)?.lastArchivedRowid ?? 0;\n if (currentRowid !== afterRowid) return { kind: \"stale\" } as const;\n const timestamp = new Date(now).toISOString();\n db.query(\n `INSERT INTO api_topic_archive_jobs\n (topic_id, after_rowid, last_rowid, archive_path, message_count, status, updated_at)\n VALUES (?, ?, ?, ?, ?, 'running', ?)`,\n ).run(\n topicId,\n afterRowid,\n candidate.lastRowid,\n candidate.archivePath,\n candidate.messageCount,\n timestamp,\n );\n return {\n kind: \"claimed\",\n job: {\n topicId,\n afterRowid,\n lastRowid: candidate.lastRowid,\n archivePath: candidate.archivePath,\n messageCount: candidate.messageCount,\n status: \"running\",\n updatedAt: timestamp,\n },\n } as const;\n })();\n if (result.kind === \"claimed\") return result;\n rmSync(candidate.archivePath, { force: true });\n if (result.kind === \"busy\") return result;\n }\n return claimExisting() ?? { kind: \"busy\" };\n}\n\n/** Advance the durable cursor only after the memory turn completes. */\nexport function settleTopicArchiveJob(\n topicId: string,\n archivePath: string,\n success: boolean,\n): void {\n db.transaction(() => {\n const job = db\n .query<TopicArchiveJobRow, [string, string]>(\n \"SELECT * FROM api_topic_archive_jobs WHERE topic_id = ? AND archive_path = ?\",\n )\n .get(topicId, archivePath);\n if (!job) return;\n if (!success) {\n db.query(\n \"UPDATE api_topic_archive_jobs SET status = 'pending', updated_at = ? WHERE topic_id = ? AND archive_path = ?\",\n ).run(new Date().toISOString(), topicId, archivePath);\n return;\n }\n const current = getTopicArchiveState(topicId)?.lastArchivedRowid ?? 0;\n setTopicArchiveState(topicId, Math.max(current, job.last_rowid), job.archive_path);\n db.query(\"DELETE FROM api_topic_archive_jobs WHERE topic_id = ? AND archive_path = ?\").run(\n topicId,\n archivePath,\n );\n })();\n}\n\n/** Remove the idle-archive cursor for a topic that no longer exists. */\nexport function deleteTopicArchiveState(topicId: string): boolean {\n return db.transaction(() => {\n db.query(\"DELETE FROM api_topic_archive_jobs WHERE topic_id = ?\").run(topicId);\n return (\n db.query(\"DELETE FROM api_topic_archive_state WHERE topic_id = ?\").run(topicId).changes > 0\n );\n })();\n}\n",
42
+ "import { db } from \"#storage/forum-db\";\nimport { type AgentKind, isAgentKind } from \"#types\";\n\nexport interface TopicAgentSwitchState {\n name: string;\n agent: AgentKind;\n}\n\nfunction toTopicAgentSwitchState(row: {\n name: string;\n agent: string | null;\n}): TopicAgentSwitchState {\n if (!isAgentKind(row.agent)) throw new Error(`Invalid agent in DB: ${row.agent}`);\n return {\n name: row.name,\n agent: row.agent,\n };\n}\n\nexport function getTopicAgentSwitchState(\n userId: number,\n topicName: string,\n): TopicAgentSwitchState | null {\n const row = db\n .query<{ name: string; agent: string | null }, [string, string]>(\n \"SELECT name, agent FROM topics WHERE user_id = ? AND name = ?\",\n )\n .get(String(userId), topicName);\n return row ? toTopicAgentSwitchState(row) : null;\n}\n\nexport interface SetTopicAgentAndSessionOptions {\n userId: number;\n topicName: string;\n agent: AgentKind;\n sessionId: string;\n}\n\nexport function setTopicAgentAndSession(opts: SetTopicAgentAndSessionOptions): void {\n const { userId, topicName, agent, sessionId } = opts;\n db.transaction(() => {\n const r = db\n .query(\"UPDATE topics SET agent = ?, session_id = ? WHERE user_id = ? AND name = ?\")\n .run(agent, sessionId, String(userId), topicName);\n if (r.changes === 0) {\n throw new Error(`setTopicAgentAndSession: row missing for ${userId}/${topicName}`);\n }\n })();\n}\n\nexport interface SetTopicAgentAndClearSessionOptions {\n userId: number;\n topicName: string;\n agent: AgentKind;\n}\n\nexport function setTopicAgentAndClearSession(opts: SetTopicAgentAndClearSessionOptions): boolean {\n const { userId, topicName, agent } = opts;\n let changed = false;\n db.transaction(() => {\n const r = db\n .query(\"UPDATE topics SET agent = ?, session_id = NULL WHERE user_id = ? AND name = ?\")\n .run(agent, String(userId), topicName);\n changed = r.changes > 0;\n })();\n return changed;\n}\n"
43
+ ],
44
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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