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