@eloxiv/kernel 0.0.0-stage → 0.1.1

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 (1167) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +6 -2
  3. package/dist/AccountMail.d.ts +40 -0
  4. package/dist/AccountMail.d.ts.map +1 -0
  5. package/dist/AccountMail.js +169 -0
  6. package/dist/AccountMail.js.map +1 -0
  7. package/dist/AppConfig.d.ts +72 -0
  8. package/dist/AppConfig.d.ts.map +1 -0
  9. package/dist/AppConfig.js +87 -0
  10. package/dist/AppConfig.js.map +1 -0
  11. package/dist/Approvals.d.ts +132 -0
  12. package/dist/Approvals.d.ts.map +1 -0
  13. package/dist/Approvals.js +342 -0
  14. package/dist/Approvals.js.map +1 -0
  15. package/dist/Audit.d.ts +93 -0
  16. package/dist/Audit.d.ts.map +1 -0
  17. package/dist/Audit.js +275 -0
  18. package/dist/Audit.js.map +1 -0
  19. package/dist/AuthSeam.d.ts +58 -0
  20. package/dist/AuthSeam.d.ts.map +1 -0
  21. package/dist/AuthSeam.js +101 -0
  22. package/dist/AuthSeam.js.map +1 -0
  23. package/dist/Authority.d.ts +160 -0
  24. package/dist/Authority.d.ts.map +1 -0
  25. package/dist/Authority.js +325 -0
  26. package/dist/Authority.js.map +1 -0
  27. package/dist/Avatars.d.ts +26 -0
  28. package/dist/Avatars.d.ts.map +1 -0
  29. package/dist/Avatars.js +140 -0
  30. package/dist/Avatars.js.map +1 -0
  31. package/dist/Base64url.d.ts +9 -0
  32. package/dist/Base64url.d.ts.map +1 -0
  33. package/dist/Base64url.js +26 -0
  34. package/dist/Base64url.js.map +1 -0
  35. package/dist/BasePath.d.ts +39 -0
  36. package/dist/BasePath.d.ts.map +1 -0
  37. package/dist/BasePath.js +70 -0
  38. package/dist/BasePath.js.map +1 -0
  39. package/dist/CallActed.d.ts +10 -0
  40. package/dist/CallActed.d.ts.map +1 -0
  41. package/dist/CallActed.js +10 -0
  42. package/dist/CallActed.js.map +1 -0
  43. package/dist/Config.d.ts +459 -0
  44. package/dist/Config.d.ts.map +1 -0
  45. package/dist/Config.js +415 -0
  46. package/dist/Config.js.map +1 -0
  47. package/dist/DeliveryPolicy.d.ts +20 -0
  48. package/dist/DeliveryPolicy.d.ts.map +1 -0
  49. package/dist/DeliveryPolicy.js +35 -0
  50. package/dist/DeliveryPolicy.js.map +1 -0
  51. package/dist/DesktopSignIn.d.ts +24 -0
  52. package/dist/DesktopSignIn.d.ts.map +1 -0
  53. package/dist/DesktopSignIn.js +148 -0
  54. package/dist/DesktopSignIn.js.map +1 -0
  55. package/dist/Directory.d.ts +179 -0
  56. package/dist/Directory.d.ts.map +1 -0
  57. package/dist/Directory.js +1184 -0
  58. package/dist/Directory.js.map +1 -0
  59. package/dist/Flags.d.ts +59 -0
  60. package/dist/Flags.d.ts.map +1 -0
  61. package/dist/Flags.js +195 -0
  62. package/dist/Flags.js.map +1 -0
  63. package/dist/Gate.d.ts +42 -0
  64. package/dist/Gate.d.ts.map +1 -0
  65. package/dist/Gate.js +132 -0
  66. package/dist/Gate.js.map +1 -0
  67. package/dist/Hash.d.ts +4 -0
  68. package/dist/Hash.d.ts.map +1 -0
  69. package/dist/Hash.js +16 -0
  70. package/dist/Hash.js.map +1 -0
  71. package/dist/Identity.d.ts +327 -0
  72. package/dist/Identity.d.ts.map +1 -0
  73. package/dist/Identity.js +1232 -0
  74. package/dist/Identity.js.map +1 -0
  75. package/dist/IntervalJob.d.ts +40 -0
  76. package/dist/IntervalJob.d.ts.map +1 -0
  77. package/dist/IntervalJob.js +76 -0
  78. package/dist/IntervalJob.js.map +1 -0
  79. package/dist/Invocation.d.ts +210 -0
  80. package/dist/Invocation.d.ts.map +1 -0
  81. package/dist/Invocation.js +1680 -0
  82. package/dist/Invocation.js.map +1 -0
  83. package/dist/KernelHandlers.d.ts +19 -0
  84. package/dist/KernelHandlers.d.ts.map +1 -0
  85. package/dist/KernelHandlers.js +15 -0
  86. package/dist/KernelHandlers.js.map +1 -0
  87. package/dist/KernelModule.d.ts +65 -0
  88. package/dist/KernelModule.d.ts.map +1 -0
  89. package/dist/KernelModule.js +116 -0
  90. package/dist/KernelModule.js.map +1 -0
  91. package/dist/MemberRoutes.d.ts +6 -0
  92. package/dist/MemberRoutes.d.ts.map +1 -0
  93. package/dist/MemberRoutes.js +107 -0
  94. package/dist/MemberRoutes.js.map +1 -0
  95. package/dist/Module.d.ts +479 -0
  96. package/dist/Module.d.ts.map +1 -0
  97. package/dist/Module.js +30 -0
  98. package/dist/Module.js.map +1 -0
  99. package/dist/ModuleIdentity.d.ts +17 -0
  100. package/dist/ModuleIdentity.d.ts.map +1 -0
  101. package/dist/ModuleIdentity.js +106 -0
  102. package/dist/ModuleIdentity.js.map +1 -0
  103. package/dist/Notifications.d.ts +107 -0
  104. package/dist/Notifications.d.ts.map +1 -0
  105. package/dist/Notifications.js +475 -0
  106. package/dist/Notifications.js.map +1 -0
  107. package/dist/Outbox.d.ts +146 -0
  108. package/dist/Outbox.d.ts.map +1 -0
  109. package/dist/Outbox.js +518 -0
  110. package/dist/Outbox.js.map +1 -0
  111. package/dist/Privacy.d.ts +50 -0
  112. package/dist/Privacy.d.ts.map +1 -0
  113. package/dist/Privacy.js +167 -0
  114. package/dist/Privacy.js.map +1 -0
  115. package/dist/Progress.d.ts +42 -0
  116. package/dist/Progress.d.ts.map +1 -0
  117. package/dist/Progress.js +215 -0
  118. package/dist/Progress.js.map +1 -0
  119. package/dist/QuerySurface.d.ts +73 -0
  120. package/dist/QuerySurface.d.ts.map +1 -0
  121. package/dist/QuerySurface.js +440 -0
  122. package/dist/QuerySurface.js.map +1 -0
  123. package/dist/QueryViews.d.ts +70 -0
  124. package/dist/QueryViews.d.ts.map +1 -0
  125. package/dist/QueryViews.js +94 -0
  126. package/dist/QueryViews.js.map +1 -0
  127. package/dist/Readiness.d.ts +40 -0
  128. package/dist/Readiness.d.ts.map +1 -0
  129. package/dist/Readiness.js +203 -0
  130. package/dist/Readiness.js.map +1 -0
  131. package/dist/Redact.d.ts +11 -0
  132. package/dist/Redact.d.ts.map +1 -0
  133. package/dist/Redact.js +21 -0
  134. package/dist/Redact.js.map +1 -0
  135. package/dist/Registry.d.ts +117 -0
  136. package/dist/Registry.d.ts.map +1 -0
  137. package/dist/Registry.js +297 -0
  138. package/dist/Registry.js.map +1 -0
  139. package/dist/Release.d.ts +205 -0
  140. package/dist/Release.d.ts.map +1 -0
  141. package/dist/Release.js +880 -0
  142. package/dist/Release.js.map +1 -0
  143. package/dist/Retention.d.ts +43 -0
  144. package/dist/Retention.d.ts.map +1 -0
  145. package/dist/Retention.js +124 -0
  146. package/dist/Retention.js.map +1 -0
  147. package/dist/Scheduler.d.ts +56 -0
  148. package/dist/Scheduler.d.ts.map +1 -0
  149. package/dist/Scheduler.js +470 -0
  150. package/dist/Scheduler.js.map +1 -0
  151. package/dist/Server.d.ts +341 -0
  152. package/dist/Server.d.ts.map +1 -0
  153. package/dist/Server.js +1106 -0
  154. package/dist/Server.js.map +1 -0
  155. package/dist/Sessions.d.ts +38 -0
  156. package/dist/Sessions.d.ts.map +1 -0
  157. package/dist/Sessions.js +45 -0
  158. package/dist/Sessions.js.map +1 -0
  159. package/dist/Settings.d.ts +63 -0
  160. package/dist/Settings.d.ts.map +1 -0
  161. package/dist/Settings.js +219 -0
  162. package/dist/Settings.js.map +1 -0
  163. package/dist/Sharing.d.ts +99 -0
  164. package/dist/Sharing.d.ts.map +1 -0
  165. package/dist/Sharing.js +315 -0
  166. package/dist/Sharing.js.map +1 -0
  167. package/dist/Sync.d.ts +188 -0
  168. package/dist/Sync.d.ts.map +1 -0
  169. package/dist/Sync.js +1100 -0
  170. package/dist/Sync.js.map +1 -0
  171. package/dist/Telemetry.d.ts +154 -0
  172. package/dist/Telemetry.d.ts.map +1 -0
  173. package/dist/Telemetry.js +536 -0
  174. package/dist/Telemetry.js.map +1 -0
  175. package/dist/Versioning.d.ts +98 -0
  176. package/dist/Versioning.d.ts.map +1 -0
  177. package/dist/Versioning.js +387 -0
  178. package/dist/Versioning.js.map +1 -0
  179. package/dist/WorkItems.d.ts +67 -0
  180. package/dist/WorkItems.d.ts.map +1 -0
  181. package/dist/WorkItems.js +211 -0
  182. package/dist/WorkItems.js.map +1 -0
  183. package/dist/Workflows.d.ts +78 -0
  184. package/dist/Workflows.d.ts.map +1 -0
  185. package/dist/Workflows.js +478 -0
  186. package/dist/Workflows.js.map +1 -0
  187. package/dist/agent/Admission.d.ts +22 -0
  188. package/dist/agent/Admission.d.ts.map +1 -0
  189. package/dist/agent/Admission.js +34 -0
  190. package/dist/agent/Admission.js.map +1 -0
  191. package/dist/agent/Channels.d.ts +15 -0
  192. package/dist/agent/Channels.d.ts.map +1 -0
  193. package/dist/agent/Channels.js +50 -0
  194. package/dist/agent/Channels.js.map +1 -0
  195. package/dist/agent/Context.d.ts +73 -0
  196. package/dist/agent/Context.d.ts.map +1 -0
  197. package/dist/agent/Context.js +338 -0
  198. package/dist/agent/Context.js.map +1 -0
  199. package/dist/agent/Http.d.ts +18 -0
  200. package/dist/agent/Http.d.ts.map +1 -0
  201. package/dist/agent/Http.js +410 -0
  202. package/dist/agent/Http.js.map +1 -0
  203. package/dist/agent/Metering.d.ts +162 -0
  204. package/dist/agent/Metering.d.ts.map +1 -0
  205. package/dist/agent/Metering.js +315 -0
  206. package/dist/agent/Metering.js.map +1 -0
  207. package/dist/agent/ModelSetup.d.ts +10 -0
  208. package/dist/agent/ModelSetup.d.ts.map +1 -0
  209. package/dist/agent/ModelSetup.js +331 -0
  210. package/dist/agent/ModelSetup.js.map +1 -0
  211. package/dist/agent/Models.d.ts +197 -0
  212. package/dist/agent/Models.d.ts.map +1 -0
  213. package/dist/agent/Models.js +489 -0
  214. package/dist/agent/Models.js.map +1 -0
  215. package/dist/agent/Processors.d.ts +102 -0
  216. package/dist/agent/Processors.d.ts.map +1 -0
  217. package/dist/agent/Processors.js +80 -0
  218. package/dist/agent/Processors.js.map +1 -0
  219. package/dist/agent/Queue.d.ts +21 -0
  220. package/dist/agent/Queue.d.ts.map +1 -0
  221. package/dist/agent/Queue.js +64 -0
  222. package/dist/agent/Queue.js.map +1 -0
  223. package/dist/agent/Receipts.d.ts +41 -0
  224. package/dist/agent/Receipts.d.ts.map +1 -0
  225. package/dist/agent/Receipts.js +142 -0
  226. package/dist/agent/Receipts.js.map +1 -0
  227. package/dist/agent/Resources.d.ts +68 -0
  228. package/dist/agent/Resources.d.ts.map +1 -0
  229. package/dist/agent/Resources.js +207 -0
  230. package/dist/agent/Resources.js.map +1 -0
  231. package/dist/agent/Run.d.ts +178 -0
  232. package/dist/agent/Run.d.ts.map +1 -0
  233. package/dist/agent/Run.js +2896 -0
  234. package/dist/agent/Run.js.map +1 -0
  235. package/dist/agent/Runtime.d.ts +79 -0
  236. package/dist/agent/Runtime.d.ts.map +1 -0
  237. package/dist/agent/Runtime.js +366 -0
  238. package/dist/agent/Runtime.js.map +1 -0
  239. package/dist/agent/Settings.d.ts +126 -0
  240. package/dist/agent/Settings.d.ts.map +1 -0
  241. package/dist/agent/Settings.js +44 -0
  242. package/dist/agent/Settings.js.map +1 -0
  243. package/dist/agent/Skills.d.ts +73 -0
  244. package/dist/agent/Skills.d.ts.map +1 -0
  245. package/dist/agent/Skills.js +95 -0
  246. package/dist/agent/Skills.js.map +1 -0
  247. package/dist/agent/Store.d.ts +37 -0
  248. package/dist/agent/Store.d.ts.map +1 -0
  249. package/dist/agent/Store.js +50 -0
  250. package/dist/agent/Store.js.map +1 -0
  251. package/dist/agent/ToolSearch.d.ts +37 -0
  252. package/dist/agent/ToolSearch.d.ts.map +1 -0
  253. package/dist/agent/ToolSearch.js +119 -0
  254. package/dist/agent/ToolSearch.js.map +1 -0
  255. package/dist/agent/index.d.ts +37 -0
  256. package/dist/agent/index.d.ts.map +1 -0
  257. package/dist/agent/index.js +44 -0
  258. package/dist/agent/index.js.map +1 -0
  259. package/dist/agent/module.d.ts +12889 -0
  260. package/dist/agent/module.d.ts.map +1 -0
  261. package/dist/agent/module.js +1550 -0
  262. package/dist/agent/module.js.map +1 -0
  263. package/dist/appState/Sweep.d.ts +21 -0
  264. package/dist/appState/Sweep.d.ts.map +1 -0
  265. package/dist/appState/Sweep.js +46 -0
  266. package/dist/appState/Sweep.js.map +1 -0
  267. package/dist/appState/module.d.ts +1710 -0
  268. package/dist/appState/module.d.ts.map +1 -0
  269. package/dist/appState/module.js +344 -0
  270. package/dist/appState/module.js.map +1 -0
  271. package/dist/audit/module.d.ts +158 -0
  272. package/dist/audit/module.d.ts.map +1 -0
  273. package/dist/audit/module.js +72 -0
  274. package/dist/audit/module.js.map +1 -0
  275. package/dist/auth/AuthProvider.d.ts +224 -0
  276. package/dist/auth/AuthProvider.d.ts.map +1 -0
  277. package/dist/auth/AuthProvider.js +104 -0
  278. package/dist/auth/AuthProvider.js.map +1 -0
  279. package/dist/auth/BetterAuthProvider.d.ts +40 -0
  280. package/dist/auth/BetterAuthProvider.d.ts.map +1 -0
  281. package/dist/auth/BetterAuthProvider.js +458 -0
  282. package/dist/auth/BetterAuthProvider.js.map +1 -0
  283. package/dist/auth/Methods.d.ts +7 -0
  284. package/dist/auth/Methods.d.ts.map +1 -0
  285. package/dist/auth/Methods.js +7 -0
  286. package/dist/auth/Methods.js.map +1 -0
  287. package/dist/auth/SessionTokens.d.ts +23 -0
  288. package/dist/auth/SessionTokens.d.ts.map +1 -0
  289. package/dist/auth/SessionTokens.js +150 -0
  290. package/dist/auth/SessionTokens.js.map +1 -0
  291. package/dist/collab/Collab.d.ts +105 -0
  292. package/dist/collab/Collab.d.ts.map +1 -0
  293. package/dist/collab/Collab.js +475 -0
  294. package/dist/collab/Collab.js.map +1 -0
  295. package/dist/collab/Housekeeping.d.ts +38 -0
  296. package/dist/collab/Housekeeping.d.ts.map +1 -0
  297. package/dist/collab/Housekeeping.js +146 -0
  298. package/dist/collab/Housekeeping.js.map +1 -0
  299. package/dist/collab/LiveCopy.d.ts +7 -0
  300. package/dist/collab/LiveCopy.d.ts.map +1 -0
  301. package/dist/collab/LiveCopy.js +79 -0
  302. package/dist/collab/LiveCopy.js.map +1 -0
  303. package/dist/collab/Socket.d.ts +19 -0
  304. package/dist/collab/Socket.d.ts.map +1 -0
  305. package/dist/collab/Socket.js +323 -0
  306. package/dist/collab/Socket.js.map +1 -0
  307. package/dist/collab/Store.d.ts +42 -0
  308. package/dist/collab/Store.d.ts.map +1 -0
  309. package/dist/collab/Store.js +59 -0
  310. package/dist/collab/Store.js.map +1 -0
  311. package/dist/collab/Ydoc.d.ts +88 -0
  312. package/dist/collab/Ydoc.d.ts.map +1 -0
  313. package/dist/collab/Ydoc.js +314 -0
  314. package/dist/collab/Ydoc.js.map +1 -0
  315. package/dist/collab/derive/bundle.gen.d.ts +2 -0
  316. package/dist/collab/derive/bundle.gen.d.ts.map +1 -0
  317. package/dist/collab/derive/bundle.gen.js +3 -0
  318. package/dist/collab/derive/bundle.gen.js.map +1 -0
  319. package/dist/collab/derive/entry.d.ts +3 -0
  320. package/dist/collab/derive/entry.d.ts.map +1 -0
  321. package/dist/collab/derive/entry.js +35 -0
  322. package/dist/collab/derive/entry.js.map +1 -0
  323. package/dist/collab/derive/polyfill.d.ts +3 -0
  324. package/dist/collab/derive/polyfill.d.ts.map +1 -0
  325. package/dist/collab/derive/polyfill.js +17 -0
  326. package/dist/collab/derive/polyfill.js.map +1 -0
  327. package/dist/collab/module.d.ts +305 -0
  328. package/dist/collab/module.d.ts.map +1 -0
  329. package/dist/collab/module.js +161 -0
  330. package/dist/collab/module.js.map +1 -0
  331. package/dist/connections/Connections.d.ts +199 -0
  332. package/dist/connections/Connections.d.ts.map +1 -0
  333. package/dist/connections/Connections.js +1633 -0
  334. package/dist/connections/Connections.js.map +1 -0
  335. package/dist/connections/Connector.d.ts +213 -0
  336. package/dist/connections/Connector.d.ts.map +1 -0
  337. package/dist/connections/Connector.js +55 -0
  338. package/dist/connections/Connector.js.map +1 -0
  339. package/dist/connections/Crypto.d.ts +55 -0
  340. package/dist/connections/Crypto.d.ts.map +1 -0
  341. package/dist/connections/Crypto.js +100 -0
  342. package/dist/connections/Crypto.js.map +1 -0
  343. package/dist/connections/Destinations.d.ts +63 -0
  344. package/dist/connections/Destinations.d.ts.map +1 -0
  345. package/dist/connections/Destinations.js +338 -0
  346. package/dist/connections/Destinations.js.map +1 -0
  347. package/dist/connections/Discovery.d.ts +53 -0
  348. package/dist/connections/Discovery.d.ts.map +1 -0
  349. package/dist/connections/Discovery.js +209 -0
  350. package/dist/connections/Discovery.js.map +1 -0
  351. package/dist/connections/EffectKinds.d.ts +17 -0
  352. package/dist/connections/EffectKinds.d.ts.map +1 -0
  353. package/dist/connections/EffectKinds.js +26 -0
  354. package/dist/connections/EffectKinds.js.map +1 -0
  355. package/dist/connections/Effects.d.ts +49 -0
  356. package/dist/connections/Effects.d.ts.map +1 -0
  357. package/dist/connections/Effects.js +347 -0
  358. package/dist/connections/Effects.js.map +1 -0
  359. package/dist/connections/Metering.d.ts +40 -0
  360. package/dist/connections/Metering.d.ts.map +1 -0
  361. package/dist/connections/Metering.js +142 -0
  362. package/dist/connections/Metering.js.map +1 -0
  363. package/dist/connections/ProviderApi.d.ts +47 -0
  364. package/dist/connections/ProviderApi.d.ts.map +1 -0
  365. package/dist/connections/ProviderApi.js +103 -0
  366. package/dist/connections/ProviderApi.js.map +1 -0
  367. package/dist/connections/Secrets.d.ts +78 -0
  368. package/dist/connections/Secrets.d.ts.map +1 -0
  369. package/dist/connections/Secrets.js +342 -0
  370. package/dist/connections/Secrets.js.map +1 -0
  371. package/dist/connections/Sync.d.ts +85 -0
  372. package/dist/connections/Sync.d.ts.map +1 -0
  373. package/dist/connections/Sync.js +201 -0
  374. package/dist/connections/Sync.js.map +1 -0
  375. package/dist/connections/module.d.ts +1061 -0
  376. package/dist/connections/module.d.ts.map +1 -0
  377. package/dist/connections/module.js +485 -0
  378. package/dist/connections/module.js.map +1 -0
  379. package/dist/data/Corpus.d.ts +79 -0
  380. package/dist/data/Corpus.d.ts.map +1 -0
  381. package/dist/data/Corpus.js +343 -0
  382. package/dist/data/Corpus.js.map +1 -0
  383. package/dist/data/Datasets.d.ts +88 -0
  384. package/dist/data/Datasets.d.ts.map +1 -0
  385. package/dist/data/Datasets.js +375 -0
  386. package/dist/data/Datasets.js.map +1 -0
  387. package/dist/data/Programs.d.ts +58 -0
  388. package/dist/data/Programs.d.ts.map +1 -0
  389. package/dist/data/Programs.js +197 -0
  390. package/dist/data/Programs.js.map +1 -0
  391. package/dist/data/module.d.ts +210 -0
  392. package/dist/data/module.d.ts.map +1 -0
  393. package/dist/data/module.js +140 -0
  394. package/dist/data/module.js.map +1 -0
  395. package/dist/db/Bootstrap.d.ts +508 -0
  396. package/dist/db/Bootstrap.d.ts.map +1 -0
  397. package/dist/db/Bootstrap.js +2368 -0
  398. package/dist/db/Bootstrap.js.map +1 -0
  399. package/dist/db/Catalog.d.ts +10 -0
  400. package/dist/db/Catalog.d.ts.map +1 -0
  401. package/dist/db/Catalog.js +9 -0
  402. package/dist/db/Catalog.js.map +1 -0
  403. package/dist/db/Conflicts.d.ts +18 -0
  404. package/dist/db/Conflicts.d.ts.map +1 -0
  405. package/dist/db/Conflicts.js +29 -0
  406. package/dist/db/Conflicts.js.map +1 -0
  407. package/dist/db/DirectoryLock.d.ts +16 -0
  408. package/dist/db/DirectoryLock.d.ts.map +1 -0
  409. package/dist/db/DirectoryLock.js +15 -0
  410. package/dist/db/DirectoryLock.js.map +1 -0
  411. package/dist/db/HandlerGate.d.ts +28 -0
  412. package/dist/db/HandlerGate.d.ts.map +1 -0
  413. package/dist/db/HandlerGate.js +76 -0
  414. package/dist/db/HandlerGate.js.map +1 -0
  415. package/dist/db/Host.d.ts +94 -0
  416. package/dist/db/Host.d.ts.map +1 -0
  417. package/dist/db/Host.js +189 -0
  418. package/dist/db/Host.js.map +1 -0
  419. package/dist/db/KernelSchema.d.ts +52 -0
  420. package/dist/db/KernelSchema.d.ts.map +1 -0
  421. package/dist/db/KernelSchema.js +4313 -0
  422. package/dist/db/KernelSchema.js.map +1 -0
  423. package/dist/db/MigrationCheck.d.ts +38 -0
  424. package/dist/db/MigrationCheck.d.ts.map +1 -0
  425. package/dist/db/MigrationCheck.js +180 -0
  426. package/dist/db/MigrationCheck.js.map +1 -0
  427. package/dist/db/QueryViewCheck.d.ts +172 -0
  428. package/dist/db/QueryViewCheck.d.ts.map +1 -0
  429. package/dist/db/QueryViewCheck.js +967 -0
  430. package/dist/db/QueryViewCheck.js.map +1 -0
  431. package/dist/db/ReadOnly.d.ts +13 -0
  432. package/dist/db/ReadOnly.d.ts.map +1 -0
  433. package/dist/db/ReadOnly.js +16 -0
  434. package/dist/db/ReadOnly.js.map +1 -0
  435. package/dist/db/Scram.d.ts +5 -0
  436. package/dist/db/Scram.d.ts.map +1 -0
  437. package/dist/db/Scram.js +17 -0
  438. package/dist/db/Scram.js.map +1 -0
  439. package/dist/db/SqlState.d.ts +36 -0
  440. package/dist/db/SqlState.d.ts.map +1 -0
  441. package/dist/db/SqlState.js +64 -0
  442. package/dist/db/SqlState.js.map +1 -0
  443. package/dist/db/Startup.d.ts +18 -0
  444. package/dist/db/Startup.d.ts.map +1 -0
  445. package/dist/db/Startup.js +22 -0
  446. package/dist/db/Startup.js.map +1 -0
  447. package/dist/db/ZeroDdl.d.ts +85 -0
  448. package/dist/db/ZeroDdl.d.ts.map +1 -0
  449. package/dist/db/ZeroDdl.js +240 -0
  450. package/dist/db/ZeroDdl.js.map +1 -0
  451. package/dist/db/ZeroPush.d.ts +7 -0
  452. package/dist/db/ZeroPush.d.ts.map +1 -0
  453. package/dist/db/ZeroPush.js +126 -0
  454. package/dist/db/ZeroPush.js.map +1 -0
  455. package/dist/devices/Devices.d.ts +130 -0
  456. package/dist/devices/Devices.d.ts.map +1 -0
  457. package/dist/devices/Devices.js +769 -0
  458. package/dist/devices/Devices.js.map +1 -0
  459. package/dist/devices/Flow.d.ts +47 -0
  460. package/dist/devices/Flow.d.ts.map +1 -0
  461. package/dist/devices/Flow.js +131 -0
  462. package/dist/devices/Flow.js.map +1 -0
  463. package/dist/devices/Http.d.ts +6 -0
  464. package/dist/devices/Http.d.ts.map +1 -0
  465. package/dist/devices/Http.js +103 -0
  466. package/dist/devices/Http.js.map +1 -0
  467. package/dist/devices/module.d.ts +1313 -0
  468. package/dist/devices/module.d.ts.map +1 -0
  469. package/dist/devices/module.js +266 -0
  470. package/dist/devices/module.js.map +1 -0
  471. package/dist/durable/Cluster.d.ts +13 -0
  472. package/dist/durable/Cluster.d.ts.map +1 -0
  473. package/dist/durable/Cluster.js +57 -0
  474. package/dist/durable/Cluster.js.map +1 -0
  475. package/dist/durable/Definition.d.ts +215 -0
  476. package/dist/durable/Definition.d.ts.map +1 -0
  477. package/dist/durable/Definition.js +18 -0
  478. package/dist/durable/Definition.js.map +1 -0
  479. package/dist/durable/Schedule.d.ts +46 -0
  480. package/dist/durable/Schedule.d.ts.map +1 -0
  481. package/dist/durable/Schedule.js +120 -0
  482. package/dist/durable/Schedule.js.map +1 -0
  483. package/dist/durable/Trust.d.ts +90 -0
  484. package/dist/durable/Trust.d.ts.map +1 -0
  485. package/dist/durable/Trust.js +61 -0
  486. package/dist/durable/Trust.js.map +1 -0
  487. package/dist/enterprise/Routes.d.ts +32 -0
  488. package/dist/enterprise/Routes.d.ts.map +1 -0
  489. package/dist/enterprise/Routes.js +448 -0
  490. package/dist/enterprise/Routes.js.map +1 -0
  491. package/dist/enterprise/WorkOs.d.ts +42 -0
  492. package/dist/enterprise/WorkOs.d.ts.map +1 -0
  493. package/dist/enterprise/WorkOs.js +109 -0
  494. package/dist/enterprise/WorkOs.js.map +1 -0
  495. package/dist/files/FileTable.d.ts +937 -0
  496. package/dist/files/FileTable.d.ts.map +1 -0
  497. package/dist/files/FileTable.js +79 -0
  498. package/dist/files/FileTable.js.map +1 -0
  499. package/dist/files/Files.d.ts +169 -0
  500. package/dist/files/Files.d.ts.map +1 -0
  501. package/dist/files/Files.js +1232 -0
  502. package/dist/files/Files.js.map +1 -0
  503. package/dist/files/Http.d.ts +13 -0
  504. package/dist/files/Http.d.ts.map +1 -0
  505. package/dist/files/Http.js +30 -0
  506. package/dist/files/Http.js.map +1 -0
  507. package/dist/files/LocalStorage.d.ts +7 -0
  508. package/dist/files/LocalStorage.d.ts.map +1 -0
  509. package/dist/files/LocalStorage.js +284 -0
  510. package/dist/files/LocalStorage.js.map +1 -0
  511. package/dist/files/Providers.d.ts +64 -0
  512. package/dist/files/Providers.d.ts.map +1 -0
  513. package/dist/files/Providers.js +245 -0
  514. package/dist/files/Providers.js.map +1 -0
  515. package/dist/files/S3Storage.d.ts +27 -0
  516. package/dist/files/S3Storage.d.ts.map +1 -0
  517. package/dist/files/S3Storage.js +301 -0
  518. package/dist/files/S3Storage.js.map +1 -0
  519. package/dist/files/SigV4.d.ts +65 -0
  520. package/dist/files/SigV4.d.ts.map +1 -0
  521. package/dist/files/SigV4.js +152 -0
  522. package/dist/files/SigV4.js.map +1 -0
  523. package/dist/files/Sniff.d.ts +50 -0
  524. package/dist/files/Sniff.d.ts.map +1 -0
  525. package/dist/files/Sniff.js +223 -0
  526. package/dist/files/Sniff.js.map +1 -0
  527. package/dist/files/Storage.d.ts +75 -0
  528. package/dist/files/Storage.d.ts.map +1 -0
  529. package/dist/files/Storage.js +70 -0
  530. package/dist/files/Storage.js.map +1 -0
  531. package/dist/files/module.d.ts +666 -0
  532. package/dist/files/module.d.ts.map +1 -0
  533. package/dist/files/module.js +217 -0
  534. package/dist/files/module.js.map +1 -0
  535. package/dist/flags/module.d.ts +966 -0
  536. package/dist/flags/module.d.ts.map +1 -0
  537. package/dist/flags/module.js +146 -0
  538. package/dist/flags/module.js.map +1 -0
  539. package/dist/inbox/Flow.d.ts +49 -0
  540. package/dist/inbox/Flow.d.ts.map +1 -0
  541. package/dist/inbox/Flow.js +425 -0
  542. package/dist/inbox/Flow.js.map +1 -0
  543. package/dist/inbox/System.d.ts +11 -0
  544. package/dist/inbox/System.d.ts.map +1 -0
  545. package/dist/inbox/System.js +26 -0
  546. package/dist/inbox/System.js.map +1 -0
  547. package/dist/inbox/approvals.d.ts +1548 -0
  548. package/dist/inbox/approvals.d.ts.map +1 -0
  549. package/dist/inbox/approvals.js +268 -0
  550. package/dist/inbox/approvals.js.map +1 -0
  551. package/dist/inbox/consent.d.ts +1213 -0
  552. package/dist/inbox/consent.d.ts.map +1 -0
  553. package/dist/inbox/consent.js +281 -0
  554. package/dist/inbox/consent.js.map +1 -0
  555. package/dist/inbox/index.d.ts +2231 -0
  556. package/dist/inbox/index.d.ts.map +1 -0
  557. package/dist/inbox/index.js +22 -0
  558. package/dist/inbox/index.js.map +1 -0
  559. package/dist/inbox/notifications.d.ts +2743 -0
  560. package/dist/inbox/notifications.d.ts.map +1 -0
  561. package/dist/inbox/notifications.js +362 -0
  562. package/dist/inbox/notifications.js.map +1 -0
  563. package/dist/inbox/tables.d.ts +1992 -0
  564. package/dist/inbox/tables.d.ts.map +1 -0
  565. package/dist/inbox/tables.js +149 -0
  566. package/dist/inbox/tables.js.map +1 -0
  567. package/dist/inbox/workItems.d.ts +1188 -0
  568. package/dist/inbox/workItems.d.ts.map +1 -0
  569. package/dist/inbox/workItems.js +158 -0
  570. package/dist/inbox/workItems.js.map +1 -0
  571. package/dist/index.d.ts +152 -0
  572. package/dist/index.d.ts.map +1 -0
  573. package/dist/index.js +154 -0
  574. package/dist/index.js.map +1 -0
  575. package/dist/ingestion/Chunk.d.ts +15 -0
  576. package/dist/ingestion/Chunk.d.ts.map +1 -0
  577. package/dist/ingestion/Chunk.js +49 -0
  578. package/dist/ingestion/Chunk.js.map +1 -0
  579. package/dist/ingestion/Extract.d.ts +69 -0
  580. package/dist/ingestion/Extract.d.ts.map +1 -0
  581. package/dist/ingestion/Extract.js +376 -0
  582. package/dist/ingestion/Extract.js.map +1 -0
  583. package/dist/ingestion/ExtractChild.d.ts +2 -0
  584. package/dist/ingestion/ExtractChild.d.ts.map +1 -0
  585. package/dist/ingestion/ExtractChild.js +54 -0
  586. package/dist/ingestion/ExtractChild.js.map +1 -0
  587. package/dist/ingestion/ExtractPool.d.ts +38 -0
  588. package/dist/ingestion/ExtractPool.d.ts.map +1 -0
  589. package/dist/ingestion/ExtractPool.js +203 -0
  590. package/dist/ingestion/ExtractPool.js.map +1 -0
  591. package/dist/ingestion/Ingestion.d.ts +183 -0
  592. package/dist/ingestion/Ingestion.d.ts.map +1 -0
  593. package/dist/ingestion/Ingestion.js +650 -0
  594. package/dist/ingestion/Ingestion.js.map +1 -0
  595. package/dist/ingestion/Isolated.d.ts +18 -0
  596. package/dist/ingestion/Isolated.d.ts.map +1 -0
  597. package/dist/ingestion/Isolated.js +15 -0
  598. package/dist/ingestion/Isolated.js.map +1 -0
  599. package/dist/ingestion/Markup.d.ts +29 -0
  600. package/dist/ingestion/Markup.d.ts.map +1 -0
  601. package/dist/ingestion/Markup.js +111 -0
  602. package/dist/ingestion/Markup.js.map +1 -0
  603. package/dist/ingestion/Pdf.d.ts +6 -0
  604. package/dist/ingestion/Pdf.d.ts.map +1 -0
  605. package/dist/ingestion/Pdf.js +192 -0
  606. package/dist/ingestion/Pdf.js.map +1 -0
  607. package/dist/ingestion/Runs.d.ts +59 -0
  608. package/dist/ingestion/Runs.d.ts.map +1 -0
  609. package/dist/ingestion/Runs.js +128 -0
  610. package/dist/ingestion/Runs.js.map +1 -0
  611. package/dist/ingestion/Scrub.d.ts +16 -0
  612. package/dist/ingestion/Scrub.d.ts.map +1 -0
  613. package/dist/ingestion/Scrub.js +15 -0
  614. package/dist/ingestion/Scrub.js.map +1 -0
  615. package/dist/ingestion/Zip.d.ts +19 -0
  616. package/dist/ingestion/Zip.d.ts.map +1 -0
  617. package/dist/ingestion/Zip.js +85 -0
  618. package/dist/ingestion/Zip.js.map +1 -0
  619. package/dist/ingestion/module.d.ts +111 -0
  620. package/dist/ingestion/module.d.ts.map +1 -0
  621. package/dist/ingestion/module.js +51 -0
  622. package/dist/ingestion/module.js.map +1 -0
  623. package/dist/ingress/Definition.d.ts +146 -0
  624. package/dist/ingress/Definition.d.ts.map +1 -0
  625. package/dist/ingress/Definition.js +12 -0
  626. package/dist/ingress/Definition.js.map +1 -0
  627. package/dist/ingress/Ingress.d.ts +61 -0
  628. package/dist/ingress/Ingress.d.ts.map +1 -0
  629. package/dist/ingress/Ingress.js +929 -0
  630. package/dist/ingress/Ingress.js.map +1 -0
  631. package/dist/ingress/Verifiers.d.ts +43 -0
  632. package/dist/ingress/Verifiers.d.ts.map +1 -0
  633. package/dist/ingress/Verifiers.js +137 -0
  634. package/dist/ingress/Verifiers.js.map +1 -0
  635. package/dist/machine/MachineIdentity.d.ts +34 -0
  636. package/dist/machine/MachineIdentity.d.ts.map +1 -0
  637. package/dist/machine/MachineIdentity.js +200 -0
  638. package/dist/machine/MachineIdentity.js.map +1 -0
  639. package/dist/machine/Managed.d.ts +40 -0
  640. package/dist/machine/Managed.d.ts.map +1 -0
  641. package/dist/machine/Managed.js +163 -0
  642. package/dist/machine/Managed.js.map +1 -0
  643. package/dist/machine/OAuth.d.ts +11 -0
  644. package/dist/machine/OAuth.d.ts.map +1 -0
  645. package/dist/machine/OAuth.js +913 -0
  646. package/dist/machine/OAuth.js.map +1 -0
  647. package/dist/machine/Pages.d.ts +64 -0
  648. package/dist/machine/Pages.d.ts.map +1 -0
  649. package/dist/machine/Pages.js +54 -0
  650. package/dist/machine/Pages.js.map +1 -0
  651. package/dist/machine/Tokens.d.ts +25 -0
  652. package/dist/machine/Tokens.d.ts.map +1 -0
  653. package/dist/machine/Tokens.js +62 -0
  654. package/dist/machine/Tokens.js.map +1 -0
  655. package/dist/make/Credentials.d.ts +8 -0
  656. package/dist/make/Credentials.d.ts.map +1 -0
  657. package/dist/make/Credentials.js +29 -0
  658. package/dist/make/Credentials.js.map +1 -0
  659. package/dist/make/Example.d.ts +159 -0
  660. package/dist/make/Example.d.ts.map +1 -0
  661. package/dist/make/Example.js +94 -0
  662. package/dist/make/Example.js.map +1 -0
  663. package/dist/make/Execute.d.ts +151 -0
  664. package/dist/make/Execute.d.ts.map +1 -0
  665. package/dist/make/Execute.js +316 -0
  666. package/dist/make/Execute.js.map +1 -0
  667. package/dist/make/Http.d.ts +17 -0
  668. package/dist/make/Http.d.ts.map +1 -0
  669. package/dist/make/Http.js +63 -0
  670. package/dist/make/Http.js.map +1 -0
  671. package/dist/make/Lifecycle.d.ts +167 -0
  672. package/dist/make/Lifecycle.d.ts.map +1 -0
  673. package/dist/make/Lifecycle.js +580 -0
  674. package/dist/make/Lifecycle.js.map +1 -0
  675. package/dist/make/Manifest.d.ts +61 -0
  676. package/dist/make/Manifest.d.ts.map +1 -0
  677. package/dist/make/Manifest.js +792 -0
  678. package/dist/make/Manifest.js.map +1 -0
  679. package/dist/make/Repair.d.ts +111 -0
  680. package/dist/make/Repair.d.ts.map +1 -0
  681. package/dist/make/Repair.js +236 -0
  682. package/dist/make/Repair.js.map +1 -0
  683. package/dist/make/Runtime.d.ts +144 -0
  684. package/dist/make/Runtime.d.ts.map +1 -0
  685. package/dist/make/Runtime.js +309 -0
  686. package/dist/make/Runtime.js.map +1 -0
  687. package/dist/make/Session.d.ts +19 -0
  688. package/dist/make/Session.d.ts.map +1 -0
  689. package/dist/make/Session.js +27 -0
  690. package/dist/make/Session.js.map +1 -0
  691. package/dist/make/SqlGuard.d.ts +48 -0
  692. package/dist/make/SqlGuard.d.ts.map +1 -0
  693. package/dist/make/SqlGuard.js +333 -0
  694. package/dist/make/SqlGuard.js.map +1 -0
  695. package/dist/make/Subscribe.d.ts +18 -0
  696. package/dist/make/Subscribe.d.ts.map +1 -0
  697. package/dist/make/Subscribe.js +175 -0
  698. package/dist/make/Subscribe.js.map +1 -0
  699. package/dist/make/Validate.d.ts +47 -0
  700. package/dist/make/Validate.d.ts.map +1 -0
  701. package/dist/make/Validate.js +222 -0
  702. package/dist/make/Validate.js.map +1 -0
  703. package/dist/make/ViewStep.d.ts +27 -0
  704. package/dist/make/ViewStep.d.ts.map +1 -0
  705. package/dist/make/ViewStep.js +43 -0
  706. package/dist/make/ViewStep.js.map +1 -0
  707. package/dist/make/module.d.ts +808 -0
  708. package/dist/make/module.d.ts.map +1 -0
  709. package/dist/make/module.js +232 -0
  710. package/dist/make/module.js.map +1 -0
  711. package/dist/notifications/Decide.d.ts +29 -0
  712. package/dist/notifications/Decide.d.ts.map +1 -0
  713. package/dist/notifications/Decide.js +395 -0
  714. package/dist/notifications/Decide.js.map +1 -0
  715. package/dist/notifications/Providers.d.ts +110 -0
  716. package/dist/notifications/Providers.d.ts.map +1 -0
  717. package/dist/notifications/Providers.js +404 -0
  718. package/dist/notifications/Providers.js.map +1 -0
  719. package/dist/notifications/Push.d.ts +189 -0
  720. package/dist/notifications/Push.d.ts.map +1 -0
  721. package/dist/notifications/Push.js +457 -0
  722. package/dist/notifications/Push.js.map +1 -0
  723. package/dist/notifications/Smtp.d.ts +74 -0
  724. package/dist/notifications/Smtp.d.ts.map +1 -0
  725. package/dist/notifications/Smtp.js +344 -0
  726. package/dist/notifications/Smtp.js.map +1 -0
  727. package/dist/policy/CedarSchema.d.ts +47 -0
  728. package/dist/policy/CedarSchema.d.ts.map +1 -0
  729. package/dist/policy/CedarSchema.js +115 -0
  730. package/dist/policy/CedarSchema.js.map +1 -0
  731. package/dist/policy/Compiler.d.ts +364 -0
  732. package/dist/policy/Compiler.d.ts.map +1 -0
  733. package/dist/policy/Compiler.js +1311 -0
  734. package/dist/policy/Compiler.js.map +1 -0
  735. package/dist/policy/Policy.d.ts +70 -0
  736. package/dist/policy/Policy.d.ts.map +1 -0
  737. package/dist/policy/Policy.js +114 -0
  738. package/dist/policy/Policy.js.map +1 -0
  739. package/dist/policy/Rls.d.ts +110 -0
  740. package/dist/policy/Rls.d.ts.map +1 -0
  741. package/dist/policy/Rls.js +314 -0
  742. package/dist/policy/Rls.js.map +1 -0
  743. package/dist/policy/Row.d.ts +17 -0
  744. package/dist/policy/Row.d.ts.map +1 -0
  745. package/dist/policy/Row.js +3 -0
  746. package/dist/policy/Row.js.map +1 -0
  747. package/dist/privacy/Flow.d.ts +20 -0
  748. package/dist/privacy/Flow.d.ts.map +1 -0
  749. package/dist/privacy/Flow.js +193 -0
  750. package/dist/privacy/Flow.js.map +1 -0
  751. package/dist/privacy/Inventory.d.ts +110 -0
  752. package/dist/privacy/Inventory.d.ts.map +1 -0
  753. package/dist/privacy/Inventory.js +1704 -0
  754. package/dist/privacy/Inventory.js.map +1 -0
  755. package/dist/privacy/Sources.d.ts +86 -0
  756. package/dist/privacy/Sources.d.ts.map +1 -0
  757. package/dist/privacy/Sources.js +598 -0
  758. package/dist/privacy/Sources.js.map +1 -0
  759. package/dist/privacy/Visits.d.ts +21 -0
  760. package/dist/privacy/Visits.d.ts.map +1 -0
  761. package/dist/privacy/Visits.js +279 -0
  762. package/dist/privacy/Visits.js.map +1 -0
  763. package/dist/privacy/ZeroCvr.d.ts +15 -0
  764. package/dist/privacy/ZeroCvr.d.ts.map +1 -0
  765. package/dist/privacy/ZeroCvr.js +63 -0
  766. package/dist/privacy/ZeroCvr.js.map +1 -0
  767. package/dist/privacy/module.d.ts +2505 -0
  768. package/dist/privacy/module.d.ts.map +1 -0
  769. package/dist/privacy/module.js +228 -0
  770. package/dist/privacy/module.js.map +1 -0
  771. package/dist/progress/module.d.ts +1572 -0
  772. package/dist/progress/module.d.ts.map +1 -0
  773. package/dist/progress/module.js +139 -0
  774. package/dist/progress/module.js.map +1 -0
  775. package/dist/proposals/module.d.ts +275 -0
  776. package/dist/proposals/module.d.ts.map +1 -0
  777. package/dist/proposals/module.js +269 -0
  778. package/dist/proposals/module.js.map +1 -0
  779. package/dist/query/module.d.ts +91 -0
  780. package/dist/query/module.d.ts.map +1 -0
  781. package/dist/query/module.js +50 -0
  782. package/dist/query/module.js.map +1 -0
  783. package/dist/records/Access.d.ts +26 -0
  784. package/dist/records/Access.d.ts.map +1 -0
  785. package/dist/records/Access.js +43 -0
  786. package/dist/records/Access.js.map +1 -0
  787. package/dist/records/References.d.ts +18 -0
  788. package/dist/records/References.d.ts.map +1 -0
  789. package/dist/records/References.js +47 -0
  790. package/dist/records/References.js.map +1 -0
  791. package/dist/runtime/bun.d.ts +29 -0
  792. package/dist/runtime/bun.d.ts.map +1 -0
  793. package/dist/runtime/bun.js +71 -0
  794. package/dist/runtime/bun.js.map +1 -0
  795. package/dist/runtime/idle.d.ts +5 -0
  796. package/dist/runtime/idle.d.ts.map +1 -0
  797. package/dist/runtime/idle.js +61 -0
  798. package/dist/runtime/idle.js.map +1 -0
  799. package/dist/runtime/node.d.ts +36 -0
  800. package/dist/runtime/node.d.ts.map +1 -0
  801. package/dist/runtime/node.js +86 -0
  802. package/dist/runtime/node.js.map +1 -0
  803. package/dist/runtime/resolve.d.ts +8 -0
  804. package/dist/runtime/resolve.d.ts.map +1 -0
  805. package/dist/runtime/resolve.js +136 -0
  806. package/dist/runtime/resolve.js.map +1 -0
  807. package/dist/sandbox/Sandbox.d.ts +86 -0
  808. package/dist/sandbox/Sandbox.d.ts.map +1 -0
  809. package/dist/sandbox/Sandbox.js +246 -0
  810. package/dist/sandbox/Sandbox.js.map +1 -0
  811. package/dist/sandbox/worker.d.ts +93 -0
  812. package/dist/sandbox/worker.d.ts.map +1 -0
  813. package/dist/sandbox/worker.js +503 -0
  814. package/dist/sandbox/worker.js.map +1 -0
  815. package/dist/scheduler/Automations.d.ts +99 -0
  816. package/dist/scheduler/Automations.d.ts.map +1 -0
  817. package/dist/scheduler/Automations.js +247 -0
  818. package/dist/scheduler/Automations.js.map +1 -0
  819. package/dist/scheduler/History.d.ts +61 -0
  820. package/dist/scheduler/History.d.ts.map +1 -0
  821. package/dist/scheduler/History.js +154 -0
  822. package/dist/scheduler/History.js.map +1 -0
  823. package/dist/scheduler/module.d.ts +2365 -0
  824. package/dist/scheduler/module.d.ts.map +1 -0
  825. package/dist/scheduler/module.js +370 -0
  826. package/dist/scheduler/module.js.map +1 -0
  827. package/dist/search/RecordLock.d.ts +22 -0
  828. package/dist/search/RecordLock.d.ts.map +1 -0
  829. package/dist/search/RecordLock.js +21 -0
  830. package/dist/search/RecordLock.js.map +1 -0
  831. package/dist/search/Search.d.ts +63 -0
  832. package/dist/search/Search.d.ts.map +1 -0
  833. package/dist/search/Search.js +424 -0
  834. package/dist/search/Search.js.map +1 -0
  835. package/dist/search/Sources.d.ts +56 -0
  836. package/dist/search/Sources.d.ts.map +1 -0
  837. package/dist/search/Sources.js +121 -0
  838. package/dist/search/Sources.js.map +1 -0
  839. package/dist/search/module.d.ts +72 -0
  840. package/dist/search/module.d.ts.map +1 -0
  841. package/dist/search/module.js +44 -0
  842. package/dist/search/module.js.map +1 -0
  843. package/dist/settings/module.d.ts +677 -0
  844. package/dist/settings/module.d.ts.map +1 -0
  845. package/dist/settings/module.js +103 -0
  846. package/dist/settings/module.js.map +1 -0
  847. package/dist/sharing/module.d.ts +1105 -0
  848. package/dist/sharing/module.d.ts.map +1 -0
  849. package/dist/sharing/module.js +295 -0
  850. package/dist/sharing/module.js.map +1 -0
  851. package/dist/spaces/module.d.ts +1787 -0
  852. package/dist/spaces/module.d.ts.map +1 -0
  853. package/dist/spaces/module.js +248 -0
  854. package/dist/spaces/module.js.map +1 -0
  855. package/dist/surfaces/Agent.d.ts +89 -0
  856. package/dist/surfaces/Agent.d.ts.map +1 -0
  857. package/dist/surfaces/Agent.js +112 -0
  858. package/dist/surfaces/Agent.js.map +1 -0
  859. package/dist/surfaces/CookieGuard.d.ts +77 -0
  860. package/dist/surfaces/CookieGuard.d.ts.map +1 -0
  861. package/dist/surfaces/CookieGuard.js +373 -0
  862. package/dist/surfaces/CookieGuard.js.map +1 -0
  863. package/dist/surfaces/Http.d.ts +15 -0
  864. package/dist/surfaces/Http.d.ts.map +1 -0
  865. package/dist/surfaces/Http.js +250 -0
  866. package/dist/surfaces/Http.js.map +1 -0
  867. package/dist/surfaces/Mcp.d.ts +90 -0
  868. package/dist/surfaces/Mcp.d.ts.map +1 -0
  869. package/dist/surfaces/Mcp.js +443 -0
  870. package/dist/surfaces/Mcp.js.map +1 -0
  871. package/dist/surfaces/Rpc.d.ts +15 -0
  872. package/dist/surfaces/Rpc.d.ts.map +1 -0
  873. package/dist/surfaces/Rpc.js +68 -0
  874. package/dist/surfaces/Rpc.js.map +1 -0
  875. package/dist/surfaces/headers.d.ts +9 -0
  876. package/dist/surfaces/headers.d.ts.map +1 -0
  877. package/dist/surfaces/headers.js +15 -0
  878. package/dist/surfaces/headers.js.map +1 -0
  879. package/dist/surfaces/request.d.ts +68 -0
  880. package/dist/surfaces/request.d.ts.map +1 -0
  881. package/dist/surfaces/request.js +130 -0
  882. package/dist/surfaces/request.js.map +1 -0
  883. package/dist/telemetry/module.d.ts +74 -0
  884. package/dist/telemetry/module.d.ts.map +1 -0
  885. package/dist/telemetry/module.js +77 -0
  886. package/dist/telemetry/module.js.map +1 -0
  887. package/dist/versioning/module.d.ts +231 -0
  888. package/dist/versioning/module.d.ts.map +1 -0
  889. package/dist/versioning/module.js +151 -0
  890. package/dist/versioning/module.js.map +1 -0
  891. package/package.json +71 -3
  892. package/src/AccountMail.ts +218 -0
  893. package/src/AppConfig.ts +148 -0
  894. package/src/Approvals.ts +555 -0
  895. package/src/Audit.ts +381 -0
  896. package/src/AuthSeam.ts +136 -0
  897. package/src/Authority.ts +577 -0
  898. package/src/Avatars.ts +172 -0
  899. package/src/Base64url.ts +23 -0
  900. package/src/BasePath.ts +80 -0
  901. package/src/CallActed.ts +10 -0
  902. package/src/Config.ts +857 -0
  903. package/src/DeliveryPolicy.ts +52 -0
  904. package/src/DesktopSignIn.ts +181 -0
  905. package/src/Directory.ts +1792 -0
  906. package/src/Flags.ts +281 -0
  907. package/src/Gate.ts +159 -0
  908. package/src/Hash.ts +14 -0
  909. package/src/Identity.ts +1811 -0
  910. package/src/IntervalJob.ts +96 -0
  911. package/src/Invocation.ts +2387 -0
  912. package/src/KernelHandlers.ts +29 -0
  913. package/src/KernelModule.ts +165 -0
  914. package/src/MemberRoutes.ts +146 -0
  915. package/src/Module.ts +573 -0
  916. package/src/ModuleIdentity.ts +134 -0
  917. package/src/Notifications.ts +665 -0
  918. package/src/Outbox.ts +761 -0
  919. package/src/Privacy.ts +265 -0
  920. package/src/Progress.ts +360 -0
  921. package/src/QuerySurface.ts +559 -0
  922. package/src/QueryViews.ts +165 -0
  923. package/src/Readiness.ts +284 -0
  924. package/src/Redact.ts +22 -0
  925. package/src/Registry.ts +399 -0
  926. package/src/Release.ts +1197 -0
  927. package/src/Retention.ts +167 -0
  928. package/src/Scheduler.ts +657 -0
  929. package/src/Server.ts +1838 -0
  930. package/src/Sessions.ts +56 -0
  931. package/src/Settings.ts +312 -0
  932. package/src/Sharing.ts +525 -0
  933. package/src/Sync.ts +1478 -0
  934. package/src/Telemetry.ts +754 -0
  935. package/src/Versioning.ts +588 -0
  936. package/src/WorkItems.ts +367 -0
  937. package/src/Workflows.ts +746 -0
  938. package/src/agent/Admission.ts +37 -0
  939. package/src/agent/Channels.ts +58 -0
  940. package/src/agent/Context.ts +430 -0
  941. package/src/agent/Http.ts +523 -0
  942. package/src/agent/Metering.ts +625 -0
  943. package/src/agent/ModelSetup.ts +414 -0
  944. package/src/agent/Models.ts +850 -0
  945. package/src/agent/Processors.ts +156 -0
  946. package/src/agent/Queue.ts +97 -0
  947. package/src/agent/Receipts.ts +192 -0
  948. package/src/agent/Resources.ts +376 -0
  949. package/src/agent/Run.ts +3762 -0
  950. package/src/agent/Runtime.ts +635 -0
  951. package/src/agent/Settings.ts +171 -0
  952. package/src/agent/Skills.ts +118 -0
  953. package/src/agent/Store.ts +73 -0
  954. package/src/agent/ToolSearch.ts +152 -0
  955. package/src/agent/index.ts +68 -0
  956. package/src/agent/migrations/agent/0000_agent.sql +162 -0
  957. package/src/agent/migrations/agent/0001_model_call.sql +33 -0
  958. package/src/agent/migrations/agent/0002_device.sql +2 -0
  959. package/src/agent/migrations/agent/0003_authority.sql +1 -0
  960. package/src/agent/migrations/agent/0004_budget_alert.sql +2 -0
  961. package/src/agent/migrations/agent/0005_feedback.sql +13 -0
  962. package/src/agent/migrations/agent/0095_run_options.sql +3 -0
  963. package/src/agent/migrations/agent/0096_conversation_meta.sql +7 -0
  964. package/src/agent/migrations/agent/0097_submission.sql +26 -0
  965. package/src/agent/migrations/agent/0098_threads.sql +21 -0
  966. package/src/agent/migrations/agent/0099_submission_refused.sql +4 -0
  967. package/src/agent/migrations/agent/0142_teams.sql +19 -0
  968. package/src/agent/module.ts +1793 -0
  969. package/src/appState/Sweep.ts +66 -0
  970. package/src/appState/migrations/0000_app_state.sql +35 -0
  971. package/src/appState/module.ts +418 -0
  972. package/src/audit/migrations/README.md +1 -0
  973. package/src/audit/module.ts +95 -0
  974. package/src/auth/AuthProvider.ts +293 -0
  975. package/src/auth/BetterAuthProvider.ts +476 -0
  976. package/src/auth/Methods.ts +7 -0
  977. package/src/auth/SessionTokens.ts +156 -0
  978. package/src/collab/Collab.ts +708 -0
  979. package/src/collab/Housekeeping.ts +193 -0
  980. package/src/collab/LiveCopy.ts +98 -0
  981. package/src/collab/Socket.ts +380 -0
  982. package/src/collab/Store.ts +105 -0
  983. package/src/collab/Ydoc.ts +337 -0
  984. package/src/collab/derive/bundle.gen.ts +2 -0
  985. package/src/collab/derive/entry.ts +34 -0
  986. package/src/collab/derive/polyfill.ts +15 -0
  987. package/src/collab/migrations/.gitkeep +0 -0
  988. package/src/collab/module.ts +237 -0
  989. package/src/connections/Connections.ts +2315 -0
  990. package/src/connections/Connector.ts +304 -0
  991. package/src/connections/Crypto.ts +134 -0
  992. package/src/connections/Destinations.ts +351 -0
  993. package/src/connections/Discovery.ts +251 -0
  994. package/src/connections/EffectKinds.ts +30 -0
  995. package/src/connections/Effects.ts +541 -0
  996. package/src/connections/Metering.ts +205 -0
  997. package/src/connections/ProviderApi.ts +137 -0
  998. package/src/connections/Secrets.ts +581 -0
  999. package/src/connections/Sync.ts +318 -0
  1000. package/src/connections/migrations/.gitkeep +0 -0
  1001. package/src/connections/module.ts +584 -0
  1002. package/src/data/Corpus.ts +434 -0
  1003. package/src/data/Datasets.ts +479 -0
  1004. package/src/data/Programs.ts +285 -0
  1005. package/src/data/migrations/README.md +1 -0
  1006. package/src/data/module.ts +177 -0
  1007. package/src/db/Bootstrap.ts +2832 -0
  1008. package/src/db/Catalog.ts +10 -0
  1009. package/src/db/Conflicts.ts +42 -0
  1010. package/src/db/DirectoryLock.ts +19 -0
  1011. package/src/db/HandlerGate.ts +107 -0
  1012. package/src/db/Host.ts +250 -0
  1013. package/src/db/KernelSchema.ts +4422 -0
  1014. package/src/db/MigrationCheck.ts +221 -0
  1015. package/src/db/QueryViewCheck.ts +1035 -0
  1016. package/src/db/ReadOnly.ts +23 -0
  1017. package/src/db/Scram.ts +20 -0
  1018. package/src/db/SqlState.ts +77 -0
  1019. package/src/db/Startup.ts +25 -0
  1020. package/src/db/ZeroDdl.ts +272 -0
  1021. package/src/db/ZeroPush.ts +128 -0
  1022. package/src/db/schema.snapshot.json +13831 -0
  1023. package/src/devices/Devices.ts +1219 -0
  1024. package/src/devices/Flow.ts +198 -0
  1025. package/src/devices/Http.ts +212 -0
  1026. package/src/devices/migrations/0000_devices.sql +53 -0
  1027. package/src/devices/migrations/0001_parent_run.sql +2 -0
  1028. package/src/devices/migrations/0002_authority.sql +1 -0
  1029. package/src/devices/migrations/0003_follow_up.sql +4 -0
  1030. package/src/devices/migrations/0004_commands.sql +30 -0
  1031. package/src/devices/migrations/0005_command_cancel.sql +7 -0
  1032. package/src/devices/module.ts +313 -0
  1033. package/src/durable/Cluster.ts +90 -0
  1034. package/src/durable/Definition.ts +244 -0
  1035. package/src/durable/Schedule.ts +155 -0
  1036. package/src/durable/Trust.ts +149 -0
  1037. package/src/enterprise/Routes.ts +501 -0
  1038. package/src/enterprise/WorkOs.ts +133 -0
  1039. package/src/files/FileTable.ts +84 -0
  1040. package/src/files/Files.ts +1652 -0
  1041. package/src/files/Http.ts +46 -0
  1042. package/src/files/LocalStorage.ts +348 -0
  1043. package/src/files/Providers.ts +356 -0
  1044. package/src/files/S3Storage.ts +403 -0
  1045. package/src/files/SigV4.ts +222 -0
  1046. package/src/files/Sniff.ts +218 -0
  1047. package/src/files/Storage.ts +143 -0
  1048. package/src/files/migrations/README.md +1 -0
  1049. package/src/files/module.ts +282 -0
  1050. package/src/flags/migrations/0000_flags.sql +20 -0
  1051. package/src/flags/module.ts +178 -0
  1052. package/src/inbox/Flow.ts +548 -0
  1053. package/src/inbox/System.ts +33 -0
  1054. package/src/inbox/approvals.ts +335 -0
  1055. package/src/inbox/consent.ts +331 -0
  1056. package/src/inbox/index.ts +24 -0
  1057. package/src/inbox/migrations/approvals/0000_approvals.sql +36 -0
  1058. package/src/inbox/migrations/approvals/0001_provenance.sql +1 -0
  1059. package/src/inbox/migrations/approvals/0002_withdrawn.sql +3 -0
  1060. package/src/inbox/migrations/approvals/0003_title.sql +11 -0
  1061. package/src/inbox/migrations/consent/0000_consent.sql +31 -0
  1062. package/src/inbox/migrations/consent/0001_consent_revoked.sql +3 -0
  1063. package/src/inbox/migrations/consent/0002_permission_request.sql +1 -0
  1064. package/src/inbox/migrations/consent/0003_title.sql +11 -0
  1065. package/src/inbox/migrations/inbox/0000_work_items.sql +31 -0
  1066. package/src/inbox/migrations/notifications/0000_notifications.sql +66 -0
  1067. package/src/inbox/notifications.ts +471 -0
  1068. package/src/inbox/tables.ts +163 -0
  1069. package/src/inbox/workItems.ts +199 -0
  1070. package/src/index.ts +229 -0
  1071. package/src/ingestion/Chunk.ts +49 -0
  1072. package/src/ingestion/Extract.ts +387 -0
  1073. package/src/ingestion/ExtractChild.ts +67 -0
  1074. package/src/ingestion/ExtractPool.ts +270 -0
  1075. package/src/ingestion/Ingestion.ts +929 -0
  1076. package/src/ingestion/Isolated.ts +26 -0
  1077. package/src/ingestion/Markup.ts +117 -0
  1078. package/src/ingestion/Pdf.ts +167 -0
  1079. package/src/ingestion/Runs.ts +192 -0
  1080. package/src/ingestion/Scrub.ts +22 -0
  1081. package/src/ingestion/Zip.ts +87 -0
  1082. package/src/ingestion/migrations/README.md +1 -0
  1083. package/src/ingestion/module.ts +65 -0
  1084. package/src/ingress/Definition.ts +158 -0
  1085. package/src/ingress/Ingress.ts +1220 -0
  1086. package/src/ingress/Verifiers.ts +166 -0
  1087. package/src/machine/MachineIdentity.ts +310 -0
  1088. package/src/machine/Managed.ts +228 -0
  1089. package/src/machine/OAuth.ts +1140 -0
  1090. package/src/machine/Pages.ts +139 -0
  1091. package/src/machine/Tokens.ts +75 -0
  1092. package/src/make/Credentials.ts +36 -0
  1093. package/src/make/Example.ts +104 -0
  1094. package/src/make/Execute.ts +534 -0
  1095. package/src/make/Http.ts +71 -0
  1096. package/src/make/Lifecycle.ts +911 -0
  1097. package/src/make/Manifest.ts +884 -0
  1098. package/src/make/Repair.ts +262 -0
  1099. package/src/make/Runtime.ts +494 -0
  1100. package/src/make/Session.ts +33 -0
  1101. package/src/make/SqlGuard.ts +362 -0
  1102. package/src/make/Subscribe.ts +282 -0
  1103. package/src/make/Validate.ts +247 -0
  1104. package/src/make/ViewStep.ts +64 -0
  1105. package/src/make/migrations/README.md +1 -0
  1106. package/src/make/module.ts +261 -0
  1107. package/src/notifications/Decide.ts +483 -0
  1108. package/src/notifications/Providers.ts +532 -0
  1109. package/src/notifications/Push.ts +594 -0
  1110. package/src/notifications/Smtp.ts +379 -0
  1111. package/src/policy/CedarSchema.ts +156 -0
  1112. package/src/policy/Compiler.ts +1627 -0
  1113. package/src/policy/Policy.ts +178 -0
  1114. package/src/policy/Rls.ts +460 -0
  1115. package/src/policy/Row.ts +15 -0
  1116. package/src/privacy/Flow.ts +283 -0
  1117. package/src/privacy/Inventory.ts +2414 -0
  1118. package/src/privacy/Sources.ts +831 -0
  1119. package/src/privacy/Visits.ts +339 -0
  1120. package/src/privacy/ZeroCvr.ts +66 -0
  1121. package/src/privacy/migrations/0000_privacy.sql +48 -0
  1122. package/src/privacy/module.ts +280 -0
  1123. package/src/progress/migrations/0000_progress.sql +27 -0
  1124. package/src/progress/migrations/0001_notify.sql +1 -0
  1125. package/src/progress/module.ts +161 -0
  1126. package/src/proposals/migrations/README.md +1 -0
  1127. package/src/proposals/module.ts +338 -0
  1128. package/src/query/migrations/README.md +1 -0
  1129. package/src/query/module.ts +66 -0
  1130. package/src/records/Access.ts +97 -0
  1131. package/src/records/References.ts +65 -0
  1132. package/src/runtime/bun.ts +131 -0
  1133. package/src/runtime/idle.ts +88 -0
  1134. package/src/runtime/node.ts +140 -0
  1135. package/src/runtime/resolve.ts +141 -0
  1136. package/src/sandbox/Sandbox.ts +330 -0
  1137. package/src/sandbox/worker.ts +577 -0
  1138. package/src/scheduler/Automations.ts +319 -0
  1139. package/src/scheduler/History.ts +231 -0
  1140. package/src/scheduler/migrations/0000_schedules.sql +11 -0
  1141. package/src/scheduler/migrations/0001_resumed_at.sql +1 -0
  1142. package/src/scheduler/migrations/0002_origin.sql +3 -0
  1143. package/src/scheduler/migrations/0003_authority.sql +1 -0
  1144. package/src/scheduler/migrations/0004_operate.sql +18 -0
  1145. package/src/scheduler/module.ts +445 -0
  1146. package/src/search/RecordLock.ts +25 -0
  1147. package/src/search/Search.ts +563 -0
  1148. package/src/search/Sources.ts +157 -0
  1149. package/src/search/migrations/README.md +1 -0
  1150. package/src/search/module.ts +49 -0
  1151. package/src/settings/migrations/0000_settings.sql +15 -0
  1152. package/src/settings/module.ts +126 -0
  1153. package/src/sharing/migrations/0000_access_requests.sql +17 -0
  1154. package/src/sharing/module.ts +351 -0
  1155. package/src/spaces/migrations/0000_spaces.sql +35 -0
  1156. package/src/spaces/module.ts +287 -0
  1157. package/src/surfaces/Agent.ts +224 -0
  1158. package/src/surfaces/CookieGuard.ts +433 -0
  1159. package/src/surfaces/Http.ts +341 -0
  1160. package/src/surfaces/Mcp.ts +585 -0
  1161. package/src/surfaces/Rpc.ts +101 -0
  1162. package/src/surfaces/headers.ts +16 -0
  1163. package/src/surfaces/request.ts +173 -0
  1164. package/src/telemetry/migrations/.gitkeep +0 -0
  1165. package/src/telemetry/module.ts +94 -0
  1166. package/src/versioning/migrations/.gitkeep +0 -0
  1167. package/src/versioning/module.ts +194 -0
@@ -0,0 +1,4422 @@
1
+ /**
2
+ * The kernel's own tables, in the `eloxiv` schema owned by the kernel role.
3
+ * Statements are applied in order and recorded in `eloxiv.module_migration`.
4
+ */
5
+ /** The schema Effect cluster's storage lives in (see migration 0009_durable_work). */
6
+ export const CLUSTER_SCHEMA = "eloxiv_cluster"
7
+ /** The table prefix of Effect cluster's storage inside it (`cluster_messages`, `cluster_runners`, ...). */
8
+ export const CLUSTER_PREFIX = "cluster"
9
+
10
+ export interface Migration {
11
+ readonly name: string
12
+ readonly statements: ReadonlyArray<string>
13
+ /**
14
+ * False for a migration declared to run outside the setup's transaction (`-- eloxiv:no-transaction`, the
15
+ * Release contract). Every kernel migration is transactional.
16
+ */
17
+ readonly transactional?: boolean | undefined
18
+ }
19
+
20
+ export const kernelMigrations: ReadonlyArray<Migration> = [
21
+ {
22
+ name: "0000_kernel",
23
+ statements: [
24
+ `CREATE TABLE eloxiv.organization (
25
+ id text PRIMARY KEY,
26
+ name text NOT NULL,
27
+ created_at timestamptz NOT NULL DEFAULT now()
28
+ )`,
29
+ `CREATE TABLE eloxiv.membership (
30
+ org_id text NOT NULL REFERENCES eloxiv.organization(id),
31
+ user_id text NOT NULL,
32
+ role text NOT NULL DEFAULT 'member',
33
+ created_at timestamptz NOT NULL DEFAULT now(),
34
+ PRIMARY KEY (org_id, user_id)
35
+ )`,
36
+ `CREATE INDEX membership_user_idx ON eloxiv.membership (user_id)`,
37
+ `CREATE TABLE eloxiv.audit_log (
38
+ id text PRIMARY KEY,
39
+ invocation_id text NOT NULL,
40
+ at timestamptz NOT NULL DEFAULT now(),
41
+ action text NOT NULL,
42
+ surface text NOT NULL,
43
+ actor_user_id text,
44
+ org_id text,
45
+ outcome text NOT NULL,
46
+ input_hash text NOT NULL,
47
+ idempotency_key text,
48
+ error_tag text
49
+ )`,
50
+ `CREATE INDEX audit_log_invocation_idx ON eloxiv.audit_log (invocation_id)`,
51
+ `CREATE TABLE eloxiv.idempotency_key (
52
+ actor_user_id text NOT NULL,
53
+ action text NOT NULL,
54
+ key text NOT NULL,
55
+ request_hash text NOT NULL,
56
+ response jsonb NOT NULL,
57
+ invocation_id text NOT NULL,
58
+ created_at timestamptz NOT NULL DEFAULT now(),
59
+ PRIMARY KEY (actor_user_id, action, key)
60
+ )`,
61
+ `CREATE TABLE eloxiv.outbox (
62
+ id text PRIMARY KEY,
63
+ seq bigserial UNIQUE,
64
+ invocation_id text NOT NULL,
65
+ type text NOT NULL,
66
+ module text NOT NULL,
67
+ org_id text NOT NULL,
68
+ payload jsonb NOT NULL,
69
+ occurred_at timestamptz NOT NULL DEFAULT now(),
70
+ delivered_at timestamptz,
71
+ attempts integer NOT NULL DEFAULT 0,
72
+ next_attempt_at timestamptz NOT NULL DEFAULT now(),
73
+ last_error text
74
+ )`,
75
+ `CREATE INDEX outbox_pending_idx ON eloxiv.outbox (next_attempt_at) WHERE delivered_at IS NULL`,
76
+ `CREATE TABLE eloxiv.outbox_delivery (
77
+ event_id text NOT NULL REFERENCES eloxiv.outbox(id),
78
+ subscriber text NOT NULL,
79
+ delivered_at timestamptz NOT NULL DEFAULT now(),
80
+ PRIMARY KEY (event_id, subscriber)
81
+ )`,
82
+ `CREATE TABLE eloxiv.approval (
83
+ id text PRIMARY KEY,
84
+ action text NOT NULL,
85
+ actor_user_id text NOT NULL,
86
+ org_id text NOT NULL,
87
+ input jsonb NOT NULL,
88
+ status text NOT NULL,
89
+ reason text NOT NULL,
90
+ created_at timestamptz NOT NULL DEFAULT now()
91
+ )`,
92
+ `CREATE TABLE eloxiv.share_grant (
93
+ id text PRIMARY KEY,
94
+ resource_type text NOT NULL,
95
+ resource_id text NOT NULL,
96
+ grantee_user_id text NOT NULL,
97
+ permission text NOT NULL,
98
+ granted_by text NOT NULL,
99
+ created_at timestamptz NOT NULL DEFAULT now(),
100
+ UNIQUE (resource_type, resource_id, grantee_user_id, permission)
101
+ )`,
102
+ `CREATE INDEX share_grant_resource_idx ON eloxiv.share_grant (resource_id)`,
103
+ ],
104
+ },
105
+ ]
106
+
107
+ /**
108
+ * Invocation safety (review fixes): idempotency keys are scoped by organisation
109
+ * and remember the rows the call wrote (to re-authorise replays); every write to
110
+ * a module table is logged per transaction by a trigger, so the invocation path
111
+ * can authorise each inserted, updated and deleted row, savepoints included.
112
+ */
113
+ const invocationSafety: Migration = {
114
+ name: "0001_invocation_safety",
115
+ statements: [
116
+ `DELETE FROM eloxiv.idempotency_key`,
117
+ `ALTER TABLE eloxiv.idempotency_key ADD COLUMN org_id text NOT NULL`,
118
+ `ALTER TABLE eloxiv.idempotency_key ADD COLUMN writes jsonb NOT NULL DEFAULT '[]'::jsonb`,
119
+ `ALTER TABLE eloxiv.idempotency_key DROP CONSTRAINT idempotency_key_pkey`,
120
+ `ALTER TABLE eloxiv.idempotency_key ADD PRIMARY KEY (org_id, actor_user_id, action, key)`,
121
+ `CREATE TABLE eloxiv.invocation_write (
122
+ id bigserial PRIMARY KEY,
123
+ xid xid8 NOT NULL DEFAULT pg_current_xact_id(),
124
+ table_schema text NOT NULL,
125
+ table_name text NOT NULL,
126
+ pk text,
127
+ op text NOT NULL
128
+ )`,
129
+ `CREATE INDEX invocation_write_xid_idx ON eloxiv.invocation_write (xid)`,
130
+ `CREATE FUNCTION eloxiv.track_write() RETURNS trigger
131
+ LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog AS $$
132
+ DECLARE
133
+ written jsonb;
134
+ BEGIN
135
+ IF TG_OP = 'DELETE' THEN written := to_jsonb(OLD); ELSE written := to_jsonb(NEW); END IF;
136
+ INSERT INTO eloxiv.invocation_write (table_schema, table_name, pk, op)
137
+ VALUES (TG_TABLE_SCHEMA, TG_TABLE_NAME, CASE WHEN TG_ARGV[0] = '' THEN NULL ELSE written ->> TG_ARGV[0] END, TG_OP);
138
+ RETURN NULL;
139
+ END
140
+ $$`,
141
+ `REVOKE ALL ON FUNCTION eloxiv.track_write() FROM PUBLIC`,
142
+ ],
143
+ }
144
+
145
+ /**
146
+ * Row-level security context. Each transaction that touches module tables
147
+ * records who is acting, in which organisation, for which action, keyed by the
148
+ * top-level transaction id. Module runtime roles cannot write this table, so
149
+ * the context the generated RLS policies read cannot be forged with `SET`.
150
+ */
151
+ const rlsContext: Migration = {
152
+ name: "0002_rls_context",
153
+ statements: [
154
+ `CREATE SCHEMA eloxiv_ctx`,
155
+ `CREATE TABLE eloxiv.invocation_context (
156
+ xid xid8 PRIMARY KEY DEFAULT pg_current_xact_id(),
157
+ actor text NOT NULL,
158
+ org text NOT NULL,
159
+ action text NOT NULL
160
+ )`,
161
+ `CREATE FUNCTION eloxiv_ctx.current_actor() RETURNS text
162
+ LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog
163
+ AS $$ SELECT actor FROM eloxiv.invocation_context WHERE xid = pg_current_xact_id() $$`,
164
+ `CREATE FUNCTION eloxiv_ctx.current_org() RETURNS text
165
+ LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog
166
+ AS $$ SELECT org FROM eloxiv.invocation_context WHERE xid = pg_current_xact_id() $$`,
167
+ `CREATE FUNCTION eloxiv_ctx.current_action() RETURNS text
168
+ LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog
169
+ AS $$ SELECT action FROM eloxiv.invocation_context WHERE xid = pg_current_xact_id() $$`,
170
+ `CREATE FUNCTION eloxiv_ctx.has_grant(p_type text, p_id text, p_grantee text, p_permission text) RETURNS boolean
171
+ LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog
172
+ AS $$ SELECT EXISTS (
173
+ SELECT 1 FROM eloxiv.share_grant g
174
+ WHERE g.resource_type = p_type AND g.resource_id = p_id AND g.grantee_user_id = p_grantee AND g.permission = p_permission) $$`,
175
+ `REVOKE ALL ON ALL FUNCTIONS IN SCHEMA eloxiv_ctx FROM PUBLIC`,
176
+ ],
177
+ }
178
+
179
+ /** What setup last installed for each module (privileges, RLS, triggers), so unchanged modules are left alone. */
180
+ const hardening: Migration = {
181
+ name: "0003_module_hardening",
182
+ statements: [
183
+ `CREATE TABLE eloxiv.module_hardening (
184
+ module text PRIMARY KEY,
185
+ fingerprint text NOT NULL,
186
+ hardened_at timestamptz NOT NULL DEFAULT now()
187
+ )`,
188
+ ],
189
+ }
190
+
191
+ /**
192
+ * Round 3: audit records carry best-effort completion; stored idempotent
193
+ * results carry the resources they depend on (rows written, rows returned,
194
+ * deletion receipts) instead of only the rows written. Results stored in the
195
+ * old shape cannot be re-authorised completely, so they are discarded.
196
+ */
197
+ const completionAndDependencies: Migration = {
198
+ name: "0004_completion_and_dependencies",
199
+ statements: [
200
+ `ALTER TABLE eloxiv.audit_log ADD COLUMN affected integer, ADD COLUMN requested integer, ADD COLUMN completion text`,
201
+ `DELETE FROM eloxiv.idempotency_key`,
202
+ `ALTER TABLE eloxiv.idempotency_key DROP COLUMN writes`,
203
+ `ALTER TABLE eloxiv.idempotency_key ADD COLUMN dependencies jsonb NOT NULL DEFAULT '{"written":[],"deleted":[],"returned":[],"verifiable":false}'::jsonb`,
204
+ ],
205
+ }
206
+
207
+ /**
208
+ * Round 4: record identities are immutable, and exact actions may insert or
209
+ * update only their declared targets.
210
+ *
211
+ * - `eloxiv.guard_key(pk, owner)`: a BEFORE UPDATE row trigger setup installs
212
+ * on every module table with a single-column primary key. It rejects any
213
+ * update that changes the key (insufficient_privilege, so the call is
214
+ * Forbidden), except for the module's owner role (migrations). The write log
215
+ * records an update's key, so a key change could otherwise move one record
216
+ * onto another's identity.
217
+ * - `eloxiv.invocation_target` and `eloxiv_ctx.is_target(pk)`: the declared
218
+ * targets of the current transaction's call, which the generated row-level
219
+ * security policies of exact actions require of every inserted or updated
220
+ * row. The check runs at the statement, before an INSERT's conflict
221
+ * arbitration, so an undeclared insert fails the same way whether or not
222
+ * some (possibly unreadable) record already holds the key.
223
+ */
224
+ const identities: Migration = {
225
+ name: "0005_identities",
226
+ statements: [
227
+ `CREATE FUNCTION eloxiv.guard_key() RETURNS trigger
228
+ LANGUAGE plpgsql SET search_path = pg_catalog AS $$
229
+ BEGIN
230
+ IF current_user::text <> TG_ARGV[1]
231
+ AND (to_jsonb(NEW) ->> TG_ARGV[0]) IS DISTINCT FROM (to_jsonb(OLD) ->> TG_ARGV[0]) THEN
232
+ RAISE EXCEPTION 'The primary key of %.% is immutable', TG_TABLE_SCHEMA, TG_TABLE_NAME
233
+ USING ERRCODE = 'insufficient_privilege';
234
+ END IF;
235
+ RETURN NEW;
236
+ END
237
+ $$`,
238
+ `REVOKE ALL ON FUNCTION eloxiv.guard_key() FROM PUBLIC`,
239
+ `CREATE TABLE eloxiv.invocation_target (
240
+ xid xid8 NOT NULL DEFAULT pg_current_xact_id(),
241
+ pk text NOT NULL,
242
+ PRIMARY KEY (xid, pk)
243
+ )`,
244
+ `CREATE FUNCTION eloxiv_ctx.is_target(p_pk text) RETURNS boolean
245
+ LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog
246
+ AS $$ SELECT EXISTS (SELECT 1 FROM eloxiv.invocation_target WHERE xid = pg_current_xact_id() AND pk = p_pk) $$`,
247
+ `REVOKE ALL ON FUNCTION eloxiv_ctx.is_target(text) FROM PUBLIC`,
248
+ ],
249
+ }
250
+
251
+ /**
252
+ * Round 5: replayable outputs are checked against an allowlist derived from the
253
+ * action's contract, and stored dependencies carry a format version. Results
254
+ * cached under the earlier coverage rules may depend on records they did not
255
+ * record, so they are discarded (a retry runs the action again). From now on a
256
+ * format change needs no migration: the kernel refuses to replay a result whose
257
+ * `dependencies.format` is not the current one.
258
+ */
259
+ const dependencyFormat: Migration = {
260
+ name: "0006_dependency_format",
261
+ statements: [`DELETE FROM eloxiv.idempotency_key`],
262
+ }
263
+
264
+ /**
265
+ * Round 6: an idempotent replay returns a receipt of the original call's own
266
+ * effects (records written or deleted, completion), never its cached output.
267
+ * Cached outputs and their dependency records are discarded; receipts carry a
268
+ * format (`receipt_format`) so a later change to what they hold invalidates old
269
+ * ones without a migration. Written to be safe to apply again.
270
+ */
271
+ const replayReceipts: Migration = {
272
+ name: "0007_replay_receipts",
273
+ statements: [
274
+ `DELETE FROM eloxiv.idempotency_key`,
275
+ `ALTER TABLE eloxiv.idempotency_key DROP COLUMN IF EXISTS response`,
276
+ `ALTER TABLE eloxiv.idempotency_key DROP COLUMN IF EXISTS dependencies`,
277
+ `ALTER TABLE eloxiv.idempotency_key ADD COLUMN IF NOT EXISTS receipt jsonb`,
278
+ `ALTER TABLE eloxiv.idempotency_key ADD COLUMN IF NOT EXISTS receipt_format integer NOT NULL DEFAULT 0`,
279
+ ],
280
+ }
281
+
282
+ /**
283
+ * Decision 1: groups and roles. Roles are org-scoped and grant permissions from
284
+ * the kernel's and the modules' permission vocabularies; a membership holds
285
+ * roles (the old single `membership.role` string becomes one role each); groups
286
+ * are org-scoped, flat (no nesting), and hold members of the organisation.
287
+ * Removing a membership removes its roles and group memberships.
288
+ *
289
+ * Policies read them through `eloxiv_ctx.in_group`, `has_role` and
290
+ * `has_permission`: SECURITY DEFINER functions that answer only for the acting
291
+ * user in the acting organisation of the current transaction's invocation
292
+ * context, from the live tables (a change applies to the next statement), and
293
+ * answer false without a context (fail closed). Module runtime roles cannot
294
+ * read the directory tables themselves. Written to be safe to apply again.
295
+ */
296
+ const directory: Migration = {
297
+ name: "0008_directory",
298
+ statements: [
299
+ `CREATE TABLE IF NOT EXISTS eloxiv.role (
300
+ org_id text NOT NULL REFERENCES eloxiv.organization(id) ON DELETE CASCADE,
301
+ id text NOT NULL,
302
+ name text NOT NULL,
303
+ created_at timestamptz NOT NULL DEFAULT now(),
304
+ PRIMARY KEY (org_id, id)
305
+ )`,
306
+ `CREATE TABLE IF NOT EXISTS eloxiv.role_permission (
307
+ org_id text NOT NULL,
308
+ role_id text NOT NULL,
309
+ permission text NOT NULL,
310
+ PRIMARY KEY (org_id, role_id, permission),
311
+ FOREIGN KEY (org_id, role_id) REFERENCES eloxiv.role(org_id, id) ON DELETE CASCADE
312
+ )`,
313
+ `CREATE TABLE IF NOT EXISTS eloxiv.membership_role (
314
+ org_id text NOT NULL,
315
+ user_id text NOT NULL,
316
+ role_id text NOT NULL,
317
+ PRIMARY KEY (org_id, user_id, role_id),
318
+ FOREIGN KEY (org_id, user_id) REFERENCES eloxiv.membership(org_id, user_id) ON DELETE CASCADE,
319
+ FOREIGN KEY (org_id, role_id) REFERENCES eloxiv.role(org_id, id) ON DELETE CASCADE
320
+ )`,
321
+ `CREATE TABLE IF NOT EXISTS eloxiv.org_group (
322
+ org_id text NOT NULL REFERENCES eloxiv.organization(id) ON DELETE CASCADE,
323
+ id text NOT NULL,
324
+ name text NOT NULL,
325
+ created_at timestamptz NOT NULL DEFAULT now(),
326
+ PRIMARY KEY (org_id, id)
327
+ )`,
328
+ `CREATE TABLE IF NOT EXISTS eloxiv.group_member (
329
+ org_id text NOT NULL,
330
+ group_id text NOT NULL,
331
+ user_id text NOT NULL,
332
+ PRIMARY KEY (org_id, group_id, user_id),
333
+ FOREIGN KEY (org_id, group_id) REFERENCES eloxiv.org_group(org_id, id) ON DELETE CASCADE,
334
+ FOREIGN KEY (org_id, user_id) REFERENCES eloxiv.membership(org_id, user_id) ON DELETE CASCADE
335
+ )`,
336
+ `CREATE INDEX IF NOT EXISTS group_member_user_idx ON eloxiv.group_member (org_id, user_id)`,
337
+ `ALTER TABLE eloxiv.membership DROP CONSTRAINT IF EXISTS membership_org_id_fkey`,
338
+ `ALTER TABLE eloxiv.membership ADD CONSTRAINT membership_org_id_fkey
339
+ FOREIGN KEY (org_id) REFERENCES eloxiv.organization(id) ON DELETE CASCADE`,
340
+ // Once, while the old column exists: every organisation gets the built-in roles (admin manages the
341
+ // directory), each membership's role string becomes a role it holds, and the column goes.
342
+ `DO $$ BEGIN
343
+ IF EXISTS (SELECT 1 FROM information_schema.columns
344
+ WHERE table_schema = 'eloxiv' AND table_name = 'membership' AND column_name = 'role') THEN
345
+ INSERT INTO eloxiv.role (org_id, id, name)
346
+ SELECT o.id, r.id, r.name FROM eloxiv.organization o
347
+ CROSS JOIN (VALUES ('admin', 'Administrator'), ('member', 'Member')) AS r(id, name)
348
+ ON CONFLICT DO NOTHING;
349
+ INSERT INTO eloxiv.role (org_id, id, name)
350
+ SELECT DISTINCT org_id, role, role FROM eloxiv.membership ON CONFLICT DO NOTHING;
351
+ INSERT INTO eloxiv.membership_role (org_id, user_id, role_id)
352
+ SELECT org_id, user_id, role FROM eloxiv.membership ON CONFLICT DO NOTHING;
353
+ INSERT INTO eloxiv.role_permission (org_id, role_id, permission)
354
+ SELECT org_id, id, 'eloxiv.directory.manage' FROM eloxiv.role WHERE id = 'admin' ON CONFLICT DO NOTHING;
355
+ ALTER TABLE eloxiv.membership DROP COLUMN role;
356
+ END IF;
357
+ END $$`,
358
+ `CREATE OR REPLACE FUNCTION eloxiv_ctx.in_group(p_group text) RETURNS boolean
359
+ LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog
360
+ AS $$ SELECT EXISTS (
361
+ SELECT 1 FROM eloxiv.invocation_context c JOIN eloxiv.group_member m ON m.org_id = c.org AND m.user_id = c.actor
362
+ WHERE c.xid = pg_current_xact_id() AND m.group_id = p_group) $$`,
363
+ `CREATE OR REPLACE FUNCTION eloxiv_ctx.has_role(p_role text) RETURNS boolean
364
+ LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog
365
+ AS $$ SELECT EXISTS (
366
+ SELECT 1 FROM eloxiv.invocation_context c JOIN eloxiv.membership_role r ON r.org_id = c.org AND r.user_id = c.actor
367
+ WHERE c.xid = pg_current_xact_id() AND r.role_id = p_role) $$`,
368
+ `CREATE OR REPLACE FUNCTION eloxiv_ctx.has_permission(p_permission text) RETURNS boolean
369
+ LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog
370
+ AS $$ SELECT EXISTS (
371
+ SELECT 1 FROM eloxiv.invocation_context c
372
+ JOIN eloxiv.membership_role r ON r.org_id = c.org AND r.user_id = c.actor
373
+ JOIN eloxiv.role_permission p ON p.org_id = r.org_id AND p.role_id = r.role_id
374
+ WHERE c.xid = pg_current_xact_id() AND p.permission = p_permission) $$`,
375
+ `REVOKE ALL ON FUNCTION eloxiv_ctx.in_group(text), eloxiv_ctx.has_role(text), eloxiv_ctx.has_permission(text) FROM PUBLIC`,
376
+ ],
377
+ }
378
+
379
+ /**
380
+ * Durable work (the Workflow and Scheduler contracts).
381
+ *
382
+ * - `eloxiv_cluster`: the schema Effect cluster's message and runner storage live in (mailboxes, replies,
383
+ * the activity journal, runner registrations and shard locks). The kernel role owns it; module roles have
384
+ * no access. Its tables are created by Effect's own versioned migrations, which `migrateKernel` runs right
385
+ * after the kernel's, with the schema as the search path (`migrateCluster`).
386
+ * - `workflow_execution`: one row per execution, by (workflow, key), with the identity it acts as.
387
+ * - `workflow_step`: the kernel's journal of each step (attempts, the invocation that ran, whether it
388
+ * returned a replay receipt). Effect's activity replies are the authoritative record of completion.
389
+ * - `workflow_signal`: the first value sent for each (execution, signal); later sends are not delivered.
390
+ * - `schedule_state`: per schedule, its anchor (interval origin) and cursor (the latest due time handled).
391
+ * - `schedule_run`: every run the scheduler started, keyed by (schedule, scheduled time) (and, from 0036, the
392
+ * start request of a recorded run the engine does not have yet).
393
+ *
394
+ * Written to be safe to apply again.
395
+ */
396
+ const durableWork: Migration = {
397
+ name: "0009_durable_work",
398
+ statements: [
399
+ `CREATE SCHEMA IF NOT EXISTS ${CLUSTER_SCHEMA}`,
400
+ `REVOKE ALL ON SCHEMA ${CLUSTER_SCHEMA} FROM PUBLIC`,
401
+ `CREATE TABLE IF NOT EXISTS eloxiv.workflow_execution (
402
+ id text PRIMARY KEY,
403
+ workflow text NOT NULL,
404
+ key text NOT NULL,
405
+ org_id text NOT NULL,
406
+ identity jsonb NOT NULL,
407
+ started_at timestamptz NOT NULL DEFAULT now(),
408
+ UNIQUE (workflow, key)
409
+ )`,
410
+ `CREATE TABLE IF NOT EXISTS eloxiv.workflow_step (
411
+ execution_id text NOT NULL,
412
+ step text NOT NULL,
413
+ seq bigserial,
414
+ attempts integer NOT NULL DEFAULT 1,
415
+ state text NOT NULL,
416
+ invocation_id text,
417
+ replayed boolean,
418
+ error text,
419
+ started_at timestamptz NOT NULL DEFAULT now(),
420
+ finished_at timestamptz,
421
+ PRIMARY KEY (execution_id, step)
422
+ )`,
423
+ `CREATE TABLE IF NOT EXISTS eloxiv.workflow_signal (
424
+ execution_id text NOT NULL,
425
+ name text NOT NULL,
426
+ value jsonb,
427
+ signalled_at timestamptz NOT NULL DEFAULT now(),
428
+ PRIMARY KEY (execution_id, name)
429
+ )`,
430
+ `CREATE TABLE IF NOT EXISTS eloxiv.schedule_state (
431
+ key text PRIMARY KEY,
432
+ anchor timestamptz NOT NULL,
433
+ cursor timestamptz NOT NULL,
434
+ updated_at timestamptz NOT NULL DEFAULT now()
435
+ )`,
436
+ `CREATE TABLE IF NOT EXISTS eloxiv.schedule_run (
437
+ key text NOT NULL,
438
+ scheduled_at timestamptz NOT NULL,
439
+ execution_id text NOT NULL,
440
+ missed boolean NOT NULL,
441
+ started_at timestamptz NOT NULL DEFAULT now(),
442
+ PRIMARY KEY (key, scheduled_at)
443
+ )`,
444
+ ],
445
+ }
446
+
447
+ /**
448
+ * Directory writes record what they changed: the subject (a member, role or group) and its state just
449
+ * before and just after the change, read in the change's transaction. Written to be safe to apply again.
450
+ */
451
+ const auditDetail: Migration = {
452
+ name: "0010_audit_detail",
453
+ statements: [`ALTER TABLE eloxiv.audit_log ADD COLUMN IF NOT EXISTS detail jsonb`],
454
+ }
455
+
456
+ /**
457
+ * Live directory facts for sync (decision 2; independent review). A connected replica's queries are
458
+ * transformed once, so the directory must not be bound into them: zero-cache evaluates the read filter's
459
+ * directory tests against these replicated tables instead, so a change applies to every connected replica
460
+ * as soon as zero-cache replicates the transaction that made it.
461
+ *
462
+ * - `sync_fact`: what each member is in each organisation: `member` (value ''), each `group`, `role` and
463
+ * `permission` (through roles). Maintained in the directory change's own transaction by triggers on
464
+ * membership, group membership, membership roles and role permissions (`refresh_sync_facts` writes only
465
+ * the difference, so an unchanged fact is never deleted and recreated). Migration 0024 makes the triggers
466
+ * take the organisation's directory lock before they read, so concurrent writers cannot leave a stale fact.
467
+ * - `sync_org`: one row per organisation. Zero joins only on columns, so a record reaches the facts of the
468
+ * acting organisation through its own organisation's row and the constant `scope` both tables share.
469
+ *
470
+ * Both are in the sync publication; zero-cache uses their rows only inside permission subqueries and never
471
+ * sends them to clients. Written to be safe to apply again.
472
+ */
473
+ const syncDirectory: Migration = {
474
+ name: "0011_sync_directory",
475
+ statements: [
476
+ `CREATE TABLE IF NOT EXISTS eloxiv.sync_org (
477
+ id text PRIMARY KEY,
478
+ scope smallint NOT NULL DEFAULT 1 CHECK (scope = 1)
479
+ )`,
480
+ `CREATE TABLE IF NOT EXISTS eloxiv.sync_fact (
481
+ scope smallint NOT NULL DEFAULT 1 CHECK (scope = 1),
482
+ org_id text NOT NULL,
483
+ user_id text NOT NULL,
484
+ kind text NOT NULL CHECK (kind IN ('member', 'group', 'role', 'permission')),
485
+ value text NOT NULL,
486
+ PRIMARY KEY (org_id, user_id, kind, value)
487
+ )`,
488
+ `CREATE OR REPLACE FUNCTION eloxiv.refresh_sync_facts(p_org text, p_user text) RETURNS void
489
+ LANGUAGE sql SET search_path = pg_catalog AS $$
490
+ WITH wanted (kind, value) AS (
491
+ SELECT 'member', '' FROM eloxiv.membership WHERE org_id = p_org AND user_id = p_user
492
+ UNION SELECT 'group', group_id FROM eloxiv.group_member WHERE org_id = p_org AND user_id = p_user
493
+ UNION SELECT 'role', role_id FROM eloxiv.membership_role WHERE org_id = p_org AND user_id = p_user
494
+ UNION SELECT 'permission', p.permission FROM eloxiv.membership_role r
495
+ JOIN eloxiv.role_permission p ON p.org_id = r.org_id AND p.role_id = r.role_id
496
+ WHERE r.org_id = p_org AND r.user_id = p_user
497
+ ), removed AS (
498
+ DELETE FROM eloxiv.sync_fact f WHERE f.org_id = p_org AND f.user_id = p_user
499
+ AND NOT EXISTS (SELECT 1 FROM wanted w WHERE w.kind = f.kind AND w.value = f.value)
500
+ )
501
+ INSERT INTO eloxiv.sync_fact (org_id, user_id, kind, value)
502
+ SELECT p_org, p_user, kind, value FROM wanted ON CONFLICT DO NOTHING
503
+ $$`,
504
+ `CREATE OR REPLACE FUNCTION eloxiv.sync_member_changed() RETURNS trigger
505
+ LANGUAGE plpgsql SET search_path = pg_catalog AS $$
506
+ BEGIN
507
+ IF TG_OP IN ('UPDATE', 'DELETE') THEN PERFORM eloxiv.refresh_sync_facts(OLD.org_id, OLD.user_id); END IF;
508
+ IF TG_OP IN ('UPDATE', 'INSERT') THEN PERFORM eloxiv.refresh_sync_facts(NEW.org_id, NEW.user_id); END IF;
509
+ RETURN NULL;
510
+ END
511
+ $$`,
512
+ `CREATE OR REPLACE FUNCTION eloxiv.sync_role_permission_changed() RETURNS trigger
513
+ LANGUAGE plpgsql SET search_path = pg_catalog AS $$
514
+ BEGIN
515
+ IF TG_OP IN ('UPDATE', 'DELETE') THEN
516
+ PERFORM eloxiv.refresh_sync_facts(m.org_id, m.user_id) FROM eloxiv.membership_role m
517
+ WHERE m.org_id = OLD.org_id AND m.role_id = OLD.role_id;
518
+ END IF;
519
+ IF TG_OP IN ('UPDATE', 'INSERT') THEN
520
+ PERFORM eloxiv.refresh_sync_facts(m.org_id, m.user_id) FROM eloxiv.membership_role m
521
+ WHERE m.org_id = NEW.org_id AND m.role_id = NEW.role_id;
522
+ END IF;
523
+ RETURN NULL;
524
+ END
525
+ $$`,
526
+ `CREATE OR REPLACE FUNCTION eloxiv.sync_org_changed() RETURNS trigger
527
+ LANGUAGE plpgsql SET search_path = pg_catalog AS $$
528
+ BEGIN
529
+ IF TG_OP = 'DELETE' THEN DELETE FROM eloxiv.sync_org WHERE id = OLD.id;
530
+ ELSE INSERT INTO eloxiv.sync_org (id) VALUES (NEW.id) ON CONFLICT DO NOTHING;
531
+ END IF;
532
+ RETURN NULL;
533
+ END
534
+ $$`,
535
+ `REVOKE ALL ON FUNCTION eloxiv.refresh_sync_facts(text, text), eloxiv.sync_member_changed(),
536
+ eloxiv.sync_role_permission_changed(), eloxiv.sync_org_changed() FROM PUBLIC`,
537
+ `CREATE OR REPLACE TRIGGER eloxiv_sync_facts AFTER INSERT OR UPDATE OR DELETE ON eloxiv.membership
538
+ FOR EACH ROW EXECUTE FUNCTION eloxiv.sync_member_changed()`,
539
+ `CREATE OR REPLACE TRIGGER eloxiv_sync_facts AFTER INSERT OR UPDATE OR DELETE ON eloxiv.group_member
540
+ FOR EACH ROW EXECUTE FUNCTION eloxiv.sync_member_changed()`,
541
+ `CREATE OR REPLACE TRIGGER eloxiv_sync_facts AFTER INSERT OR UPDATE OR DELETE ON eloxiv.membership_role
542
+ FOR EACH ROW EXECUTE FUNCTION eloxiv.sync_member_changed()`,
543
+ `CREATE OR REPLACE TRIGGER eloxiv_sync_facts AFTER INSERT OR UPDATE OR DELETE ON eloxiv.role_permission
544
+ FOR EACH ROW EXECUTE FUNCTION eloxiv.sync_role_permission_changed()`,
545
+ `CREATE OR REPLACE TRIGGER eloxiv_sync_org AFTER INSERT OR DELETE ON eloxiv.organization
546
+ FOR EACH ROW EXECUTE FUNCTION eloxiv.sync_org_changed()`,
547
+ // Existing directories.
548
+ `INSERT INTO eloxiv.sync_org (id) SELECT id FROM eloxiv.organization ON CONFLICT DO NOTHING`,
549
+ `SELECT eloxiv.refresh_sync_facts(org_id, user_id) FROM eloxiv.membership`,
550
+ ],
551
+ }
552
+
553
+ /**
554
+ * ActionConsent: agent sessions. A credential the kernel issues for an agent acting for one person in one
555
+ * organisation (`eloxiv_agent.<secret>`, stored as its sha256). Every call it authenticates is
556
+ * agent-originated, on every surface. Written to be safe to apply again.
557
+ */
558
+ const agentSessions: Migration = {
559
+ name: "0012_agent_sessions",
560
+ statements: [
561
+ `CREATE TABLE IF NOT EXISTS eloxiv.agent_session (
562
+ id text PRIMARY KEY,
563
+ token_hash text NOT NULL UNIQUE,
564
+ user_id text NOT NULL,
565
+ org_id text NOT NULL,
566
+ label text NOT NULL,
567
+ created_at timestamptz NOT NULL DEFAULT now(),
568
+ expires_at timestamptz NOT NULL,
569
+ revoked_at timestamptz
570
+ )`,
571
+ ],
572
+ }
573
+
574
+ /**
575
+ * WorkItems: a module may ask whether a user is a member, or a group exists, of the organisation it acts in
576
+ * (to validate an assignee), and nothing else about the directory. Both answer false without a context.
577
+ * Written to be safe to apply again.
578
+ */
579
+ const membershipChecks: Migration = {
580
+ name: "0013_membership_checks",
581
+ statements: [
582
+ `CREATE OR REPLACE FUNCTION eloxiv_ctx.is_member(p_user text) RETURNS boolean
583
+ LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog
584
+ AS $$ SELECT EXISTS (
585
+ SELECT 1 FROM eloxiv.invocation_context c JOIN eloxiv.membership m ON m.org_id = c.org
586
+ WHERE c.xid = pg_current_xact_id() AND m.user_id = p_user) $$`,
587
+ `CREATE OR REPLACE FUNCTION eloxiv_ctx.is_group(p_group text) RETURNS boolean
588
+ LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog
589
+ AS $$ SELECT EXISTS (
590
+ SELECT 1 FROM eloxiv.invocation_context c JOIN eloxiv.org_group g ON g.org_id = c.org
591
+ WHERE c.xid = pg_current_xact_id() AND g.id = p_group) $$`,
592
+ `REVOKE ALL ON FUNCTION eloxiv_ctx.is_member(text), eloxiv_ctx.is_group(text) FROM PUBLIC`,
593
+ ],
594
+ }
595
+
596
+ /**
597
+ * MachineIdentity: service principals, API tokens and the OAuth authorisation server's state. Every secret
598
+ * (token, code, client secret) is stored as its SHA-256 hash only. A service principal is an organisation
599
+ * member like a user (a `membership` row keyed by its `sp_` id), so roles, groups, permissions and the
600
+ * row-level security functions apply to it unchanged. Existing organisations' `admin` roles get the new
601
+ * kernel permission. Written to be safe to apply again.
602
+ */
603
+ const machineIdentity: Migration = {
604
+ name: "0014_machine_identity",
605
+ statements: [
606
+ `CREATE TABLE IF NOT EXISTS eloxiv.service_principal (
607
+ id text PRIMARY KEY,
608
+ org_id text NOT NULL REFERENCES eloxiv.organization(id) ON DELETE CASCADE,
609
+ name text NOT NULL,
610
+ description text NOT NULL DEFAULT '',
611
+ created_by text NOT NULL,
612
+ created_at timestamptz NOT NULL DEFAULT now(),
613
+ disabled_at timestamptz,
614
+ UNIQUE (org_id, name)
615
+ )`,
616
+ `CREATE TABLE IF NOT EXISTS eloxiv.api_token (
617
+ id text PRIMARY KEY,
618
+ token_hash text NOT NULL UNIQUE,
619
+ prefix text NOT NULL,
620
+ kind text NOT NULL CHECK (kind IN ('personal', 'service')),
621
+ subject text NOT NULL,
622
+ org_id text NOT NULL REFERENCES eloxiv.organization(id) ON DELETE CASCADE,
623
+ name text NOT NULL,
624
+ scope text[],
625
+ created_by text NOT NULL,
626
+ created_at timestamptz NOT NULL DEFAULT now(),
627
+ expires_at timestamptz NOT NULL,
628
+ revoked_at timestamptz,
629
+ last_used_at timestamptz
630
+ )`,
631
+ `CREATE INDEX IF NOT EXISTS api_token_subject_idx ON eloxiv.api_token (org_id, subject)`,
632
+ `CREATE TABLE IF NOT EXISTS eloxiv.oauth_client (
633
+ id text PRIMARY KEY,
634
+ secret_hash text,
635
+ name text NOT NULL,
636
+ redirect_uris text[] NOT NULL,
637
+ grant_types text[] NOT NULL,
638
+ auth_method text NOT NULL,
639
+ registered_from text,
640
+ created_at timestamptz NOT NULL DEFAULT now(),
641
+ last_used_at timestamptz
642
+ )`,
643
+ `CREATE TABLE IF NOT EXISTS eloxiv.oauth_request (
644
+ id text PRIMARY KEY,
645
+ client_id text NOT NULL REFERENCES eloxiv.oauth_client(id) ON DELETE CASCADE,
646
+ redirect_uri text NOT NULL,
647
+ scope text[] NOT NULL,
648
+ resource text NOT NULL,
649
+ state text,
650
+ code_challenge text NOT NULL,
651
+ created_at timestamptz NOT NULL DEFAULT now(),
652
+ expires_at timestamptz NOT NULL
653
+ )`,
654
+ `CREATE TABLE IF NOT EXISTS eloxiv.oauth_grant (
655
+ id text PRIMARY KEY,
656
+ client_id text NOT NULL REFERENCES eloxiv.oauth_client(id) ON DELETE CASCADE,
657
+ user_id text NOT NULL,
658
+ org_id text NOT NULL REFERENCES eloxiv.organization(id) ON DELETE CASCADE,
659
+ scope text[] NOT NULL,
660
+ resource text NOT NULL,
661
+ created_at timestamptz NOT NULL DEFAULT now(),
662
+ revoked_at timestamptz,
663
+ revoked_reason text
664
+ )`,
665
+ `CREATE TABLE IF NOT EXISTS eloxiv.oauth_code (
666
+ hash text PRIMARY KEY,
667
+ client_id text NOT NULL REFERENCES eloxiv.oauth_client(id) ON DELETE CASCADE,
668
+ user_id text NOT NULL,
669
+ org_id text NOT NULL,
670
+ redirect_uri text NOT NULL,
671
+ scope text[] NOT NULL,
672
+ resource text NOT NULL,
673
+ code_challenge text NOT NULL,
674
+ created_at timestamptz NOT NULL DEFAULT now(),
675
+ expires_at timestamptz NOT NULL,
676
+ used_at timestamptz,
677
+ grant_id text
678
+ )`,
679
+ `CREATE TABLE IF NOT EXISTS eloxiv.oauth_device (
680
+ device_hash text PRIMARY KEY,
681
+ user_code_hash text NOT NULL UNIQUE,
682
+ client_id text NOT NULL REFERENCES eloxiv.oauth_client(id) ON DELETE CASCADE,
683
+ scope text[] NOT NULL,
684
+ resource text NOT NULL,
685
+ interval_s integer NOT NULL,
686
+ created_at timestamptz NOT NULL DEFAULT now(),
687
+ expires_at timestamptz NOT NULL,
688
+ last_polled_at timestamptz,
689
+ status text NOT NULL DEFAULT 'pending' CHECK (status IN ('pending', 'approved', 'denied', 'done')),
690
+ user_id text,
691
+ org_id text,
692
+ grant_id text
693
+ )`,
694
+ `CREATE TABLE IF NOT EXISTS eloxiv.oauth_token (
695
+ hash text PRIMARY KEY,
696
+ kind text NOT NULL CHECK (kind IN ('access', 'refresh')),
697
+ grant_id text NOT NULL REFERENCES eloxiv.oauth_grant(id) ON DELETE CASCADE,
698
+ created_at timestamptz NOT NULL DEFAULT now(),
699
+ expires_at timestamptz NOT NULL,
700
+ used_at timestamptz,
701
+ revoked_at timestamptz,
702
+ last_used_at timestamptz
703
+ )`,
704
+ `CREATE INDEX IF NOT EXISTS oauth_token_grant_idx ON eloxiv.oauth_token (grant_id)`,
705
+ `CREATE TABLE IF NOT EXISTS eloxiv.rate_limit (
706
+ bucket text NOT NULL,
707
+ window_start timestamptz NOT NULL,
708
+ count integer NOT NULL,
709
+ PRIMARY KEY (bucket, window_start)
710
+ )`,
711
+ `INSERT INTO eloxiv.role_permission (org_id, role_id, permission)
712
+ SELECT org_id, id, 'eloxiv.machine.manage' FROM eloxiv.role WHERE id = 'admin' ON CONFLICT DO NOTHING`,
713
+ ],
714
+ }
715
+
716
+ /**
717
+ * Ingress: accepted deliveries (the raw body, kept for processing and the replay window), linked platform
718
+ * identities and one-time link codes (hashed). Written to be safe to apply again.
719
+ */
720
+ const ingress: Migration = {
721
+ name: "0015_ingress",
722
+ statements: [
723
+ `CREATE TABLE IF NOT EXISTS eloxiv.ingress_delivery (
724
+ source text NOT NULL,
725
+ delivery_id text NOT NULL,
726
+ body bytea NOT NULL,
727
+ body_hash text NOT NULL,
728
+ headers jsonb NOT NULL,
729
+ signed_at timestamptz,
730
+ received_at timestamptz NOT NULL DEFAULT now(),
731
+ state text NOT NULL DEFAULT 'accepted' CHECK (state IN ('accepted', 'processed', 'refused', 'failed')),
732
+ outcome text,
733
+ execution_id text,
734
+ started_at timestamptz,
735
+ finished_at timestamptz,
736
+ PRIMARY KEY (source, delivery_id)
737
+ )`,
738
+ `CREATE INDEX IF NOT EXISTS ingress_delivery_unstarted_idx ON eloxiv.ingress_delivery (received_at)
739
+ WHERE started_at IS NULL`,
740
+ `CREATE TABLE IF NOT EXISTS eloxiv.linked_identity (
741
+ platform text NOT NULL,
742
+ external_id text NOT NULL,
743
+ org_id text NOT NULL REFERENCES eloxiv.organization(id) ON DELETE CASCADE,
744
+ actor_id text NOT NULL,
745
+ linked_by text NOT NULL,
746
+ created_at timestamptz NOT NULL DEFAULT now(),
747
+ PRIMARY KEY (platform, external_id)
748
+ )`,
749
+ `CREATE TABLE IF NOT EXISTS eloxiv.link_code (
750
+ hash text PRIMARY KEY,
751
+ platform text NOT NULL,
752
+ org_id text NOT NULL REFERENCES eloxiv.organization(id) ON DELETE CASCADE,
753
+ actor_id text NOT NULL,
754
+ created_at timestamptz NOT NULL DEFAULT now(),
755
+ expires_at timestamptz NOT NULL,
756
+ used_at timestamptz,
757
+ used_by text
758
+ )`,
759
+ ],
760
+ }
761
+
762
+ /**
763
+ * Outbox dead letters (backlog 6). A delivery that has failed is tracked per (event, subscriber) in
764
+ * `outbox_failure` until it succeeds (the row goes and an `outbox_delivery` row records the success) or its
765
+ * delivery policy is exhausted (`dead`, or `discarded` by policy or by an administrator). `budget_from` is
766
+ * where the policy's maximum age counts from: the event, or the latest retry of a dead letter. An event is
767
+ * `settled` once nothing is outstanding; only unsettled events are claimed. Existing administrators get the
768
+ * new `eloxiv.outbox.manage` permission. Written to be safe to apply again.
769
+ */
770
+ const deadLetters: Migration = {
771
+ name: "0016_dead_letters",
772
+ statements: [
773
+ `ALTER TABLE eloxiv.outbox ADD COLUMN IF NOT EXISTS settled_at timestamptz`,
774
+ `UPDATE eloxiv.outbox SET settled_at = delivered_at WHERE delivered_at IS NOT NULL AND settled_at IS NULL`,
775
+ `DROP INDEX IF EXISTS eloxiv.outbox_pending_idx`,
776
+ `CREATE INDEX IF NOT EXISTS outbox_unsettled_idx ON eloxiv.outbox (next_attempt_at) WHERE settled_at IS NULL`,
777
+ `CREATE TABLE IF NOT EXISTS eloxiv.outbox_failure (
778
+ event_id text NOT NULL REFERENCES eloxiv.outbox(id),
779
+ subscriber text NOT NULL,
780
+ state text NOT NULL CHECK (state IN ('retrying', 'dead', 'discarded')),
781
+ attempts integer NOT NULL,
782
+ last_error text NOT NULL,
783
+ first_failed_at timestamptz NOT NULL DEFAULT now(),
784
+ budget_from timestamptz NOT NULL,
785
+ next_attempt_at timestamptz,
786
+ dead_at timestamptz,
787
+ closed_by text,
788
+ closed_at timestamptz,
789
+ PRIMARY KEY (event_id, subscriber)
790
+ )`,
791
+ `CREATE INDEX IF NOT EXISTS outbox_failure_dead_idx ON eloxiv.outbox_failure (state) WHERE state = 'dead'`,
792
+ `INSERT INTO eloxiv.role_permission (org_id, role_id, permission)
793
+ SELECT org_id, id, 'eloxiv.outbox.manage' FROM eloxiv.role WHERE id = 'admin' ON CONFLICT DO NOTHING`,
794
+ ],
795
+ }
796
+
797
+ /**
798
+ * Settings and Flags. Deployment values of settings (`app` and `module` levels) set by a deployment
799
+ * administrator (`Settings.configure`) live in the kernel's own schema, where no module role reaches; values
800
+ * people and organisations set live in the `settings` module's schema. Existing administrators get the new
801
+ * `eloxiv.settings.manage` and `eloxiv.flags.manage` permissions. Written to be safe to apply again.
802
+ */
803
+ const settingsAndFlags: Migration = {
804
+ name: "0017_settings_flags",
805
+ statements: [
806
+ `CREATE TABLE IF NOT EXISTS eloxiv.deployment_setting (
807
+ key text NOT NULL,
808
+ level text NOT NULL CHECK (level IN ('app', 'module')),
809
+ value jsonb NOT NULL,
810
+ updated_at timestamptz NOT NULL DEFAULT now(),
811
+ PRIMARY KEY (key, level)
812
+ )`,
813
+ `INSERT INTO eloxiv.role_permission (org_id, role_id, permission)
814
+ SELECT org_id, id, 'eloxiv.settings.manage' FROM eloxiv.role WHERE id = 'admin' ON CONFLICT DO NOTHING`,
815
+ `INSERT INTO eloxiv.role_permission (org_id, role_id, permission)
816
+ SELECT org_id, id, 'eloxiv.flags.manage' FROM eloxiv.role WHERE id = 'admin' ON CONFLICT DO NOTHING`,
817
+ ],
818
+ }
819
+
820
+ /**
821
+ * The agent (AgentRuntime and its family): existing administrators get the new `eloxiv.agent.manage`
822
+ * permission (the organisation's agent memory, resources, model and budgets). The agent's records live in the
823
+ * kernel-provided `agent` module's schema. Safe to apply again.
824
+ */
825
+ const agentManage: Migration = {
826
+ name: "0018_agent_manage",
827
+ statements: [
828
+ `INSERT INTO eloxiv.role_permission (org_id, role_id, permission)
829
+ SELECT org_id, id, 'eloxiv.agent.manage' FROM eloxiv.role WHERE id = 'admin' ON CONFLICT DO NOTHING`,
830
+ ],
831
+ }
832
+
833
+ /**
834
+ * Ingress replay protection on signed material: the hash of exactly what a delivery's signature covers, unique
835
+ * per source, so the same signed payload is accepted once whatever (unsigned) delivery id comes with it.
836
+ * Deliveries accepted before this migration have none. Written to be safe to apply again.
837
+ */
838
+ const ingressSignedHash: Migration = {
839
+ name: "0019_ingress_signed_hash",
840
+ statements: [
841
+ `ALTER TABLE eloxiv.ingress_delivery ADD COLUMN IF NOT EXISTS signed_hash text`,
842
+ `CREATE UNIQUE INDEX IF NOT EXISTS ingress_delivery_signed_idx ON eloxiv.ingress_delivery (source, signed_hash)`,
843
+ ],
844
+ }
845
+
846
+ /**
847
+ * Sharing (the Sharing contract; backlog 4). A grant names its grantee by kind: a `user`, a `group` of the
848
+ * organisation it was made in (`org_id`), a whole `org`, or a `link` (an unguessable token, stored here only as
849
+ * its SHA-256 in `share_link`, that members of `org_id` redeem once, recorded in `share_redemption`). Any grant
850
+ * may expire (`expires_at`); the kernel deletes expired grants (and with them their links and redemptions).
851
+ *
852
+ * `eloxiv_ctx.has_grant(type, id, permission)` replaces the four-argument form: it answers only for the acting
853
+ * principal of the transaction's invocation context (its user grants, its groups' grants in the acting
854
+ * organisation, the acting organisation's grants, and links it redeemed there), never for an arbitrary
855
+ * grantee, so module code cannot learn who holds a grant. The old form is dropped with the row-level security
856
+ * policies that called it, which setup's hardening recreates in the same transaction.
857
+ *
858
+ * `eloxiv_ctx.current_email()` is the acting user's email (empty for service principals), so policies on
859
+ * `principal.email` are answered in the database; the live sync facts gain the member's `email`, kept current
860
+ * by a trigger on Better Auth's users. Written to be safe to apply again.
861
+ */
862
+ const sharing: Migration = {
863
+ name: "0020_sharing",
864
+ statements: [
865
+ `ALTER TABLE eloxiv.share_grant ADD COLUMN IF NOT EXISTS grantee_kind text NOT NULL DEFAULT 'user'
866
+ CHECK (grantee_kind IN ('user', 'group', 'org', 'link'))`,
867
+ `ALTER TABLE eloxiv.share_grant ADD COLUMN IF NOT EXISTS grantee_id text`,
868
+ `DO $$ BEGIN
869
+ IF EXISTS (SELECT 1 FROM information_schema.columns
870
+ WHERE table_schema = 'eloxiv' AND table_name = 'share_grant' AND column_name = 'grantee_user_id') THEN
871
+ UPDATE eloxiv.share_grant SET grantee_id = grantee_user_id WHERE grantee_id IS NULL;
872
+ ALTER TABLE eloxiv.share_grant DROP COLUMN grantee_user_id;
873
+ END IF;
874
+ END $$`,
875
+ `ALTER TABLE eloxiv.share_grant ALTER COLUMN grantee_id SET NOT NULL`,
876
+ `ALTER TABLE eloxiv.share_grant ADD COLUMN IF NOT EXISTS org_id text`,
877
+ `ALTER TABLE eloxiv.share_grant ADD COLUMN IF NOT EXISTS expires_at timestamptz`,
878
+ `CREATE UNIQUE INDEX IF NOT EXISTS share_grant_grantee_key
879
+ ON eloxiv.share_grant (resource_type, resource_id, grantee_kind, grantee_id, permission, (coalesce(org_id, '')))`,
880
+ `CREATE INDEX IF NOT EXISTS share_grant_expiry_idx ON eloxiv.share_grant (expires_at) WHERE expires_at IS NOT NULL`,
881
+ `CREATE TABLE IF NOT EXISTS eloxiv.share_link (
882
+ grant_id text PRIMARY KEY REFERENCES eloxiv.share_grant(id) ON DELETE CASCADE,
883
+ token_hash text NOT NULL UNIQUE
884
+ )`,
885
+ `CREATE TABLE IF NOT EXISTS eloxiv.share_redemption (
886
+ grant_id text NOT NULL REFERENCES eloxiv.share_grant(id) ON DELETE CASCADE,
887
+ user_id text NOT NULL,
888
+ redeemed_at timestamptz NOT NULL DEFAULT now(),
889
+ PRIMARY KEY (grant_id, user_id)
890
+ )`,
891
+ `DROP FUNCTION IF EXISTS eloxiv_ctx.has_grant(text, text, text, text) CASCADE`,
892
+ `CREATE OR REPLACE FUNCTION eloxiv_ctx.has_grant(p_type text, p_id text, p_permission text) RETURNS boolean
893
+ LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog
894
+ AS $$ SELECT EXISTS (
895
+ SELECT 1 FROM eloxiv.invocation_context c
896
+ JOIN eloxiv.share_grant g ON g.resource_type = p_type AND g.resource_id = p_id AND g.permission = p_permission
897
+ WHERE c.xid = pg_current_xact_id()
898
+ AND (g.expires_at IS NULL OR g.expires_at > now())
899
+ AND ((g.grantee_kind = 'user' AND g.grantee_id = c.actor)
900
+ OR (g.grantee_kind = 'org' AND g.grantee_id = c.org)
901
+ OR (g.grantee_kind = 'group' AND g.org_id = c.org AND EXISTS (
902
+ SELECT 1 FROM eloxiv.group_member m
903
+ WHERE m.org_id = c.org AND m.group_id = g.grantee_id AND m.user_id = c.actor))
904
+ OR (g.grantee_kind = 'link' AND g.org_id = c.org AND EXISTS (
905
+ SELECT 1 FROM eloxiv.share_redemption r WHERE r.grant_id = g.id AND r.user_id = c.actor)))) $$`,
906
+ `REVOKE ALL ON FUNCTION eloxiv_ctx.has_grant(text, text, text) FROM PUBLIC`,
907
+ `CREATE OR REPLACE FUNCTION eloxiv_ctx.current_email() RETURNS text
908
+ LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog
909
+ AS $$ SELECT coalesce((SELECT u.email FROM auth."user" u WHERE u.id = c.actor), '')
910
+ FROM eloxiv.invocation_context c WHERE c.xid = pg_current_xact_id() $$`,
911
+ `REVOKE ALL ON FUNCTION eloxiv_ctx.current_email() FROM PUBLIC`,
912
+ // The live facts: a member's email too.
913
+ `ALTER TABLE eloxiv.sync_fact DROP CONSTRAINT IF EXISTS sync_fact_kind_check`,
914
+ `ALTER TABLE eloxiv.sync_fact ADD CONSTRAINT sync_fact_kind_check
915
+ CHECK (kind IN ('member', 'group', 'role', 'permission', 'email'))`,
916
+ `CREATE OR REPLACE FUNCTION eloxiv.refresh_sync_facts(p_org text, p_user text) RETURNS void
917
+ LANGUAGE sql SET search_path = pg_catalog AS $$
918
+ WITH wanted (kind, value) AS (
919
+ SELECT 'member', '' FROM eloxiv.membership WHERE org_id = p_org AND user_id = p_user
920
+ UNION SELECT 'group', group_id FROM eloxiv.group_member WHERE org_id = p_org AND user_id = p_user
921
+ UNION SELECT 'role', role_id FROM eloxiv.membership_role WHERE org_id = p_org AND user_id = p_user
922
+ UNION SELECT 'permission', p.permission FROM eloxiv.membership_role r
923
+ JOIN eloxiv.role_permission p ON p.org_id = r.org_id AND p.role_id = r.role_id
924
+ WHERE r.org_id = p_org AND r.user_id = p_user
925
+ UNION SELECT 'email', coalesce((SELECT u.email FROM auth."user" u WHERE u.id = m.user_id), '')
926
+ FROM eloxiv.membership m WHERE m.org_id = p_org AND m.user_id = p_user
927
+ ), removed AS (
928
+ DELETE FROM eloxiv.sync_fact f WHERE f.org_id = p_org AND f.user_id = p_user
929
+ AND NOT EXISTS (SELECT 1 FROM wanted w WHERE w.kind = f.kind AND w.value = f.value)
930
+ )
931
+ INSERT INTO eloxiv.sync_fact (org_id, user_id, kind, value)
932
+ SELECT p_org, p_user, kind, value FROM wanted ON CONFLICT DO NOTHING
933
+ $$`,
934
+ `CREATE OR REPLACE FUNCTION eloxiv.sync_user_changed() RETURNS trigger
935
+ LANGUAGE plpgsql SET search_path = pg_catalog AS $$
936
+ BEGIN
937
+ PERFORM eloxiv.refresh_sync_facts(m.org_id, m.user_id) FROM eloxiv.membership m WHERE m.user_id = NEW.id;
938
+ RETURN NULL;
939
+ END
940
+ $$`,
941
+ `REVOKE ALL ON FUNCTION eloxiv.refresh_sync_facts(text, text), eloxiv.sync_user_changed() FROM PUBLIC`,
942
+ `CREATE OR REPLACE TRIGGER eloxiv_sync_facts AFTER INSERT OR UPDATE OF email ON auth."user"
943
+ FOR EACH ROW EXECUTE FUNCTION eloxiv.sync_user_changed()`,
944
+ `SELECT eloxiv.refresh_sync_facts(org_id, user_id) FROM eloxiv.membership`,
945
+ ],
946
+ }
947
+
948
+ /**
949
+ * A grant is always in its record's organisation, and counts only there (the Sharing contract, guarantee 5).
950
+ * `eloxiv_ctx.has_grant(type, id, permission, record_org)` replaces the three-argument form: besides answering
951
+ * only for the acting principal, it requires the record's organisation (which the compiled filter passes from
952
+ * the record's own column), the grant's organisation and the acting organisation to be one, for every kind of
953
+ * grantee, a user's included. A grant made in another organisation, or without one, authorises nothing. The old
954
+ * form is dropped with the row-level security policies that called it, which setup's hardening recreates in the
955
+ * same transaction.
956
+ */
957
+ const sharingOrganisation: Migration = {
958
+ name: "0021_sharing_organisation",
959
+ statements: [
960
+ `DROP FUNCTION IF EXISTS eloxiv_ctx.has_grant(text, text, text) CASCADE`,
961
+ `CREATE OR REPLACE FUNCTION eloxiv_ctx.has_grant(p_type text, p_id text, p_permission text, p_org text)
962
+ RETURNS boolean
963
+ LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog
964
+ AS $$ SELECT EXISTS (
965
+ SELECT 1 FROM eloxiv.invocation_context c
966
+ JOIN eloxiv.share_grant g ON g.resource_type = p_type AND g.resource_id = p_id AND g.permission = p_permission
967
+ WHERE c.xid = pg_current_xact_id()
968
+ AND p_org = c.org AND g.org_id = c.org
969
+ AND (g.expires_at IS NULL OR g.expires_at > now())
970
+ AND ((g.grantee_kind = 'user' AND g.grantee_id = c.actor)
971
+ OR (g.grantee_kind = 'org' AND g.grantee_id = c.org)
972
+ OR (g.grantee_kind = 'group' AND EXISTS (
973
+ SELECT 1 FROM eloxiv.group_member m
974
+ WHERE m.org_id = c.org AND m.group_id = g.grantee_id AND m.user_id = c.actor))
975
+ OR (g.grantee_kind = 'link' AND EXISTS (
976
+ SELECT 1 FROM eloxiv.share_redemption r WHERE r.grant_id = g.id AND r.user_id = c.actor)))) $$`,
977
+ `REVOKE ALL ON FUNCTION eloxiv_ctx.has_grant(text, text, text, text) FROM PUBLIC`,
978
+ ],
979
+ }
980
+
981
+ /**
982
+ * Secrets and Connections: encrypted secrets (envelope encryption: only ciphertext, the wrapped data key and the
983
+ * key's id are stored), Connections (metadata only; their tokens are secrets of scope `connection`), consent
984
+ * flows, the per-connection backpressure state Metering shares across processes (cooldowns, quota windows),
985
+ * and connection sync cursors. Administrators get `eloxiv.connections.manage` and `eloxiv.secrets.manage`.
986
+ * Written to be safe to apply again.
987
+ */
988
+ const connections: Migration = {
989
+ name: "0022_connections",
990
+ statements: [
991
+ `CREATE TABLE IF NOT EXISTS eloxiv.secret (
992
+ id text PRIMARY KEY,
993
+ org_id text NOT NULL REFERENCES eloxiv.organization(id) ON DELETE CASCADE,
994
+ scope_kind text NOT NULL CHECK (scope_kind IN ('org', 'user', 'connection')),
995
+ subject text NOT NULL,
996
+ name text NOT NULL,
997
+ key_id text NOT NULL,
998
+ wrapped_key bytea NOT NULL,
999
+ ciphertext bytea NOT NULL,
1000
+ version integer NOT NULL DEFAULT 1,
1001
+ created_at timestamptz NOT NULL DEFAULT now(),
1002
+ updated_at timestamptz NOT NULL DEFAULT now(),
1003
+ UNIQUE (org_id, scope_kind, subject, name)
1004
+ )`,
1005
+ `CREATE INDEX IF NOT EXISTS secret_key_idx ON eloxiv.secret (key_id)`,
1006
+ `CREATE TABLE IF NOT EXISTS eloxiv.connection (
1007
+ id text PRIMARY KEY,
1008
+ org_id text NOT NULL REFERENCES eloxiv.organization(id) ON DELETE CASCADE,
1009
+ owner_id text NOT NULL,
1010
+ provider text NOT NULL,
1011
+ account_id text NOT NULL,
1012
+ account_label text NOT NULL,
1013
+ scopes text[] NOT NULL DEFAULT '{}',
1014
+ status text NOT NULL CHECK (status IN ('active', 'needs-reauth', 'disconnected')),
1015
+ status_reason text,
1016
+ access_expires_at timestamptz,
1017
+ token_version integer NOT NULL DEFAULT 0,
1018
+ refreshed_at timestamptz,
1019
+ created_at timestamptz NOT NULL DEFAULT now(),
1020
+ updated_at timestamptz NOT NULL DEFAULT now(),
1021
+ UNIQUE (org_id, owner_id, provider, account_id)
1022
+ )`,
1023
+ `CREATE TABLE IF NOT EXISTS eloxiv.connection_flow (
1024
+ id text PRIMARY KEY,
1025
+ org_id text NOT NULL REFERENCES eloxiv.organization(id) ON DELETE CASCADE,
1026
+ user_id text NOT NULL,
1027
+ provider text NOT NULL,
1028
+ connection_id text,
1029
+ scopes text[] NOT NULL,
1030
+ return_to text,
1031
+ state_hash text UNIQUE,
1032
+ session_hash text,
1033
+ created_at timestamptz NOT NULL DEFAULT now(),
1034
+ expires_at timestamptz NOT NULL,
1035
+ authorized_at timestamptz,
1036
+ completed_at timestamptz
1037
+ )`,
1038
+ `CREATE TABLE IF NOT EXISTS eloxiv.connection_cooldown (
1039
+ connection_id text PRIMARY KEY,
1040
+ until timestamptz NOT NULL,
1041
+ status integer,
1042
+ reason text,
1043
+ updated_at timestamptz NOT NULL DEFAULT now()
1044
+ )`,
1045
+ `CREATE TABLE IF NOT EXISTS eloxiv.connection_usage (
1046
+ connection_id text NOT NULL,
1047
+ window_start timestamptz NOT NULL,
1048
+ count integer NOT NULL,
1049
+ PRIMARY KEY (connection_id, window_start)
1050
+ )`,
1051
+ `CREATE TABLE IF NOT EXISTS eloxiv.connection_sync (
1052
+ connection_id text NOT NULL REFERENCES eloxiv.connection(id) ON DELETE CASCADE,
1053
+ sync text NOT NULL,
1054
+ cursor text,
1055
+ generation integer NOT NULL DEFAULT 0,
1056
+ run integer NOT NULL DEFAULT 0,
1057
+ pages integer NOT NULL DEFAULT 0,
1058
+ next_due_at timestamptz NOT NULL DEFAULT now(),
1059
+ last_synced_at timestamptz,
1060
+ last_error text,
1061
+ PRIMARY KEY (connection_id, sync)
1062
+ )`,
1063
+ `INSERT INTO eloxiv.role_permission (org_id, role_id, permission)
1064
+ SELECT org_id, id, p.permission FROM eloxiv.role
1065
+ CROSS JOIN (VALUES ('eloxiv.connections.manage'), ('eloxiv.secrets.manage')) AS p(permission)
1066
+ WHERE id = 'admin' ON CONFLICT DO NOTHING`,
1067
+ ],
1068
+ }
1069
+
1070
+ /**
1071
+ * Devices (the Daemon and DeviceControl contracts). A device is paired to a subject (a person or a service
1072
+ * principal) in one organisation; its credential is stored only as a SHA-256 hash. A pairing has RFC 8628's
1073
+ * shape: the daemon polls with a secret only it holds (hashed here) while a signed-in person confirms the user
1074
+ * code (hashed too). Sessions are what a device reports (DeviceControl).
1075
+ * Agent sessions issued to a device carry its id, so revoking the device ends them. Safe to apply again.
1076
+ */
1077
+ const devices: Migration = {
1078
+ name: "0023_devices",
1079
+ statements: [
1080
+ `CREATE TABLE IF NOT EXISTS eloxiv.device (
1081
+ id text PRIMARY KEY,
1082
+ org_id text NOT NULL REFERENCES eloxiv.organization(id),
1083
+ subject text NOT NULL,
1084
+ subject_kind text NOT NULL CHECK (subject_kind IN ('user', 'service')),
1085
+ paired_by text NOT NULL,
1086
+ name text NOT NULL,
1087
+ kind text NOT NULL CHECK (kind IN ('desktop', 'runner')),
1088
+ platform text NOT NULL,
1089
+ capabilities jsonb NOT NULL,
1090
+ token_hash text NOT NULL UNIQUE,
1091
+ created_at timestamptz NOT NULL DEFAULT now(),
1092
+ last_seen_at timestamptz,
1093
+ revoked_at timestamptz,
1094
+ revoked_by text
1095
+ )`,
1096
+ `CREATE INDEX IF NOT EXISTS device_org_idx ON eloxiv.device (org_id, subject)`,
1097
+ `CREATE TABLE IF NOT EXISTS eloxiv.device_pairing (
1098
+ id text PRIMARY KEY,
1099
+ poll_hash text NOT NULL,
1100
+ user_code_hash text NOT NULL UNIQUE,
1101
+ source text NOT NULL,
1102
+ name text NOT NULL,
1103
+ kind text NOT NULL CHECK (kind IN ('desktop', 'runner')),
1104
+ platform text NOT NULL,
1105
+ capabilities jsonb NOT NULL,
1106
+ status text NOT NULL DEFAULT 'pending' CHECK (status IN ('pending', 'approved', 'denied', 'claimed')),
1107
+ org_id text,
1108
+ subject text,
1109
+ subject_kind text,
1110
+ decided_by text,
1111
+ device_id text,
1112
+ created_at timestamptz NOT NULL DEFAULT now(),
1113
+ expires_at timestamptz NOT NULL,
1114
+ decided_at timestamptz,
1115
+ claimed_at timestamptz,
1116
+ reclaimed_at timestamptz
1117
+ )`,
1118
+ `CREATE INDEX IF NOT EXISTS device_pairing_source_idx ON eloxiv.device_pairing (source, created_at)`,
1119
+ // Counters for the device limits (pairings per address, wrong codes per person), updated atomically.
1120
+ `CREATE TABLE IF NOT EXISTS eloxiv.device_limit (
1121
+ bucket text PRIMARY KEY,
1122
+ window_start timestamptz NOT NULL,
1123
+ count integer NOT NULL
1124
+ )`,
1125
+ `CREATE TABLE IF NOT EXISTS eloxiv.device_session (
1126
+ device_id text NOT NULL REFERENCES eloxiv.device(id),
1127
+ id text NOT NULL,
1128
+ kind text NOT NULL,
1129
+ label text NOT NULL,
1130
+ detail text,
1131
+ started_at timestamptz NOT NULL,
1132
+ ended_at timestamptz,
1133
+ PRIMARY KEY (device_id, id)
1134
+ )`,
1135
+ `ALTER TABLE eloxiv.agent_session ADD COLUMN IF NOT EXISTS device_id text REFERENCES eloxiv.device(id)`,
1136
+ `CREATE INDEX IF NOT EXISTS agent_session_device_idx ON eloxiv.agent_session (device_id) WHERE device_id IS NOT NULL`,
1137
+ ],
1138
+ }
1139
+
1140
+ /**
1141
+ * The directory's sync facts are right under any concurrency, whoever writes the directory (second review of
1142
+ * the manifest fixes). Before this, the triggers recomputed a member's facts from their statement's snapshot
1143
+ * and inserted with `ON CONFLICT DO NOTHING`: a writer that did not take the organisation's lock (the trusted
1144
+ * `Directory.addMember`, or plain SQL) could read a permission a concurrent revocation was deleting, wait on the
1145
+ * fact row the revocation deleted, and insert it again after the revocation committed.
1146
+ *
1147
+ * Now every trigger that maintains `sync_fact` or `sync_org` first takes the organisation's directory lock (the
1148
+ * transaction-level advisory lock managed directory writes take, `eloxiv.directory:<org>`), and only then
1149
+ * reads. Each statement after it runs on a fresh snapshot (READ COMMITTED; the functions are volatile), so
1150
+ * whichever of two concurrent writers takes the lock second recomputes from what the first committed. The lock
1151
+ * is reentrant within a transaction, so writers that take it first (managed and system directory writes,
1152
+ * machine identity) are unaffected. Under REPEATABLE READ or SERIALIZABLE the snapshot would not move once the
1153
+ * lock is held, so a directory change at those levels is refused rather than risk a stale fact. Existing facts
1154
+ * are recomputed once, under each organisation's lock. Written to be safe to apply again.
1155
+ */
1156
+ const serialisedSyncFacts: Migration = {
1157
+ name: "0024_serialised_sync_facts",
1158
+ statements: [
1159
+ `CREATE OR REPLACE FUNCTION eloxiv.lock_directory(p_org text) RETURNS void
1160
+ LANGUAGE plpgsql SET search_path = pg_catalog AS $$
1161
+ BEGIN
1162
+ IF current_setting('transaction_isolation') <> 'read committed' THEN
1163
+ RAISE EXCEPTION 'Directory changes run at READ COMMITTED isolation (this transaction is %)',
1164
+ current_setting('transaction_isolation') USING ERRCODE = 'feature_not_supported';
1165
+ END IF;
1166
+ PERFORM pg_advisory_xact_lock(hashtext('eloxiv.directory:' || p_org));
1167
+ END
1168
+ $$`,
1169
+ `CREATE OR REPLACE FUNCTION eloxiv.sync_member_changed() RETURNS trigger
1170
+ LANGUAGE plpgsql SET search_path = pg_catalog AS $$
1171
+ BEGIN
1172
+ IF TG_OP IN ('UPDATE', 'DELETE') THEN PERFORM eloxiv.lock_directory(OLD.org_id); END IF;
1173
+ IF TG_OP IN ('UPDATE', 'INSERT') THEN PERFORM eloxiv.lock_directory(NEW.org_id); END IF;
1174
+ IF TG_OP IN ('UPDATE', 'DELETE') THEN PERFORM eloxiv.refresh_sync_facts(OLD.org_id, OLD.user_id); END IF;
1175
+ IF TG_OP IN ('UPDATE', 'INSERT') THEN PERFORM eloxiv.refresh_sync_facts(NEW.org_id, NEW.user_id); END IF;
1176
+ RETURN NULL;
1177
+ END
1178
+ $$`,
1179
+ `CREATE OR REPLACE FUNCTION eloxiv.sync_role_permission_changed() RETURNS trigger
1180
+ LANGUAGE plpgsql SET search_path = pg_catalog AS $$
1181
+ BEGIN
1182
+ IF TG_OP IN ('UPDATE', 'DELETE') THEN PERFORM eloxiv.lock_directory(OLD.org_id); END IF;
1183
+ IF TG_OP IN ('UPDATE', 'INSERT') THEN PERFORM eloxiv.lock_directory(NEW.org_id); END IF;
1184
+ IF TG_OP IN ('UPDATE', 'DELETE') THEN
1185
+ PERFORM eloxiv.refresh_sync_facts(m.org_id, m.user_id) FROM eloxiv.membership_role m
1186
+ WHERE m.org_id = OLD.org_id AND m.role_id = OLD.role_id;
1187
+ END IF;
1188
+ IF TG_OP IN ('UPDATE', 'INSERT') THEN
1189
+ PERFORM eloxiv.refresh_sync_facts(m.org_id, m.user_id) FROM eloxiv.membership_role m
1190
+ WHERE m.org_id = NEW.org_id AND m.role_id = NEW.role_id;
1191
+ END IF;
1192
+ RETURN NULL;
1193
+ END
1194
+ $$`,
1195
+ `CREATE OR REPLACE FUNCTION eloxiv.sync_org_changed() RETURNS trigger
1196
+ LANGUAGE plpgsql SET search_path = pg_catalog AS $$
1197
+ BEGIN
1198
+ IF TG_OP = 'DELETE' THEN
1199
+ PERFORM eloxiv.lock_directory(OLD.id);
1200
+ DELETE FROM eloxiv.sync_org WHERE id = OLD.id;
1201
+ ELSE
1202
+ PERFORM eloxiv.lock_directory(NEW.id);
1203
+ INSERT INTO eloxiv.sync_org (id) VALUES (NEW.id) ON CONFLICT DO NOTHING;
1204
+ END IF;
1205
+ RETURN NULL;
1206
+ END
1207
+ $$`,
1208
+ // A member's email (0020_sharing's trigger on Better Auth's users) recomputes all of their facts in each of
1209
+ // their organisations: under each organisation's lock too, taken in one order.
1210
+ `CREATE OR REPLACE FUNCTION eloxiv.sync_user_changed() RETURNS trigger
1211
+ LANGUAGE plpgsql SET search_path = pg_catalog AS $$
1212
+ DECLARE m record;
1213
+ BEGIN
1214
+ FOR m IN SELECT org_id FROM eloxiv.membership WHERE user_id = NEW.id ORDER BY org_id LOOP
1215
+ PERFORM eloxiv.lock_directory(m.org_id);
1216
+ PERFORM eloxiv.refresh_sync_facts(m.org_id, NEW.id);
1217
+ END LOOP;
1218
+ RETURN NULL;
1219
+ END
1220
+ $$`,
1221
+ `REVOKE ALL ON FUNCTION eloxiv.lock_directory(text) FROM PUBLIC`,
1222
+ // Existing facts: recomputed once, each organisation under its lock.
1223
+ `DO $$
1224
+ DECLARE org record;
1225
+ BEGIN
1226
+ FOR org IN SELECT id FROM eloxiv.organization ORDER BY id LOOP
1227
+ PERFORM eloxiv.lock_directory(org.id);
1228
+ PERFORM eloxiv.refresh_sync_facts(m.org_id, m.user_id) FROM eloxiv.membership m WHERE m.org_id = org.id;
1229
+ DELETE FROM eloxiv.sync_fact f WHERE f.org_id = org.id AND NOT EXISTS (
1230
+ SELECT 1 FROM eloxiv.membership m WHERE m.org_id = f.org_id AND m.user_id = f.user_id);
1231
+ END LOOP;
1232
+ DELETE FROM eloxiv.sync_fact f WHERE NOT EXISTS (SELECT 1 FROM eloxiv.organization o WHERE o.id = f.org_id);
1233
+ INSERT INTO eloxiv.sync_org (id) SELECT id FROM eloxiv.organization ON CONFLICT DO NOTHING;
1234
+ DELETE FROM eloxiv.sync_org s WHERE NOT EXISTS (SELECT 1 FROM eloxiv.organization o WHERE o.id = s.id);
1235
+ END
1236
+ $$`,
1237
+ ],
1238
+ }
1239
+
1240
+ /**
1241
+ * Module migrations on the owner's own connection (third review of the manifest fixes), and no TRUNCATE of the
1242
+ * directory.
1243
+ *
1244
+ * - `eloxiv_setup.record_migration(name)`: a module's migrations run on a connection that logs in as the
1245
+ * module's owner role, so there is no more privileged role a migration could return to. That connection
1246
+ * records each migration it applies in the same transaction, through this function: it runs as the kernel
1247
+ * role, and records the name only for the module whose owner role the session logged in as (`session_user`,
1248
+ * which only a superuser can change), so a module can only ever mark its own migrations. Setup grants it to
1249
+ * each module's owner role.
1250
+ * - TRUNCATE skips row triggers, so it would leave `sync_fact` and `sync_org` behind the directory: a statement
1251
+ * trigger refuses it on every directory table. Delete rows instead.
1252
+ *
1253
+ * Written to be safe to apply again.
1254
+ */
1255
+ /**
1256
+ * How a module's owner session records its migrations (kernel migration 0025, as revised by the setup review).
1257
+ * `eloxiv_setup.record_migration(name)` runs as the kernel role and records the name for the module whose owner
1258
+ * role the session logged in as (`session_user`, which only a superuser can change), and only if setup planned
1259
+ * it: before any owner session connects, setup lists each module's pending migrations in
1260
+ * `eloxiv_setup.migration_plan` (which only the kernel role can write), and each name can be recorded once. A
1261
+ * migration cannot mark a migration of another module, nor one its module does not ship (`9999_future`, which
1262
+ * would make a later version skip it), and only the one being applied now (`current`, which setup sets before
1263
+ * each migration; a migration cannot record one after it). Setup also creates all of this before the kernel's migrations run
1264
+ * (`bootstrapDatabase`, when the plan is missing), because module migrations record themselves while the
1265
+ * kernel's migrations are still uncommitted in setup's own transaction. Safe to run again.
1266
+ */
1267
+ export const recordMigrationStatements: ReadonlyArray<string> = [
1268
+ `CREATE SCHEMA IF NOT EXISTS eloxiv_setup`,
1269
+ `REVOKE ALL ON SCHEMA eloxiv_setup FROM PUBLIC`,
1270
+ `CREATE TABLE IF NOT EXISTS eloxiv_setup.migration_plan (
1271
+ module text NOT NULL,
1272
+ name text NOT NULL,
1273
+ PRIMARY KEY (module, name)
1274
+ )`,
1275
+ `ALTER TABLE eloxiv_setup.migration_plan ADD COLUMN IF NOT EXISTS current boolean NOT NULL DEFAULT false`,
1276
+ `REVOKE ALL ON eloxiv_setup.migration_plan FROM PUBLIC`,
1277
+ `CREATE OR REPLACE FUNCTION eloxiv_setup.record_migration(p_name text) RETURNS void
1278
+ LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
1279
+ DECLARE v_module text;
1280
+ BEGIN
1281
+ IF session_user::text NOT LIKE 'eloxiv\\_own\\_%' THEN
1282
+ RAISE EXCEPTION 'Only a module''s owner session records its migrations' USING ERRCODE = 'insufficient_privilege';
1283
+ END IF;
1284
+ v_module := substr(session_user::text, length('eloxiv_own_') + 1);
1285
+ DELETE FROM eloxiv_setup.migration_plan WHERE module = v_module AND name = p_name AND current;
1286
+ IF NOT FOUND THEN
1287
+ IF EXISTS (SELECT 1 FROM eloxiv_setup.migration_plan WHERE module = v_module AND name = p_name) THEN
1288
+ RAISE EXCEPTION '% is not the migration of module % being applied', p_name, v_module
1289
+ USING ERRCODE = 'insufficient_privilege';
1290
+ END IF;
1291
+ RAISE EXCEPTION '% is not a pending migration of module %', p_name, v_module
1292
+ USING ERRCODE = 'insufficient_privilege';
1293
+ END IF;
1294
+ INSERT INTO eloxiv.module_migration (module, name) VALUES (v_module, p_name) ON CONFLICT DO NOTHING;
1295
+ END
1296
+ $$`,
1297
+ `REVOKE ALL ON FUNCTION eloxiv_setup.record_migration(text) FROM PUBLIC`,
1298
+ ]
1299
+
1300
+ const ownerMigrations: Migration = {
1301
+ name: "0025_owner_migrations",
1302
+ statements: [
1303
+ ...recordMigrationStatements,
1304
+ `CREATE OR REPLACE FUNCTION eloxiv.refuse_directory_truncate() RETURNS trigger
1305
+ LANGUAGE plpgsql SET search_path = pg_catalog, pg_temp AS $$
1306
+ BEGIN
1307
+ RAISE EXCEPTION 'TRUNCATE of %.% would leave the sync facts behind the directory; delete the rows instead',
1308
+ TG_TABLE_SCHEMA, TG_TABLE_NAME USING ERRCODE = 'feature_not_supported';
1309
+ END
1310
+ $$`,
1311
+ `REVOKE ALL ON FUNCTION eloxiv.refuse_directory_truncate() FROM PUBLIC`,
1312
+ ...["organization", "membership", "membership_role", "role", "role_permission", "org_group", "group_member"].map(
1313
+ (table) => `CREATE OR REPLACE TRIGGER eloxiv_no_truncate BEFORE TRUNCATE ON eloxiv.${table}
1314
+ FOR EACH STATEMENT EXECUTE FUNCTION eloxiv.refuse_directory_truncate()`,
1315
+ ),
1316
+ ],
1317
+ }
1318
+
1319
+ /**
1320
+ * Security drift (release review 2026-11-04): with each module's hardening, setup records the fingerprint of the
1321
+ * security-relevant state it left (row-level security, policies, privileges, triggers), so a later setup and
1322
+ * the Release status can tell when it was changed outside setup. Existing rows have none, so the next setup
1323
+ * re-hardens every module once. Numbered after the manifest fixes' migrations when the two lines of work were
1324
+ * integrated, and again after build/main's 0017 to 0023 (with them, as 0024 to 0026): a database that recorded
1325
+ * it under an earlier name (`0017_hardening_state`, `0019_hardening_state`) applies it again, which changes
1326
+ * nothing.
1327
+ */
1328
+ const hardeningState: Migration = {
1329
+ name: "0026_hardening_state",
1330
+ statements: [`ALTER TABLE eloxiv.module_hardening ADD COLUMN IF NOT EXISTS security jsonb`],
1331
+ }
1332
+
1333
+ /**
1334
+ * Sync guards (decision 9): a function the CHECK constraints setup installs on synced `jsonb` columns call. A
1335
+ * JSON number reaches a replica as a JavaScript number, so a document may sync only when every number in it is
1336
+ * exactly a double: its shortest double spelling (`float8::text`) is the same number. Pure and safe, so every
1337
+ * role (migrations included) may run it.
1338
+ */
1339
+ const syncGuards: Migration = {
1340
+ name: "0027_sync_guards",
1341
+ statements: [
1342
+ `CREATE SCHEMA IF NOT EXISTS eloxiv_guard`,
1343
+ `GRANT USAGE ON SCHEMA eloxiv_guard TO PUBLIC`,
1344
+ `CREATE OR REPLACE FUNCTION eloxiv_guard.json_doubles(value jsonb) RETURNS boolean
1345
+ LANGUAGE sql IMMUTABLE STRICT PARALLEL SAFE SET search_path = pg_catalog AS $$
1346
+ -- Every number JavaScript reads as the same number and spells back the same: within ±(2^53 - 1) (beyond,
1347
+ -- doubles are integers JavaScript spells otherwise), and already in its shortest double spelling, which
1348
+ -- Postgres and JavaScript share (CASE keeps the cast from numbers out of a double's range).
1349
+ SELECT NOT EXISTS (
1350
+ SELECT 1 FROM jsonb_path_query(value, 'strict $.**') AS n,
1351
+ LATERAL (SELECT CASE WHEN jsonb_typeof(n) = 'number' THEN (n #>> '{}')::numeric END AS x) AS m
1352
+ WHERE m.x IS NOT NULL
1353
+ AND NOT CASE
1354
+ WHEN abs(m.x) > 9007199254740991 THEN false
1355
+ WHEN m.x <> 0 AND abs(m.x) < 4.9406564584124654e-324 THEN false
1356
+ ELSE m.x = ((m.x)::float8)::text::numeric
1357
+ END)
1358
+ $$`,
1359
+ `GRANT EXECUTE ON FUNCTION eloxiv_guard.json_doubles(jsonb) TO PUBLIC`,
1360
+ ],
1361
+ }
1362
+
1363
+ /**
1364
+ * Spaces (the Space contract): existing administrators get the new `eloxiv.spaces.manage` permission (define
1365
+ * and withdraw the organisation's spaces). The spaces themselves live in the kernel-provided `spaces` module's
1366
+ * schema. Safe to apply again.
1367
+ */
1368
+ const spacesManage: Migration = {
1369
+ name: "0028_spaces_manage",
1370
+ statements: [
1371
+ `INSERT INTO eloxiv.role_permission (org_id, role_id, permission)
1372
+ SELECT org_id, id, 'eloxiv.spaces.manage' FROM eloxiv.role WHERE id = 'admin' ON CONFLICT DO NOTHING`,
1373
+ ],
1374
+ }
1375
+
1376
+ /**
1377
+ * Files, Search and Ingestion (docs/contracts/files.md, search.md, ingestion.md). Numbered after
1378
+ * `0028_spaces_manage` when the lines of work were integrated.
1379
+ *
1380
+ * - `file` and `file_part`: file records (metadata, attachment by reference, lifecycle) and the parts of uploads
1381
+ * in progress; `storage_quota`: each organisation's quota (Metering's storage part). The bytes are in the
1382
+ * deployment's StorageBackend. `file` is replicated to zero-cache; the sync endpoint filters it by the read
1383
+ * policy of each file's record. Its columns are `files/FileTable.ts`'s, and what syncs is held to sync's exact
1384
+ * window by CHECKs (as setup's guards hold a module's synced columns).
1385
+ * - `record_source`: which module tables setup tracks (entities declaring `search` or `files`), with their
1386
+ * search fields; `search_document`: the full-text index, one row per record (part `''`), per attached file's
1387
+ * name (`file:<id>`) and per ingested chunk (`chunk:<item>:<seq>`), keyed by the record it belongs to.
1388
+ * - `eloxiv.track_record()`: the AFTER row trigger setup installs on tracked tables. It indexes a record in the
1389
+ * same transaction as every write to it, and when a record is deleted it removes its documents, deletes its
1390
+ * files (their bytes purged later, after retention) and supersedes its ingestion items. SECURITY DEFINER (it
1391
+ * writes the kernel's tables); it reads which table it fires on from the trigger itself and its configuration
1392
+ * from `record_source`, never from arguments, and nobody but the kernel may execute it (so no migration can
1393
+ * attach it to a table of its own choosing).
1394
+ * - `ingestion_item` and `ingestion_chunk`: source items (idempotent per record, source key and version), their
1395
+ * state, progress and extracted text, and each chunk's character range.
1396
+ *
1397
+ * Safe to apply again.
1398
+ */
1399
+ const filesSearchIngestion: Migration = {
1400
+ name: "0029_files_search_ingestion",
1401
+ statements: [
1402
+ `CREATE TABLE IF NOT EXISTS eloxiv.file (
1403
+ id text PRIMARY KEY,
1404
+ org_id text NOT NULL,
1405
+ owner_type text,
1406
+ owner_id text,
1407
+ name text NOT NULL,
1408
+ declared_type text NOT NULL,
1409
+ content_type text,
1410
+ size bigint NOT NULL,
1411
+ sha256 text,
1412
+ state text NOT NULL,
1413
+ state_reason text,
1414
+ scan text,
1415
+ storage_key text NOT NULL,
1416
+ upload_id text,
1417
+ part_size integer NOT NULL,
1418
+ parts integer NOT NULL,
1419
+ uploaded_by text NOT NULL,
1420
+ created_at timestamptz NOT NULL DEFAULT now(),
1421
+ updated_at timestamptz NOT NULL DEFAULT now(),
1422
+ completed_at timestamptz,
1423
+ expires_at timestamptz,
1424
+ deleted_at timestamptz,
1425
+ purged_at timestamptz,
1426
+ retain_until timestamptz,
1427
+ etag text,
1428
+ CONSTRAINT file_state CHECK (state IN ('uploading', 'processing', 'available', 'quarantined', 'rejected', 'deleted')),
1429
+ CONSTRAINT file_owner CHECK ((owner_type IS NULL) = (owner_id IS NULL)),
1430
+ CONSTRAINT file_scan CHECK (scan IS NULL OR scan IN ('clean', 'infected', 'skipped', 'error')),
1431
+ -- What syncs is held to the window sync carries exactly (setup's guards for module tables: safe-integer, instant).
1432
+ CONSTRAINT file_size_sync CHECK (size BETWEEN 0 AND 9007199254740991),
1433
+ CONSTRAINT file_created_sync CHECK (pg_catalog.isfinite(created_at) AND EXTRACT(epoch FROM created_at) >= 0
1434
+ AND EXTRACT(epoch FROM created_at) < 2145916800),
1435
+ CONSTRAINT file_completed_sync CHECK (pg_catalog.isfinite(completed_at) AND EXTRACT(epoch FROM completed_at) >= 0
1436
+ AND EXTRACT(epoch FROM completed_at) < 2145916800)
1437
+ )`,
1438
+ `CREATE INDEX IF NOT EXISTS file_owner_idx ON eloxiv.file (owner_type, owner_id)`,
1439
+ `CREATE INDEX IF NOT EXISTS file_org_state_idx ON eloxiv.file (org_id, state)`,
1440
+ `CREATE INDEX IF NOT EXISTS file_unpurged_idx ON eloxiv.file (deleted_at) WHERE purged_at IS NULL AND state = 'deleted'`,
1441
+ `CREATE TABLE IF NOT EXISTS eloxiv.file_part (
1442
+ file_id text NOT NULL REFERENCES eloxiv.file(id) ON DELETE CASCADE,
1443
+ part_number integer NOT NULL,
1444
+ size bigint NOT NULL,
1445
+ etag text NOT NULL,
1446
+ staged_key text,
1447
+ received_at timestamptz NOT NULL DEFAULT now(),
1448
+ PRIMARY KEY (file_id, part_number)
1449
+ )`,
1450
+ `CREATE TABLE IF NOT EXISTS eloxiv.file_part_claim (
1451
+ nonce text PRIMARY KEY,
1452
+ file_id text NOT NULL REFERENCES eloxiv.file(id) ON DELETE CASCADE,
1453
+ part_number integer NOT NULL,
1454
+ claimed_at timestamptz NOT NULL DEFAULT now()
1455
+ )`,
1456
+ `CREATE TABLE IF NOT EXISTS eloxiv.storage_quota (
1457
+ org_id text PRIMARY KEY,
1458
+ limit_bytes bigint,
1459
+ updated_by text NOT NULL,
1460
+ updated_at timestamptz NOT NULL DEFAULT now()
1461
+ )`,
1462
+ `CREATE TABLE IF NOT EXISTS eloxiv.record_source (
1463
+ cedar_type text PRIMARY KEY,
1464
+ table_schema text NOT NULL,
1465
+ table_name text NOT NULL,
1466
+ pk_column text NOT NULL,
1467
+ org_column text NOT NULL,
1468
+ searchable boolean NOT NULL,
1469
+ config regconfig NOT NULL DEFAULT 'simple',
1470
+ title_column text,
1471
+ fields jsonb NOT NULL DEFAULT '[]'::jsonb,
1472
+ fingerprint text NOT NULL,
1473
+ UNIQUE (table_schema, table_name)
1474
+ )`,
1475
+ `CREATE TABLE IF NOT EXISTS eloxiv.search_document (
1476
+ record_type text NOT NULL,
1477
+ record_id text NOT NULL,
1478
+ part text NOT NULL,
1479
+ org_id text NOT NULL,
1480
+ title text,
1481
+ body text NOT NULL DEFAULT '',
1482
+ config regconfig NOT NULL,
1483
+ tsv tsvector NOT NULL,
1484
+ updated_at timestamptz NOT NULL DEFAULT now(),
1485
+ PRIMARY KEY (record_type, record_id, part)
1486
+ )`,
1487
+ `CREATE INDEX IF NOT EXISTS search_document_tsv_idx ON eloxiv.search_document USING gin (tsv)`,
1488
+ `CREATE INDEX IF NOT EXISTS search_document_org_idx ON eloxiv.search_document (org_id, record_type)`,
1489
+ `CREATE TABLE IF NOT EXISTS eloxiv.ingestion_item (
1490
+ id text PRIMARY KEY,
1491
+ seq bigserial NOT NULL,
1492
+ org_id text NOT NULL,
1493
+ record_type text NOT NULL,
1494
+ record_id text NOT NULL,
1495
+ module text NOT NULL,
1496
+ source_kind text NOT NULL,
1497
+ source_key text NOT NULL,
1498
+ version text NOT NULL,
1499
+ source jsonb NOT NULL,
1500
+ title text,
1501
+ media_type text,
1502
+ state text NOT NULL,
1503
+ progress real NOT NULL DEFAULT 0,
1504
+ chunks integer NOT NULL DEFAULT 0,
1505
+ characters integer NOT NULL DEFAULT 0,
1506
+ truncated boolean NOT NULL DEFAULT false,
1507
+ error text,
1508
+ text text,
1509
+ attempt integer NOT NULL DEFAULT 1,
1510
+ submitted_by text NOT NULL,
1511
+ created_at timestamptz NOT NULL DEFAULT now(),
1512
+ updated_at timestamptz NOT NULL DEFAULT now(),
1513
+ completed_at timestamptz,
1514
+ CONSTRAINT ingestion_item_state CHECK
1515
+ (state IN ('queued', 'fetching', 'extracting', 'indexing', 'done', 'failed', 'superseded')),
1516
+ UNIQUE (org_id, record_type, record_id, source_key, version)
1517
+ )`,
1518
+ `CREATE INDEX IF NOT EXISTS ingestion_item_record_idx ON eloxiv.ingestion_item (record_type, record_id)`,
1519
+ `CREATE TABLE IF NOT EXISTS eloxiv.ingestion_chunk (
1520
+ item_id text NOT NULL REFERENCES eloxiv.ingestion_item(id) ON DELETE CASCADE,
1521
+ seq integer NOT NULL,
1522
+ start_at integer NOT NULL,
1523
+ end_at integer NOT NULL,
1524
+ PRIMARY KEY (item_id, seq)
1525
+ )`,
1526
+ `CREATE OR REPLACE FUNCTION eloxiv.index_record(src eloxiv.record_source, rec jsonb) RETURNS void
1527
+ LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog AS $$
1528
+ DECLARE
1529
+ f jsonb;
1530
+ piece text;
1531
+ v_doc tsvector := ''::tsvector;
1532
+ v_body text := '';
1533
+ v_total integer := 0;
1534
+ v_id text := rec ->> src.pk_column;
1535
+ v_org text := rec ->> src.org_column;
1536
+ BEGIN
1537
+ IF NOT src.searchable OR v_id IS NULL THEN RETURN; END IF;
1538
+ IF v_org IS NULL THEN
1539
+ DELETE FROM eloxiv.search_document WHERE record_type = src.cedar_type AND record_id = v_id AND part = '';
1540
+ RETURN;
1541
+ END IF;
1542
+ FOR f IN SELECT value FROM jsonb_array_elements(src.fields) LOOP
1543
+ -- Bounded, so a tsvector never passes PostgreSQL's limit (the write would fail).
1544
+ piece := left(coalesce(rec ->> (f ->> 'column'), ''), greatest(0, least(100000, 200000 - v_total)));
1545
+ v_total := v_total + length(piece);
1546
+ v_doc := v_doc || setweight(to_tsvector(src.config, piece), (f ->> 'weight')::"char");
1547
+ IF (f ->> 'column') IS DISTINCT FROM src.title_column AND piece <> '' THEN
1548
+ v_body := v_body || CASE WHEN v_body = '' THEN '' ELSE E'\\n' END || piece;
1549
+ END IF;
1550
+ END LOOP;
1551
+ INSERT INTO eloxiv.search_document (record_type, record_id, part, org_id, title, body, config, tsv, updated_at)
1552
+ VALUES (src.cedar_type, v_id, '', v_org, left(rec ->> src.title_column, 1000), v_body, src.config, v_doc, now())
1553
+ ON CONFLICT (record_type, record_id, part) DO UPDATE
1554
+ SET org_id = EXCLUDED.org_id, title = EXCLUDED.title, body = EXCLUDED.body, config = EXCLUDED.config,
1555
+ tsv = EXCLUDED.tsv, updated_at = now();
1556
+ END
1557
+ $$`,
1558
+ `CREATE OR REPLACE FUNCTION eloxiv.forget_record(p_type text, p_id text) RETURNS void
1559
+ LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog AS $$
1560
+ BEGIN
1561
+ -- The record's lock before any row (the order every index writer takes, after the search lock).
1562
+ PERFORM pg_advisory_xact_lock(hashtextextended('eloxiv.record:' || p_type || ':' || p_id, 0));
1563
+ DELETE FROM eloxiv.search_document WHERE record_type = p_type AND record_id = p_id;
1564
+ -- Its files are deleted, each announced (files.deleted) in the same transaction, as an action's are.
1565
+ WITH deleted AS (
1566
+ UPDATE eloxiv.file SET state = 'deleted', state_reason = 'Its record was deleted',
1567
+ deleted_at = coalesce(deleted_at, now()), updated_at = now()
1568
+ WHERE owner_type = p_type AND owner_id = p_id AND state <> 'deleted'
1569
+ RETURNING id, org_id
1570
+ )
1571
+ INSERT INTO eloxiv.outbox (id, invocation_id, type, module, org_id, payload)
1572
+ SELECT gen_random_uuid()::text, d.id, 'files.deleted', 'files', d.org_id,
1573
+ jsonb_build_object('fileId', d.id, 'attachedTo', jsonb_build_object('entity', p_type, 'id', p_id),
1574
+ 'state', 'deleted')
1575
+ FROM deleted d;
1576
+ IF FOUND THEN PERFORM pg_notify('eloxiv_outbox', p_id); END IF;
1577
+ UPDATE eloxiv.ingestion_item SET state = 'superseded', error = 'Its record was deleted', text = NULL,
1578
+ updated_at = now()
1579
+ WHERE record_type = p_type AND record_id = p_id AND state <> 'superseded';
1580
+ DELETE FROM eloxiv.ingestion_chunk c USING eloxiv.ingestion_item i
1581
+ WHERE c.item_id = i.id AND i.record_type = p_type AND i.record_id = p_id;
1582
+ END
1583
+ $$`,
1584
+ `CREATE OR REPLACE FUNCTION eloxiv.track_record() RETURNS trigger
1585
+ LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog AS $$
1586
+ DECLARE
1587
+ src eloxiv.record_source;
1588
+ BEGIN
1589
+ -- A rebuild by setup holds this exclusively (one lock, whatever entity types it rebuilds): a write waits
1590
+ -- for it, and it waits for writes in flight. Taken before the declaration is read, so a write that waited
1591
+ -- reads the declaration the rebuild left.
1592
+ PERFORM pg_advisory_xact_lock_shared(hashtextextended('eloxiv.search', 0));
1593
+ SELECT * INTO src FROM eloxiv.record_source s
1594
+ WHERE s.table_schema = TG_TABLE_SCHEMA AND s.table_name = TG_TABLE_NAME;
1595
+ IF NOT FOUND THEN RETURN NULL; END IF;
1596
+ IF TG_OP = 'DELETE' THEN
1597
+ PERFORM eloxiv.forget_record(src.cedar_type, to_jsonb(OLD) ->> src.pk_column);
1598
+ ELSE
1599
+ PERFORM eloxiv.index_record(src, to_jsonb(NEW));
1600
+ END IF;
1601
+ RETURN NULL;
1602
+ END
1603
+ $$`,
1604
+ `REVOKE ALL ON FUNCTION eloxiv.index_record(eloxiv.record_source, jsonb) FROM PUBLIC`,
1605
+ `REVOKE ALL ON FUNCTION eloxiv.forget_record(text, text) FROM PUBLIC`,
1606
+ `REVOKE ALL ON FUNCTION eloxiv.track_record() FROM PUBLIC`,
1607
+ ],
1608
+ }
1609
+
1610
+ /**
1611
+ * Platform services. Versioning: each module's installed version and every change of it, recorded by setup; the
1612
+ * append-only history of records of entities that keep one, written only by the invocation path (module roles
1613
+ * have no privilege on it); and the write log keeps the row a change left (as it was, for a delete) for those
1614
+ * entities' tables (`eloxiv.track_write(<pk>, 'history')`), so the history holds deletes too. Safe to run twice.
1615
+ */
1616
+ const platformServices: Migration = {
1617
+ name: "0030_platform_services",
1618
+ statements: [
1619
+ `CREATE TABLE IF NOT EXISTS eloxiv.module_version (
1620
+ module text PRIMARY KEY,
1621
+ version text NOT NULL,
1622
+ kernel_range text NOT NULL,
1623
+ installed_at timestamptz NOT NULL DEFAULT now(),
1624
+ updated_at timestamptz NOT NULL DEFAULT now()
1625
+ )`,
1626
+ `CREATE TABLE IF NOT EXISTS eloxiv.module_version_history (
1627
+ id bigserial PRIMARY KEY,
1628
+ module text NOT NULL,
1629
+ from_version text,
1630
+ to_version text NOT NULL,
1631
+ kernel_version text NOT NULL,
1632
+ at timestamptz NOT NULL DEFAULT now()
1633
+ )`,
1634
+ `CREATE TABLE IF NOT EXISTS eloxiv.record_history (
1635
+ id bigserial PRIMARY KEY,
1636
+ org_id text NOT NULL,
1637
+ entity text NOT NULL,
1638
+ record_id text NOT NULL,
1639
+ version integer NOT NULL,
1640
+ op text NOT NULL CHECK (op IN ('insert', 'update', 'delete')),
1641
+ snapshot jsonb NOT NULL,
1642
+ actor_user_id text NOT NULL,
1643
+ action text NOT NULL,
1644
+ invocation_id text NOT NULL,
1645
+ at timestamptz NOT NULL DEFAULT now(),
1646
+ UNIQUE (entity, record_id, version)
1647
+ )`,
1648
+ `CREATE INDEX IF NOT EXISTS record_history_org_idx ON eloxiv.record_history (org_id, entity)`,
1649
+ `ALTER TABLE eloxiv.invocation_write ADD COLUMN IF NOT EXISTS row jsonb`,
1650
+ `CREATE OR REPLACE FUNCTION eloxiv.track_write() RETURNS trigger
1651
+ LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog AS $$
1652
+ DECLARE
1653
+ written jsonb;
1654
+ BEGIN
1655
+ IF TG_OP = 'DELETE' THEN written := to_jsonb(OLD); ELSE written := to_jsonb(NEW); END IF;
1656
+ INSERT INTO eloxiv.invocation_write (table_schema, table_name, pk, op, row)
1657
+ VALUES (TG_TABLE_SCHEMA, TG_TABLE_NAME, CASE WHEN TG_ARGV[0] = '' THEN NULL ELSE written ->> TG_ARGV[0] END, TG_OP,
1658
+ CASE WHEN TG_NARGS > 1 AND TG_ARGV[1] = 'history' THEN written ELSE NULL END);
1659
+ RETURN NULL;
1660
+ END
1661
+ $$`,
1662
+ `REVOKE ALL ON FUNCTION eloxiv.track_write() FROM PUBLIC`,
1663
+ // Privacy: which source of which data-subject request is done, recorded in the source's own transaction, so a
1664
+ // source is never done twice whatever happens to the workflow's journal.
1665
+ `CREATE TABLE IF NOT EXISTS eloxiv.privacy_step (
1666
+ request_id text NOT NULL,
1667
+ source text NOT NULL,
1668
+ outcome jsonb NOT NULL,
1669
+ at timestamptz NOT NULL DEFAULT now(),
1670
+ PRIMARY KEY (request_id, source)
1671
+ )`,
1672
+ // Privacy: the pseudonym an erasure names the person by where a record of what they did is kept: random, per
1673
+ // request, held only while the request runs (nothing links it to the person afterwards).
1674
+ `CREATE TABLE IF NOT EXISTS eloxiv.privacy_pseudonym (
1675
+ request_id text PRIMARY KEY,
1676
+ pseudonym text NOT NULL
1677
+ )`,
1678
+ // Progress: the outbox event that started an execution (an event trigger's), so its work can continue the task
1679
+ // the call that emitted the event started.
1680
+ `ALTER TABLE eloxiv.workflow_execution ADD COLUMN IF NOT EXISTS event_id text`,
1681
+ // Existing administrators get the new kernel permission (Privacy requests about other members).
1682
+ `INSERT INTO eloxiv.role_permission (org_id, role_id, permission)
1683
+ SELECT org_id, id, 'eloxiv.privacy.manage' FROM eloxiv.role WHERE id = 'admin' ON CONFLICT DO NOTHING`,
1684
+ ],
1685
+ }
1686
+
1687
+ /**
1688
+ * MAKE (criterion 13): modules made by a person or the agent, drafted, previewed, approved, installed, versioned
1689
+ * and rolled back at runtime, their code run in the sandbox (`make/`).
1690
+ *
1691
+ * - `make_draft`: each draft's source (manifest, policy, capabilities, migrations, code, view) and its hash, the
1692
+ * problems found when it was checked, and its last preview.
1693
+ * - `make_version`: every version installed, with the source it was installed from; `make_installation`: the
1694
+ * version each module runs now (a rollback points it back at the one before). Only the kernel role reads them;
1695
+ * setup (as superuser) reads them to include installed MAKE modules.
1696
+ * - `eloxiv_ctx.transaction_writes()`: the write log of the calling transaction only. A MAKE module's statements
1697
+ * run on a session of its own runtime role, in a transaction the kernel cannot see into until it commits, so the
1698
+ * kernel reads that transaction's writes through it (from within the transaction) to hold the call to its action
1699
+ * contract. It reveals nothing but the caller's own writes.
1700
+ *
1701
+ * Written to be safe to apply again.
1702
+ */
1703
+ const make: Migration = {
1704
+ name: "0031_make",
1705
+ statements: [
1706
+ `CREATE TABLE IF NOT EXISTS eloxiv.make_draft (
1707
+ id text PRIMARY KEY,
1708
+ org_id text NOT NULL REFERENCES eloxiv.organization(id) ON DELETE CASCADE,
1709
+ module text NOT NULL,
1710
+ version text NOT NULL,
1711
+ source jsonb NOT NULL,
1712
+ hash text NOT NULL,
1713
+ created_by text NOT NULL,
1714
+ created_at timestamptz NOT NULL DEFAULT now(),
1715
+ problems jsonb NOT NULL DEFAULT '[]'::jsonb,
1716
+ preview jsonb
1717
+ )`,
1718
+ `CREATE INDEX IF NOT EXISTS make_draft_module_idx ON eloxiv.make_draft (org_id, module)`,
1719
+ `CREATE TABLE IF NOT EXISTS eloxiv.make_version (
1720
+ module text NOT NULL,
1721
+ version text NOT NULL,
1722
+ org_id text NOT NULL REFERENCES eloxiv.organization(id) ON DELETE CASCADE,
1723
+ draft_id text NOT NULL,
1724
+ hash text NOT NULL,
1725
+ source jsonb NOT NULL,
1726
+ installed_by text NOT NULL,
1727
+ installed_at timestamptz NOT NULL DEFAULT now(),
1728
+ PRIMARY KEY (module, version)
1729
+ )`,
1730
+ `CREATE TABLE IF NOT EXISTS eloxiv.make_installation (
1731
+ module text PRIMARY KEY,
1732
+ org_id text NOT NULL REFERENCES eloxiv.organization(id) ON DELETE CASCADE,
1733
+ version text NOT NULL,
1734
+ changed_at timestamptz NOT NULL DEFAULT now(),
1735
+ FOREIGN KEY (module, version) REFERENCES eloxiv.make_version (module, version)
1736
+ )`,
1737
+ `CREATE OR REPLACE FUNCTION eloxiv_ctx.transaction_writes()
1738
+ RETURNS TABLE (table_schema text, table_name text, pk text, op text)
1739
+ LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog
1740
+ AS $$ SELECT w.table_schema, w.table_name, w.pk, w.op FROM eloxiv.invocation_write w
1741
+ WHERE w.xid = pg_current_xact_id() ORDER BY w.id $$`,
1742
+ `REVOKE ALL ON FUNCTION eloxiv_ctx.transaction_writes() FROM PUBLIC`,
1743
+ // Drafts and previews, per person, for their rate limits (recorded whether or not the call then succeeds).
1744
+ `CREATE TABLE IF NOT EXISTS eloxiv.make_activity (
1745
+ org_id text NOT NULL,
1746
+ user_id text NOT NULL,
1747
+ kind text NOT NULL,
1748
+ at timestamptz NOT NULL DEFAULT now()
1749
+ )`,
1750
+ `CREATE INDEX IF NOT EXISTS make_activity_idx ON eloxiv.make_activity (org_id, user_id, kind, at)`,
1751
+ // A call of a MAKE module's action, keyed by its own transaction on the module's session (committed by the
1752
+ // kernel on its own connection before the code runs): the invocation, the module, the hash of the one-time
1753
+ // ticket only the kernel holds, and whether the kernel's records of it were written (`finished`, committed
1754
+ // only with the module's transaction).
1755
+ `CREATE TABLE IF NOT EXISTS eloxiv.make_call (
1756
+ xid xid8 PRIMARY KEY,
1757
+ invocation_id text NOT NULL UNIQUE,
1758
+ module text NOT NULL,
1759
+ ticket text NOT NULL,
1760
+ state text NOT NULL DEFAULT 'open' CHECK (state IN ('open', 'finished')),
1761
+ created_at timestamptz NOT NULL DEFAULT now()
1762
+ )`,
1763
+ // The call of the current transaction, if its ticket is right and the session is its module's runtime role.
1764
+ `CREATE OR REPLACE FUNCTION eloxiv_ctx.make_call_of(p_ticket text)
1765
+ RETURNS TABLE (invocation_id text, module text, actor text, org text, action text)
1766
+ LANGUAGE plpgsql STABLE SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
1767
+ BEGIN
1768
+ RETURN QUERY SELECT c.invocation_id, c.module, x.actor, x.org, x.action
1769
+ FROM eloxiv.make_call c JOIN eloxiv.invocation_context x ON x.xid = c.xid
1770
+ WHERE c.xid = pg_current_xact_id() AND c.state = 'open'
1771
+ AND c.ticket = encode(sha256(convert_to(p_ticket, 'UTF8')), 'hex')
1772
+ AND session_user::text = 'eloxiv_mod_' || c.module
1773
+ AND pg_catalog.starts_with(x.action, c.module || '.');
1774
+ IF NOT FOUND THEN
1775
+ RAISE EXCEPTION 'No MAKE call of this transaction answers to this ticket' USING ERRCODE = 'insufficient_privilege';
1776
+ END IF;
1777
+ END
1778
+ $$`,
1779
+ `REVOKE ALL ON FUNCTION eloxiv_ctx.make_call_of(text) FROM PUBLIC`,
1780
+ // The call's idempotency claim, in the module's transaction (a concurrent claim of the key waits for it).
1781
+ `CREATE OR REPLACE FUNCTION eloxiv_ctx.make_claim(p_ticket text, p_key text, p_request_hash text) RETURNS boolean
1782
+ LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
1783
+ DECLARE c record;
1784
+ BEGIN
1785
+ SELECT * INTO c FROM eloxiv_ctx.make_call_of(p_ticket);
1786
+ INSERT INTO eloxiv.idempotency_key (org_id, actor_user_id, action, key, request_hash, invocation_id)
1787
+ VALUES (c.org, c.actor, c.action, p_key, p_request_hash, c.invocation_id) ON CONFLICT DO NOTHING;
1788
+ RETURN FOUND;
1789
+ END
1790
+ $$`,
1791
+ `REVOKE ALL ON FUNCTION eloxiv_ctx.make_claim(text, text, text) FROM PUBLIC`,
1792
+ // The kernel's records of the call (its receipt, audit record and events), in the module's transaction. The
1793
+ // actor, organisation and action are the kernel's context row's; events are of the module's own types.
1794
+ `CREATE OR REPLACE FUNCTION eloxiv_ctx.make_finish(p_ticket text, p_record jsonb) RETURNS void
1795
+ LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
1796
+ DECLARE c record; e jsonb;
1797
+ BEGIN
1798
+ SELECT * INTO c FROM eloxiv_ctx.make_call_of(p_ticket);
1799
+ IF p_record->>'idempotencyKey' IS NOT NULL THEN
1800
+ UPDATE eloxiv.idempotency_key SET receipt = p_record->'receipt', receipt_format = (p_record->>'receiptFormat')::int
1801
+ WHERE org_id = c.org AND actor_user_id = c.actor AND action = c.action AND key = p_record->>'idempotencyKey'
1802
+ AND invocation_id = c.invocation_id;
1803
+ IF NOT FOUND THEN
1804
+ RAISE EXCEPTION 'The MAKE call holds no claim on its idempotency key' USING ERRCODE = 'insufficient_privilege';
1805
+ END IF;
1806
+ END IF;
1807
+ INSERT INTO eloxiv.audit_log (id, invocation_id, action, surface, actor_user_id, org_id, outcome, input_hash,
1808
+ idempotency_key, error_tag, affected, requested, completion)
1809
+ VALUES (gen_random_uuid()::text, c.invocation_id, c.action, p_record->>'surface', c.actor, c.org, 'succeeded',
1810
+ p_record->>'inputHash', p_record->>'idempotencyKey', NULL, (p_record->'completion'->>'affected')::int,
1811
+ (p_record->'completion'->>'requested')::int, p_record->'completion'->>'completion');
1812
+ FOR e IN SELECT value FROM jsonb_array_elements(coalesce(p_record->'events', '[]'::jsonb)) LOOP
1813
+ IF e->>'type' IS NULL OR NOT pg_catalog.starts_with(e->>'type', c.module || '.') THEN
1814
+ RAISE EXCEPTION 'A MAKE module emits only its own events' USING ERRCODE = 'insufficient_privilege';
1815
+ END IF;
1816
+ INSERT INTO eloxiv.outbox (id, invocation_id, type, module, org_id, payload)
1817
+ VALUES (gen_random_uuid()::text, c.invocation_id, e->>'type', c.module, c.org, e->'payload');
1818
+ PERFORM pg_notify('eloxiv_outbox', c.invocation_id);
1819
+ END LOOP;
1820
+ UPDATE eloxiv.make_call SET state = 'finished' WHERE xid = pg_current_xact_id();
1821
+ END
1822
+ $$`,
1823
+ `REVOKE ALL ON FUNCTION eloxiv_ctx.make_finish(text, jsonb) FROM PUBLIC`,
1824
+ ],
1825
+ }
1826
+
1827
+ /**
1828
+ * Data-subject requests over JSON fields (the Privacy contract): `eloxiv_guard.json_without(value, id, replacement)`
1829
+ * is `value` with every string equal to `id` replaced by `replacement`, at any depth (an array's element, an
1830
+ * object's value), and every object entry keyed by `id` removed; with a NULL `replacement`, such array elements are
1831
+ * removed and such object values become JSON null. A record names the person in a JSON field exactly when the
1832
+ * result differs from the value. Pure and safe, so every role (a module's runtime role) may run it.
1833
+ */
1834
+ const jsonSubjects: Migration = {
1835
+ name: "0032_json_subjects",
1836
+ statements: [
1837
+ `CREATE SCHEMA IF NOT EXISTS eloxiv_guard`,
1838
+ `GRANT USAGE ON SCHEMA eloxiv_guard TO PUBLIC`,
1839
+ `CREATE OR REPLACE FUNCTION eloxiv_guard.json_without(value jsonb, id text, replacement jsonb) RETURNS jsonb
1840
+ LANGUAGE plpgsql IMMUTABLE PARALLEL SAFE SET search_path = pg_catalog AS $$
1841
+ DECLARE
1842
+ result jsonb;
1843
+ BEGIN
1844
+ IF value IS NULL OR id IS NULL THEN
1845
+ RETURN value;
1846
+ END IF;
1847
+ CASE jsonb_typeof(value)
1848
+ WHEN 'string' THEN
1849
+ RETURN CASE WHEN value #>> '{}' = id THEN COALESCE(replacement, 'null'::jsonb) ELSE value END;
1850
+ WHEN 'array' THEN
1851
+ SELECT COALESCE(jsonb_agg(eloxiv_guard.json_without(e.value, id, replacement) ORDER BY e.ordinality), '[]'::jsonb)
1852
+ INTO result
1853
+ FROM jsonb_array_elements(value) WITH ORDINALITY AS e(value, ordinality)
1854
+ WHERE NOT (replacement IS NULL AND jsonb_typeof(e.value) = 'string' AND e.value #>> '{}' = id);
1855
+ RETURN result;
1856
+ WHEN 'object' THEN
1857
+ SELECT COALESCE(jsonb_object_agg(e.key, eloxiv_guard.json_without(e.value, id, replacement)), '{}'::jsonb)
1858
+ INTO result
1859
+ FROM jsonb_each(value) AS e(key, value)
1860
+ WHERE e.key <> id;
1861
+ RETURN result;
1862
+ ELSE
1863
+ RETURN value;
1864
+ END CASE;
1865
+ END
1866
+ $$`,
1867
+ `GRANT EXECUTE ON FUNCTION eloxiv_guard.json_without(jsonb, text, jsonb) TO PUBLIC`,
1868
+ ],
1869
+ }
1870
+
1871
+ /**
1872
+ * A one-time consent used up, as a fact that commits with the call that used it (Authority.consume). A kernel call
1873
+ * records it in its own transaction; a MAKE call's runs on its module's session, so the call records it there through
1874
+ * `eloxiv_ctx.make_consume` (bound to the call's ticket, for the consents the kernel listed on the call's record:
1875
+ * `make_call.consumes`), and it commits or rolls back with the module's writes. A request with a use is used, whatever
1876
+ * its status says.
1877
+ */
1878
+ const consentUse: Migration = {
1879
+ name: "0034_consent_use",
1880
+ statements: [
1881
+ `CREATE TABLE IF NOT EXISTS eloxiv.consent_use (
1882
+ request_id text PRIMARY KEY,
1883
+ org_id text NOT NULL,
1884
+ invocation_id text NOT NULL,
1885
+ used_at timestamptz NOT NULL DEFAULT now()
1886
+ )`,
1887
+ `ALTER TABLE eloxiv.make_call ADD COLUMN IF NOT EXISTS consumes text[] NOT NULL DEFAULT '{}'`,
1888
+ `CREATE OR REPLACE FUNCTION eloxiv_ctx.make_consume(p_ticket text) RETURNS void
1889
+ LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
1890
+ DECLARE c record;
1891
+ BEGIN
1892
+ SELECT * INTO c FROM eloxiv_ctx.make_call_of(p_ticket);
1893
+ INSERT INTO eloxiv.consent_use (request_id, org_id, invocation_id)
1894
+ SELECT u.id, c.org, c.invocation_id
1895
+ FROM eloxiv.make_call m, pg_catalog.unnest(m.consumes) AS u(id)
1896
+ WHERE m.xid = pg_current_xact_id();
1897
+ END
1898
+ $$`,
1899
+ `REVOKE ALL ON FUNCTION eloxiv_ctx.make_consume(text) FROM PUBLIC`,
1900
+ ],
1901
+ }
1902
+
1903
+ /**
1904
+ * MAKE subscribers (the Sandbox contract): a delivery of an outbox event to a MAKE module's subscriber runs on the
1905
+ * module's own session, like a call, and records its success there through `eloxiv_ctx.make_deliver`, bound to the
1906
+ * delivery's ticket and to the event and subscriber the kernel wrote on its record (`make_call.event_id`,
1907
+ * `make_call.subscriber`), so the module's writes and the record that the event was delivered commit together: a
1908
+ * subscriber runs once per event. Only a delivery's own record answers: its context row is the subscriber branch's
1909
+ * (`$subscriber`) in the event's organisation, so `make_call_of` (and with it the call functions) never answers it.
1910
+ * Numbered after build/main's `0044_scheduled_run_starts` when the lines of work were merged.
1911
+ */
1912
+ const makeSubscribers: Migration = {
1913
+ name: "0045_make_subscribers",
1914
+ statements: [
1915
+ `ALTER TABLE eloxiv.make_call ADD COLUMN IF NOT EXISTS event_id text`,
1916
+ `ALTER TABLE eloxiv.make_call ADD COLUMN IF NOT EXISTS subscriber text`,
1917
+ `CREATE OR REPLACE FUNCTION eloxiv_ctx.make_deliver(p_ticket text) RETURNS void
1918
+ LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
1919
+ DECLARE m record;
1920
+ BEGIN
1921
+ SELECT c.event_id, c.subscriber INTO m
1922
+ FROM eloxiv.make_call c
1923
+ JOIN eloxiv.invocation_context x ON x.xid = c.xid
1924
+ JOIN eloxiv.outbox o ON o.id = c.event_id
1925
+ WHERE c.xid = pg_current_xact_id() AND c.state = 'open'
1926
+ AND c.ticket = encode(sha256(convert_to(p_ticket, 'UTF8')), 'hex')
1927
+ AND session_user::text = 'eloxiv_mod_' || c.module
1928
+ AND x.action = '$subscriber' AND x.org = o.org_id
1929
+ AND c.subscriber IS NOT NULL AND pg_catalog.starts_with(c.subscriber, c.module || '.');
1930
+ IF NOT FOUND THEN
1931
+ RAISE EXCEPTION 'No MAKE delivery of this transaction answers to this ticket' USING ERRCODE = 'insufficient_privilege';
1932
+ END IF;
1933
+ -- In MAKE subscribers' own namespace of delivery records (Registry.ts MAKE_DELIVERY_PREFIX).
1934
+ INSERT INTO eloxiv.outbox_delivery (event_id, subscriber) VALUES (m.event_id, 'make:' || m.subscriber);
1935
+ UPDATE eloxiv.make_call SET state = 'finished' WHERE xid = pg_current_xact_id();
1936
+ END
1937
+ $$`,
1938
+ `REVOKE ALL ON FUNCTION eloxiv_ctx.make_deliver(text) FROM PUBLIC`,
1939
+ ],
1940
+ }
1941
+
1942
+ /**
1943
+ * An agent session issued for deferred work (a device turn) carries the authority of the call that queued the
1944
+ * work (`AuthorityRecord`: the scope of its credential and its chain of authorities), which every call made with
1945
+ * the session asserts. Numbered after main's `0032_json_subjects` when the lines of work were integrated.
1946
+ */
1947
+ const agentSessionAuthority: Migration = {
1948
+ name: "0033_agent_session_authority",
1949
+ statements: [`ALTER TABLE eloxiv.agent_session ADD COLUMN IF NOT EXISTS authority jsonb`],
1950
+ }
1951
+
1952
+ /**
1953
+ * Collaborative documents (the CollabDocument contract, `collab/`), owned by module records.
1954
+ *
1955
+ * - `collab_document`: one per record of an entity that declares `collab` (its Cedar type and key), with the
1956
+ * merged snapshot up to `snapshot_seq`, the head (`head_seq`, `head_id`: the last update's number and id) and its
1957
+ * size. Only the kernel role touches it.
1958
+ * - `collab_update`: every update after the snapshot, numbered under the document row's lock, with who made it, how
1959
+ * (`person`, `agent`, `system`) and the invocation it came from (its audit record's id). **Append-only**: a
1960
+ * trigger refuses any change but an erasure's pseudonym of `actor_user_id`, and the deletion of an update the
1961
+ * snapshot does not yet hold (compaction deletes only what it merged; a document's deletion takes all of it).
1962
+ * - `collab_version`: checkpoints (the snapshot at each compaction), the most recent kept.
1963
+ * - `collab_contribution`: who contributed to which document (updates, bytes, first and last time): what privacy
1964
+ * exports promise, kept when compaction deletes the updates themselves.
1965
+ * - `collab_rate`: when each person's updates to a document in the last minute were made (a sliding window).
1966
+ * - `collab_presence` (unlogged: never in the write-ahead log, emptied after a crash): each client's presence, the
1967
+ * person the kernel stamped on it, the client's clock and its expiry; a withdrawal stays as a tombstone for a while.
1968
+ * - `collab_change` (unlogged): which record's document changed, read by kernel processes that an empty notification
1969
+ * on `eloxiv_collab` wakes; no notification carries what changed, since any role may listen.
1970
+ * - `eloxiv.forget_record` (a tracked record deleted) also deletes the record's document and presence, and wakes.
1971
+ *
1972
+ * Safe to apply again.
1973
+ */
1974
+ const collabDocuments: Migration = {
1975
+ name: "0035_collab",
1976
+ statements: [
1977
+ `CREATE TABLE IF NOT EXISTS eloxiv.collab_document (
1978
+ id text PRIMARY KEY,
1979
+ org_id text NOT NULL,
1980
+ entity text NOT NULL,
1981
+ record_id text NOT NULL,
1982
+ snapshot bytea NOT NULL DEFAULT '\\x0000'::bytea,
1983
+ snapshot_seq bigint NOT NULL DEFAULT 0,
1984
+ head_seq bigint NOT NULL DEFAULT 0,
1985
+ head_id text,
1986
+ bytes integer NOT NULL DEFAULT 0,
1987
+ created_at timestamptz NOT NULL DEFAULT now(),
1988
+ updated_at timestamptz NOT NULL DEFAULT now(),
1989
+ compacted_at timestamptz,
1990
+ UNIQUE (entity, record_id),
1991
+ CONSTRAINT collab_document_seq CHECK (snapshot_seq >= 0 AND snapshot_seq <= head_seq)
1992
+ )`,
1993
+ `CREATE INDEX IF NOT EXISTS collab_document_org_idx ON eloxiv.collab_document (org_id)`,
1994
+ `CREATE TABLE IF NOT EXISTS eloxiv.collab_update (
1995
+ document_id text NOT NULL REFERENCES eloxiv.collab_document(id) ON DELETE CASCADE,
1996
+ seq bigint NOT NULL,
1997
+ id text NOT NULL UNIQUE,
1998
+ org_id text NOT NULL,
1999
+ update bytea NOT NULL,
2000
+ bytes integer NOT NULL,
2001
+ actor_user_id text NOT NULL,
2002
+ origin text NOT NULL CHECK (origin IN ('person', 'agent', 'system')),
2003
+ invocation_id text NOT NULL,
2004
+ at timestamptz NOT NULL DEFAULT now(),
2005
+ PRIMARY KEY (document_id, seq)
2006
+ )`,
2007
+ `CREATE INDEX IF NOT EXISTS collab_update_actor_idx ON eloxiv.collab_update (org_id, actor_user_id)`,
2008
+ `CREATE TABLE IF NOT EXISTS eloxiv.collab_version (
2009
+ document_id text NOT NULL REFERENCES eloxiv.collab_document(id) ON DELETE CASCADE,
2010
+ version integer NOT NULL,
2011
+ seq bigint NOT NULL,
2012
+ state bytea NOT NULL,
2013
+ bytes integer NOT NULL,
2014
+ reason text NOT NULL CHECK (reason IN ('compaction')),
2015
+ at timestamptz NOT NULL DEFAULT now(),
2016
+ PRIMARY KEY (document_id, version)
2017
+ )`,
2018
+ `CREATE TABLE IF NOT EXISTS eloxiv.collab_contribution (
2019
+ document_id text NOT NULL REFERENCES eloxiv.collab_document(id) ON DELETE CASCADE,
2020
+ org_id text NOT NULL,
2021
+ entity text NOT NULL,
2022
+ record_id text NOT NULL,
2023
+ user_id text NOT NULL,
2024
+ updates bigint NOT NULL,
2025
+ bytes bigint NOT NULL,
2026
+ first_at timestamptz NOT NULL,
2027
+ last_at timestamptz NOT NULL,
2028
+ PRIMARY KEY (document_id, user_id)
2029
+ )`,
2030
+ `CREATE INDEX IF NOT EXISTS collab_contribution_user_idx ON eloxiv.collab_contribution (org_id, user_id)`,
2031
+ `CREATE TABLE IF NOT EXISTS eloxiv.collab_rate (
2032
+ document_id text NOT NULL REFERENCES eloxiv.collab_document(id) ON DELETE CASCADE,
2033
+ user_id text NOT NULL,
2034
+ recent bigint[] NOT NULL,
2035
+ PRIMARY KEY (document_id, user_id)
2036
+ )`,
2037
+ `CREATE UNLOGGED TABLE IF NOT EXISTS eloxiv.collab_presence (
2038
+ entity text NOT NULL,
2039
+ record_id text NOT NULL,
2040
+ client_id bigint NOT NULL,
2041
+ org_id text NOT NULL,
2042
+ user_id text NOT NULL,
2043
+ state text,
2044
+ clock bigint NOT NULL,
2045
+ expires_at timestamptz NOT NULL,
2046
+ PRIMARY KEY (entity, record_id, client_id)
2047
+ )`,
2048
+ `CREATE UNLOGGED TABLE IF NOT EXISTS eloxiv.collab_change (
2049
+ id bigserial PRIMARY KEY,
2050
+ entity text NOT NULL,
2051
+ record_id text NOT NULL,
2052
+ kind text NOT NULL CHECK (kind IN ('update', 'presence', 'gone')),
2053
+ at timestamptz NOT NULL DEFAULT clock_timestamp()
2054
+ )`,
2055
+ `CREATE OR REPLACE FUNCTION eloxiv.collab_update_append_only() RETURNS trigger
2056
+ LANGUAGE plpgsql SET search_path = pg_catalog AS $$
2057
+ BEGIN
2058
+ IF TG_OP = 'UPDATE' THEN
2059
+ -- Only an erasure's pseudonym of who made it: never the update itself, its place, its origin or its time.
2060
+ IF NEW.document_id IS DISTINCT FROM OLD.document_id OR NEW.seq IS DISTINCT FROM OLD.seq
2061
+ OR NEW.id IS DISTINCT FROM OLD.id OR NEW.org_id IS DISTINCT FROM OLD.org_id
2062
+ OR NEW.update IS DISTINCT FROM OLD.update
2063
+ OR NEW.bytes IS DISTINCT FROM OLD.bytes OR NEW.origin IS DISTINCT FROM OLD.origin
2064
+ OR NEW.invocation_id IS DISTINCT FROM OLD.invocation_id OR NEW.at IS DISTINCT FROM OLD.at THEN
2065
+ RAISE EXCEPTION 'Collaborative updates are append-only' USING ERRCODE = 'insufficient_privilege';
2066
+ END IF;
2067
+ RETURN NEW;
2068
+ END IF;
2069
+ -- A deletion: only of an update the snapshot holds, or with its document (gone by then).
2070
+ IF EXISTS (SELECT 1 FROM eloxiv.collab_document d WHERE d.id = OLD.document_id AND d.snapshot_seq < OLD.seq) THEN
2071
+ RAISE EXCEPTION 'A collaborative update the snapshot does not hold cannot be deleted'
2072
+ USING ERRCODE = 'insufficient_privilege';
2073
+ END IF;
2074
+ RETURN OLD;
2075
+ END
2076
+ $$`,
2077
+ `REVOKE ALL ON FUNCTION eloxiv.collab_update_append_only() FROM PUBLIC`,
2078
+ `CREATE OR REPLACE TRIGGER collab_update_append_only BEFORE UPDATE OR DELETE ON eloxiv.collab_update
2079
+ FOR EACH ROW EXECUTE FUNCTION eloxiv.collab_update_append_only()`,
2080
+ `CREATE OR REPLACE FUNCTION eloxiv.forget_record(p_type text, p_id text) RETURNS void
2081
+ LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog AS $$
2082
+ DECLARE
2083
+ gone boolean;
2084
+ BEGIN
2085
+ -- The record's lock before any row (the order every index writer takes, after the search lock).
2086
+ PERFORM pg_advisory_xact_lock(hashtextextended('eloxiv.record:' || p_type || ':' || p_id, 0));
2087
+ DELETE FROM eloxiv.search_document WHERE record_type = p_type AND record_id = p_id;
2088
+ -- Its files are deleted, each announced (files.deleted) in the same transaction, as an action's are.
2089
+ WITH deleted AS (
2090
+ UPDATE eloxiv.file SET state = 'deleted', state_reason = 'Its record was deleted',
2091
+ deleted_at = coalesce(deleted_at, now()), updated_at = now()
2092
+ WHERE owner_type = p_type AND owner_id = p_id AND state <> 'deleted'
2093
+ RETURNING id, org_id
2094
+ )
2095
+ INSERT INTO eloxiv.outbox (id, invocation_id, type, module, org_id, payload)
2096
+ SELECT gen_random_uuid()::text, d.id, 'files.deleted', 'files', d.org_id,
2097
+ jsonb_build_object('fileId', d.id, 'attachedTo', jsonb_build_object('entity', p_type, 'id', p_id),
2098
+ 'state', 'deleted')
2099
+ FROM deleted d;
2100
+ IF FOUND THEN PERFORM pg_notify('eloxiv_outbox', p_id); END IF;
2101
+ UPDATE eloxiv.ingestion_item SET state = 'superseded', error = 'Its record was deleted', text = NULL,
2102
+ updated_at = now()
2103
+ WHERE record_type = p_type AND record_id = p_id AND state <> 'superseded';
2104
+ DELETE FROM eloxiv.ingestion_chunk c USING eloxiv.ingestion_item i
2105
+ WHERE c.item_id = i.id AND i.record_type = p_type AND i.record_id = p_id;
2106
+ -- Its collaborative document (updates, checkpoints, contributions) and presence; connections on it are woken
2107
+ -- (by a notification that says nothing) and find it gone.
2108
+ DELETE FROM eloxiv.collab_document WHERE entity = p_type AND record_id = p_id;
2109
+ gone := FOUND;
2110
+ DELETE FROM eloxiv.collab_presence WHERE entity = p_type AND record_id = p_id;
2111
+ IF gone OR FOUND THEN
2112
+ INSERT INTO eloxiv.collab_change (entity, record_id, kind) VALUES (p_type, p_id, 'gone');
2113
+ PERFORM pg_notify('eloxiv_collab', '');
2114
+ END IF;
2115
+ END
2116
+ $$`,
2117
+ `REVOKE ALL ON FUNCTION eloxiv.forget_record(text, text) FROM PUBLIC`,
2118
+ ],
2119
+ }
2120
+
2121
+ /**
2122
+ * External effects after commit (`connections/Effects.ts`): a capability operation others see, recorded in the
2123
+ * scheduling action's transaction and delivered at most once by the `eloxiv.connection-effect` workflow. Written to
2124
+ * be safe to apply again.
2125
+ */
2126
+ const connectionEffects: Migration = {
2127
+ name: "0036_connection_effects",
2128
+ statements: [
2129
+ `CREATE TABLE IF NOT EXISTS eloxiv.connection_effect (
2130
+ id text PRIMARY KEY,
2131
+ org_id text NOT NULL,
2132
+ owner_id text NOT NULL,
2133
+ module text NOT NULL,
2134
+ action text NOT NULL,
2135
+ invocation_id text NOT NULL,
2136
+ connection_id text NOT NULL,
2137
+ capability text NOT NULL,
2138
+ operation text NOT NULL,
2139
+ input jsonb,
2140
+ on_done text,
2141
+ state text NOT NULL DEFAULT 'pending'
2142
+ CHECK (state IN ('pending', 'running', 'succeeded', 'failed', 'unknown')),
2143
+ attempts integer NOT NULL DEFAULT 0,
2144
+ result jsonb,
2145
+ error text,
2146
+ created_at timestamptz NOT NULL DEFAULT now(),
2147
+ updated_at timestamptz NOT NULL DEFAULT now(),
2148
+ finished_at timestamptz
2149
+ )`,
2150
+ `CREATE INDEX IF NOT EXISTS connection_effect_owner_idx ON eloxiv.connection_effect (org_id, owner_id)`,
2151
+ `CREATE INDEX IF NOT EXISTS connection_effect_connection_idx ON eloxiv.connection_effect (connection_id)`,
2152
+ // The call's authority, bound to the effect when it was scheduled (Authority's `bindDeferred`): asserted again,
2153
+ // with its Connection, when the delivery claims it, and what its module is told under.
2154
+ `ALTER TABLE eloxiv.connection_effect ADD COLUMN IF NOT EXISTS authority jsonb`,
2155
+ ],
2156
+ }
2157
+
2158
+ /**
2159
+ * What was ingested into a record goes with it, every copy: deleting the record (or superseding an item) clears the
2160
+ * item's original content (`source`, which holds an email's body or a text's characters), its `title` and its
2161
+ * extracted `text`, besides its chunks; and items already superseded by a deletion are cleared now. Written to be
2162
+ * safe to apply again.
2163
+ */
2164
+ const ingestedContentErasure: Migration = {
2165
+ name: "0037_ingested_content_erasure",
2166
+ statements: [
2167
+ `CREATE OR REPLACE FUNCTION eloxiv.forget_record(p_type text, p_id text) RETURNS void
2168
+ LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog AS $$
2169
+ BEGIN
2170
+ -- The record's lock before any row (the order every index writer takes, after the search lock).
2171
+ PERFORM pg_advisory_xact_lock(hashtextextended('eloxiv.record:' || p_type || ':' || p_id, 0));
2172
+ DELETE FROM eloxiv.search_document WHERE record_type = p_type AND record_id = p_id;
2173
+ -- Its files are deleted, each announced (files.deleted) in the same transaction, as an action's are.
2174
+ WITH deleted AS (
2175
+ UPDATE eloxiv.file SET state = 'deleted', state_reason = 'Its record was deleted',
2176
+ deleted_at = coalesce(deleted_at, now()), updated_at = now()
2177
+ WHERE owner_type = p_type AND owner_id = p_id AND state <> 'deleted'
2178
+ RETURNING id, org_id
2179
+ )
2180
+ INSERT INTO eloxiv.outbox (id, invocation_id, type, module, org_id, payload)
2181
+ SELECT gen_random_uuid()::text, d.id, 'files.deleted', 'files', d.org_id,
2182
+ jsonb_build_object('fileId', d.id, 'attachedTo', jsonb_build_object('entity', p_type, 'id', p_id),
2183
+ 'state', 'deleted')
2184
+ FROM deleted d;
2185
+ IF FOUND THEN PERFORM pg_notify('eloxiv_outbox', p_id); END IF;
2186
+ -- Every copy of what was ingested into it: the original content, its title and its extracted text.
2187
+ UPDATE eloxiv.ingestion_item SET state = 'superseded', error = 'Its record was deleted', text = NULL,
2188
+ title = NULL, source = jsonb_build_object('kind', source ->> 'kind'), updated_at = now()
2189
+ WHERE record_type = p_type AND record_id = p_id;
2190
+ DELETE FROM eloxiv.ingestion_chunk c USING eloxiv.ingestion_item i
2191
+ WHERE c.item_id = i.id AND i.record_type = p_type AND i.record_id = p_id;
2192
+ END
2193
+ $$`,
2194
+ `REVOKE ALL ON FUNCTION eloxiv.forget_record(text, text) FROM PUBLIC`,
2195
+ `UPDATE eloxiv.ingestion_item SET text = NULL, title = NULL, source = jsonb_build_object('kind', source ->> 'kind')
2196
+ WHERE state = 'superseded' AND (text IS NOT NULL OR title IS NOT NULL OR source - 'kind' <> '{}'::jsonb)`,
2197
+ ],
2198
+ }
2199
+
2200
+ /**
2201
+ * One way ingested content is removed, whatever removes it (`eloxiv.scrub_ingested`): a record deleted
2202
+ * (`eloxiv.forget_record`), a change to a record's personal data (its `dataSubjects` fields, or what an anonymising
2203
+ * erasure sets: `record_source.personal_columns`, compared by `eloxiv.track_record`), a file deleted, or a newer
2204
+ * version of a source item indexed. Each supersedes the items and clears every copy of their content: the original
2205
+ * (`source`, down to its kind), the `title`, the extracted `text`, the chunks and their search documents. And an
2206
+ * effect that succeeded always holds the provider's resource (`result`), reconciled or not. Written to be safe to
2207
+ * apply again.
2208
+ */
2209
+ const ingestionScrub: Migration = {
2210
+ name: "0038_ingestion_scrub",
2211
+ statements: [
2212
+ `ALTER TABLE eloxiv.record_source ADD COLUMN IF NOT EXISTS personal_columns jsonb NOT NULL DEFAULT '[]'::jsonb`,
2213
+ `CREATE OR REPLACE FUNCTION eloxiv.scrub_ingested(p_type text, p_id text, p_items text[], p_reason text)
2214
+ RETURNS integer
2215
+ LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog AS $$
2216
+ DECLARE
2217
+ v_items text[];
2218
+ BEGIN
2219
+ -- The lock order of every index writer (search/RecordLock.ts): the search lock, shared, then the record's.
2220
+ -- Both are held already by every caller that took them first; taken again, they are not waited for.
2221
+ PERFORM pg_advisory_xact_lock_shared(hashtextextended('eloxiv.search', 0));
2222
+ PERFORM pg_advisory_xact_lock(hashtextextended('eloxiv.record:' || p_type || ':' || p_id, 0));
2223
+ WITH scrubbed AS (
2224
+ UPDATE eloxiv.ingestion_item
2225
+ SET error = CASE WHEN state = 'superseded' THEN error ELSE p_reason END, state = 'superseded',
2226
+ text = NULL, title = NULL, source = jsonb_build_object('kind', source ->> 'kind'), updated_at = now()
2227
+ WHERE record_type = p_type AND record_id = p_id AND (p_items IS NULL OR id = ANY (p_items))
2228
+ RETURNING id
2229
+ )
2230
+ SELECT coalesce(array_agg(id), '{}'::text[]) INTO v_items FROM scrubbed;
2231
+ DELETE FROM eloxiv.search_document
2232
+ WHERE record_type = p_type AND record_id = p_id AND part LIKE 'chunk:%'
2233
+ AND split_part(part, ':', 2) = ANY (v_items);
2234
+ DELETE FROM eloxiv.ingestion_chunk WHERE item_id = ANY (v_items);
2235
+ RETURN cardinality(v_items);
2236
+ END
2237
+ $$`,
2238
+ `REVOKE ALL ON FUNCTION eloxiv.scrub_ingested(text, text, text[], text) FROM PUBLIC`,
2239
+ `CREATE OR REPLACE FUNCTION eloxiv.forget_record(p_type text, p_id text) RETURNS void
2240
+ LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog AS $$
2241
+ DECLARE
2242
+ gone boolean;
2243
+ BEGIN
2244
+ -- The record's lock before any row (the order every index writer takes, after the search lock).
2245
+ PERFORM pg_advisory_xact_lock(hashtextextended('eloxiv.record:' || p_type || ':' || p_id, 0));
2246
+ DELETE FROM eloxiv.search_document WHERE record_type = p_type AND record_id = p_id;
2247
+ -- Its files are deleted, each announced (files.deleted) in the same transaction, as an action's are.
2248
+ WITH deleted AS (
2249
+ UPDATE eloxiv.file SET state = 'deleted', state_reason = 'Its record was deleted',
2250
+ deleted_at = coalesce(deleted_at, now()), updated_at = now()
2251
+ WHERE owner_type = p_type AND owner_id = p_id AND state <> 'deleted'
2252
+ RETURNING id, org_id
2253
+ )
2254
+ INSERT INTO eloxiv.outbox (id, invocation_id, type, module, org_id, payload)
2255
+ SELECT gen_random_uuid()::text, d.id, 'files.deleted', 'files', d.org_id,
2256
+ jsonb_build_object('fileId', d.id, 'attachedTo', jsonb_build_object('entity', p_type, 'id', p_id),
2257
+ 'state', 'deleted')
2258
+ FROM deleted d;
2259
+ IF FOUND THEN PERFORM pg_notify('eloxiv_outbox', p_id); END IF;
2260
+ -- Every copy of what was ingested into it.
2261
+ PERFORM eloxiv.scrub_ingested(p_type, p_id, NULL, 'Its record was deleted');
2262
+ -- Its collaborative document (updates, checkpoints, contributions) and presence (\`0035_collab\`, kept when this
2263
+ -- definition replaced it at integration); connections on it are woken (by a notification that says nothing)
2264
+ -- and find it gone.
2265
+ DELETE FROM eloxiv.collab_document WHERE entity = p_type AND record_id = p_id;
2266
+ gone := FOUND;
2267
+ DELETE FROM eloxiv.collab_presence WHERE entity = p_type AND record_id = p_id;
2268
+ IF gone OR FOUND THEN
2269
+ INSERT INTO eloxiv.collab_change (entity, record_id, kind) VALUES (p_type, p_id, 'gone');
2270
+ PERFORM pg_notify('eloxiv_collab', '');
2271
+ END IF;
2272
+ END
2273
+ $$`,
2274
+ `REVOKE ALL ON FUNCTION eloxiv.forget_record(text, text) FROM PUBLIC`,
2275
+ `CREATE OR REPLACE FUNCTION eloxiv.track_record() RETURNS trigger
2276
+ LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog AS $$
2277
+ DECLARE
2278
+ src eloxiv.record_source;
2279
+ BEGIN
2280
+ -- A rebuild by setup holds this exclusively (one lock, whatever entity types it rebuilds): a write waits
2281
+ -- for it, and it waits for writes in flight. Taken before the declaration is read, so a write that waited
2282
+ -- reads the declaration the rebuild left.
2283
+ PERFORM pg_advisory_xact_lock_shared(hashtextextended('eloxiv.search', 0));
2284
+ SELECT * INTO src FROM eloxiv.record_source s
2285
+ WHERE s.table_schema = TG_TABLE_SCHEMA AND s.table_name = TG_TABLE_NAME;
2286
+ IF NOT FOUND THEN RETURN NULL; END IF;
2287
+ IF TG_OP = 'DELETE' THEN
2288
+ PERFORM eloxiv.forget_record(src.cedar_type, to_jsonb(OLD) ->> src.pk_column);
2289
+ ELSE
2290
+ PERFORM eloxiv.index_record(src, to_jsonb(NEW));
2291
+ -- The record's personal data changed (an anonymising erasure, or a module clearing it): what was ingested
2292
+ -- into it may hold the old values, so every copy goes. A module that still wants it indexed submits it
2293
+ -- again, from the new values.
2294
+ IF TG_OP = 'UPDATE' AND EXISTS (
2295
+ SELECT 1 FROM jsonb_array_elements_text(src.personal_columns) AS c(name)
2296
+ WHERE (to_jsonb(OLD) -> c.name) IS DISTINCT FROM (to_jsonb(NEW) -> c.name)
2297
+ ) THEN
2298
+ PERFORM eloxiv.scrub_ingested(src.cedar_type, to_jsonb(NEW) ->> src.pk_column, NULL,
2299
+ 'Its record''s personal data changed');
2300
+ END IF;
2301
+ END IF;
2302
+ RETURN NULL;
2303
+ END
2304
+ $$`,
2305
+ `REVOKE ALL ON FUNCTION eloxiv.track_record() FROM PUBLIC`,
2306
+ `ALTER TABLE eloxiv.connection_effect ADD COLUMN IF NOT EXISTS reconciled boolean NOT NULL DEFAULT false`,
2307
+ `DO $$ BEGIN
2308
+ ALTER TABLE eloxiv.connection_effect ADD CONSTRAINT connection_effect_result
2309
+ CHECK (state <> 'succeeded' OR result IS NOT NULL) NOT VALID;
2310
+ EXCEPTION WHEN duplicate_object THEN NULL;
2311
+ END $$`,
2312
+ ],
2313
+ }
2314
+
2315
+ /**
2316
+ * What an ingested item was derived from: a module names the record's fields its source comes from
2317
+ * (`ctx.ingestion.basis`, which `submit` requires); the item keeps those columns and a hash of their values
2318
+ * (`eloxiv.derived_hash`), and any write that changes them supersedes and scrubs it (`eloxiv.track_record`), so the
2319
+ * module submits it again from the new values. And effects recorded as succeeded without a result (before the
2320
+ * result became required) are `unknown` now, the check on it validated. Written to be safe to apply again.
2321
+ */
2322
+ const derivedIngestion: Migration = {
2323
+ name: "0039_derived_ingestion",
2324
+ statements: [
2325
+ `ALTER TABLE eloxiv.ingestion_item ADD COLUMN IF NOT EXISTS derived_columns jsonb NOT NULL DEFAULT '[]'::jsonb`,
2326
+ `ALTER TABLE eloxiv.ingestion_item ADD COLUMN IF NOT EXISTS derived_hash text`,
2327
+ // The one scrub clears the hash of what the content was derived from too.
2328
+ `CREATE OR REPLACE FUNCTION eloxiv.scrub_ingested(p_type text, p_id text, p_items text[], p_reason text)
2329
+ RETURNS integer
2330
+ LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog AS $$
2331
+ DECLARE
2332
+ v_items text[];
2333
+ BEGIN
2334
+ -- The lock order of every index writer (search/RecordLock.ts): the search lock, shared, then the record's.
2335
+ -- Both are held already by every caller that took them first; taken again, they are not waited for.
2336
+ PERFORM pg_advisory_xact_lock_shared(hashtextextended('eloxiv.search', 0));
2337
+ PERFORM pg_advisory_xact_lock(hashtextextended('eloxiv.record:' || p_type || ':' || p_id, 0));
2338
+ WITH scrubbed AS (
2339
+ UPDATE eloxiv.ingestion_item
2340
+ SET error = CASE WHEN state = 'superseded' THEN error ELSE p_reason END, state = 'superseded',
2341
+ text = NULL, title = NULL, derived_hash = NULL,
2342
+ source = jsonb_build_object('kind', source ->> 'kind'), updated_at = now()
2343
+ WHERE record_type = p_type AND record_id = p_id AND (p_items IS NULL OR id = ANY (p_items))
2344
+ RETURNING id
2345
+ )
2346
+ SELECT coalesce(array_agg(id), '{}'::text[]) INTO v_items FROM scrubbed;
2347
+ DELETE FROM eloxiv.search_document
2348
+ WHERE record_type = p_type AND record_id = p_id AND part LIKE 'chunk:%'
2349
+ AND split_part(part, ':', 2) = ANY (v_items);
2350
+ DELETE FROM eloxiv.ingestion_chunk WHERE item_id = ANY (v_items);
2351
+ RETURN cardinality(v_items);
2352
+ END
2353
+ $$`,
2354
+ `REVOKE ALL ON FUNCTION eloxiv.scrub_ingested(text, text, text[], text) FROM PUBLIC`,
2355
+ // The values of a record's columns, in the order named, hashed (the same whoever computes it: the submission,
2356
+ // reading the row, and the trigger, comparing a write).
2357
+ `CREATE OR REPLACE FUNCTION eloxiv.derived_hash(rec jsonb, cols jsonb) RETURNS text
2358
+ LANGUAGE sql IMMUTABLE PARALLEL SAFE SET search_path = pg_catalog AS $$
2359
+ SELECT encode(sha256(convert_to(coalesce(
2360
+ (SELECT jsonb_agg(coalesce(rec -> c.name, 'null'::jsonb) ORDER BY c.ord)
2361
+ FROM jsonb_array_elements_text(cols) WITH ORDINALITY AS c(name, ord)),
2362
+ '[]'::jsonb)::text, 'UTF8')), 'hex')
2363
+ $$`,
2364
+ `CREATE OR REPLACE FUNCTION eloxiv.track_record() RETURNS trigger
2365
+ LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog AS $$
2366
+ DECLARE
2367
+ src eloxiv.record_source;
2368
+ v_id text;
2369
+ v_stale text[];
2370
+ BEGIN
2371
+ -- A rebuild by setup holds this exclusively (one lock, whatever entity types it rebuilds): a write waits
2372
+ -- for it, and it waits for writes in flight. Taken before the declaration is read, so a write that waited
2373
+ -- reads the declaration the rebuild left.
2374
+ PERFORM pg_advisory_xact_lock_shared(hashtextextended('eloxiv.search', 0));
2375
+ SELECT * INTO src FROM eloxiv.record_source s
2376
+ WHERE s.table_schema = TG_TABLE_SCHEMA AND s.table_name = TG_TABLE_NAME;
2377
+ IF NOT FOUND THEN RETURN NULL; END IF;
2378
+ IF TG_OP = 'DELETE' THEN
2379
+ PERFORM eloxiv.forget_record(src.cedar_type, to_jsonb(OLD) ->> src.pk_column);
2380
+ RETURN NULL;
2381
+ END IF;
2382
+ PERFORM eloxiv.index_record(src, to_jsonb(NEW));
2383
+ IF TG_OP <> 'UPDATE' THEN RETURN NULL; END IF;
2384
+ v_id := to_jsonb(NEW) ->> src.pk_column;
2385
+ -- The record's personal data changed (an anonymising erasure, or a module clearing it): what was ingested
2386
+ -- into it may hold the old values, so every copy goes.
2387
+ IF EXISTS (
2388
+ SELECT 1 FROM jsonb_array_elements_text(src.personal_columns) AS c(name)
2389
+ WHERE (to_jsonb(OLD) -> c.name) IS DISTINCT FROM (to_jsonb(NEW) -> c.name)
2390
+ ) THEN
2391
+ PERFORM eloxiv.scrub_ingested(src.cedar_type, v_id, NULL, 'Its record''s personal data changed');
2392
+ RETURN NULL;
2393
+ END IF;
2394
+ -- Items derived from fields this write changed: superseded and scrubbed; the module submits them again
2395
+ -- from the new values.
2396
+ SELECT array_agg(i.id) INTO v_stale FROM eloxiv.ingestion_item i
2397
+ WHERE i.record_type = src.cedar_type AND i.record_id = v_id AND i.state <> 'superseded'
2398
+ AND i.derived_hash IS NOT NULL
2399
+ AND i.derived_hash IS DISTINCT FROM eloxiv.derived_hash(to_jsonb(NEW), i.derived_columns);
2400
+ IF v_stale IS NOT NULL THEN
2401
+ PERFORM eloxiv.scrub_ingested(src.cedar_type, v_id, v_stale, 'What it was derived from changed');
2402
+ END IF;
2403
+ RETURN NULL;
2404
+ END
2405
+ $$`,
2406
+ `REVOKE ALL ON FUNCTION eloxiv.track_record() FROM PUBLIC`,
2407
+ `UPDATE eloxiv.connection_effect SET state = 'unknown',
2408
+ error = 'Recorded as succeeded without the provider''s answer: check it before relying on it'
2409
+ WHERE state = 'succeeded' AND result IS NULL`,
2410
+ `ALTER TABLE eloxiv.connection_effect VALIDATE CONSTRAINT connection_effect_result`,
2411
+ ],
2412
+ }
2413
+
2414
+ /**
2415
+ * Invalidation without gaps: the tracking trigger takes the record's lock on every update before it looks for
2416
+ * items derived from what changed (so a submission, which holds that lock from reading the record to storing the
2417
+ * item, either sees the write or is invalidated by it), and an item with no hash (submitted before items recorded
2418
+ * what they were derived from) counts as derived from the record and is invalidated by its next change; a module
2419
+ * submits it again. An item ingested from a file comes from the file, never from the record's fields: its hash
2420
+ * is the one of no fields. Written to be safe to apply again.
2421
+ */
2422
+ const derivedInvalidation: Migration = {
2423
+ name: "0040_derived_invalidation",
2424
+ statements: [
2425
+ `UPDATE eloxiv.ingestion_item SET derived_columns = '[]'::jsonb,
2426
+ derived_hash = eloxiv.derived_hash('{}'::jsonb, '[]'::jsonb)
2427
+ WHERE derived_hash IS NULL AND state <> 'superseded' AND source_kind = 'file'`,
2428
+ `CREATE OR REPLACE FUNCTION eloxiv.track_record() RETURNS trigger
2429
+ LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog AS $$
2430
+ DECLARE
2431
+ src eloxiv.record_source;
2432
+ v_id text;
2433
+ v_stale text[];
2434
+ BEGIN
2435
+ -- A rebuild by setup holds this exclusively (one lock, whatever entity types it rebuilds): a write waits
2436
+ -- for it, and it waits for writes in flight. Taken before the declaration is read, so a write that waited
2437
+ -- reads the declaration the rebuild left.
2438
+ PERFORM pg_advisory_xact_lock_shared(hashtextextended('eloxiv.search', 0));
2439
+ SELECT * INTO src FROM eloxiv.record_source s
2440
+ WHERE s.table_schema = TG_TABLE_SCHEMA AND s.table_name = TG_TABLE_NAME;
2441
+ IF NOT FOUND THEN RETURN NULL; END IF;
2442
+ IF TG_OP = 'DELETE' THEN
2443
+ PERFORM eloxiv.forget_record(src.cedar_type, to_jsonb(OLD) ->> src.pk_column);
2444
+ RETURN NULL;
2445
+ END IF;
2446
+ PERFORM eloxiv.index_record(src, to_jsonb(NEW));
2447
+ IF TG_OP <> 'UPDATE' THEN RETURN NULL; END IF;
2448
+ v_id := to_jsonb(NEW) ->> src.pk_column;
2449
+ -- The record's lock, always, before its items are looked at: a submission holds it from reading the record
2450
+ -- to storing its item, so this write waits for it and then finds its item (or the submission waited for this
2451
+ -- write and read the new values).
2452
+ PERFORM pg_advisory_xact_lock(hashtextextended('eloxiv.record:' || src.cedar_type || ':' || v_id, 0));
2453
+ -- The record's personal data changed (an anonymising erasure, or a module clearing it): what was ingested
2454
+ -- into it may hold the old values, so every copy goes.
2455
+ IF EXISTS (
2456
+ SELECT 1 FROM jsonb_array_elements_text(src.personal_columns) AS c(name)
2457
+ WHERE (to_jsonb(OLD) -> c.name) IS DISTINCT FROM (to_jsonb(NEW) -> c.name)
2458
+ ) THEN
2459
+ PERFORM eloxiv.scrub_ingested(src.cedar_type, v_id, NULL, 'Its record''s personal data changed');
2460
+ RETURN NULL;
2461
+ END IF;
2462
+ -- Items derived from fields this write changed, and items with no hash (from before items recorded what they
2463
+ -- were derived from): superseded and scrubbed; the module submits them again from the new values.
2464
+ SELECT array_agg(i.id) INTO v_stale FROM eloxiv.ingestion_item i
2465
+ WHERE i.record_type = src.cedar_type AND i.record_id = v_id AND i.state <> 'superseded'
2466
+ AND i.derived_hash IS DISTINCT FROM eloxiv.derived_hash(to_jsonb(NEW), i.derived_columns);
2467
+ IF v_stale IS NOT NULL THEN
2468
+ PERFORM eloxiv.scrub_ingested(src.cedar_type, v_id, v_stale, 'What it was derived from changed');
2469
+ END IF;
2470
+ RETURN NULL;
2471
+ END
2472
+ $$`,
2473
+ `REVOKE ALL ON FUNCTION eloxiv.track_record() FROM PUBLIC`,
2474
+ ],
2475
+ }
2476
+
2477
+ /**
2478
+ * Every search document derived from a record goes with what it was derived from (docs/contracts/search.md, "What
2479
+ * is indexed, and how each copy goes"): scrubbing all of a record's ingested items (its deletion, a change to its
2480
+ * personal data) also removes the documents of its attached files' names (`file:<id>`), not only the chunks of its
2481
+ * items. Written to be safe to apply again.
2482
+ */
2483
+ const derivedDocuments: Migration = {
2484
+ name: "0041_derived_documents",
2485
+ statements: [
2486
+ `CREATE OR REPLACE FUNCTION eloxiv.scrub_ingested(p_type text, p_id text, p_items text[], p_reason text)
2487
+ RETURNS integer
2488
+ LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog AS $$
2489
+ DECLARE
2490
+ v_items text[];
2491
+ BEGIN
2492
+ -- The lock order of every index writer (search/RecordLock.ts): the search lock, shared, then the record's.
2493
+ -- Both are held already by every caller that took them first; taken again, they are not waited for.
2494
+ PERFORM pg_advisory_xact_lock_shared(hashtextextended('eloxiv.search', 0));
2495
+ PERFORM pg_advisory_xact_lock(hashtextextended('eloxiv.record:' || p_type || ':' || p_id, 0));
2496
+ WITH scrubbed AS (
2497
+ UPDATE eloxiv.ingestion_item
2498
+ SET error = CASE WHEN state = 'superseded' THEN error ELSE p_reason END, state = 'superseded',
2499
+ text = NULL, title = NULL, derived_hash = NULL,
2500
+ source = jsonb_build_object('kind', source ->> 'kind'), updated_at = now()
2501
+ WHERE record_type = p_type AND record_id = p_id AND (p_items IS NULL OR id = ANY (p_items))
2502
+ RETURNING id
2503
+ )
2504
+ SELECT coalesce(array_agg(id), '{}'::text[]) INTO v_items FROM scrubbed;
2505
+ DELETE FROM eloxiv.search_document
2506
+ WHERE record_type = p_type AND record_id = p_id AND part LIKE 'chunk:%'
2507
+ AND split_part(part, ':', 2) = ANY (v_items);
2508
+ DELETE FROM eloxiv.ingestion_chunk WHERE item_id = ANY (v_items);
2509
+ -- The whole record scrubbed: the documents of its files' names go too (a name can hold personal data).
2510
+ IF p_items IS NULL THEN
2511
+ DELETE FROM eloxiv.search_document
2512
+ WHERE record_type = p_type AND record_id = p_id AND part LIKE 'file:%';
2513
+ END IF;
2514
+ RETURN cardinality(v_items);
2515
+ END
2516
+ $$`,
2517
+ `REVOKE ALL ON FUNCTION eloxiv.scrub_ingested(text, text, text[], text) FROM PUBLIC`,
2518
+ ],
2519
+ }
2520
+
2521
+ /**
2522
+ * One invalidation primitive (docs/contracts/search.md, "Derived copies"): every tracked record has a generation
2523
+ * (`eloxiv.record_generation`), bumped under the record's lock by every write to its row (the tracking trigger, on
2524
+ * insert, update and delete) and by every whole-record scrub (deletion, personal data). A producer of a derived
2525
+ * copy takes the generation before it prepares the copy and makes the copy visible only if it has not moved:
2526
+ * Ingestion's `submit` (its basis), Files' finalisation (a file attached at upload start captures it,
2527
+ * `eloxiv.file.record_generation`). Written to be safe to apply again.
2528
+ */
2529
+ const recordGenerations: Migration = {
2530
+ name: "0042_record_generations",
2531
+ statements: [
2532
+ `CREATE TABLE IF NOT EXISTS eloxiv.record_generation (
2533
+ record_type text NOT NULL,
2534
+ record_id text NOT NULL,
2535
+ generation bigint NOT NULL DEFAULT 0,
2536
+ PRIMARY KEY (record_type, record_id)
2537
+ )`,
2538
+ `ALTER TABLE eloxiv.file ADD COLUMN IF NOT EXISTS record_generation bigint`,
2539
+ // In the caller's transaction, which holds the record's lock.
2540
+ `CREATE OR REPLACE FUNCTION eloxiv.bump_generation(p_type text, p_id text) RETURNS bigint
2541
+ LANGUAGE sql SECURITY DEFINER SET search_path = pg_catalog AS $$
2542
+ INSERT INTO eloxiv.record_generation (record_type, record_id, generation) VALUES (p_type, p_id, 1)
2543
+ ON CONFLICT (record_type, record_id) DO UPDATE SET generation = eloxiv.record_generation.generation + 1
2544
+ RETURNING generation
2545
+ $$`,
2546
+ `REVOKE ALL ON FUNCTION eloxiv.bump_generation(text, text) FROM PUBLIC`,
2547
+ `CREATE OR REPLACE FUNCTION eloxiv.scrub_ingested(p_type text, p_id text, p_items text[], p_reason text)
2548
+ RETURNS integer
2549
+ LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog AS $$
2550
+ DECLARE
2551
+ v_items text[];
2552
+ BEGIN
2553
+ -- The lock order of every index writer (search/RecordLock.ts): the search lock, shared, then the record's.
2554
+ -- Both are held already by every caller that took them first; taken again, they are not waited for.
2555
+ PERFORM pg_advisory_xact_lock_shared(hashtextextended('eloxiv.search', 0));
2556
+ PERFORM pg_advisory_xact_lock(hashtextextended('eloxiv.record:' || p_type || ':' || p_id, 0));
2557
+ WITH scrubbed AS (
2558
+ UPDATE eloxiv.ingestion_item
2559
+ SET error = CASE WHEN state = 'superseded' THEN error ELSE p_reason END, state = 'superseded',
2560
+ text = NULL, title = NULL, derived_hash = NULL,
2561
+ source = jsonb_build_object('kind', source ->> 'kind'), updated_at = now()
2562
+ WHERE record_type = p_type AND record_id = p_id AND (p_items IS NULL OR id = ANY (p_items))
2563
+ RETURNING id
2564
+ )
2565
+ SELECT coalesce(array_agg(id), '{}'::text[]) INTO v_items FROM scrubbed;
2566
+ DELETE FROM eloxiv.search_document
2567
+ WHERE record_type = p_type AND record_id = p_id AND part LIKE 'chunk:%'
2568
+ AND split_part(part, ':', 2) = ANY (v_items);
2569
+ DELETE FROM eloxiv.ingestion_chunk WHERE item_id = ANY (v_items);
2570
+ -- The whole record scrubbed: the documents of its files' names go too (a name can hold personal data),
2571
+ -- and its generation moves, so no copy prepared before the scrub is made visible after it.
2572
+ IF p_items IS NULL THEN
2573
+ DELETE FROM eloxiv.search_document
2574
+ WHERE record_type = p_type AND record_id = p_id AND part LIKE 'file:%';
2575
+ PERFORM eloxiv.bump_generation(p_type, p_id);
2576
+ END IF;
2577
+ RETURN cardinality(v_items);
2578
+ END
2579
+ $$`,
2580
+ `REVOKE ALL ON FUNCTION eloxiv.scrub_ingested(text, text, text[], text) FROM PUBLIC`,
2581
+ `CREATE OR REPLACE FUNCTION eloxiv.track_record() RETURNS trigger
2582
+ LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog AS $$
2583
+ DECLARE
2584
+ src eloxiv.record_source;
2585
+ v_id text;
2586
+ v_stale text[];
2587
+ BEGIN
2588
+ -- A rebuild by setup holds this exclusively (one lock, whatever entity types it rebuilds): a write waits
2589
+ -- for it, and it waits for writes in flight. Taken before the declaration is read, so a write that waited
2590
+ -- reads the declaration the rebuild left.
2591
+ PERFORM pg_advisory_xact_lock_shared(hashtextextended('eloxiv.search', 0));
2592
+ SELECT * INTO src FROM eloxiv.record_source s
2593
+ WHERE s.table_schema = TG_TABLE_SCHEMA AND s.table_name = TG_TABLE_NAME;
2594
+ IF NOT FOUND THEN RETURN NULL; END IF;
2595
+ v_id := CASE WHEN TG_OP = 'DELETE' THEN to_jsonb(OLD) ELSE to_jsonb(NEW) END ->> src.pk_column;
2596
+ -- The record's lock, always, before anything of it is looked at; then its generation moves: whatever was
2597
+ -- prepared from the record before this write is refused if it is offered after it.
2598
+ PERFORM pg_advisory_xact_lock(hashtextextended('eloxiv.record:' || src.cedar_type || ':' || v_id, 0));
2599
+ PERFORM eloxiv.bump_generation(src.cedar_type, v_id);
2600
+ IF TG_OP = 'DELETE' THEN
2601
+ PERFORM eloxiv.forget_record(src.cedar_type, v_id);
2602
+ RETURN NULL;
2603
+ END IF;
2604
+ PERFORM eloxiv.index_record(src, to_jsonb(NEW));
2605
+ IF TG_OP <> 'UPDATE' THEN RETURN NULL; END IF;
2606
+ -- The record's personal data changed (an anonymising erasure, or a module clearing it): what was ingested
2607
+ -- into it may hold the old values, so every copy goes.
2608
+ IF EXISTS (
2609
+ SELECT 1 FROM jsonb_array_elements_text(src.personal_columns) AS c(name)
2610
+ WHERE (to_jsonb(OLD) -> c.name) IS DISTINCT FROM (to_jsonb(NEW) -> c.name)
2611
+ ) THEN
2612
+ PERFORM eloxiv.scrub_ingested(src.cedar_type, v_id, NULL, 'Its record''s personal data changed');
2613
+ RETURN NULL;
2614
+ END IF;
2615
+ -- Items derived from fields this write changed, and items with no hash (from before items recorded what they
2616
+ -- were derived from): superseded and scrubbed; the module submits them again from the new values.
2617
+ SELECT array_agg(i.id) INTO v_stale FROM eloxiv.ingestion_item i
2618
+ WHERE i.record_type = src.cedar_type AND i.record_id = v_id AND i.state <> 'superseded'
2619
+ AND i.derived_hash IS DISTINCT FROM eloxiv.derived_hash(to_jsonb(NEW), i.derived_columns);
2620
+ IF v_stale IS NOT NULL THEN
2621
+ PERFORM eloxiv.scrub_ingested(src.cedar_type, v_id, v_stale, 'What it was derived from changed');
2622
+ END IF;
2623
+ RETURN NULL;
2624
+ END
2625
+ $$`,
2626
+ `REVOKE ALL ON FUNCTION eloxiv.track_record() FROM PUBLIC`,
2627
+ ],
2628
+ }
2629
+
2630
+ /**
2631
+ * Generations for records whose work items copy their text, where Search and Files do not track them: setup puts
2632
+ * `eloxiv.track_generation(<cedar type>, <primary-key column>)` on their tables, which moves the record's generation
2633
+ * under its lock on every write, as the tracking trigger does for tracked records. Written to be safe to apply
2634
+ * again.
2635
+ */
2636
+ const workItemGenerations: Migration = {
2637
+ name: "0043_work_item_generations",
2638
+ statements: [
2639
+ `CREATE OR REPLACE FUNCTION eloxiv.track_generation() RETURNS trigger
2640
+ LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog AS $$
2641
+ DECLARE
2642
+ v_id text := CASE WHEN TG_OP = 'DELETE' THEN to_jsonb(OLD) ELSE to_jsonb(NEW) END ->> TG_ARGV[1];
2643
+ BEGIN
2644
+ -- The lock order of every index writer (search/RecordLock.ts): the search lock, shared, then the record's.
2645
+ PERFORM pg_advisory_xact_lock_shared(hashtextextended('eloxiv.search', 0));
2646
+ PERFORM pg_advisory_xact_lock(hashtextextended('eloxiv.record:' || TG_ARGV[0] || ':' || v_id, 0));
2647
+ PERFORM eloxiv.bump_generation(TG_ARGV[0], v_id);
2648
+ RETURN NULL;
2649
+ END
2650
+ $$`,
2651
+ `REVOKE ALL ON FUNCTION eloxiv.track_generation() FROM PUBLIC`,
2652
+ ],
2653
+ }
2654
+
2655
+ /**
2656
+ * A sweep records its runs, and moves its cursor, before it starts them: `pending` holds a recorded run's start
2657
+ * request until the engine has it (NULL once started), so a kernel that dies between the record and the start
2658
+ * has the next sweep start it. Before, a run handed to the engine before its record could run without one, and
2659
+ * a catch-up policy that passes over missed times (`once`, `skip`) then never recorded it. `refused`: why the
2660
+ * engine refused a recorded run's start (the app no longer has its workflow, or its input no longer decodes), for a
2661
+ * run that never reached the engine; the record stays either way.
2662
+ */
2663
+ const scheduledRunStarts: Migration = {
2664
+ name: "0044_scheduled_run_starts",
2665
+ statements: [
2666
+ `ALTER TABLE eloxiv.schedule_run ADD COLUMN IF NOT EXISTS pending jsonb`,
2667
+ `ALTER TABLE eloxiv.schedule_run ADD COLUMN IF NOT EXISTS refused text`,
2668
+ `CREATE INDEX IF NOT EXISTS schedule_run_pending ON eloxiv.schedule_run (scheduled_at) WHERE pending IS NOT NULL`,
2669
+ ],
2670
+ }
2671
+
2672
+ /**
2673
+ * An external effect the provider rate-limited goes back to `pending` until `not_before` (connections/Effects.ts):
2674
+ * the claim refuses to run it earlier, so the wait holds when the process dies before the workflow recorded it.
2675
+ * (0045 is build/make-complete's.)
2676
+ */
2677
+ const effectNotBefore: Migration = {
2678
+ name: "0046_effect_not_before",
2679
+ statements: [`ALTER TABLE eloxiv.connection_effect ADD COLUMN IF NOT EXISTS not_before timestamptz`],
2680
+ }
2681
+
2682
+ /**
2683
+ * A person's session ended by the kernel without its row (Identity's sign-out): when work holds the row longer than
2684
+ * sign-out waits for it, the session is revoked here instead, and every check of a session (authentication, the
2685
+ * session link's assertion, a hold, the check at commit) refuses it. The row is deleted once its holders let go.
2686
+ * Written to be safe to apply again.
2687
+ */
2688
+ const sessionRevocation: Migration = {
2689
+ name: "0047_session_revocation",
2690
+ statements: [
2691
+ `CREATE TABLE IF NOT EXISTS eloxiv.session_revocation (
2692
+ session_id text PRIMARY KEY,
2693
+ revoked_at timestamptz NOT NULL DEFAULT now()
2694
+ )`,
2695
+ ],
2696
+ }
2697
+
2698
+ /**
2699
+ * A synced session (Sync's query endpoint): every query a person's replica runs also tests a live fact naming the
2700
+ * session it was transformed for (`kind = 'session'`, `value` the session id), which the endpoint records while the
2701
+ * session holds and the kernel deletes when it ends the session. zero-cache evaluates the facts live, so the moment a
2702
+ * sign-out's deletion replicates, that replica receives nothing more and its rows are withdrawn, without waiting for
2703
+ * zero-cache's revalidation; the person's other sessions keep their own facts. The directory's refresh of a person's
2704
+ * facts leaves session facts alone. Written to be safe to apply again.
2705
+ */
2706
+ const syncSessionFacts: Migration = {
2707
+ name: "0048_sync_session_facts",
2708
+ statements: [
2709
+ `ALTER TABLE eloxiv.sync_fact DROP CONSTRAINT IF EXISTS sync_fact_kind_check`,
2710
+ `ALTER TABLE eloxiv.sync_fact ADD CONSTRAINT sync_fact_kind_check
2711
+ CHECK (kind IN ('member', 'group', 'role', 'permission', 'email', 'session'))`,
2712
+ `CREATE OR REPLACE FUNCTION eloxiv.refresh_sync_facts(p_org text, p_user text) RETURNS void
2713
+ LANGUAGE sql SET search_path = pg_catalog AS $$
2714
+ WITH wanted (kind, value) AS (
2715
+ SELECT 'member', '' FROM eloxiv.membership WHERE org_id = p_org AND user_id = p_user
2716
+ UNION SELECT 'group', group_id FROM eloxiv.group_member WHERE org_id = p_org AND user_id = p_user
2717
+ UNION SELECT 'role', role_id FROM eloxiv.membership_role WHERE org_id = p_org AND user_id = p_user
2718
+ UNION SELECT 'permission', p.permission FROM eloxiv.membership_role r
2719
+ JOIN eloxiv.role_permission p ON p.org_id = r.org_id AND p.role_id = r.role_id
2720
+ WHERE r.org_id = p_org AND r.user_id = p_user
2721
+ UNION SELECT 'email', coalesce((SELECT u.email FROM auth."user" u WHERE u.id = m.user_id), '')
2722
+ FROM eloxiv.membership m WHERE m.org_id = p_org AND m.user_id = p_user
2723
+ ), removed AS (
2724
+ DELETE FROM eloxiv.sync_fact f WHERE f.org_id = p_org AND f.user_id = p_user AND f.kind <> 'session'
2725
+ AND NOT EXISTS (SELECT 1 FROM wanted w WHERE w.kind = f.kind AND w.value = f.value)
2726
+ )
2727
+ INSERT INTO eloxiv.sync_fact (org_id, user_id, kind, value)
2728
+ SELECT p_org, p_user, kind, value FROM wanted ON CONFLICT DO NOTHING
2729
+ $$`,
2730
+ `REVOKE ALL ON FUNCTION eloxiv.refresh_sync_facts(text, text) FROM PUBLIC`,
2731
+ ],
2732
+ }
2733
+
2734
+ /**
2735
+ * What the sessions' housekeeping (Identity's `sweepSessions`) and the ending of a session read, indexed: the session
2736
+ * facts by session (an ending deletes its session's facts; the sweep reads only session facts, never the directory's),
2737
+ * and the rate-limit windows by start (the sweep deletes the windows a day old). Written to be safe to apply again.
2738
+ */
2739
+ const sessionSweepIndexes: Migration = {
2740
+ name: "0049_session_sweep_indexes",
2741
+ statements: [
2742
+ `CREATE INDEX IF NOT EXISTS sync_fact_session_idx ON eloxiv.sync_fact (value) WHERE kind = 'session'`,
2743
+ `CREATE INDEX IF NOT EXISTS rate_limit_window_idx ON eloxiv.rate_limit (window_start)`,
2744
+ ],
2745
+ }
2746
+
2747
+ /**
2748
+ * Every ending of a session waits for the requests of Better Auth's that hold it (Identity's `holdDuring`: a shared
2749
+ * advisory lock on the session's request key while Better Auth's handler runs), within one bound, then ends it
2750
+ * anyway: `eloxiv.await_session_requests` takes each session's request key exclusively, trying until the bound and
2751
+ * then giving up (never failing), so the kernel's set-based ending (AuthSeam.ts), in Better Auth's statements and the
2752
+ * kernel's own alike, waits for them as sign-out does. A revocation records the request of Better Auth's whose own
2753
+ * statement recorded it (`by_request`), so that request, once its handler returns, can tell an ending of its own (a
2754
+ * password change ending every session, its own included) from a sign-out's past the bound. Written to be safe to
2755
+ * apply again.
2756
+ */
2757
+ const sessionRequestWaits: Migration = {
2758
+ name: "0050_session_request_waits",
2759
+ statements: [
2760
+ `ALTER TABLE eloxiv.session_revocation ADD COLUMN IF NOT EXISTS by_request text`,
2761
+ `CREATE OR REPLACE FUNCTION eloxiv.await_session_requests(p_ids text[], p_wait_ms integer) RETURNS boolean
2762
+ LANGUAGE plpgsql SET search_path = pg_catalog AS $$
2763
+ DECLARE
2764
+ deadline timestamptz := clock_timestamp() + make_interval(secs => greatest(p_wait_ms, 0) / 1000.0);
2765
+ session_id text;
2766
+ every boolean := true;
2767
+ BEGIN
2768
+ FOREACH session_id IN ARRAY coalesce(p_ids, ARRAY[]::text[]) LOOP
2769
+ LOOP
2770
+ EXIT WHEN pg_try_advisory_xact_lock(hashtextextended('eloxiv.session-request:' || session_id, 0));
2771
+ IF clock_timestamp() >= deadline THEN
2772
+ every := false;
2773
+ EXIT;
2774
+ END IF;
2775
+ PERFORM pg_sleep(0.01);
2776
+ END LOOP;
2777
+ END LOOP;
2778
+ RETURN every;
2779
+ END $$`,
2780
+ ],
2781
+ }
2782
+
2783
+ /**
2784
+ * Endpoint and shared Connections (docs/contracts/connections.md): a Connection may name its own endpoint (a remote
2785
+ * MCP server, an HTTP API), authenticate with a secret it references or an OAuth client discovered for the endpoint,
2786
+ * and belong to the organisation (`shared`), used through grants to members, groups and modules. A personal
2787
+ * Connection stays unique per owner and account; a shared one per account. Secrets record who manages them, the
2788
+ * origins they may be sent to and a short hint. (0047 to 0059 are other lines of work's.) Safe to apply again.
2789
+ */
2790
+ const endpointConnections: Migration = {
2791
+ name: "0060_endpoint_connections",
2792
+ statements: [
2793
+ `ALTER TABLE eloxiv.connection ADD COLUMN IF NOT EXISTS shared boolean NOT NULL DEFAULT false`,
2794
+ `ALTER TABLE eloxiv.connection ADD COLUMN IF NOT EXISTS endpoint text`,
2795
+ `ALTER TABLE eloxiv.connection ADD COLUMN IF NOT EXISTS auth jsonb`,
2796
+ `ALTER TABLE eloxiv.connection ADD COLUMN IF NOT EXISTS oauth_client jsonb`,
2797
+ `ALTER TABLE eloxiv.connection ADD COLUMN IF NOT EXISTS options jsonb`,
2798
+ `ALTER TABLE eloxiv.connection ADD COLUMN IF NOT EXISTS tools text[]`,
2799
+ `ALTER TABLE eloxiv.connection DROP CONSTRAINT IF EXISTS connection_org_id_owner_id_provider_account_id_key`,
2800
+ `CREATE UNIQUE INDEX IF NOT EXISTS connection_personal_account_idx
2801
+ ON eloxiv.connection (org_id, owner_id, provider, account_id) WHERE NOT shared`,
2802
+ `CREATE UNIQUE INDEX IF NOT EXISTS connection_shared_account_idx
2803
+ ON eloxiv.connection (org_id, provider, account_id) WHERE shared`,
2804
+ `ALTER TABLE eloxiv.connection_flow ADD COLUMN IF NOT EXISTS shared boolean NOT NULL DEFAULT false`,
2805
+ `CREATE TABLE IF NOT EXISTS eloxiv.connection_grant (
2806
+ connection_id text NOT NULL REFERENCES eloxiv.connection(id) ON DELETE CASCADE,
2807
+ org_id text NOT NULL REFERENCES eloxiv.organization(id) ON DELETE CASCADE,
2808
+ grantee_kind text NOT NULL CHECK (grantee_kind IN ('org', 'user', 'group', 'module')),
2809
+ grantee_id text NOT NULL,
2810
+ granted_by text NOT NULL,
2811
+ created_at timestamptz NOT NULL DEFAULT now(),
2812
+ PRIMARY KEY (connection_id, grantee_kind, grantee_id)
2813
+ )`,
2814
+ `ALTER TABLE eloxiv.secret ADD COLUMN IF NOT EXISTS managed_by text`,
2815
+ `ALTER TABLE eloxiv.secret ADD COLUMN IF NOT EXISTS allowed_origins text[]`,
2816
+ `ALTER TABLE eloxiv.secret ADD COLUMN IF NOT EXISTS hint text`,
2817
+ ],
2818
+ }
2819
+
2820
+ /**
2821
+ * Audit lineage and export (the Audit contract 1.3.0): each record keeps the call's lineage (origin, credential kind,
2822
+ * authority links, agent run, executed approval, consent, client version) and a successful call's change summary
2823
+ * (per entity: counts and ids, never values); an organisation's records are read in time order by `audit.records`
2824
+ * and `audit.export`, so they are indexed by organisation and time. Existing administrators get the new
2825
+ * `eloxiv.audit.read`. (0051 to 0109 are other branches'.) Safe to apply again.
2826
+ */
2827
+ const auditLineage: Migration = {
2828
+ name: "0110_audit_lineage",
2829
+ statements: [
2830
+ `ALTER TABLE eloxiv.audit_log ADD COLUMN IF NOT EXISTS lineage jsonb`,
2831
+ `ALTER TABLE eloxiv.audit_log ADD COLUMN IF NOT EXISTS changes jsonb`,
2832
+ `CREATE INDEX IF NOT EXISTS audit_log_org_at ON eloxiv.audit_log (org_id, at, id) WHERE org_id IS NOT NULL`,
2833
+ `INSERT INTO eloxiv.role_permission (org_id, role_id, permission)
2834
+ SELECT org_id, id, 'eloxiv.audit.read' FROM eloxiv.role WHERE id = 'admin' ON CONFLICT DO NOTHING`,
2835
+ ],
2836
+ }
2837
+
2838
+ /**
2839
+ * Embeddings of the search index (the Search contract 1.1.0, hybrid search): one vector per index document, of its
2840
+ * text as it was embedded (`text_hash`, the document's own generated hash of its title and body), by the deployment's
2841
+ * embedding model. A vector follows its document: deleted with it (the foreign key), and deleted in the same
2842
+ * transaction as any change to its text (the trigger), so no vector of text a record no longer holds survives the
2843
+ * change; the kernel embeds the documents without a current one in the background. Safe to apply again.
2844
+ */
2845
+ const searchEmbeddings: Migration = {
2846
+ name: "0111_search_embeddings",
2847
+ statements: [
2848
+ `ALTER TABLE eloxiv.search_document ADD COLUMN IF NOT EXISTS text_hash text
2849
+ GENERATED ALWAYS AS (md5(coalesce(title, '') || E'\n' || body)) STORED`,
2850
+ `CREATE TABLE IF NOT EXISTS eloxiv.search_embedding (
2851
+ record_type text NOT NULL,
2852
+ record_id text NOT NULL,
2853
+ part text NOT NULL,
2854
+ org_id text NOT NULL,
2855
+ model text NOT NULL,
2856
+ text_hash text NOT NULL,
2857
+ embedding real[] NOT NULL,
2858
+ embedded_at timestamptz NOT NULL DEFAULT now(),
2859
+ PRIMARY KEY (record_type, record_id, part),
2860
+ FOREIGN KEY (record_type, record_id, part) REFERENCES eloxiv.search_document ON DELETE CASCADE
2861
+ )`,
2862
+ `CREATE INDEX IF NOT EXISTS search_embedding_org_idx ON eloxiv.search_embedding (org_id, model, record_type)`,
2863
+ `CREATE OR REPLACE FUNCTION eloxiv.search_embedding_forget() RETURNS trigger
2864
+ LANGUAGE plpgsql SET search_path = pg_catalog AS $$
2865
+ BEGIN
2866
+ DELETE FROM eloxiv.search_embedding
2867
+ WHERE record_type = NEW.record_type AND record_id = NEW.record_id AND part = NEW.part;
2868
+ RETURN NULL;
2869
+ END $$`,
2870
+ `REVOKE ALL ON FUNCTION eloxiv.search_embedding_forget() FROM PUBLIC`,
2871
+ `DROP TRIGGER IF EXISTS search_embedding_forget ON eloxiv.search_document`,
2872
+ `CREATE TRIGGER search_embedding_forget AFTER UPDATE OF title, body ON eloxiv.search_document
2873
+ FOR EACH ROW WHEN (OLD.text_hash IS DISTINCT FROM NEW.text_hash)
2874
+ EXECUTE FUNCTION eloxiv.search_embedding_forget()`,
2875
+ ],
2876
+ }
2877
+
2878
+ /**
2879
+ * Visitors' consent and attribution before they sign in (the Privacy contract 1.1.0, `privacy/Visits.ts`): one row per
2880
+ * visit, keyed by the SHA-256 of its cookie, with the visitor's choices and region, the first and last touch (kept only
2881
+ * with marketing consent), and who claimed it once signed in and in which organisations. Safe to apply again.
2882
+ */
2883
+ const privacyVisits: Migration = {
2884
+ name: "0112_privacy_visits",
2885
+ statements: [
2886
+ `CREATE TABLE IF NOT EXISTS eloxiv.privacy_visit (
2887
+ id_hash text PRIMARY KEY,
2888
+ choices jsonb NOT NULL DEFAULT '{}'::jsonb,
2889
+ region text,
2890
+ first_touch jsonb,
2891
+ last_touch jsonb,
2892
+ claimed_by text,
2893
+ claimed_orgs text[] NOT NULL DEFAULT ARRAY[]::text[],
2894
+ claimed_at timestamptz,
2895
+ created_at timestamptz NOT NULL DEFAULT now(),
2896
+ seen_at timestamptz NOT NULL DEFAULT now()
2897
+ )`,
2898
+ `CREATE INDEX IF NOT EXISTS privacy_visit_seen ON eloxiv.privacy_visit (seen_at)`,
2899
+ `CREATE INDEX IF NOT EXISTS privacy_visit_claimed ON eloxiv.privacy_visit (claimed_by) WHERE claimed_by IS NOT NULL`,
2900
+ ],
2901
+ }
2902
+
2903
+ /**
2904
+ * Run outcomes (Scheduler: run history, failure streaks, no-op outcomes). An execution records how it ended
2905
+ * (`state`: `succeeded`, `noop`, `failed`, `cancelled`; NULL while it runs), the no-op it declared (`outcome`), its
2906
+ * failure's tag (never its message) and when it finished. A recorded run says who asked for it when it was started
2907
+ * by hand (`requested_by`), and when the scheduler settled it (`settled_at`: its failure counted and alerted, once);
2908
+ * runs recorded before this migration count as settled. `scheduler_sweep` is the sweeping kernel's heartbeat, for
2909
+ * the scheduler's health.
2910
+ */
2911
+ const runOutcomes: Migration = {
2912
+ name: "0070_run_outcomes",
2913
+ statements: [
2914
+ `ALTER TABLE eloxiv.workflow_execution ADD COLUMN IF NOT EXISTS state text`,
2915
+ `ALTER TABLE eloxiv.workflow_execution ADD COLUMN IF NOT EXISTS outcome jsonb`,
2916
+ `ALTER TABLE eloxiv.workflow_execution ADD COLUMN IF NOT EXISTS error_tag text`,
2917
+ `ALTER TABLE eloxiv.workflow_execution ADD COLUMN IF NOT EXISTS finished_at timestamptz`,
2918
+ `ALTER TABLE eloxiv.schedule_run ADD COLUMN IF NOT EXISTS requested_by text`,
2919
+ // Existing runs take the default (settled now): they are never alerted on, nor counted as new failures.
2920
+ `ALTER TABLE eloxiv.schedule_run ADD COLUMN IF NOT EXISTS settled_at timestamptz DEFAULT now()`,
2921
+ `ALTER TABLE eloxiv.schedule_run ALTER COLUMN settled_at DROP DEFAULT`,
2922
+ `CREATE INDEX IF NOT EXISTS schedule_run_unsettled ON eloxiv.schedule_run (scheduled_at) WHERE settled_at IS NULL`,
2923
+ `CREATE TABLE IF NOT EXISTS eloxiv.scheduler_sweep (
2924
+ id int PRIMARY KEY CHECK (id = 1),
2925
+ swept_at timestamptz NOT NULL
2926
+ )`,
2927
+ ],
2928
+ }
2929
+
2930
+ /**
2931
+ * A recorded run's organisation (the schedule's): what a person's erasure there is scoped to (`requested_by` is
2932
+ * pseudonymised in that organisation's runs only). Runs recorded before take it from their execution; a run that
2933
+ * never reached the engine before this has none, and names no requester.
2934
+ */
2935
+ const runOrganisations: Migration = {
2936
+ name: "0072_run_organisations",
2937
+ statements: [
2938
+ `ALTER TABLE eloxiv.schedule_run ADD COLUMN IF NOT EXISTS org_id text`,
2939
+ `UPDATE eloxiv.schedule_run r SET org_id = e.org_id FROM eloxiv.workflow_execution e
2940
+ WHERE r.org_id IS NULL AND e.id = r.execution_id`,
2941
+ `CREATE INDEX IF NOT EXISTS schedule_run_requester ON eloxiv.schedule_run (org_id, requested_by)
2942
+ WHERE requested_by IS NOT NULL`,
2943
+ ],
2944
+ }
2945
+
2946
+ /** Retention: the kernel prunes settled outbox events and (when configured) audit records by age. */
2947
+ const retention: Migration = {
2948
+ name: "0071_retention",
2949
+ statements: [
2950
+ `CREATE INDEX IF NOT EXISTS outbox_settled_idx ON eloxiv.outbox (settled_at) WHERE settled_at IS NOT NULL`,
2951
+ `CREATE INDEX IF NOT EXISTS audit_log_at_idx ON eloxiv.audit_log (at)`,
2952
+ ],
2953
+ }
2954
+
2955
+ /**
2956
+ * Snapshots a person asks for (`collab.snapshot`): a checkpoint's reason may be `snapshot`, and it may carry a label.
2957
+ * Kept apart from compaction's checkpoints (the latest 20 of each). Safe to apply again.
2958
+ */
2959
+ const collabSnapshots: Migration = {
2960
+ name: "0075_collab_snapshots",
2961
+ statements: [
2962
+ `ALTER TABLE eloxiv.collab_version ADD COLUMN IF NOT EXISTS label text`,
2963
+ `ALTER TABLE eloxiv.collab_version DROP CONSTRAINT IF EXISTS collab_version_reason_check`,
2964
+ `ALTER TABLE eloxiv.collab_version ADD CONSTRAINT collab_version_reason_check
2965
+ CHECK (reason IN ('compaction', 'snapshot'))`,
2966
+ ],
2967
+ }
2968
+
2969
+ /**
2970
+ * A paired device's push subscription (DeviceControl's `registerPush`): the host beside the daemon registers where
2971
+ * pushes for the device's person reach it (Web Push, APNs or FCM), one per device. Revoking the device deletes it.
2972
+ * Written to be safe to apply again.
2973
+ */
2974
+ const devicePush: Migration = {
2975
+ name: "0105_device_push",
2976
+ statements: [
2977
+ `CREATE TABLE IF NOT EXISTS eloxiv.device_push (
2978
+ device_id text PRIMARY KEY REFERENCES eloxiv.device(id),
2979
+ org_id text NOT NULL,
2980
+ subject text NOT NULL,
2981
+ subscription jsonb NOT NULL,
2982
+ updated_at timestamptz NOT NULL DEFAULT now()
2983
+ )`,
2984
+ `CREATE INDEX IF NOT EXISTS device_push_subject_idx ON eloxiv.device_push (org_id, subject)`,
2985
+ ],
2986
+ }
2987
+
2988
+ /**
2989
+ * Replies an Ingress handler posted in its delivery's own conversation (ingress/Ingress.ts, `ctx.ingress.reply`): one
2990
+ * row per delivery and step, claimed (`running`) before the platform is asked, so a step re-run after a crash is
2991
+ * `unknown` and never posted again; which Connection posted it (its owner's) and for which sender. No text is kept.
2992
+ * Deleted with its delivery when the retention ends. (0051 to 0114, except 0075, are other branches'.) Written to be safe to apply
2993
+ * again.
2994
+ */
2995
+ const ingressReply: Migration = {
2996
+ name: "0115_ingress_reply",
2997
+ statements: [
2998
+ `CREATE TABLE IF NOT EXISTS eloxiv.ingress_reply (
2999
+ source text NOT NULL,
3000
+ delivery_id text NOT NULL,
3001
+ step text NOT NULL,
3002
+ org_id text NOT NULL,
3003
+ actor_id text NOT NULL,
3004
+ connection_id text NOT NULL,
3005
+ connection_owner text NOT NULL,
3006
+ channel_id text NOT NULL,
3007
+ thread_id text,
3008
+ state text NOT NULL CHECK (state IN ('running', 'sent', 'failed', 'unknown')),
3009
+ message_id text,
3010
+ error text,
3011
+ created_at timestamptz NOT NULL DEFAULT now(),
3012
+ finished_at timestamptz,
3013
+ PRIMARY KEY (source, delivery_id, step)
3014
+ )`,
3015
+ ],
3016
+ }
3017
+
3018
+ /**
3019
+ * Which module's subscriber a delivery's invocation context is for (its Cedar namespace), recorded by the kernel's
3020
+ * dispatcher: the live-copy read (`eloxiv_platform.collab_state`) answers only for that module's documents. Null for
3021
+ * every other context. Safe to apply again.
3022
+ */
3023
+ const subscriberContext: Migration = {
3024
+ name: "0076_subscriber_context",
3025
+ statements: [`ALTER TABLE eloxiv.invocation_context ADD COLUMN IF NOT EXISTS subscriber text`],
3026
+ }
3027
+
3028
+ /**
3029
+ * Directory administration (the Directory contract 1.2.0): an organisation's invitations (a hashed token, the invited
3030
+ * address lower-cased, the roles it grants; one pending invitation per address), its domains (claimed with a DNS TXT
3031
+ * challenge; a domain verified by one organisation only, and joinable by people whose verified address is at it when
3032
+ * the organisation says so), and a group's metadata (a small JSON object an app keeps beside it). Written to be safe
3033
+ * to apply again.
3034
+ */
3035
+ const directoryAdministration: Migration = {
3036
+ name: "0085_directory_administration",
3037
+ statements: [
3038
+ `CREATE TABLE IF NOT EXISTS eloxiv.invitation (
3039
+ id text PRIMARY KEY,
3040
+ org_id text NOT NULL REFERENCES eloxiv.organization(id),
3041
+ email text NOT NULL CHECK (email = lower(email)),
3042
+ roles text[] NOT NULL,
3043
+ token_hash text NOT NULL UNIQUE,
3044
+ invited_by text,
3045
+ created_at timestamptz NOT NULL DEFAULT now(),
3046
+ expires_at timestamptz NOT NULL,
3047
+ accepted_at timestamptz,
3048
+ accepted_by text,
3049
+ revoked_at timestamptz
3050
+ )`,
3051
+ `CREATE UNIQUE INDEX IF NOT EXISTS invitation_pending_idx ON eloxiv.invitation (org_id, email)
3052
+ WHERE accepted_at IS NULL AND revoked_at IS NULL`,
3053
+ `CREATE TABLE IF NOT EXISTS eloxiv.org_domain (
3054
+ org_id text NOT NULL REFERENCES eloxiv.organization(id),
3055
+ domain text NOT NULL CHECK (domain = lower(domain)),
3056
+ token text NOT NULL,
3057
+ verified_at timestamptz,
3058
+ auto_join boolean NOT NULL DEFAULT false,
3059
+ join_roles text[] NOT NULL DEFAULT ARRAY['member']::text[],
3060
+ created_at timestamptz NOT NULL DEFAULT now(),
3061
+ PRIMARY KEY (org_id, domain)
3062
+ )`,
3063
+ `CREATE UNIQUE INDEX IF NOT EXISTS org_domain_verified_idx ON eloxiv.org_domain (domain)
3064
+ WHERE verified_at IS NOT NULL`,
3065
+ `ALTER TABLE eloxiv.org_group ADD COLUMN IF NOT EXISTS metadata jsonb NOT NULL DEFAULT '{}'::jsonb`,
3066
+ ],
3067
+ }
3068
+
3069
+ /**
3070
+ * Avatars (Avatars.ts): a person's profile photo, kept by the kernel, at most 256 KiB of PNG, JPEG, WebP or GIF.
3071
+ * Written to be safe to apply again.
3072
+ */
3073
+ const userAvatars: Migration = {
3074
+ name: "0086_user_avatars",
3075
+ statements: [
3076
+ `CREATE TABLE IF NOT EXISTS eloxiv.user_avatar (
3077
+ user_id text PRIMARY KEY,
3078
+ content_type text NOT NULL CHECK (content_type IN ('image/png', 'image/jpeg', 'image/webp', 'image/gif')),
3079
+ bytes bytea NOT NULL CHECK (octet_length(bytes) <= 262144),
3080
+ etag text NOT NULL,
3081
+ updated_at timestamptz NOT NULL DEFAULT now()
3082
+ )`,
3083
+ ],
3084
+ }
3085
+
3086
+ /**
3087
+ * An address reaches policy only once it is verified (threat model ID-13): anyone can sign up with an address they
3088
+ * do not receive mail at, so a policy on `principal.email` must not trust it before Better Auth's verification. Row-
3089
+ * level security's `eloxiv_ctx.current_email()` and the live `email` sync fact answer the verified address, and `''`
3090
+ * (no email, as for a service principal) otherwise, as the pre-handler principal does (`principalOf`). A
3091
+ * verification (or its loss, an address change) recomputes the person's facts. Written to be safe to apply again.
3092
+ */
3093
+ const verifiedEmailPolicy: Migration = {
3094
+ name: "0087_verified_email_policy",
3095
+ statements: [
3096
+ `CREATE OR REPLACE FUNCTION eloxiv_ctx.current_email() RETURNS text
3097
+ LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog
3098
+ AS $$ SELECT coalesce((SELECT u.email FROM auth."user" u WHERE u.id = c.actor AND u."emailVerified"), '')
3099
+ FROM eloxiv.invocation_context c WHERE c.xid = pg_current_xact_id() $$`,
3100
+ `REVOKE ALL ON FUNCTION eloxiv_ctx.current_email() FROM PUBLIC`,
3101
+ `CREATE OR REPLACE FUNCTION eloxiv.refresh_sync_facts(p_org text, p_user text) RETURNS void
3102
+ LANGUAGE sql SET search_path = pg_catalog AS $$
3103
+ WITH wanted (kind, value) AS (
3104
+ SELECT 'member', '' FROM eloxiv.membership WHERE org_id = p_org AND user_id = p_user
3105
+ UNION SELECT 'group', group_id FROM eloxiv.group_member WHERE org_id = p_org AND user_id = p_user
3106
+ UNION SELECT 'role', role_id FROM eloxiv.membership_role WHERE org_id = p_org AND user_id = p_user
3107
+ UNION SELECT 'permission', p.permission FROM eloxiv.membership_role r
3108
+ JOIN eloxiv.role_permission p ON p.org_id = r.org_id AND p.role_id = r.role_id
3109
+ WHERE r.org_id = p_org AND r.user_id = p_user
3110
+ UNION SELECT 'email',
3111
+ coalesce((SELECT u.email FROM auth."user" u WHERE u.id = m.user_id AND u."emailVerified"), '')
3112
+ FROM eloxiv.membership m WHERE m.org_id = p_org AND m.user_id = p_user
3113
+ ), removed AS (
3114
+ DELETE FROM eloxiv.sync_fact f WHERE f.org_id = p_org AND f.user_id = p_user AND f.kind <> 'session'
3115
+ AND NOT EXISTS (SELECT 1 FROM wanted w WHERE w.kind = f.kind AND w.value = f.value)
3116
+ )
3117
+ INSERT INTO eloxiv.sync_fact (org_id, user_id, kind, value)
3118
+ SELECT p_org, p_user, kind, value FROM wanted ON CONFLICT DO NOTHING
3119
+ $$`,
3120
+ `REVOKE ALL ON FUNCTION eloxiv.refresh_sync_facts(text, text) FROM PUBLIC`,
3121
+ `CREATE OR REPLACE TRIGGER eloxiv_sync_facts AFTER INSERT OR UPDATE OF email, "emailVerified" ON auth."user"
3122
+ FOR EACH ROW EXECUTE FUNCTION eloxiv.sync_user_changed()`,
3123
+ `DO $$
3124
+ DECLARE org record;
3125
+ BEGIN
3126
+ FOR org IN SELECT id FROM eloxiv.organization ORDER BY id LOOP
3127
+ PERFORM eloxiv.lock_directory(org.id);
3128
+ PERFORM eloxiv.refresh_sync_facts(m.org_id, m.user_id) FROM eloxiv.membership m WHERE m.org_id = org.id;
3129
+ END LOOP;
3130
+ END $$`,
3131
+ ],
3132
+ }
3133
+
3134
+ /**
3135
+ * A pending change of address, bound to the session that asked for it (Identity's `/change-email` guard, the
3136
+ * security review of PR #43): its links are honoured only when opened in that same session while it is in force, each
3137
+ * stage once (`confirmed_at` the confirmation's use; the row deleted by the verification's). A password reset ends
3138
+ * that session, and with it every link it was sent. One pending change per account. Written to be safe to apply
3139
+ * again.
3140
+ */
3141
+ const emailChanges: Migration = {
3142
+ name: "0088_email_changes",
3143
+ statements: [
3144
+ `CREATE TABLE IF NOT EXISTS eloxiv.email_change (
3145
+ user_id text PRIMARY KEY,
3146
+ session_id text NOT NULL,
3147
+ update_to text NOT NULL CHECK (update_to = lower(update_to)),
3148
+ confirmed_at timestamptz,
3149
+ created_at timestamptz NOT NULL DEFAULT now()
3150
+ )`,
3151
+ ],
3152
+ }
3153
+
3154
+ /**
3155
+ * The credential fence (Identity, backlog 45): a sign-in never issues a session, or a two-factor challenge, against a
3156
+ * password that changed while it ran. `credential_change` records, per account, the transaction that last changed its
3157
+ * password (`xid`) and the request of Better Auth's that made the change (`by_request`, from `eloxiv.auth_request`): a
3158
+ * change of password (Better Auth's update of the credential account) and a reset (its consumption of an unexpired
3159
+ * reset token, the reset transaction's first statement, before it ends the sessions; the cleanup of an expired token
3160
+ * is no change) record it under an exclusive advisory lock on the account's credentials, and void the account's
3161
+ * pending two-factor challenges (each issued against the old password). A session, or a two-factor challenge (`2fa-*`
3162
+ * in Better Auth's verification table, inserted after the password was checked), that Better Auth inserts for a
3163
+ * request (`Identity` sets `eloxiv.auth_snapshot` to the snapshot taken when the request arrived, before Better Auth
3164
+ * read any password, whether or not it presented a session) is checked at its commit, under the same lock shared:
3165
+ * refused (`EA001`) when the account's last change is not visible in that snapshot and was not the request's own (a
3166
+ * password change that issues the caller a new session). So a sign-in either commits its session or challenge before
3167
+ * a reset takes the lock (and the reset, which ends the sessions and voids the challenges after, ends it) or is
3168
+ * refused. Written to be safe to apply again.
3169
+ */
3170
+ const credentialFence: Migration = {
3171
+ name: "0200_credential_fence",
3172
+ statements: [
3173
+ `CREATE TABLE IF NOT EXISTS eloxiv.credential_change (
3174
+ user_id text PRIMARY KEY,
3175
+ xid xid8 NOT NULL,
3176
+ by_request text,
3177
+ changed_at timestamptz NOT NULL DEFAULT now()
3178
+ )`,
3179
+ `ALTER TABLE eloxiv.credential_change ADD COLUMN IF NOT EXISTS by_request text`,
3180
+ `CREATE OR REPLACE FUNCTION eloxiv.credential_changed(p_user text) RETURNS void
3181
+ LANGUAGE plpgsql SET search_path = pg_catalog AS $$
3182
+ BEGIN
3183
+ PERFORM pg_advisory_xact_lock(hashtextextended('eloxiv.credentials:' || p_user, 0));
3184
+ INSERT INTO eloxiv.credential_change (user_id, xid, by_request, changed_at)
3185
+ VALUES (p_user, pg_current_xact_id(), nullif(current_setting('eloxiv.auth_request', true), ''), now())
3186
+ ON CONFLICT (user_id) DO UPDATE
3187
+ SET xid = EXCLUDED.xid, by_request = EXCLUDED.by_request, changed_at = EXCLUDED.changed_at;
3188
+ DELETE FROM auth.verification v WHERE v.value = p_user AND v.identifier LIKE '2fa-%'
3189
+ AND v.identifier NOT LIKE '2fa-attempts-%';
3190
+ END $$`,
3191
+ `REVOKE ALL ON FUNCTION eloxiv.credential_changed(text) FROM PUBLIC`,
3192
+ `CREATE OR REPLACE FUNCTION eloxiv.password_changed() RETURNS trigger
3193
+ LANGUAGE plpgsql SET search_path = pg_catalog AS $$
3194
+ BEGIN PERFORM eloxiv.credential_changed(NEW."userId"); RETURN NULL; END $$`,
3195
+ `CREATE OR REPLACE TRIGGER eloxiv_password_changed AFTER UPDATE OF password ON auth.account
3196
+ FOR EACH ROW WHEN (NEW."providerId" = 'credential' AND OLD.password IS DISTINCT FROM NEW.password)
3197
+ EXECUTE FUNCTION eloxiv.password_changed()`,
3198
+ `CREATE OR REPLACE FUNCTION eloxiv.reset_consumed() RETURNS trigger
3199
+ LANGUAGE plpgsql SET search_path = pg_catalog AS $$
3200
+ BEGIN PERFORM eloxiv.credential_changed(OLD.value); RETURN NULL; END $$`,
3201
+ `CREATE OR REPLACE TRIGGER eloxiv_reset_consumed AFTER DELETE ON auth.verification
3202
+ FOR EACH ROW WHEN (OLD.identifier LIKE 'reset-password:%' AND OLD."expiresAt" > now())
3203
+ EXECUTE FUNCTION eloxiv.reset_consumed()`,
3204
+ `CREATE OR REPLACE FUNCTION eloxiv.credentials_fenced(p_user text) RETURNS void
3205
+ LANGUAGE plpgsql SET search_path = pg_catalog AS $$
3206
+ DECLARE
3207
+ snapshot text := current_setting('eloxiv.auth_snapshot', true);
3208
+ request text := nullif(current_setting('eloxiv.auth_request', true), '');
3209
+ changed record;
3210
+ BEGIN
3211
+ IF snapshot IS NULL OR snapshot = '' THEN RETURN; END IF;
3212
+ PERFORM pg_advisory_xact_lock_shared(hashtextextended('eloxiv.credentials:' || p_user, 0));
3213
+ SELECT c.xid, c.by_request INTO changed FROM eloxiv.credential_change c WHERE c.user_id = p_user;
3214
+ IF FOUND AND NOT pg_visible_in_snapshot(changed.xid, snapshot::pg_snapshot)
3215
+ AND changed.by_request IS DISTINCT FROM request THEN
3216
+ RAISE EXCEPTION 'The password changed while this sign-in ran' USING ERRCODE = 'EA001';
3217
+ END IF;
3218
+ END $$`,
3219
+ `REVOKE ALL ON FUNCTION eloxiv.credentials_fenced(text) FROM PUBLIC`,
3220
+ `CREATE OR REPLACE FUNCTION eloxiv.session_fenced() RETURNS trigger
3221
+ LANGUAGE plpgsql SET search_path = pg_catalog AS $$
3222
+ BEGIN PERFORM eloxiv.credentials_fenced(NEW."userId"); RETURN NULL; END $$`,
3223
+ `DROP TRIGGER IF EXISTS eloxiv_session_fenced ON auth.session`,
3224
+ `CREATE CONSTRAINT TRIGGER eloxiv_session_fenced AFTER INSERT ON auth.session
3225
+ DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION eloxiv.session_fenced()`,
3226
+ `CREATE OR REPLACE FUNCTION eloxiv.challenge_fenced() RETURNS trigger
3227
+ LANGUAGE plpgsql SET search_path = pg_catalog AS $$
3228
+ BEGIN PERFORM eloxiv.credentials_fenced(NEW.value); RETURN NULL; END $$`,
3229
+ `DROP TRIGGER IF EXISTS eloxiv_challenge_fenced ON auth.verification`,
3230
+ `CREATE CONSTRAINT TRIGGER eloxiv_challenge_fenced AFTER INSERT ON auth.verification
3231
+ DEFERRABLE INITIALLY DEFERRED FOR EACH ROW
3232
+ WHEN (NEW.identifier LIKE '2fa-%' AND NEW.identifier NOT LIKE '2fa-attempts-%')
3233
+ EXECUTE FUNCTION eloxiv.challenge_fenced()`,
3234
+ ],
3235
+ }
3236
+
3237
+ /**
3238
+ * The account-write fence (Identity, backlog 27): a write of Better Auth's to an account (the user, its credential
3239
+ * and provider accounts, its two-factor secret, its verification tokens) made for a request that presented a session
3240
+ * commits only while that session is in force. `Identity` sets `eloxiv.auth_session` to the session and the request
3241
+ * (`<session> <request>`) on Better Auth's connection for the request's statements; each such write is checked at its
3242
+ * transaction's commit, under the advisory lock a revocation takes exclusively (taken shared, kept to the commit): the session still in
3243
+ * force, or ended by this request's own statement (a password change ending every session). Otherwise it is refused
3244
+ * (`EA002`) and nothing of the transaction commits. So a sign-out past its bound, which revokes the session while the
3245
+ * request runs, leaves nothing of the request to land after it. Written to be safe to apply again.
3246
+ */
3247
+ const accountWriteFence: Migration = {
3248
+ name: "0201_account_write_fence",
3249
+ statements: [
3250
+ `CREATE OR REPLACE FUNCTION eloxiv.account_write_held() RETURNS trigger
3251
+ LANGUAGE plpgsql SET search_path = pg_catalog AS $$
3252
+ DECLARE
3253
+ held text := current_setting('eloxiv.auth_session', true);
3254
+ v_session text;
3255
+ v_request text;
3256
+ BEGIN
3257
+ IF held IS NULL OR held = '' THEN RETURN NULL; END IF;
3258
+ v_session := split_part(held, ' ', 1);
3259
+ v_request := split_part(held, ' ', 2);
3260
+ PERFORM pg_advisory_xact_lock_shared(hashtextextended('eloxiv.session:' || v_session, 0));
3261
+ IF NOT EXISTS (SELECT 1 FROM auth.session c WHERE c.id = v_session AND c."expiresAt" > clock_timestamp()
3262
+ AND NOT EXISTS (SELECT 1 FROM eloxiv.session_revocation r WHERE r.session_id = c.id))
3263
+ AND NOT EXISTS (SELECT 1 FROM eloxiv.session_revocation r
3264
+ WHERE r.session_id = v_session AND r.by_request = v_request) THEN
3265
+ RAISE EXCEPTION 'The session this request was made with has ended' USING ERRCODE = 'EA002';
3266
+ END IF;
3267
+ RETURN NULL;
3268
+ END $$`,
3269
+ `DROP TRIGGER IF EXISTS eloxiv_account_write_held ON auth."user"`,
3270
+ `CREATE CONSTRAINT TRIGGER eloxiv_account_write_held AFTER INSERT OR UPDATE OR DELETE ON auth."user"
3271
+ DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION eloxiv.account_write_held()`,
3272
+ `DROP TRIGGER IF EXISTS eloxiv_account_write_held ON auth.account`,
3273
+ `CREATE CONSTRAINT TRIGGER eloxiv_account_write_held AFTER INSERT OR UPDATE OR DELETE ON auth.account
3274
+ DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION eloxiv.account_write_held()`,
3275
+ `DROP TRIGGER IF EXISTS eloxiv_account_write_held ON auth."twoFactor"`,
3276
+ `CREATE CONSTRAINT TRIGGER eloxiv_account_write_held AFTER INSERT OR UPDATE OR DELETE ON auth."twoFactor"
3277
+ DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION eloxiv.account_write_held()`,
3278
+ `DROP TRIGGER IF EXISTS eloxiv_account_write_held ON auth.verification`,
3279
+ `CREATE CONSTRAINT TRIGGER eloxiv_account_write_held AFTER INSERT OR UPDATE OR DELETE ON auth.verification
3280
+ DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION eloxiv.account_write_held()`,
3281
+ ],
3282
+ }
3283
+
3284
+ /**
3285
+ * Domain claims re-checked (Directory's `recheckDomains`, backlog 42): when a verified claim's TXT record is next due
3286
+ * to be looked up (`next_check_at`), and since when DNS has failed to answer for it (`failing_since`). A claim verified
3287
+ * before this is due a day after its verification. Written to be safe to apply again.
3288
+ */
3289
+ const domainChecks: Migration = {
3290
+ name: "0202_domain_checks",
3291
+ statements: [
3292
+ `ALTER TABLE eloxiv.org_domain ADD COLUMN IF NOT EXISTS next_check_at timestamptz`,
3293
+ `ALTER TABLE eloxiv.org_domain ADD COLUMN IF NOT EXISTS failing_since timestamptz`,
3294
+ `UPDATE eloxiv.org_domain SET next_check_at = verified_at + interval '1 day'
3295
+ WHERE verified_at IS NOT NULL AND next_check_at IS NULL`,
3296
+ `CREATE INDEX IF NOT EXISTS org_domain_check_due ON eloxiv.org_domain (next_check_at)
3297
+ WHERE verified_at IS NOT NULL`,
3298
+ ],
3299
+ }
3300
+
3301
+ /**
3302
+ * Account mail kept until sent (AccountMail's `accountOutbox`, backlog 43): one row per verification, reset or
3303
+ * change-of-address message, its variables (the link and its token) sealed (`sealed`, erased once the message is sent,
3304
+ * given up or expired), its attempts, when it is next tried, the lease of the claim sending it (`lease_owner`), and
3305
+ * when its link expires. Rows go a day after they were queued. Written to be safe to apply again.
3306
+ */
3307
+ const accountMail: Migration = {
3308
+ name: "0203_account_mail",
3309
+ statements: [
3310
+ `CREATE TABLE IF NOT EXISTS eloxiv.account_mail (
3311
+ id text PRIMARY KEY,
3312
+ recipient text NOT NULL,
3313
+ template text NOT NULL,
3314
+ sealed bytea,
3315
+ attempts integer NOT NULL DEFAULT 0,
3316
+ next_attempt_at timestamptz NOT NULL DEFAULT now(),
3317
+ lease_until timestamptz,
3318
+ lease_owner text,
3319
+ expires_at timestamptz NOT NULL,
3320
+ sent_at timestamptz,
3321
+ last_error text,
3322
+ created_at timestamptz NOT NULL DEFAULT now()
3323
+ )`,
3324
+ `ALTER TABLE eloxiv.account_mail ADD COLUMN IF NOT EXISTS lease_owner text`,
3325
+ `CREATE INDEX IF NOT EXISTS account_mail_due ON eloxiv.account_mail (next_attempt_at) WHERE sealed IS NOT NULL`,
3326
+ `CREATE INDEX IF NOT EXISTS account_mail_created ON eloxiv.account_mail (created_at)`,
3327
+ ],
3328
+ }
3329
+
3330
+ /**
3331
+ * Model setup (docs/contracts/model-provider.md, "Model setup"): an organisation's policy for its agent's models
3332
+ * (whether members may use keys of their own, which models they may choose) and each member's checked model choice.
3333
+ * The keys themselves are secrets (`model.<provider>.<name>`, managed by the agent). Safe to apply again.
3334
+ */
3335
+ const modelSetup: Migration = {
3336
+ name: "0061_model_setup",
3337
+ statements: [
3338
+ `CREATE TABLE IF NOT EXISTS eloxiv.model_policy (
3339
+ org_id text PRIMARY KEY REFERENCES eloxiv.organization(id) ON DELETE CASCADE,
3340
+ personal_keys boolean NOT NULL DEFAULT false,
3341
+ allowed_models text[],
3342
+ updated_by text NOT NULL,
3343
+ updated_at timestamptz NOT NULL DEFAULT now()
3344
+ )`,
3345
+ `CREATE TABLE IF NOT EXISTS eloxiv.model_choice (
3346
+ org_id text NOT NULL REFERENCES eloxiv.organization(id) ON DELETE CASCADE,
3347
+ user_id text NOT NULL,
3348
+ provider text NOT NULL,
3349
+ model text NOT NULL,
3350
+ checked_at timestamptz,
3351
+ updated_at timestamptz NOT NULL DEFAULT now(),
3352
+ PRIMARY KEY (org_id, user_id)
3353
+ )`,
3354
+ ],
3355
+ }
3356
+
3357
+ /**
3358
+ * Sign-in methods (Identity, Directory 1.4.0): how each person's session was signed in (`password`, `magic-link`,
3359
+ * `oauth:<provider>`; a session rotated or exchanged inherits its origin's), the methods an organisation lets its
3360
+ * members act with (`methods` null: every method), and the one-time codes of the desktop sign-in exchange (hashed,
3361
+ * bound to the desktop's PKCE challenge and redirect, a minute long). Written to be safe to apply again.
3362
+ */
3363
+ const signInMethods: Migration = {
3364
+ name: "0140_sign_in_methods",
3365
+ statements: [
3366
+ `CREATE TABLE IF NOT EXISTS eloxiv.session_method (
3367
+ session_id text PRIMARY KEY,
3368
+ method text NOT NULL,
3369
+ created_at timestamptz NOT NULL DEFAULT now()
3370
+ )`,
3371
+ `CREATE TABLE IF NOT EXISTS eloxiv.org_sign_in (
3372
+ org_id text PRIMARY KEY REFERENCES eloxiv.organization(id),
3373
+ methods text[]
3374
+ )`,
3375
+ `CREATE TABLE IF NOT EXISTS eloxiv.desktop_code (
3376
+ code_hash text PRIMARY KEY,
3377
+ user_id text NOT NULL,
3378
+ session_id text NOT NULL,
3379
+ method text NOT NULL,
3380
+ challenge text NOT NULL,
3381
+ redirect_uri text NOT NULL,
3382
+ expires_at timestamptz NOT NULL,
3383
+ used_at timestamptz
3384
+ )`,
3385
+ ],
3386
+ }
3387
+
3388
+ /**
3389
+ * Teams (Directory 1.4.0, C-007): a group can be a team (`org_group.team`), with its leads in a lead group
3390
+ * (`<id>--leads`); each person's active team in an organisation (`active_team`), whose agent context joins theirs:
3391
+ * it counts only while the group is a team and the person in it (read through both, so no reference is kept).
3392
+ * Written to be safe to apply again.
3393
+ */
3394
+ const teams: Migration = {
3395
+ name: "0141_teams",
3396
+ statements: [
3397
+ `ALTER TABLE eloxiv.org_group ADD COLUMN IF NOT EXISTS team boolean NOT NULL DEFAULT false`,
3398
+ `CREATE TABLE IF NOT EXISTS eloxiv.active_team (
3399
+ org_id text NOT NULL,
3400
+ user_id text NOT NULL,
3401
+ group_id text NOT NULL,
3402
+ PRIMARY KEY (org_id, user_id)
3403
+ )`,
3404
+ ],
3405
+ }
3406
+
3407
+ /**
3408
+ * A file's upload, recorded with the authority of the call that completed it (`bindDeferred(ctx.authority, "once")`):
3409
+ * its finalisation asserts it before it takes the record's lock and makes the file visible, so a file whose uploader's
3410
+ * credential, session or membership is gone by then is refused (backlog 18). An upload completed before this column
3411
+ * has none, and is refused the same way (unrecorded authority). (0146 to 0174 are other branches'.) Safe to apply again.
3412
+ */
3413
+ const fileAuthority: Migration = {
3414
+ name: "0175_file_authority",
3415
+ statements: [`ALTER TABLE eloxiv.file ADD COLUMN IF NOT EXISTS authority jsonb`],
3416
+ }
3417
+
3418
+ /**
3419
+ * Bulk ingestion runs (the Ingestion contract 1.1.0, `ingestion/Runs.ts`): a run of a module in an organisation over
3420
+ * the inventory of item keys a provider listed, with its budget and spending, and each item's state, lease (worker
3421
+ * and expiry), attempts, cost and the reason it was reported. (0089 to 0144 are other branches'.) Safe to apply again.
3422
+ */
3423
+ const ingestionRuns: Migration = {
3424
+ name: "0145_ingestion_runs",
3425
+ statements: [
3426
+ `CREATE TABLE IF NOT EXISTS eloxiv.ingestion_run (
3427
+ id text PRIMARY KEY,
3428
+ org_id text NOT NULL,
3429
+ module text NOT NULL,
3430
+ source text NOT NULL,
3431
+ status text NOT NULL DEFAULT 'running' CHECK (status IN ('running', 'completed', 'stopped')),
3432
+ stop_reason text CHECK (stop_reason IN ('budget')),
3433
+ budget double precision,
3434
+ spent double precision NOT NULL DEFAULT 0,
3435
+ created_at timestamptz NOT NULL DEFAULT now(),
3436
+ finished_at timestamptz
3437
+ )`,
3438
+ `CREATE INDEX IF NOT EXISTS ingestion_run_finished ON eloxiv.ingestion_run (finished_at) WHERE finished_at IS NOT NULL`,
3439
+ `CREATE TABLE IF NOT EXISTS eloxiv.ingestion_run_item (
3440
+ run_id text NOT NULL REFERENCES eloxiv.ingestion_run (id) ON DELETE CASCADE,
3441
+ key text NOT NULL,
3442
+ state text NOT NULL DEFAULT 'pending' CHECK (state IN ('pending', 'leased', 'done', 'reported')),
3443
+ lease_owner text,
3444
+ lease_until timestamptz,
3445
+ attempts integer NOT NULL DEFAULT 0,
3446
+ cost double precision NOT NULL DEFAULT 0,
3447
+ reason text,
3448
+ updated_at timestamptz NOT NULL DEFAULT now(),
3449
+ PRIMARY KEY (run_id, key)
3450
+ )`,
3451
+ `CREATE INDEX IF NOT EXISTS ingestion_run_item_claim ON eloxiv.ingestion_run_item (run_id, state, key)`,
3452
+ ],
3453
+ }
3454
+
3455
+ /**
3456
+ * Agent edit groups (the Versioning contract 1.1.0, the CollabDocument contract 1.1.0): which agent run made a change,
3457
+ * and the conversation and message that started the run (a sub-agent's, its parent's), on the call's invocation
3458
+ * context (set by the kernel for the agent runtime's tool calls), on each record version, and on a document's agent
3459
+ * autosaves (`collab_version` with reason `agent`: the document before the run's first change to it, what the run's
3460
+ * updates applied in `undo` (the ranges they inserted and the ranges they deleted, as an UndoManager stack item), how
3461
+ * many updates it made, the person it acted for, in its organisation, when a revert undid it (`undone_at`) and the
3462
+ * update that revert appended, if it appended one (`reverted_seq`)). A record version a revert made names the group it
3463
+ * reverted (`revert_conversation_id`, `revert_message_id`), so a later revert of the same chat counts it as the chat's.
3464
+ * The invocation context also records the acting module's Cedar namespace (`namespace`), so a platform read function
3465
+ * answers for that module's entities only. `versioning.agentEdits` lists a group, and `ctx.history.revert` and
3466
+ * `collab.revert` undo it. (0146 to 0184 are other branches'.) Safe to apply again.
3467
+ */
3468
+ const agentEditGroups: Migration = {
3469
+ name: "0185_agent_edit_groups",
3470
+ statements: [
3471
+ `ALTER TABLE eloxiv.invocation_context ADD COLUMN IF NOT EXISTS agent_run text`,
3472
+ `ALTER TABLE eloxiv.invocation_context ADD COLUMN IF NOT EXISTS agent_conversation text`,
3473
+ `ALTER TABLE eloxiv.invocation_context ADD COLUMN IF NOT EXISTS agent_message text`,
3474
+ `ALTER TABLE eloxiv.invocation_context ADD COLUMN IF NOT EXISTS namespace text`,
3475
+ `ALTER TABLE eloxiv.record_history ADD COLUMN IF NOT EXISTS agent_run_id text`,
3476
+ `ALTER TABLE eloxiv.record_history ADD COLUMN IF NOT EXISTS agent_conversation_id text`,
3477
+ `ALTER TABLE eloxiv.record_history ADD COLUMN IF NOT EXISTS agent_message_id text`,
3478
+ `ALTER TABLE eloxiv.record_history ADD COLUMN IF NOT EXISTS revert_conversation_id text`,
3479
+ `ALTER TABLE eloxiv.record_history ADD COLUMN IF NOT EXISTS revert_message_id text`,
3480
+ `CREATE INDEX IF NOT EXISTS record_history_agent_idx ON eloxiv.record_history (org_id, agent_conversation_id)
3481
+ WHERE agent_conversation_id IS NOT NULL`,
3482
+ `ALTER TABLE eloxiv.collab_version ADD COLUMN IF NOT EXISTS agent_run_id text`,
3483
+ `ALTER TABLE eloxiv.collab_version ADD COLUMN IF NOT EXISTS agent_conversation_id text`,
3484
+ `ALTER TABLE eloxiv.collab_version ADD COLUMN IF NOT EXISTS agent_message_id text`,
3485
+ `ALTER TABLE eloxiv.collab_version ADD COLUMN IF NOT EXISTS actor_user_id text`,
3486
+ `ALTER TABLE eloxiv.collab_version ADD COLUMN IF NOT EXISTS org_id text`,
3487
+ `ALTER TABLE eloxiv.collab_version ADD COLUMN IF NOT EXISTS undo jsonb`,
3488
+ `ALTER TABLE eloxiv.collab_version ADD COLUMN IF NOT EXISTS updates integer NOT NULL DEFAULT 0`,
3489
+ `ALTER TABLE eloxiv.collab_version ADD COLUMN IF NOT EXISTS reverted_seq bigint`,
3490
+ `ALTER TABLE eloxiv.collab_version ADD COLUMN IF NOT EXISTS undone_at timestamptz`,
3491
+ `ALTER TABLE eloxiv.collab_version DROP CONSTRAINT IF EXISTS collab_version_reason_check`,
3492
+ `ALTER TABLE eloxiv.collab_version ADD CONSTRAINT collab_version_reason_check
3493
+ CHECK (reason IN ('compaction', 'snapshot', 'agent'))`,
3494
+ `CREATE UNIQUE INDEX IF NOT EXISTS collab_version_agent_run_idx ON eloxiv.collab_version (document_id, agent_run_id)
3495
+ WHERE reason = 'agent'`,
3496
+ `CREATE INDEX IF NOT EXISTS collab_version_agent_idx ON eloxiv.collab_version (agent_conversation_id)
3497
+ WHERE reason = 'agent'`,
3498
+ ],
3499
+ }
3500
+
3501
+ /**
3502
+ * Read programs, staged datasets and corpus collections (the Sandbox contract 2.1.0 and the Ingestion contract 1.2.0,
3503
+ * `data/`): a dataset of a person or a module in an organisation, its inferred columns, size and expiry, and its rows by
3504
+ * page; each read program's run with its status, result and usage; and each corpus collection with what it was asked
3505
+ * for, under whose authority, and how far it got. (0146 to 0159 are other branches'.) Safe to apply again.
3506
+ */
3507
+ const sandboxData: Migration = {
3508
+ name: "0160_sandbox_data",
3509
+ statements: [
3510
+ `CREATE TABLE IF NOT EXISTS eloxiv.staged_dataset (
3511
+ id text PRIMARY KEY,
3512
+ org_id text NOT NULL,
3513
+ owner_kind text NOT NULL CHECK (owner_kind IN ('person', 'module')),
3514
+ owner text NOT NULL,
3515
+ name text NOT NULL,
3516
+ columns jsonb NOT NULL DEFAULT '[]',
3517
+ row_count integer NOT NULL DEFAULT 0,
3518
+ bytes bigint NOT NULL DEFAULT 0,
3519
+ expires_at timestamptz NOT NULL,
3520
+ created_at timestamptz NOT NULL DEFAULT now(),
3521
+ UNIQUE (org_id, owner_kind, owner, name)
3522
+ )`,
3523
+ `CREATE INDEX IF NOT EXISTS staged_dataset_expiry ON eloxiv.staged_dataset (expires_at)`,
3524
+ `CREATE TABLE IF NOT EXISTS eloxiv.staged_row (
3525
+ dataset_id text NOT NULL REFERENCES eloxiv.staged_dataset (id) ON DELETE CASCADE,
3526
+ page integer NOT NULL DEFAULT 0,
3527
+ n integer NOT NULL,
3528
+ row jsonb NOT NULL,
3529
+ PRIMARY KEY (dataset_id, page, n)
3530
+ )`,
3531
+ `CREATE TABLE IF NOT EXISTS eloxiv.data_run (
3532
+ id text PRIMARY KEY,
3533
+ org_id text NOT NULL,
3534
+ user_id text NOT NULL,
3535
+ status text NOT NULL DEFAULT 'running' CHECK (status IN ('running', 'succeeded', 'failed')),
3536
+ background boolean NOT NULL DEFAULT false,
3537
+ started_at timestamptz NOT NULL DEFAULT now(),
3538
+ finished_at timestamptz,
3539
+ result jsonb,
3540
+ error text,
3541
+ usage jsonb
3542
+ )`,
3543
+ `CREATE INDEX IF NOT EXISTS data_run_owner ON eloxiv.data_run (org_id, user_id, started_at)`,
3544
+ `CREATE TABLE IF NOT EXISTS eloxiv.corpus_collection (
3545
+ id text PRIMARY KEY,
3546
+ org_id text NOT NULL,
3547
+ owner_kind text NOT NULL CHECK (owner_kind IN ('person', 'module')),
3548
+ owner text NOT NULL,
3549
+ user_id text NOT NULL,
3550
+ authority jsonb NOT NULL,
3551
+ spec jsonb NOT NULL,
3552
+ status text NOT NULL DEFAULT 'running' CHECK (status IN ('running', 'completed', 'stopped', 'failed')),
3553
+ pages integer NOT NULL DEFAULT 0,
3554
+ items integer NOT NULL DEFAULT 0,
3555
+ cursor text,
3556
+ agent_session text,
3557
+ error text,
3558
+ created_at timestamptz NOT NULL DEFAULT now(),
3559
+ updated_at timestamptz NOT NULL DEFAULT now()
3560
+ )`,
3561
+ `CREATE INDEX IF NOT EXISTS corpus_collection_owner ON eloxiv.corpus_collection (org_id, owner_kind, owner, status)`,
3562
+ ],
3563
+ }
3564
+
3565
+ /**
3566
+ * Proposals (the Approvals contract, "Proposals"): grouped edits proposed for review, each item a proposed call (an
3567
+ * action and its encoded input, with the hash the invocation path computes for it), its revision, its decision and the
3568
+ * invocation that applied it. (0146 to 0169 are other branches'.) Safe to apply again.
3569
+ */
3570
+ const proposals: Migration = {
3571
+ name: "0170_proposals",
3572
+ statements: [
3573
+ `CREATE TABLE IF NOT EXISTS eloxiv.proposal (
3574
+ id text PRIMARY KEY,
3575
+ org_id text NOT NULL REFERENCES eloxiv.organization(id) ON DELETE CASCADE,
3576
+ author_id text NOT NULL,
3577
+ summary text NOT NULL,
3578
+ creation_key text,
3579
+ status text NOT NULL DEFAULT 'open' CHECK (status IN ('open', 'withdrawn')),
3580
+ created_at timestamptz NOT NULL DEFAULT now()
3581
+ )`,
3582
+ `CREATE UNIQUE INDEX IF NOT EXISTS proposal_creation_key ON eloxiv.proposal (org_id, author_id, creation_key)
3583
+ WHERE creation_key IS NOT NULL`,
3584
+ `CREATE TABLE IF NOT EXISTS eloxiv.proposal_item (
3585
+ id text PRIMARY KEY,
3586
+ proposal_id text NOT NULL REFERENCES eloxiv.proposal(id) ON DELETE CASCADE,
3587
+ ordinal integer NOT NULL,
3588
+ summary text NOT NULL,
3589
+ action text NOT NULL,
3590
+ input jsonb NOT NULL,
3591
+ input_hash text NOT NULL,
3592
+ revision integer NOT NULL DEFAULT 1,
3593
+ status text NOT NULL DEFAULT 'pending'
3594
+ CHECK (status IN ('pending', 'accepted', 'rejected', 'applied', 'withdrawn')),
3595
+ decided_by text,
3596
+ decided_at timestamptz,
3597
+ applied_invocation text,
3598
+ applied_at timestamptz,
3599
+ UNIQUE (proposal_id, ordinal)
3600
+ )`,
3601
+ ],
3602
+ }
3603
+
3604
+ /**
3605
+ * Storage providers per organisation and per person (the Files contract, "Where files are stored"): an S3-compatible
3606
+ * store's coordinates and access key id (its secret is a Secret), never changed: a new one retires the old, which
3607
+ * keeps the files it holds. Safe to apply again.
3608
+ */
3609
+ const storageProviders: Migration = {
3610
+ name: "0171_storage_providers",
3611
+ statements: [
3612
+ `CREATE TABLE IF NOT EXISTS eloxiv.storage_provider (
3613
+ id text PRIMARY KEY,
3614
+ org_id text NOT NULL REFERENCES eloxiv.organization(id) ON DELETE CASCADE,
3615
+ user_id text,
3616
+ endpoint text NOT NULL,
3617
+ region text NOT NULL,
3618
+ bucket text NOT NULL,
3619
+ prefix text NOT NULL DEFAULT '',
3620
+ force_path_style boolean NOT NULL DEFAULT true,
3621
+ access_key_id text NOT NULL,
3622
+ secret_name text NOT NULL,
3623
+ created_by text NOT NULL,
3624
+ created_at timestamptz NOT NULL DEFAULT now(),
3625
+ retired_at timestamptz
3626
+ )`,
3627
+ `CREATE UNIQUE INDEX IF NOT EXISTS storage_provider_active ON eloxiv.storage_provider
3628
+ (org_id, coalesce(user_id, '')) WHERE retired_at IS NULL`,
3629
+ ],
3630
+ }
3631
+
3632
+ /**
3633
+ * Constraint disclosure (backlog 1): a write's outcome may not depend on records the caller cannot read.
3634
+ *
3635
+ * - `eloxiv.guard_reference(owner, schema, table, child columns..., parent columns...)`: a BEFORE INSERT OR UPDATE
3636
+ * row trigger setup installs for every foreign key of a module table. A new or changed reference must name a
3637
+ * record the writing role can read (under its row-level security); a missing record and an unreadable one are
3638
+ * refused alike (insufficient_privilege, so the call is Forbidden), before the referential check, whose own
3639
+ * outcome would tell them apart. The module's owner (migrations) is exempt; a reference with a null column is not
3640
+ * checked (MATCH SIMPLE, as the foreign key).
3641
+ */
3642
+ const constraintDisclosure: Migration = {
3643
+ name: "0195_constraint_disclosure",
3644
+ statements: [
3645
+ `CREATE OR REPLACE FUNCTION eloxiv.guard_reference() RETURNS trigger
3646
+ LANGUAGE plpgsql SET search_path = pg_catalog AS $$
3647
+ DECLARE
3648
+ n integer := (TG_NARGS - 3) / 2;
3649
+ new_row jsonb := to_jsonb(NEW);
3650
+ old_row jsonb := CASE WHEN TG_OP = 'UPDATE' THEN to_jsonb(OLD) END;
3651
+ changed boolean := TG_OP = 'INSERT';
3652
+ condition text := '';
3653
+ found boolean;
3654
+ BEGIN
3655
+ IF current_user::text = TG_ARGV[0] THEN
3656
+ RETURN NEW;
3657
+ END IF;
3658
+ FOR i IN 0 .. n - 1 LOOP
3659
+ IF new_row -> TG_ARGV[3 + i] = 'null'::jsonb OR NOT new_row ? TG_ARGV[3 + i] THEN
3660
+ RETURN NEW;
3661
+ END IF;
3662
+ IF NOT changed AND (new_row -> TG_ARGV[3 + i]) IS DISTINCT FROM (old_row -> TG_ARGV[3 + i]) THEN
3663
+ changed := true;
3664
+ END IF;
3665
+ condition := condition || CASE WHEN i > 0 THEN ' AND ' ELSE '' END
3666
+ || format('p.%I = ($1).%I', TG_ARGV[3 + n + i], TG_ARGV[3 + i]);
3667
+ END LOOP;
3668
+ IF NOT changed THEN
3669
+ RETURN NEW;
3670
+ END IF;
3671
+ EXECUTE format('SELECT EXISTS (SELECT 1 FROM %I.%I p WHERE %s)', TG_ARGV[1], TG_ARGV[2], condition)
3672
+ INTO found USING NEW;
3673
+ IF NOT found THEN
3674
+ RAISE EXCEPTION 'A record of %.% refers to a record that does not exist or that the caller cannot read',
3675
+ TG_TABLE_SCHEMA, TG_TABLE_NAME USING ERRCODE = 'insufficient_privilege';
3676
+ END IF;
3677
+ RETURN NEW;
3678
+ END
3679
+ $$`,
3680
+ `REVOKE ALL ON FUNCTION eloxiv.guard_reference() FROM PUBLIC`,
3681
+ ],
3682
+ }
3683
+
3684
+ /**
3685
+ * The event an event automation's run is for: Retention keeps an event while a run recorded for it has not finished
3686
+ * (still waiting to start, or running), however long that takes.
3687
+ */
3688
+ const runEvents: Migration = {
3689
+ name: "0210_run_events",
3690
+ statements: [
3691
+ `ALTER TABLE eloxiv.schedule_run ADD COLUMN IF NOT EXISTS event_id text`,
3692
+ `CREATE INDEX IF NOT EXISTS schedule_run_event ON eloxiv.schedule_run (event_id) WHERE event_id IS NOT NULL`,
3693
+ ],
3694
+ }
3695
+
3696
+ /**
3697
+ * Whether an external effect's module was told its outcome (connections/Effects.ts, `report`): `told`, or `refused`
3698
+ * (the authority the call that scheduled it was bound to no longer holds, so the module's callback is refused and
3699
+ * the module reconciles from the kernel's record on its own later work). Null while it has not been told. (0151 to
3700
+ * 0164 are other branches'.) Safe to apply again.
3701
+ */
3702
+ const effectReported: Migration = {
3703
+ name: "0165_effect_reported",
3704
+ statements: [
3705
+ `ALTER TABLE eloxiv.connection_effect ADD COLUMN IF NOT EXISTS reported text`,
3706
+ `ALTER TABLE eloxiv.connection_effect DROP CONSTRAINT IF EXISTS connection_effect_reported_check`,
3707
+ `ALTER TABLE eloxiv.connection_effect ADD CONSTRAINT connection_effect_reported_check
3708
+ CHECK (reported IS NULL OR reported IN ('told', 'refused'))`,
3709
+ ],
3710
+ }
3711
+
3712
+ /**
3713
+ * A channel connector's channels (connections/Connections.ts `setChannel`, ingress/Ingress.ts `sendToAgent`): per
3714
+ * receiving Connection and channel, whether the agent answers there, its scope (`act`, or `plan`: it reads and plans
3715
+ * but changes nothing), a daily token budget and what it remembers (`thread`: one conversation per thread and
3716
+ * person; `channel`: per channel and person; `none`). The conversation each thread (or channel) continues, per person,
3717
+ * and each message the channel admitted: its reservation, then its run (whose tokens, and its delegates', are what
3718
+ * the channel spent). Safe to apply again.
3719
+ */
3720
+ const channelSettings: Migration = {
3721
+ name: "0166_channel_settings",
3722
+ statements: [
3723
+ `CREATE TABLE IF NOT EXISTS eloxiv.channel_setting (
3724
+ connection_id text NOT NULL,
3725
+ channel_id text NOT NULL,
3726
+ org_id text NOT NULL,
3727
+ enabled boolean NOT NULL DEFAULT true,
3728
+ scope text NOT NULL DEFAULT 'act' CHECK (scope IN ('act', 'plan')),
3729
+ daily_tokens integer CHECK (daily_tokens IS NULL OR daily_tokens >= 0),
3730
+ memory text NOT NULL DEFAULT 'thread' CHECK (memory IN ('thread', 'channel', 'none')),
3731
+ updated_at timestamptz NOT NULL DEFAULT now(),
3732
+ PRIMARY KEY (connection_id, channel_id)
3733
+ )`,
3734
+ `CREATE TABLE IF NOT EXISTS eloxiv.channel_conversation (
3735
+ connection_id text NOT NULL,
3736
+ channel_id text NOT NULL,
3737
+ thread_key text NOT NULL,
3738
+ org_id text NOT NULL,
3739
+ user_id text NOT NULL,
3740
+ conversation_id text NOT NULL,
3741
+ updated_at timestamptz NOT NULL DEFAULT now(),
3742
+ PRIMARY KEY (connection_id, channel_id, thread_key, user_id)
3743
+ )`,
3744
+ `CREATE TABLE IF NOT EXISTS eloxiv.channel_run (
3745
+ id text PRIMARY KEY,
3746
+ run_id text UNIQUE,
3747
+ connection_id text NOT NULL,
3748
+ channel_id text NOT NULL,
3749
+ org_id text NOT NULL,
3750
+ user_id text NOT NULL,
3751
+ reserved integer NOT NULL DEFAULT 0,
3752
+ created_at timestamptz NOT NULL DEFAULT now()
3753
+ )`,
3754
+ `CREATE INDEX IF NOT EXISTS channel_run_day_idx ON eloxiv.channel_run (connection_id, channel_id, created_at)`,
3755
+ ],
3756
+ }
3757
+
3758
+ /**
3759
+ * An external effect's provider answer is kept only until the module is told (backlog 14): once its `onDone` action
3760
+ * has run, `result` is cleared and `told_at` says why it is empty, so a succeeded effect is one with its answer or one
3761
+ * whose module has it. The outcome (state, reconciled, error, attempts) stays. Safe to apply again.
3762
+ */
3763
+ const effectResultTold: Migration = {
3764
+ name: "0215_effect_result_told",
3765
+ statements: [
3766
+ `ALTER TABLE eloxiv.connection_effect ADD COLUMN IF NOT EXISTS told_at timestamptz`,
3767
+ `ALTER TABLE eloxiv.connection_effect DROP CONSTRAINT IF EXISTS connection_effect_result`,
3768
+ `ALTER TABLE eloxiv.connection_effect ADD CONSTRAINT connection_effect_result
3769
+ CHECK (state <> 'succeeded' OR result IS NOT NULL OR told_at IS NOT NULL)`,
3770
+ ],
3771
+ }
3772
+
3773
+ /**
3774
+ * Why an effect's provider answer is empty, once it is (backlog 14): `told` (its module's `onDone` action ran),
3775
+ * `no-callback` (its action named none: nothing will read it, so it goes once the outcome is recorded), `expired` (its
3776
+ * module could not be told, a refused or exhausted callback, and the retention window for its own reconciling passed)
3777
+ * or `erased` (an erasure of a person it mentioned). A succeeded effect is one with its answer or one that says why it
3778
+ * has none. Effects already told say so. Safe to apply again.
3779
+ */
3780
+ const effectResultCleared: Migration = {
3781
+ name: "0240_effect_result_cleared",
3782
+ statements: [
3783
+ `ALTER TABLE eloxiv.connection_effect ADD COLUMN IF NOT EXISTS result_cleared text`,
3784
+ `ALTER TABLE eloxiv.connection_effect DROP CONSTRAINT IF EXISTS connection_effect_result_cleared_check`,
3785
+ `ALTER TABLE eloxiv.connection_effect ADD CONSTRAINT connection_effect_result_cleared_check
3786
+ CHECK (result_cleared IS NULL OR result_cleared IN ('told', 'no-callback', 'expired', 'erased'))`,
3787
+ `UPDATE eloxiv.connection_effect SET result_cleared = 'told'
3788
+ WHERE told_at IS NOT NULL AND result IS NULL AND state = 'succeeded' AND result_cleared IS NULL`,
3789
+ `ALTER TABLE eloxiv.connection_effect DROP CONSTRAINT IF EXISTS connection_effect_result`,
3790
+ `ALTER TABLE eloxiv.connection_effect ADD CONSTRAINT connection_effect_result
3791
+ CHECK (state <> 'succeeded' OR result IS NOT NULL OR result_cleared IS NOT NULL)`,
3792
+ // The retention sweep's and an erasure's search: the answers still kept.
3793
+ `CREATE INDEX IF NOT EXISTS connection_effect_kept_result_idx ON eloxiv.connection_effect (org_id, finished_at)
3794
+ WHERE result IS NOT NULL`,
3795
+ ],
3796
+ }
3797
+
3798
+ /**
3799
+ * A session's live facts exist before its replica's first query (backlog 41): a session starting records its fact in
3800
+ * every organisation its person belongs to (a trigger on `auth.session`), and a membership added later records the
3801
+ * facts of the person's live sessions in it (`refresh_sync_facts`), so they have replicated by the time a client
3802
+ * connects, and a query's first complete answer is never empty for want of them. Leaving an organisation removes its
3803
+ * session facts there. The query endpoint still records the fact (a session started before this migration).
3804
+ *
3805
+ * Writers of session facts are serialised with each other and with the ending of sessions, and each reads what it
3806
+ * depends on only once it holds its locks (a statement of its own, so a snapshot taken after them):
3807
+ *
3808
+ * - the session start and every refresh take the person's lock (`eloxiv.sync-facts:<user>`), so a session starting
3809
+ * while a membership is added is seen by whichever of the two runs second (each would miss the other's uncommitted
3810
+ * row);
3811
+ * - a refresh then takes each of the person's sessions' locks shared, the ones their endings take (a sign-out's
3812
+ * `eloxiv.session-request:<id>`, the set-based ending's `eloxiv.session:<id>`), so it never reads a session whose
3813
+ * ending has not committed yet as live, and an ending that waits for it finds the fact it wrote;
3814
+ * - a revocation deletes the session's facts by trigger, in a statement of its own after the ending's locks, so a fact
3815
+ * a refresh committed while the ending waited is deleted too (the ending's own statement read the facts before).
3816
+ *
3817
+ * One global order, so no two of these wait for each other: directory locks (`lock_directory`), sorted by
3818
+ * organisation, then the person's lock, then sessions' request locks. A change of a person's email takes every
3819
+ * directory lock of theirs before its first refresh (it took them one by one between refreshes, so it held the
3820
+ * person's lock while it waited for an organisation's); a membership row moved between organisations takes its two in
3821
+ * order (`sync_person_changed` and `sync_member_changed_ordered`, which the triggers run instead of 0024's functions).
3822
+ * Work that holds a session's row takes its request lock first, in sign-out's order (Sessions.ts).
3823
+ *
3824
+ * Safe to apply again.
3825
+ */
3826
+ const sessionFactsAtStart: Migration = {
3827
+ name: "0216_session_facts_at_start",
3828
+ statements: [
3829
+ `CREATE OR REPLACE FUNCTION eloxiv.sync_session_started() RETURNS trigger
3830
+ LANGUAGE plpgsql SET search_path = pg_catalog AS $$
3831
+ BEGIN
3832
+ PERFORM pg_advisory_xact_lock(hashtextextended('eloxiv.sync-facts:' || NEW."userId", 0));
3833
+ INSERT INTO eloxiv.sync_fact (org_id, user_id, kind, value)
3834
+ SELECT m.org_id, NEW."userId", 'session', NEW.id FROM eloxiv.membership m WHERE m.user_id = NEW."userId"
3835
+ ON CONFLICT DO NOTHING;
3836
+ RETURN NEW;
3837
+ END $$`,
3838
+ `REVOKE ALL ON FUNCTION eloxiv.sync_session_started() FROM PUBLIC`,
3839
+ `CREATE OR REPLACE TRIGGER eloxiv_sync_session_started AFTER INSERT ON auth.session
3840
+ FOR EACH ROW EXECUTE FUNCTION eloxiv.sync_session_started()`,
3841
+ `CREATE OR REPLACE FUNCTION eloxiv.sync_session_revoked() RETURNS trigger
3842
+ LANGUAGE plpgsql SET search_path = pg_catalog AS $$
3843
+ BEGIN
3844
+ DELETE FROM eloxiv.sync_fact WHERE kind = 'session' AND value = NEW.session_id;
3845
+ RETURN NULL;
3846
+ END $$`,
3847
+ `REVOKE ALL ON FUNCTION eloxiv.sync_session_revoked() FROM PUBLIC`,
3848
+ `CREATE OR REPLACE TRIGGER eloxiv_sync_session_revoked AFTER INSERT ON eloxiv.session_revocation
3849
+ FOR EACH ROW EXECUTE FUNCTION eloxiv.sync_session_revoked()`,
3850
+ `CREATE OR REPLACE FUNCTION eloxiv.refresh_sync_facts(p_org text, p_user text) RETURNS void
3851
+ LANGUAGE plpgsql SET search_path = pg_catalog AS $$
3852
+ BEGIN
3853
+ PERFORM pg_advisory_xact_lock(hashtextextended('eloxiv.sync-facts:' || p_user, 0));
3854
+ PERFORM pg_advisory_xact_lock_shared(hashtextextended('eloxiv.session-request:' || s.id, 0)),
3855
+ pg_advisory_xact_lock_shared(hashtextextended('eloxiv.session:' || s.id, 0))
3856
+ FROM (SELECT id FROM auth.session WHERE "userId" = p_user ORDER BY id) s;
3857
+ WITH wanted (kind, value) AS (
3858
+ SELECT 'member', '' FROM eloxiv.membership WHERE org_id = p_org AND user_id = p_user
3859
+ UNION SELECT 'group', group_id FROM eloxiv.group_member WHERE org_id = p_org AND user_id = p_user
3860
+ UNION SELECT 'role', role_id FROM eloxiv.membership_role WHERE org_id = p_org AND user_id = p_user
3861
+ UNION SELECT 'permission', p.permission FROM eloxiv.membership_role r
3862
+ JOIN eloxiv.role_permission p ON p.org_id = r.org_id AND p.role_id = r.role_id
3863
+ WHERE r.org_id = p_org AND r.user_id = p_user
3864
+ UNION SELECT 'email',
3865
+ coalesce((SELECT u.email FROM auth."user" u WHERE u.id = m.user_id AND u."emailVerified"), '')
3866
+ FROM eloxiv.membership m WHERE m.org_id = p_org AND m.user_id = p_user
3867
+ UNION SELECT 'session', s.id FROM eloxiv.membership m JOIN auth.session s ON s."userId" = m.user_id
3868
+ WHERE m.org_id = p_org AND m.user_id = p_user AND s."expiresAt" > clock_timestamp()
3869
+ AND NOT EXISTS (SELECT 1 FROM eloxiv.session_revocation r WHERE r.session_id = s.id)
3870
+ ), removed AS (
3871
+ DELETE FROM eloxiv.sync_fact f WHERE f.org_id = p_org AND f.user_id = p_user
3872
+ AND (f.kind <> 'session'
3873
+ OR NOT EXISTS (SELECT 1 FROM eloxiv.membership m WHERE m.org_id = p_org AND m.user_id = p_user))
3874
+ AND NOT EXISTS (SELECT 1 FROM wanted w WHERE w.kind = f.kind AND w.value = f.value)
3875
+ )
3876
+ INSERT INTO eloxiv.sync_fact (org_id, user_id, kind, value)
3877
+ SELECT p_org, p_user, kind, value FROM wanted ON CONFLICT DO NOTHING;
3878
+ END $$`,
3879
+ `REVOKE ALL ON FUNCTION eloxiv.refresh_sync_facts(text, text) FROM PUBLIC`,
3880
+ `CREATE OR REPLACE FUNCTION eloxiv.sync_member_changed_ordered() RETURNS trigger
3881
+ LANGUAGE plpgsql SET search_path = pg_catalog AS $$
3882
+ BEGIN
3883
+ IF TG_OP = 'UPDATE' THEN
3884
+ PERFORM eloxiv.lock_directory(least(OLD.org_id, NEW.org_id));
3885
+ PERFORM eloxiv.lock_directory(greatest(OLD.org_id, NEW.org_id));
3886
+ ELSIF TG_OP = 'DELETE' THEN
3887
+ PERFORM eloxiv.lock_directory(OLD.org_id);
3888
+ ELSE
3889
+ PERFORM eloxiv.lock_directory(NEW.org_id);
3890
+ END IF;
3891
+ IF TG_OP IN ('UPDATE', 'DELETE') THEN PERFORM eloxiv.refresh_sync_facts(OLD.org_id, OLD.user_id); END IF;
3892
+ IF TG_OP IN ('UPDATE', 'INSERT') THEN PERFORM eloxiv.refresh_sync_facts(NEW.org_id, NEW.user_id); END IF;
3893
+ RETURN NULL;
3894
+ END
3895
+ $$`,
3896
+ `CREATE OR REPLACE FUNCTION eloxiv.sync_person_changed() RETURNS trigger
3897
+ LANGUAGE plpgsql SET search_path = pg_catalog AS $$
3898
+ DECLARE m record;
3899
+ BEGIN
3900
+ FOR m IN SELECT org_id FROM eloxiv.membership WHERE user_id = NEW.id ORDER BY org_id LOOP
3901
+ PERFORM eloxiv.lock_directory(m.org_id);
3902
+ END LOOP;
3903
+ FOR m IN SELECT org_id FROM eloxiv.membership WHERE user_id = NEW.id ORDER BY org_id LOOP
3904
+ PERFORM eloxiv.refresh_sync_facts(m.org_id, NEW.id);
3905
+ END LOOP;
3906
+ RETURN NULL;
3907
+ END
3908
+ $$`,
3909
+ `REVOKE ALL ON FUNCTION eloxiv.sync_member_changed_ordered(), eloxiv.sync_person_changed() FROM PUBLIC`,
3910
+ // The triggers run them; 0024's functions of the old names stay as that migration made them.
3911
+ `CREATE OR REPLACE TRIGGER eloxiv_sync_facts AFTER INSERT OR UPDATE OR DELETE ON eloxiv.membership
3912
+ FOR EACH ROW EXECUTE FUNCTION eloxiv.sync_member_changed_ordered()`,
3913
+ `CREATE OR REPLACE TRIGGER eloxiv_sync_facts AFTER INSERT OR UPDATE OR DELETE ON eloxiv.group_member
3914
+ FOR EACH ROW EXECUTE FUNCTION eloxiv.sync_member_changed_ordered()`,
3915
+ `CREATE OR REPLACE TRIGGER eloxiv_sync_facts AFTER INSERT OR UPDATE OR DELETE ON eloxiv.membership_role
3916
+ FOR EACH ROW EXECUTE FUNCTION eloxiv.sync_member_changed_ordered()`,
3917
+ `CREATE OR REPLACE TRIGGER eloxiv_sync_facts AFTER INSERT OR UPDATE OF email, "emailVerified" ON auth."user"
3918
+ FOR EACH ROW EXECUTE FUNCTION eloxiv.sync_person_changed()`,
3919
+ ],
3920
+ }
3921
+
3922
+ /**
3923
+ * Which of zero-cache's client groups each person's replicas use, so an erasure purges their client view records at
3924
+ * once (backlog 21, privacy/ZeroCvr.ts). A group is claimed only by a push zero-cache forwarded (the push carries
3925
+ * zero-cache's API key, `ELOXIV_ZERO_API_KEY`, and the token of the connection the group's replica holds), and
3926
+ * belongs to the first person and organisation that claimed it: a push for it as anyone else is refused. `shard` is
3927
+ * zero-cache's (`<app id>_<n>`), whose client view records are in `<shard>/cvr`. Safe to apply again.
3928
+ */
3929
+ const syncClientGroups: Migration = {
3930
+ name: "0217_sync_client_groups",
3931
+ statements: [
3932
+ `CREATE TABLE IF NOT EXISTS eloxiv.sync_client_group (
3933
+ shard text NOT NULL CHECK (shard ~ '^[A-Za-z0-9_]{1,60}_[0-9]{1,9}$'),
3934
+ client_group_id text NOT NULL CHECK (client_group_id ~ '^[A-Za-z0-9_-]{1,100}$'),
3935
+ org_id text NOT NULL REFERENCES eloxiv.organization(id) ON DELETE CASCADE,
3936
+ user_id text NOT NULL,
3937
+ seen_at timestamptz NOT NULL DEFAULT now(),
3938
+ PRIMARY KEY (shard, client_group_id)
3939
+ )`,
3940
+ `CREATE INDEX IF NOT EXISTS sync_client_group_user_idx ON eloxiv.sync_client_group (org_id, user_id)`,
3941
+ ],
3942
+ }
3943
+
3944
+ /**
3945
+ * A MAKE call's receipt names the events it committed (ledger C-004), as an ordinary call's does: `make_finish` writes
3946
+ * the module's events first, then commits the receipt with a reference to every outbox row of the invocation (those
3947
+ * the module emitted and any the kernel published for it), in order, by CloudEvents identity, never a payload. Same
3948
+ * signature, so the module runtime roles' grants stay. Safe to apply again.
3949
+ */
3950
+ const makeReceiptEvents: Migration = {
3951
+ name: "0235_make_receipt_events",
3952
+ statements: [
3953
+ `CREATE OR REPLACE FUNCTION eloxiv_ctx.make_finish(p_ticket text, p_record jsonb) RETURNS void
3954
+ LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
3955
+ DECLARE c record; e jsonb; refs jsonb;
3956
+ BEGIN
3957
+ SELECT * INTO c FROM eloxiv_ctx.make_call_of(p_ticket);
3958
+ FOR e IN SELECT value FROM jsonb_array_elements(coalesce(p_record->'events', '[]'::jsonb)) LOOP
3959
+ IF e->>'type' IS NULL OR NOT pg_catalog.starts_with(e->>'type', c.module || '.') THEN
3960
+ RAISE EXCEPTION 'A MAKE module emits only its own events' USING ERRCODE = 'insufficient_privilege';
3961
+ END IF;
3962
+ INSERT INTO eloxiv.outbox (id, invocation_id, type, module, org_id, payload)
3963
+ VALUES (gen_random_uuid()::text, c.invocation_id, e->>'type', c.module, c.org, e->'payload');
3964
+ PERFORM pg_notify('eloxiv_outbox', c.invocation_id);
3965
+ END LOOP;
3966
+ IF p_record->>'idempotencyKey' IS NOT NULL THEN
3967
+ SELECT coalesce(jsonb_agg(jsonb_build_object('specversion', '1.0', 'id', o.id, 'source', '/modules/' || o.module,
3968
+ 'type', o.type) ORDER BY o.seq), '[]'::jsonb)
3969
+ INTO refs FROM eloxiv.outbox o WHERE o.invocation_id = c.invocation_id;
3970
+ UPDATE eloxiv.idempotency_key
3971
+ SET receipt = (p_record->'receipt') || jsonb_build_object('events', refs),
3972
+ receipt_format = (p_record->>'receiptFormat')::int
3973
+ WHERE org_id = c.org AND actor_user_id = c.actor AND action = c.action AND key = p_record->>'idempotencyKey'
3974
+ AND invocation_id = c.invocation_id;
3975
+ IF NOT FOUND THEN
3976
+ RAISE EXCEPTION 'The MAKE call holds no claim on its idempotency key' USING ERRCODE = 'insufficient_privilege';
3977
+ END IF;
3978
+ END IF;
3979
+ INSERT INTO eloxiv.audit_log (id, invocation_id, action, surface, actor_user_id, org_id, outcome, input_hash,
3980
+ idempotency_key, error_tag, affected, requested, completion)
3981
+ VALUES (gen_random_uuid()::text, c.invocation_id, c.action, p_record->>'surface', c.actor, c.org, 'succeeded',
3982
+ p_record->>'inputHash', p_record->>'idempotencyKey', NULL, (p_record->'completion'->>'affected')::int,
3983
+ (p_record->'completion'->>'requested')::int, p_record->'completion'->>'completion');
3984
+ UPDATE eloxiv.make_call SET state = 'finished' WHERE xid = pg_current_xact_id();
3985
+ END
3986
+ $$`,
3987
+ `REVOKE ALL ON FUNCTION eloxiv_ctx.make_finish(text, jsonb) FROM PUBLIC`,
3988
+ ],
3989
+ }
3990
+
3991
+ /**
3992
+ * MCP App sessions (ledger A-081, `connections.openApp`): one person's open view of a ToolSource tool's `ui://`
3993
+ * resource, with the tools the view may call. Closing deletes it; one past its lifetime is refused and deleted by its
3994
+ * person's next open. Safe to apply again.
3995
+ */
3996
+ const mcpAppSessions: Migration = {
3997
+ name: "0236_mcp_app_sessions",
3998
+ statements: [
3999
+ `CREATE TABLE IF NOT EXISTS eloxiv.mcp_app_session (
4000
+ id text PRIMARY KEY,
4001
+ org_id text NOT NULL REFERENCES eloxiv.organization(id) ON DELETE CASCADE,
4002
+ user_id text NOT NULL,
4003
+ connection_id text NOT NULL REFERENCES eloxiv.connection(id) ON DELETE CASCADE,
4004
+ tool text NOT NULL,
4005
+ resource_uri text NOT NULL,
4006
+ tools text[] NOT NULL,
4007
+ opened_at timestamptz NOT NULL DEFAULT now(),
4008
+ expires_at timestamptz NOT NULL
4009
+ )`,
4010
+ `CREATE INDEX IF NOT EXISTS mcp_app_session_user_idx ON eloxiv.mcp_app_session (org_id, user_id)`,
4011
+ ],
4012
+ }
4013
+
4014
+ /**
4015
+ * Session admission (A-015): a person's session is in force only once the kernel has recorded how it was signed in
4016
+ * (`eloxiv.session_method`), so a session Better Auth made for a sign-in the person may not use is never usable. The
4017
+ * sessions that existed before are admitted as signed in by an unrecorded method (`unknown`: every organisation that
4018
+ * restricts its methods refuses them). Written to be safe to apply again.
4019
+ */
4020
+ const sessionAdmission: Migration = {
4021
+ name: "0143_session_admission",
4022
+ statements: [
4023
+ `INSERT INTO eloxiv.session_method (session_id, method) SELECT id, 'unknown' FROM auth.session
4024
+ ON CONFLICT (session_id) DO NOTHING`,
4025
+ ],
4026
+ }
4027
+
4028
+ /**
4029
+ * The credential fence covers a removed password too (the security review of PR #81): Better Auth's cleanup of an
4030
+ * unproven account (a magic link proving its address) deletes the account's credential account before it ends the
4031
+ * sessions, which recorded no change, so a sign-in that read the old password and paused could still commit its
4032
+ * session after the owner took the account back. The deletion of a credential account is now a change of password
4033
+ * (`eloxiv.credential_changed`, under the request's identity, so the link's own session passes the fence). Written to be
4034
+ * safe to apply again.
4035
+ */
4036
+ const credentialRemoved: Migration = {
4037
+ name: "0142_credential_removed",
4038
+ statements: [
4039
+ `CREATE OR REPLACE FUNCTION eloxiv.credential_removed() RETURNS trigger
4040
+ LANGUAGE plpgsql SET search_path = pg_catalog AS $$
4041
+ BEGIN PERFORM eloxiv.credential_changed(OLD."userId"); RETURN NULL; END $$`,
4042
+ `REVOKE ALL ON FUNCTION eloxiv.credential_removed() FROM PUBLIC`,
4043
+ `CREATE OR REPLACE TRIGGER eloxiv_credential_removed AFTER DELETE ON auth.account
4044
+ FOR EACH ROW WHEN (OLD."providerId" = 'credential') EXECUTE FUNCTION eloxiv.credential_removed()`,
4045
+ ],
4046
+ }
4047
+
4048
+ /**
4049
+ * Sign-in methods in sync (the security review of PR #81): a session's facts in an organisation (`sync_fact` kind
4050
+ * `session`, what its replica's queries test live) exist only while the organisation admits how the session was signed
4051
+ * in (`eloxiv.session_admitted_in`: the organisation sets no methods, or the session's recorded method is among them; a
4052
+ * session not yet admitted, none). Every writer of session facts asks it: the session's start, its admission (the
4053
+ * kernel recording its method, which writes the facts its start could not), and every refresh, which also withdraws a
4054
+ * fact no longer admitted. A change of the organisation's methods (Directory `setSignInMethods`, under its directory
4055
+ * lock, then the people's locks in order, 0216's order) deletes the facts it no longer admits. Written to be safe to
4056
+ * apply again.
4057
+ */
4058
+ const signInMethodFacts: Migration = {
4059
+ name: "0144_sign_in_method_facts",
4060
+ statements: [
4061
+ // In order: a session not admitted yet (a new one, as it starts) is decided without reading the organisation's
4062
+ // methods.
4063
+ `CREATE OR REPLACE FUNCTION eloxiv.session_admitted_in(p_org text, p_session text) RETURNS boolean
4064
+ LANGUAGE plpgsql STABLE SET search_path = pg_catalog AS $$
4065
+ DECLARE v_method text;
4066
+ BEGIN
4067
+ SELECT m.method INTO v_method FROM eloxiv.session_method m WHERE m.session_id = p_session;
4068
+ IF NOT FOUND THEN RETURN false; END IF;
4069
+ RETURN NOT EXISTS (SELECT 1 FROM eloxiv.org_sign_in o WHERE o.org_id = p_org AND o.methods IS NOT NULL
4070
+ AND NOT (v_method = ANY(o.methods)));
4071
+ END $$`,
4072
+ `REVOKE ALL ON FUNCTION eloxiv.session_admitted_in(text, text) FROM PUBLIC`,
4073
+ `CREATE OR REPLACE FUNCTION eloxiv.sync_session_started() RETURNS trigger
4074
+ LANGUAGE plpgsql SET search_path = pg_catalog AS $$
4075
+ BEGIN
4076
+ PERFORM pg_advisory_xact_lock(hashtextextended('eloxiv.sync-facts:' || NEW."userId", 0));
4077
+ INSERT INTO eloxiv.sync_fact (org_id, user_id, kind, value)
4078
+ SELECT m.org_id, NEW."userId", 'session', NEW.id FROM eloxiv.membership m WHERE m.user_id = NEW."userId"
4079
+ AND eloxiv.session_admitted_in(m.org_id, NEW.id)
4080
+ ON CONFLICT DO NOTHING;
4081
+ RETURN NEW;
4082
+ END $$`,
4083
+ `CREATE OR REPLACE FUNCTION eloxiv.sync_session_admitted() RETURNS trigger
4084
+ LANGUAGE plpgsql SET search_path = pg_catalog AS $$
4085
+ DECLARE v_user text;
4086
+ BEGIN
4087
+ SELECT s."userId" INTO v_user FROM auth.session s WHERE s.id = NEW.session_id;
4088
+ IF v_user IS NULL THEN RETURN NULL; END IF;
4089
+ PERFORM pg_advisory_xact_lock(hashtextextended('eloxiv.sync-facts:' || v_user, 0));
4090
+ INSERT INTO eloxiv.sync_fact (org_id, user_id, kind, value)
4091
+ SELECT m.org_id, v_user, 'session', NEW.session_id FROM eloxiv.membership m
4092
+ JOIN auth.session s ON s.id = NEW.session_id AND s."expiresAt" > clock_timestamp()
4093
+ WHERE m.user_id = v_user AND eloxiv.session_admitted_in(m.org_id, NEW.session_id)
4094
+ AND NOT EXISTS (SELECT 1 FROM eloxiv.session_revocation r WHERE r.session_id = NEW.session_id)
4095
+ ON CONFLICT DO NOTHING;
4096
+ RETURN NULL;
4097
+ END $$`,
4098
+ `REVOKE ALL ON FUNCTION eloxiv.sync_session_admitted() FROM PUBLIC`,
4099
+ `CREATE OR REPLACE TRIGGER eloxiv_sync_session_admitted AFTER INSERT ON eloxiv.session_method
4100
+ FOR EACH ROW EXECUTE FUNCTION eloxiv.sync_session_admitted()`,
4101
+ `CREATE OR REPLACE FUNCTION eloxiv.refresh_sync_facts(p_org text, p_user text) RETURNS void
4102
+ LANGUAGE plpgsql SET search_path = pg_catalog AS $$
4103
+ BEGIN
4104
+ PERFORM pg_advisory_xact_lock(hashtextextended('eloxiv.sync-facts:' || p_user, 0));
4105
+ PERFORM pg_advisory_xact_lock_shared(hashtextextended('eloxiv.session-request:' || s.id, 0)),
4106
+ pg_advisory_xact_lock_shared(hashtextextended('eloxiv.session:' || s.id, 0))
4107
+ FROM (SELECT id FROM auth.session WHERE "userId" = p_user ORDER BY id) s;
4108
+ WITH wanted (kind, value) AS (
4109
+ SELECT 'member', '' FROM eloxiv.membership WHERE org_id = p_org AND user_id = p_user
4110
+ UNION SELECT 'group', group_id FROM eloxiv.group_member WHERE org_id = p_org AND user_id = p_user
4111
+ UNION SELECT 'role', role_id FROM eloxiv.membership_role WHERE org_id = p_org AND user_id = p_user
4112
+ UNION SELECT 'permission', p.permission FROM eloxiv.membership_role r
4113
+ JOIN eloxiv.role_permission p ON p.org_id = r.org_id AND p.role_id = r.role_id
4114
+ WHERE r.org_id = p_org AND r.user_id = p_user
4115
+ UNION SELECT 'email',
4116
+ coalesce((SELECT u.email FROM auth."user" u WHERE u.id = m.user_id AND u."emailVerified"), '')
4117
+ FROM eloxiv.membership m WHERE m.org_id = p_org AND m.user_id = p_user
4118
+ UNION SELECT 'session', s.id FROM eloxiv.membership m JOIN auth.session s ON s."userId" = m.user_id
4119
+ WHERE m.org_id = p_org AND m.user_id = p_user AND s."expiresAt" > clock_timestamp()
4120
+ AND NOT EXISTS (SELECT 1 FROM eloxiv.session_revocation r WHERE r.session_id = s.id)
4121
+ AND eloxiv.session_admitted_in(p_org, s.id)
4122
+ ), removed AS (
4123
+ DELETE FROM eloxiv.sync_fact f WHERE f.org_id = p_org AND f.user_id = p_user
4124
+ AND (f.kind <> 'session'
4125
+ OR NOT EXISTS (SELECT 1 FROM eloxiv.membership m WHERE m.org_id = p_org AND m.user_id = p_user)
4126
+ OR NOT eloxiv.session_admitted_in(p_org, f.value))
4127
+ AND NOT EXISTS (SELECT 1 FROM wanted w WHERE w.kind = f.kind AND w.value = f.value)
4128
+ )
4129
+ INSERT INTO eloxiv.sync_fact (org_id, user_id, kind, value)
4130
+ SELECT p_org, p_user, kind, value FROM wanted ON CONFLICT DO NOTHING;
4131
+ END $$`,
4132
+ `REVOKE ALL ON FUNCTION eloxiv.refresh_sync_facts(text, text) FROM PUBLIC`,
4133
+ // The facts the writers before this one made whatever the organisation's methods: the ones it does not admit go.
4134
+ `DELETE FROM eloxiv.sync_fact f WHERE f.kind = 'session' AND NOT eloxiv.session_admitted_in(f.org_id, f.value)`,
4135
+ ],
4136
+ }
4137
+
4138
+ /**
4139
+ * Enterprise sign-in and provisioning through WorkOS (A-016, Directory 1.5.0): an organisation's opt-in
4140
+ * (`org_enterprise`: the WorkOS organisation it is, and whether its members sign in by SSO and are provisioned by
4141
+ * Directory Sync), the pending SSO sign-ins (`sso_attempt`: each state stored hashed, single use, ten minutes), the
4142
+ * Directory Sync events applied (`directory_event`: each event once), the directory's people and groups as the
4143
+ * organisation knows them (`directory_user`, `directory_group`), and the version of each directory resource applied, with
4144
+ * a tombstone once deleted (`directory_resource`: an older event about it changes nothing). `eloxiv.method_admitted`: whether an organisation's
4145
+ * methods admit a session's (`sso` admits every `sso:<connection>`), the one rule every check of methods uses.
4146
+ * (0244 and below are other branches'.) Written to be safe to apply again.
4147
+ */
4148
+ const enterpriseAuth: Migration = {
4149
+ name: "0245_enterprise_auth",
4150
+ statements: [
4151
+ `CREATE TABLE IF NOT EXISTS eloxiv.org_enterprise (
4152
+ org_id text PRIMARY KEY REFERENCES eloxiv.organization(id) ON DELETE CASCADE,
4153
+ workos_organization_id text NOT NULL,
4154
+ sso boolean NOT NULL DEFAULT false,
4155
+ directory_sync boolean NOT NULL DEFAULT false,
4156
+ updated_at timestamptz NOT NULL DEFAULT now()
4157
+ )`,
4158
+ `CREATE INDEX IF NOT EXISTS org_enterprise_workos ON eloxiv.org_enterprise (workos_organization_id)`,
4159
+ `CREATE TABLE IF NOT EXISTS eloxiv.sso_attempt (
4160
+ state_hash text PRIMARY KEY,
4161
+ org_id text NOT NULL REFERENCES eloxiv.organization(id) ON DELETE CASCADE,
4162
+ return_to text NOT NULL,
4163
+ expires_at timestamptz NOT NULL
4164
+ )`,
4165
+ `CREATE TABLE IF NOT EXISTS eloxiv.directory_event (
4166
+ id text PRIMARY KEY,
4167
+ received_at timestamptz NOT NULL DEFAULT now()
4168
+ )`,
4169
+ `CREATE INDEX IF NOT EXISTS directory_event_received ON eloxiv.directory_event (received_at)`,
4170
+ `CREATE TABLE IF NOT EXISTS eloxiv.directory_user (
4171
+ org_id text NOT NULL REFERENCES eloxiv.organization(id) ON DELETE CASCADE,
4172
+ external_id text NOT NULL,
4173
+ directory_id text NOT NULL,
4174
+ user_id text NOT NULL,
4175
+ PRIMARY KEY (org_id, external_id)
4176
+ )`,
4177
+ // Each directory resource's latest version applied (its `updated_at`; a membership's, the event's `created_at`),
4178
+ // and whether it was deleted: an older event about it (WorkOS may deliver out of order) changes nothing.
4179
+ `CREATE TABLE IF NOT EXISTS eloxiv.directory_resource (
4180
+ org_id text NOT NULL REFERENCES eloxiv.organization(id) ON DELETE CASCADE,
4181
+ kind text NOT NULL,
4182
+ external_id text NOT NULL,
4183
+ version timestamptz NOT NULL,
4184
+ deleted boolean NOT NULL DEFAULT false,
4185
+ PRIMARY KEY (org_id, kind, external_id)
4186
+ )`,
4187
+ `CREATE TABLE IF NOT EXISTS eloxiv.directory_group (
4188
+ org_id text NOT NULL REFERENCES eloxiv.organization(id) ON DELETE CASCADE,
4189
+ external_id text NOT NULL,
4190
+ directory_id text NOT NULL,
4191
+ group_id text NOT NULL,
4192
+ PRIMARY KEY (org_id, external_id)
4193
+ )`,
4194
+ `CREATE OR REPLACE FUNCTION eloxiv.method_admitted(p_methods text[], p_method text) RETURNS boolean
4195
+ LANGUAGE sql IMMUTABLE SET search_path = pg_catalog AS $$
4196
+ SELECT p_methods IS NULL OR coalesce(p_method = ANY(p_methods), false)
4197
+ OR coalesce(p_method LIKE 'sso:%' AND 'sso' = ANY(p_methods), false)
4198
+ $$`,
4199
+ // A session's sync facts follow the same rule (0144's function, which compared methods exactly).
4200
+ `CREATE OR REPLACE FUNCTION eloxiv.session_admitted_in(p_org text, p_session text) RETURNS boolean
4201
+ LANGUAGE plpgsql STABLE SET search_path = pg_catalog AS $$
4202
+ DECLARE v_method text;
4203
+ BEGIN
4204
+ SELECT m.method INTO v_method FROM eloxiv.session_method m WHERE m.session_id = p_session;
4205
+ IF NOT FOUND THEN RETURN false; END IF;
4206
+ RETURN NOT EXISTS (SELECT 1 FROM eloxiv.org_sign_in o WHERE o.org_id = p_org
4207
+ AND NOT eloxiv.method_admitted(o.methods, v_method));
4208
+ END $$`,
4209
+ `REVOKE ALL ON FUNCTION eloxiv.session_admitted_in(text, text) FROM PUBLIC`,
4210
+ ],
4211
+ }
4212
+
4213
+ /**
4214
+ * Session tokens stored as their digests (backlog 44, `auth/SessionTokens.ts`): every session stored before keeps
4215
+ * working, its token replaced in place by `sha256:<hex of SHA-256>`, which is what the kernel and its auth provider
4216
+ * store and match from now on. A kernel of an earlier build still running looks tokens up as issued, so its people
4217
+ * sign in again once this applies. Safe to apply again: a digest is never digested twice.
4218
+ */
4219
+ const hashedSessionTokens: Migration = {
4220
+ name: "0246_hashed_session_tokens",
4221
+ statements: [
4222
+ `UPDATE auth.session SET token = 'sha256:' || encode(sha256(convert_to(token, 'UTF8')), 'hex')
4223
+ WHERE token NOT LIKE 'sha256:%'`,
4224
+ ],
4225
+ }
4226
+
4227
+ /**
4228
+ * Push notifications (Notifications 1.2.0, NotificationChannel 1.1.0; `notifications/Push.ts`):
4229
+ *
4230
+ * - `push_installation`: an app installation's APNs or FCM token, registered by a person from their own session
4231
+ * (`notifications.registerInstallation`), one row per person and installation (registering again replaces the
4232
+ * token), a token in one installation at a time. Bound to the registering session: deleting the session (sign-out,
4233
+ * the sweep) or revoking it deletes the row (the triggers below), so a signed-out device gets nothing more.
4234
+ * `token_digest` (the token's SHA-256) is what the token's uniqueness is kept on: a token may be 4 KiB, more than
4235
+ * a B-tree entry holds. `generation` counts the registrations that changed the row (its token, app, environment or
4236
+ * session); `updated_at` is when it was last registered. `invalidated_at`: the provider said the token is dead
4237
+ * (only for the registration it was sent to, and for APNs only if APNs's verdict is newer than that registration).
4238
+ * - `push_delivery`: each installation's state for a notification's push delivery, written on a connection of its own:
4239
+ * `sending` before the request goes to the provider (its answer, if it is lost, leaves it so), then `sent`,
4240
+ * `failed` (for good: the token dead, or the payload refused), `retrying` (refused for now) or `uncertain` (the
4241
+ * answer was lost: sent again, at least once). A retry sends only to an installation with no state, `retrying`,
4242
+ * `uncertain` or `sending`.
4243
+ * - `notification_decision`: the single-use decision token of an approval or consent push, per notification and
4244
+ * installation: its SHA-256 only (the token exists only in the provider payload), what it may decide, its expiry,
4245
+ * the registering session and the installation's generation it was sent to (a token of another registration never
4246
+ * redeems), and once redeemed when and the recorded answer.
4247
+ *
4248
+ * Safe to apply again.
4249
+ */
4250
+ const pushNotifications: Migration = {
4251
+ name: "0250_push_notifications",
4252
+ statements: [
4253
+ `CREATE TABLE IF NOT EXISTS eloxiv.push_installation (
4254
+ id text PRIMARY KEY,
4255
+ user_id text NOT NULL,
4256
+ installation_id text NOT NULL,
4257
+ provider text NOT NULL CHECK (provider IN ('apns', 'fcm')),
4258
+ token text NOT NULL,
4259
+ token_digest text NOT NULL,
4260
+ app_id text NOT NULL,
4261
+ environment text CHECK (environment IN ('production', 'sandbox')),
4262
+ session_id text NOT NULL,
4263
+ generation bigint NOT NULL DEFAULT 1,
4264
+ created_at timestamptz NOT NULL DEFAULT now(),
4265
+ updated_at timestamptz NOT NULL DEFAULT now(),
4266
+ invalidated_at timestamptz,
4267
+ UNIQUE (user_id, installation_id),
4268
+ UNIQUE (provider, token_digest)
4269
+ )`,
4270
+ `CREATE INDEX IF NOT EXISTS push_installation_session_idx ON eloxiv.push_installation (session_id)`,
4271
+ `CREATE TABLE IF NOT EXISTS eloxiv.push_delivery (
4272
+ delivery_id text NOT NULL,
4273
+ installation_id text NOT NULL,
4274
+ org_id text NOT NULL,
4275
+ user_id text NOT NULL,
4276
+ status text NOT NULL CHECK (status IN ('sending', 'sent', 'failed', 'retrying', 'uncertain')),
4277
+ provider_id text,
4278
+ attempts integer NOT NULL DEFAULT 0,
4279
+ last_error text,
4280
+ updated_at timestamptz NOT NULL DEFAULT now(),
4281
+ PRIMARY KEY (delivery_id, installation_id)
4282
+ )`,
4283
+ `CREATE INDEX IF NOT EXISTS push_delivery_subject_idx ON eloxiv.push_delivery (org_id, user_id)`,
4284
+ `CREATE INDEX IF NOT EXISTS push_delivery_updated_idx ON eloxiv.push_delivery (updated_at)`,
4285
+ `CREATE TABLE IF NOT EXISTS eloxiv.notification_decision (
4286
+ token_hash text PRIMARY KEY,
4287
+ user_id text NOT NULL,
4288
+ org_id text NOT NULL,
4289
+ kind text NOT NULL CHECK (kind IN ('approval', 'consent')),
4290
+ request_id text NOT NULL,
4291
+ verdicts jsonb NOT NULL,
4292
+ notification_id text NOT NULL,
4293
+ installation_id text,
4294
+ session_id text,
4295
+ generation bigint,
4296
+ expires_at timestamptz NOT NULL,
4297
+ used_at timestamptz,
4298
+ outcome jsonb,
4299
+ created_at timestamptz NOT NULL DEFAULT now()
4300
+ )`,
4301
+ `CREATE INDEX IF NOT EXISTS notification_decision_subject_idx ON eloxiv.notification_decision (org_id, user_id)`,
4302
+ `CREATE INDEX IF NOT EXISTS notification_decision_expiry_idx ON eloxiv.notification_decision (expires_at)`,
4303
+ `CREATE OR REPLACE FUNCTION eloxiv.push_session_ended() RETURNS trigger
4304
+ LANGUAGE plpgsql SET search_path = pg_catalog AS $$
4305
+ BEGIN
4306
+ IF TG_TABLE_NAME = 'session' THEN
4307
+ DELETE FROM eloxiv.push_installation WHERE session_id = OLD.id;
4308
+ ELSE
4309
+ DELETE FROM eloxiv.push_installation WHERE session_id = NEW.session_id;
4310
+ END IF;
4311
+ RETURN NULL;
4312
+ END $$`,
4313
+ `REVOKE ALL ON FUNCTION eloxiv.push_session_ended() FROM PUBLIC`,
4314
+ `CREATE OR REPLACE TRIGGER eloxiv_push_session_deleted AFTER DELETE ON auth.session
4315
+ FOR EACH ROW EXECUTE FUNCTION eloxiv.push_session_ended()`,
4316
+ `CREATE OR REPLACE TRIGGER eloxiv_push_session_revoked AFTER INSERT ON eloxiv.session_revocation
4317
+ FOR EACH ROW EXECUTE FUNCTION eloxiv.push_session_ended()`,
4318
+ ],
4319
+ }
4320
+
4321
+ export const allKernelMigrations: ReadonlyArray<Migration> = [
4322
+ ...kernelMigrations,
4323
+ invocationSafety,
4324
+ rlsContext,
4325
+ hardening,
4326
+ completionAndDependencies,
4327
+ identities,
4328
+ dependencyFormat,
4329
+ replayReceipts,
4330
+ directory,
4331
+ durableWork,
4332
+ auditDetail,
4333
+ syncDirectory,
4334
+ agentSessions,
4335
+ membershipChecks,
4336
+ machineIdentity,
4337
+ ingress,
4338
+ deadLetters,
4339
+ settingsAndFlags,
4340
+ agentManage,
4341
+ ingressSignedHash,
4342
+ sharing,
4343
+ sharingOrganisation,
4344
+ connections,
4345
+ devices,
4346
+ serialisedSyncFacts,
4347
+ ownerMigrations,
4348
+ hardeningState,
4349
+ syncGuards,
4350
+ spacesManage,
4351
+ filesSearchIngestion,
4352
+ platformServices,
4353
+ make,
4354
+ jsonSubjects,
4355
+ agentSessionAuthority,
4356
+ consentUse,
4357
+ collabDocuments,
4358
+ connectionEffects,
4359
+ ingestedContentErasure,
4360
+ ingestionScrub,
4361
+ derivedIngestion,
4362
+ derivedInvalidation,
4363
+ derivedDocuments,
4364
+ recordGenerations,
4365
+ workItemGenerations,
4366
+ scheduledRunStarts,
4367
+ makeSubscribers,
4368
+ effectNotBefore,
4369
+ sessionRevocation,
4370
+ syncSessionFacts,
4371
+ sessionSweepIndexes,
4372
+ sessionRequestWaits,
4373
+ endpointConnections,
4374
+ runOutcomes,
4375
+ retention,
4376
+ modelSetup,
4377
+ collabSnapshots,
4378
+ devicePush,
4379
+ auditLineage,
4380
+ searchEmbeddings,
4381
+ privacyVisits,
4382
+ ingressReply,
4383
+ subscriberContext,
4384
+ runOrganisations,
4385
+ directoryAdministration,
4386
+ userAvatars,
4387
+ verifiedEmailPolicy,
4388
+ emailChanges,
4389
+ ingestionRuns,
4390
+ agentEditGroups,
4391
+ fileAuthority,
4392
+ constraintDisclosure,
4393
+ credentialFence,
4394
+ accountWriteFence,
4395
+ domainChecks,
4396
+ accountMail,
4397
+ runEvents,
4398
+ effectReported,
4399
+ channelSettings,
4400
+ sandboxData,
4401
+ proposals,
4402
+ storageProviders,
4403
+ effectResultTold,
4404
+ sessionFactsAtStart,
4405
+ syncClientGroups,
4406
+ effectResultCleared,
4407
+ makeReceiptEvents,
4408
+ mcpAppSessions,
4409
+ signInMethods,
4410
+ teams,
4411
+ credentialRemoved,
4412
+ sessionAdmission,
4413
+ signInMethodFacts,
4414
+ enterpriseAuth,
4415
+ hashedSessionTokens,
4416
+ pushNotifications,
4417
+ ]
4418
+
4419
+ /** The module's runtime role: plain DML on its own tables, under row-level security. */
4420
+ export const runtimeRoleName = (module: string): string => `eloxiv_mod_${module}`
4421
+ /** The module's table-owner role: used only by migrations, on a session that logs in as it (`connectOwner`). */
4422
+ export const ownerRoleName = (module: string): string => `eloxiv_own_${module}`