@segmentstream/ontology 0.0.0-stage → 0.92.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 (483) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +2 -0
  3. package/README.md +1655 -2
  4. package/dist/action.d.ts +193 -0
  5. package/dist/action.js +41 -0
  6. package/dist/agent-chat.d.ts +44 -0
  7. package/dist/agent-chat.js +91 -0
  8. package/dist/agent-task-contract.d.ts +64 -0
  9. package/dist/agent-task-contract.js +15 -0
  10. package/dist/agent-task.d.ts +39 -0
  11. package/dist/agent-task.js +112 -0
  12. package/dist/analyze.d.ts +215 -0
  13. package/dist/analyze.js +2438 -0
  14. package/dist/app-feedback.d.ts +167 -0
  15. package/dist/app-feedback.js +176 -0
  16. package/dist/authoring-input.d.ts +3 -0
  17. package/dist/authoring-input.js +107 -0
  18. package/dist/authoring-names.d.ts +4 -0
  19. package/dist/authoring-names.js +13 -0
  20. package/dist/authoring-records.d.ts +35 -0
  21. package/dist/authoring-records.js +264 -0
  22. package/dist/authoring.d.ts +15 -0
  23. package/dist/authoring.js +331 -0
  24. package/dist/bin/check.d.ts +30 -0
  25. package/dist/bin/check.js +99 -0
  26. package/dist/bin/load.d.ts +48 -0
  27. package/dist/bin/load.js +139 -0
  28. package/dist/bin/main.d.ts +31 -0
  29. package/dist/bin/main.js +121 -0
  30. package/dist/bin/migrate.d.ts +57 -0
  31. package/dist/bin/migrate.js +170 -0
  32. package/dist/bin/output.d.ts +31 -0
  33. package/dist/bin/output.js +84 -0
  34. package/dist/bin.d.ts +2 -0
  35. package/dist/bin.js +31 -0
  36. package/dist/blob.d.ts +52 -0
  37. package/dist/blob.js +87 -0
  38. package/dist/channel-session.d.ts +16 -0
  39. package/dist/channel-session.js +16 -0
  40. package/dist/chat.d.ts +43 -0
  41. package/dist/chat.js +34 -0
  42. package/dist/confirmation.d.ts +46 -0
  43. package/dist/confirmation.js +41 -0
  44. package/dist/connection.d.ts +213 -0
  45. package/dist/connection.js +289 -0
  46. package/dist/deployment.d.ts +35 -0
  47. package/dist/deployment.js +76 -0
  48. package/dist/diagnostics.d.ts +27 -0
  49. package/dist/diagnostics.js +106 -0
  50. package/dist/emails.d.ts +70 -0
  51. package/dist/emails.js +221 -0
  52. package/dist/entity.d.ts +331 -0
  53. package/dist/entity.js +153 -0
  54. package/dist/errors.d.ts +154 -0
  55. package/dist/errors.js +109 -0
  56. package/dist/feedback-config.d.ts +24 -0
  57. package/dist/feedback-config.js +126 -0
  58. package/dist/files.d.ts +39 -0
  59. package/dist/files.js +4 -0
  60. package/dist/groups.d.ts +95 -0
  61. package/dist/groups.js +280 -0
  62. package/dist/index.d.ts +109 -0
  63. package/dist/index.js +70 -0
  64. package/dist/internal/diagnostics.js +594 -0
  65. package/dist/legacy.d.ts +160 -0
  66. package/dist/legacy.js +270 -0
  67. package/dist/manifest-compatibility.d.ts +8 -0
  68. package/dist/manifest-compatibility.js +87 -0
  69. package/dist/manifest.d.ts +3329 -0
  70. package/dist/manifest.js +757 -0
  71. package/dist/me.d.ts +46 -0
  72. package/dist/me.js +109 -0
  73. package/dist/metric-filters.d.ts +48 -0
  74. package/dist/metric-filters.js +252 -0
  75. package/dist/metric-routes.d.ts +132 -0
  76. package/dist/metric-routes.js +498 -0
  77. package/dist/metric.d.ts +172 -0
  78. package/dist/metric.js +132 -0
  79. package/dist/migrate/apply.d.ts +94 -0
  80. package/dist/migrate/apply.js +526 -0
  81. package/dist/migrate/errors.d.ts +46 -0
  82. package/dist/migrate/errors.js +38 -0
  83. package/dist/migrate/index.d.ts +10 -0
  84. package/dist/migrate/index.js +7 -0
  85. package/dist/migrate/model.d.ts +2311 -0
  86. package/dist/migrate/model.js +148 -0
  87. package/dist/migrate/plan.d.ts +51 -0
  88. package/dist/migrate/plan.js +1856 -0
  89. package/dist/migrate/preview.d.ts +13 -0
  90. package/dist/migrate/preview.js +65 -0
  91. package/dist/migrate/storage.d.ts +226 -0
  92. package/dist/migrate/storage.js +774 -0
  93. package/dist/model-metrics.d.ts +22 -0
  94. package/dist/model-metrics.js +545 -0
  95. package/dist/names.d.ts +49 -0
  96. package/dist/names.js +110 -0
  97. package/dist/navigation-artifact.d.ts +13 -0
  98. package/dist/navigation-artifact.js +11 -0
  99. package/dist/navigation-catalog.d.ts +55 -0
  100. package/dist/navigation-catalog.js +297 -0
  101. package/dist/nitro-navigation.d.ts +3 -0
  102. package/dist/nitro-navigation.js +64 -0
  103. package/dist/nitro-workflows.d.ts +108 -0
  104. package/dist/nitro-workflows.js +286 -0
  105. package/dist/nitro.d.ts +40 -0
  106. package/dist/nitro.js +50 -0
  107. package/dist/ontology.d.ts +41 -0
  108. package/dist/ontology.js +46 -0
  109. package/dist/permissions.d.ts +198 -0
  110. package/dist/permissions.js +272 -0
  111. package/dist/property.d.ts +188 -0
  112. package/dist/property.js +301 -0
  113. package/dist/query.d.ts +245 -0
  114. package/dist/query.js +615 -0
  115. package/dist/relationship.d.ts +99 -0
  116. package/dist/relationship.js +33 -0
  117. package/dist/render.d.ts +81 -0
  118. package/dist/render.js +512 -0
  119. package/dist/replication/baseline.d.ts +51 -0
  120. package/dist/replication/baseline.js +215 -0
  121. package/dist/replication/bigquery.d.ts +37 -0
  122. package/dist/replication/bigquery.js +211 -0
  123. package/dist/replication/coverage.d.ts +14 -0
  124. package/dist/replication/coverage.js +53 -0
  125. package/dist/replication/evolution.d.ts +25 -0
  126. package/dist/replication/evolution.js +184 -0
  127. package/dist/replication/identities.d.ts +6 -0
  128. package/dist/replication/identities.js +47 -0
  129. package/dist/replication/legacy-baseline.d.ts +27 -0
  130. package/dist/replication/legacy-baseline.js +109 -0
  131. package/dist/replication/legacy-store.d.ts +19 -0
  132. package/dist/replication/legacy-store.js +63 -0
  133. package/dist/replication/lineage.d.ts +36 -0
  134. package/dist/replication/lineage.js +72 -0
  135. package/dist/replication/migrate.d.ts +21 -0
  136. package/dist/replication/migrate.js +84 -0
  137. package/dist/replication/model.d.ts +52 -0
  138. package/dist/replication/model.js +99 -0
  139. package/dist/replication/scans.d.ts +34 -0
  140. package/dist/replication/scans.js +158 -0
  141. package/dist/replication/schema.d.ts +11 -0
  142. package/dist/replication/schema.js +226 -0
  143. package/dist/replication/shadow-schema.d.ts +4 -0
  144. package/dist/replication/shadow-schema.js +61 -0
  145. package/dist/replication/shadow.d.ts +127 -0
  146. package/dist/replication/shadow.js +614 -0
  147. package/dist/replication/source-replacement.d.ts +33 -0
  148. package/dist/replication/source-replacement.js +76 -0
  149. package/dist/replication/store.d.ts +36 -0
  150. package/dist/replication/store.js +382 -0
  151. package/dist/replication/transaction.d.ts +23 -0
  152. package/dist/replication/transaction.js +88 -0
  153. package/dist/role.d.ts +61 -0
  154. package/dist/role.js +76 -0
  155. package/dist/runtime/action-deadlocks.d.ts +21 -0
  156. package/dist/runtime/action-deadlocks.js +130 -0
  157. package/dist/runtime/action-transactions.d.ts +35 -0
  158. package/dist/runtime/action-transactions.js +54 -0
  159. package/dist/runtime/agent-counters.d.ts +26 -0
  160. package/dist/runtime/agent-counters.js +98 -0
  161. package/dist/runtime/agent-tasks.d.ts +63 -0
  162. package/dist/runtime/agent-tasks.js +120 -0
  163. package/dist/runtime/agents.d.ts +15 -0
  164. package/dist/runtime/agents.js +457 -0
  165. package/dist/runtime/batch-diagnostics.d.ts +22 -0
  166. package/dist/runtime/batch-diagnostics.js +89 -0
  167. package/dist/runtime/batch.d.ts +52 -0
  168. package/dist/runtime/batch.js +534 -0
  169. package/dist/runtime/channel-session-revocation.d.ts +3 -0
  170. package/dist/runtime/channel-session-revocation.js +5 -0
  171. package/dist/runtime/channel-sessions.d.ts +4 -0
  172. package/dist/runtime/channel-sessions.js +61 -0
  173. package/dist/runtime/confirmations.d.ts +29 -0
  174. package/dist/runtime/confirmations.js +57 -0
  175. package/dist/runtime/cursor.d.ts +23 -0
  176. package/dist/runtime/cursor.js +100 -0
  177. package/dist/runtime/deployment.d.ts +7 -0
  178. package/dist/runtime/deployment.js +4 -0
  179. package/dist/runtime/errors.d.ts +118 -0
  180. package/dist/runtime/errors.js +109 -0
  181. package/dist/runtime/federation-tables.d.ts +2 -0
  182. package/dist/runtime/federation-tables.js +20 -0
  183. package/dist/runtime/federation.d.ts +42 -0
  184. package/dist/runtime/federation.js +222 -0
  185. package/dist/runtime/files.d.ts +39 -0
  186. package/dist/runtime/files.js +44 -0
  187. package/dist/runtime/generated-actions.d.ts +37 -0
  188. package/dist/runtime/generated-actions.js +307 -0
  189. package/dist/runtime/history.d.ts +91 -0
  190. package/dist/runtime/history.js +77 -0
  191. package/dist/runtime/ids.d.ts +6 -0
  192. package/dist/runtime/ids.js +39 -0
  193. package/dist/runtime/member-tables.d.ts +8 -0
  194. package/dist/runtime/member-tables.js +33 -0
  195. package/dist/runtime/member-writes.d.ts +78 -0
  196. package/dist/runtime/member-writes.js +202 -0
  197. package/dist/runtime/metric-query.d.ts +19 -0
  198. package/dist/runtime/metric-query.js +411 -0
  199. package/dist/runtime/model.d.ts +67 -0
  200. package/dist/runtime/model.js +150 -0
  201. package/dist/runtime/new-user-hook.d.ts +6 -0
  202. package/dist/runtime/new-user-hook.js +37 -0
  203. package/dist/runtime/oauth.d.ts +9 -0
  204. package/dist/runtime/oauth.js +299 -0
  205. package/dist/runtime/pipeline.d.ts +155 -0
  206. package/dist/runtime/pipeline.js +597 -0
  207. package/dist/runtime/postgres-tls.d.ts +10 -0
  208. package/dist/runtime/postgres-tls.js +14 -0
  209. package/dist/runtime/principals.d.ts +302 -0
  210. package/dist/runtime/principals.js +1307 -0
  211. package/dist/runtime/reads.d.ts +55 -0
  212. package/dist/runtime/reads.js +313 -0
  213. package/dist/runtime/records.d.ts +42 -0
  214. package/dist/runtime/records.js +245 -0
  215. package/dist/runtime/resolve-agent-identity.d.ts +6 -0
  216. package/dist/runtime/resolve-agent-identity.js +181 -0
  217. package/dist/runtime/service-binding.d.ts +18 -0
  218. package/dist/runtime/service-binding.js +266 -0
  219. package/dist/runtime/sign-in-links.d.ts +68 -0
  220. package/dist/runtime/sign-in-links.js +147 -0
  221. package/dist/runtime/sql-runtime.d.ts +131 -0
  222. package/dist/runtime/sql-runtime.js +362 -0
  223. package/dist/runtime/statement.d.ts +18 -0
  224. package/dist/runtime/statement.js +31 -0
  225. package/dist/runtime/user-identities.d.ts +66 -0
  226. package/dist/runtime/user-identities.js +106 -0
  227. package/dist/runtime/user-identity-sql.d.ts +86 -0
  228. package/dist/runtime/user-identity-sql.js +297 -0
  229. package/dist/runtime/user-roles.d.ts +16 -0
  230. package/dist/runtime/user-roles.js +32 -0
  231. package/dist/runtime/validation.d.ts +16 -0
  232. package/dist/runtime/validation.js +26 -0
  233. package/dist/runtime/where.d.ts +57 -0
  234. package/dist/runtime/where.js +404 -0
  235. package/dist/runtime/workflow-admission.d.ts +49 -0
  236. package/dist/runtime/workflow-admission.js +92 -0
  237. package/dist/runtime/workflow-argument-codec.d.ts +10 -0
  238. package/dist/runtime/workflow-argument-codec.js +120 -0
  239. package/dist/runtime/workflow-arguments.d.ts +17 -0
  240. package/dist/runtime/workflow-arguments.js +99 -0
  241. package/dist/runtime/workflow-starts.d.ts +203 -0
  242. package/dist/runtime/workflow-starts.js +493 -0
  243. package/dist/runtime/workflow-users.d.ts +9 -0
  244. package/dist/runtime/workflow-users.js +17 -0
  245. package/dist/runtime/workload.d.ts +25 -0
  246. package/dist/runtime/workload.js +24 -0
  247. package/dist/runtime/writes.d.ts +108 -0
  248. package/dist/runtime/writes.js +491 -0
  249. package/dist/runtime-source.d.ts +22 -0
  250. package/dist/runtime-source.js +28 -0
  251. package/dist/runtime.d.ts +310 -0
  252. package/dist/runtime.js +31 -0
  253. package/dist/server.d.ts +23 -0
  254. package/dist/server.js +107 -0
  255. package/dist/service/agent/attachments.d.ts +33 -0
  256. package/dist/service/agent/attachments.js +228 -0
  257. package/dist/service/agent/authentication.d.ts +22 -0
  258. package/dist/service/agent/authentication.js +58 -0
  259. package/dist/service/agent/confirmations.d.ts +5 -0
  260. package/dist/service/agent/confirmations.js +73 -0
  261. package/dist/service/agent/conversation-routes.d.ts +14 -0
  262. package/dist/service/agent/conversation-routes.js +45 -0
  263. package/dist/service/agent/conversations.d.ts +40 -0
  264. package/dist/service/agent/conversations.js +69 -0
  265. package/dist/service/agent/files.d.ts +12 -0
  266. package/dist/service/agent/files.js +69 -0
  267. package/dist/service/agent/protocol.d.ts +90 -0
  268. package/dist/service/agent/protocol.js +114 -0
  269. package/dist/service/agent/server.d.ts +28 -0
  270. package/dist/service/agent/server.js +374 -0
  271. package/dist/service/agent/task-caller.d.ts +21 -0
  272. package/dist/service/agent/task-caller.js +35 -0
  273. package/dist/service/agent/task-start.d.ts +53 -0
  274. package/dist/service/agent/task-start.js +161 -0
  275. package/dist/service/agent/tasks.d.ts +40 -0
  276. package/dist/service/agent/tasks.js +155 -0
  277. package/dist/service/api.d.ts +50 -0
  278. package/dist/service/api.js +288 -0
  279. package/dist/service/authentication.d.ts +227 -0
  280. package/dist/service/authentication.js +767 -0
  281. package/dist/service/caller-context.d.ts +24 -0
  282. package/dist/service/caller-context.js +6 -0
  283. package/dist/service/catalog.d.ts +42 -0
  284. package/dist/service/catalog.js +66 -0
  285. package/dist/service/channel/provider.d.ts +10 -0
  286. package/dist/service/channel/provider.js +1 -0
  287. package/dist/service/channel/providers/telegram.d.ts +18 -0
  288. package/dist/service/channel/providers/telegram.js +108 -0
  289. package/dist/service/channel/sessions.d.ts +5 -0
  290. package/dist/service/channel/sessions.js +53 -0
  291. package/dist/service/channel/sign-in.d.ts +7 -0
  292. package/dist/service/channel/sign-in.js +78 -0
  293. package/dist/service/chat/archive.d.ts +64 -0
  294. package/dist/service/chat/archive.js +62 -0
  295. package/dist/service/chat/attribution.d.ts +26 -0
  296. package/dist/service/chat/attribution.js +28 -0
  297. package/dist/service/chat/delivery.d.ts +18 -0
  298. package/dist/service/chat/delivery.js +251 -0
  299. package/dist/service/chat/diagnostics.d.ts +2 -0
  300. package/dist/service/chat/diagnostics.js +35 -0
  301. package/dist/service/chat/envelope.d.ts +96 -0
  302. package/dist/service/chat/envelope.js +39 -0
  303. package/dist/service/chat/idempotency.d.ts +19 -0
  304. package/dist/service/chat/idempotency.js +37 -0
  305. package/dist/service/chat/providers/telegram.d.ts +36 -0
  306. package/dist/service/chat/providers/telegram.js +133 -0
  307. package/dist/service/chat/reads.d.ts +25 -0
  308. package/dist/service/chat/reads.js +75 -0
  309. package/dist/service/chat/resolve.d.ts +34 -0
  310. package/dist/service/chat/resolve.js +150 -0
  311. package/dist/service/chat/routes.d.ts +23 -0
  312. package/dist/service/chat/routes.js +75 -0
  313. package/dist/service/chat/schemas.d.ts +43 -0
  314. package/dist/service/chat/schemas.js +31 -0
  315. package/dist/service/config.d.ts +218 -0
  316. package/dist/service/config.js +265 -0
  317. package/dist/service/connection-stream.d.ts +10 -0
  318. package/dist/service/connection-stream.js +191 -0
  319. package/dist/service/connections.d.ts +60 -0
  320. package/dist/service/connections.js +271 -0
  321. package/dist/service/decisions.d.ts +35 -0
  322. package/dist/service/decisions.js +63 -0
  323. package/dist/service/descriptions.d.ts +8 -0
  324. package/dist/service/descriptions.js +20 -0
  325. package/dist/service/discovery-schemas.d.ts +92 -0
  326. package/dist/service/discovery-schemas.js +59 -0
  327. package/dist/service/discovery-search.d.ts +30 -0
  328. package/dist/service/discovery-search.js +95 -0
  329. package/dist/service/discovery.d.ts +37 -0
  330. package/dist/service/discovery.js +436 -0
  331. package/dist/service/docs.d.ts +9 -0
  332. package/dist/service/docs.js +197 -0
  333. package/dist/service/errors.d.ts +145 -0
  334. package/dist/service/errors.js +704 -0
  335. package/dist/service/federation-provider.d.ts +36 -0
  336. package/dist/service/federation-provider.js +110 -0
  337. package/dist/service/federation-server.d.ts +20 -0
  338. package/dist/service/federation-server.js +249 -0
  339. package/dist/service/federation-status.d.ts +40 -0
  340. package/dist/service/federation-status.js +151 -0
  341. package/dist/service/handlers.d.ts +18 -0
  342. package/dist/service/handlers.js +287 -0
  343. package/dist/service/mcp/confirmation.d.ts +68 -0
  344. package/dist/service/mcp/confirmation.js +178 -0
  345. package/dist/service/mcp/find-input.d.ts +12 -0
  346. package/dist/service/mcp/find-input.js +122 -0
  347. package/dist/service/mcp/input-schema.d.ts +6 -0
  348. package/dist/service/mcp/input-schema.js +126 -0
  349. package/dist/service/mcp/listing.d.ts +26 -0
  350. package/dist/service/mcp/listing.js +92 -0
  351. package/dist/service/mcp/metric-tools.d.ts +85 -0
  352. package/dist/service/mcp/metric-tools.js +258 -0
  353. package/dist/service/mcp/request-log.d.ts +5 -0
  354. package/dist/service/mcp/request-log.js +53 -0
  355. package/dist/service/mcp/runtime-policy.d.ts +27 -0
  356. package/dist/service/mcp/runtime-policy.js +62 -0
  357. package/dist/service/mcp/server.d.ts +52 -0
  358. package/dist/service/mcp/server.js +861 -0
  359. package/dist/service/mcp/tools.d.ts +99 -0
  360. package/dist/service/mcp/tools.js +938 -0
  361. package/dist/service/member-file-routes.d.ts +22 -0
  362. package/dist/service/member-file-routes.js +52 -0
  363. package/dist/service/member-files.d.ts +245 -0
  364. package/dist/service/member-files.js +258 -0
  365. package/dist/service/metric-query-platform.d.ts +77 -0
  366. package/dist/service/metric-query-platform.js +198 -0
  367. package/dist/service/metric-query-scopes.d.ts +43 -0
  368. package/dist/service/metric-query-scopes.js +147 -0
  369. package/dist/service/metric-query.d.ts +48 -0
  370. package/dist/service/metric-query.js +200 -0
  371. package/dist/service/name-suggestions.d.ts +3 -0
  372. package/dist/service/name-suggestions.js +38 -0
  373. package/dist/service/navigation-schemas.d.ts +80 -0
  374. package/dist/service/navigation-schemas.js +49 -0
  375. package/dist/service/navigation.d.ts +20 -0
  376. package/dist/service/navigation.js +165 -0
  377. package/dist/service/oauth/protocol.d.ts +70 -0
  378. package/dist/service/oauth/protocol.js +157 -0
  379. package/dist/service/oauth/refresh-replay.d.ts +2 -0
  380. package/dist/service/oauth/refresh-replay.js +20 -0
  381. package/dist/service/oauth/server.d.ts +28 -0
  382. package/dist/service/oauth/server.js +769 -0
  383. package/dist/service/operations.d.ts +170 -0
  384. package/dist/service/operations.js +392 -0
  385. package/dist/service/plan.d.ts +57 -0
  386. package/dist/service/plan.js +96 -0
  387. package/dist/service/rate-limit.d.ts +22 -0
  388. package/dist/service/rate-limit.js +52 -0
  389. package/dist/service/record-reads.d.ts +21 -0
  390. package/dist/service/record-reads.js +155 -0
  391. package/dist/service/replication.d.ts +5 -0
  392. package/dist/service/replication.js +39 -0
  393. package/dist/service/runtime-contract.d.ts +508 -0
  394. package/dist/service/runtime-contract.js +18 -0
  395. package/dist/service/runtime-identity.d.ts +71 -0
  396. package/dist/service/runtime-identity.js +122 -0
  397. package/dist/service/schemas.d.ts +961 -0
  398. package/dist/service/schemas.js +639 -0
  399. package/dist/service/service.d.ts +21 -0
  400. package/dist/service/service.js +526 -0
  401. package/dist/service/warehouse-platform.d.ts +17 -0
  402. package/dist/service/warehouse-platform.js +122 -0
  403. package/dist/service/warehouse-query.d.ts +24 -0
  404. package/dist/service/warehouse-query.js +280 -0
  405. package/dist/service/webhooks.d.ts +106 -0
  406. package/dist/service/webhooks.js +233 -0
  407. package/dist/service/workflow-admission-provider.d.ts +31 -0
  408. package/dist/service/workflow-admission-provider.js +205 -0
  409. package/dist/service/workflow-argument-serialization.d.ts +2 -0
  410. package/dist/service/workflow-argument-serialization.js +14 -0
  411. package/dist/service/workflow-callback.d.ts +22 -0
  412. package/dist/service/workflow-callback.js +75 -0
  413. package/dist/service/workflow-deployment.d.ts +8 -0
  414. package/dist/service/workflow-deployment.js +131 -0
  415. package/dist/service/workflow-diagnostics.d.ts +23 -0
  416. package/dist/service/workflow-diagnostics.js +263 -0
  417. package/dist/service/workflow-errors.d.ts +26 -0
  418. package/dist/service/workflow-errors.js +181 -0
  419. package/dist/service/workflow-logging.d.ts +2 -0
  420. package/dist/service/workflow-logging.js +50 -0
  421. package/dist/service/workflow-queue-fence.d.ts +6 -0
  422. package/dist/service/workflow-queue-fence.js +66 -0
  423. package/dist/service/workflows.d.ts +200 -0
  424. package/dist/service/workflows.js +1549 -0
  425. package/dist/sign-in.d.ts +58 -0
  426. package/dist/sign-in.js +57 -0
  427. package/dist/source.d.ts +30 -0
  428. package/dist/source.js +107 -0
  429. package/dist/start-recovery-contract.d.ts +49 -0
  430. package/dist/start-recovery-contract.js +26 -0
  431. package/dist/start-recovery.d.ts +27 -0
  432. package/dist/start-recovery.js +81 -0
  433. package/dist/storage/api.d.ts +4 -0
  434. package/dist/storage/api.js +40 -0
  435. package/dist/storage/attachments.d.ts +146 -0
  436. package/dist/storage/attachments.js +733 -0
  437. package/dist/storage/authorization.d.ts +38 -0
  438. package/dist/storage/authorization.js +83 -0
  439. package/dist/storage/file-access.d.ts +17 -0
  440. package/dist/storage/file-access.js +8 -0
  441. package/dist/storage/limits.d.ts +12 -0
  442. package/dist/storage/limits.js +17 -0
  443. package/dist/storage/maintenance-auth.d.ts +20 -0
  444. package/dist/storage/maintenance-auth.js +24 -0
  445. package/dist/storage/maintenance.d.ts +11 -0
  446. package/dist/storage/maintenance.js +67 -0
  447. package/dist/storage/neon.d.ts +4 -0
  448. package/dist/storage/neon.js +318 -0
  449. package/dist/storage/operator.d.ts +11 -0
  450. package/dist/storage/operator.js +30 -0
  451. package/dist/storage/provider.d.ts +93 -0
  452. package/dist/storage/provider.js +36 -0
  453. package/dist/storage/sessions.d.ts +184 -0
  454. package/dist/storage/sessions.js +688 -0
  455. package/dist/storage/tables.d.ts +54 -0
  456. package/dist/storage/tables.js +205 -0
  457. package/dist/storage/transfers.d.ts +16 -0
  458. package/dist/storage/transfers.js +153 -0
  459. package/dist/storage/writes.d.ts +7 -0
  460. package/dist/storage/writes.js +88 -0
  461. package/dist/telegram.d.ts +35 -0
  462. package/dist/telegram.js +173 -0
  463. package/dist/user-identity.d.ts +28 -0
  464. package/dist/user-identity.js +106 -0
  465. package/dist/user.d.ts +75 -0
  466. package/dist/user.js +111 -0
  467. package/dist/warehouse-backed.d.ts +6 -0
  468. package/dist/warehouse-backed.js +495 -0
  469. package/dist/webhook-token.d.ts +11 -0
  470. package/dist/webhook-token.js +18 -0
  471. package/dist/webhooks.d.ts +40 -0
  472. package/dist/webhooks.js +55 -0
  473. package/dist/wire.d.ts +10 -0
  474. package/dist/wire.js +35 -0
  475. package/dist/workflow-runtime.d.ts +116 -0
  476. package/dist/workflow-runtime.js +109 -0
  477. package/dist/workflow-topics.d.ts +28 -0
  478. package/dist/workflow-topics.js +28 -0
  479. package/dist/workflow.d.ts +284 -0
  480. package/dist/workflow.js +259 -0
  481. package/dist/workflows.d.ts +24 -0
  482. package/dist/workflows.js +18 -0
  483. package/package.json +127 -4
@@ -0,0 +1,526 @@
1
+ import { requestShadowSupersession } from "../replication/shadow.js";
2
+ import { replicationScanScopes } from "../replication/scans.js";
3
+ import { enableShadowCapture, refreshShadowCapturePolicy } from "../replication/shadow.js";
4
+ import { Duration, Effect, Schema } from "effect";
5
+ import { SqlClient } from "effect/unstable/sql";
6
+ import { canonicalJson, decodeManifestDocument, encodeManifest, manifestHash, } from "../manifest.js";
7
+ import { CatalogInvalid, CatalogMismatch, MigrationFailed, MigrationRefused } from "./errors.js";
8
+ import { isNoopMigration, NO_RETAINED_STORAGE, RetainedStorage, retainedStorageJson, } from "./model.js";
9
+ import { planMigration } from "./plan.js";
10
+ import { REPLICATION_DDL, REPLICATION_SCHEMA_VERSION, replicationEntityDdl, } from "../replication/schema.js";
11
+ import { lockReplicationLifecycle, lockReplicationSchema } from "../replication/transaction.js";
12
+ import { prepareReplicationBaseline } from "../replication/baseline.js";
13
+ import { randomUUID } from "node:crypto";
14
+ import { recordWorkflowCatalog } from "../runtime/workflow-admission.js";
15
+ import { prepareReplicationEvolution, dropsServingReplicationStorage, refreshReplicationProjection, retainReplicationHistory, renameReplicationHistory, } from "../replication/evolution.js";
16
+ import { migratedReplicationFills, migrationReplicationExclusions, effectiveReplicationExclusions, } from "../replication/migrate.js";
17
+ import { AGENT_TASKS_TABLE, ATTACHMENT_SOURCE_CHECK, ATTACHMENT_SOURCES, ATTACHMENTS_TABLE, SIGN_IN_EMAILS_TABLE, WORKFLOW_STARTS_TABLE, } from "../storage/tables.js";
18
+ import { principalsOntology, reconcileWorkflowUsers } from "../runtime/principals.js";
19
+ import { FEDERATION_TABLES } from "../runtime/federation-tables.js";
20
+ import { syncUserIdentities, USER_IDENTITY_ENTITY_ID } from "../runtime/user-identities.js";
21
+ import { resolveReplicationSelection, } from "../replication/model.js";
22
+ import { ACTION_ATTRIBUTION_TABLE, AGENT_TABLES, API_KEYS_TABLE, CATALOG_TABLE, OAUTH_TABLES, USER_ROLES_TABLE, quoteIdentifier, quoteLiteral, historyTableName, } from "./storage.js";
23
+ const CATALOG = quoteIdentifier(CATALOG_TABLE);
24
+ const IDENTITY_SYNC = "Copy members' sign-in identities the legacy identity stores hold.";
25
+ /**
26
+ * Whether applying the plan copies the legacy identity stores into `user_identity`: its target has
27
+ * the entity. A target an earlier SDK built has none, and the copy waits for the next deploy that
28
+ * declares it again.
29
+ */
30
+ function syncsIdentities(plan) {
31
+ return plan.target.entities.some((entity) => entity.id === USER_IDENTITY_ENTITY_ID && entity.source === undefined);
32
+ }
33
+ /** Serializes migrations of one database; transaction-scoped, so it ends with the transaction. */
34
+ const MIGRATION_LOCK = "segmentstream.ontology.migration";
35
+ const DEFAULT_STATEMENT_TIMEOUT = "5 minutes";
36
+ const DEFAULT_LOCK_TIMEOUT = "5 seconds";
37
+ const Presence = Schema.Struct({ present: Schema.Boolean });
38
+ const CatalogRow = Schema.Struct({ hash: Schema.String, manifest: Schema.String });
39
+ const RetainedRow = Schema.Struct({ retained: Schema.NullOr(Schema.String) });
40
+ const decodeManifest = decodeManifestDocument;
41
+ const readCatalogRow = (sql, options) => Effect.gen(function* () {
42
+ const presence = yield* sql
43
+ .unsafe(`SELECT to_regclass($1) IS NOT NULL AS present`, [CATALOG])
44
+ .pipe(Effect.flatMap(Schema.decodeUnknownEffect(Schema.Array(Presence))));
45
+ if (presence[0]?.present !== true) {
46
+ return undefined;
47
+ }
48
+ const lock = options.forUpdate ? "FOR UPDATE" : "";
49
+ const rows = yield* sql
50
+ .unsafe(`
51
+ SELECT "hash", "manifest"::text AS "manifest"
52
+ FROM ${CATALOG}
53
+ WHERE "id"
54
+ ${lock}
55
+ `)
56
+ .pipe(Effect.flatMap(Schema.decodeUnknownEffect(Schema.Array(CatalogRow))));
57
+ return rows[0];
58
+ }).pipe(Effect.catchTag("SchemaError", (cause) => Effect.fail(new CatalogInvalid({ message: "The _ontology catalog has an unexpected shape.", cause }))));
59
+ /**
60
+ * The manifest recorded by the last applied migration, or undefined when none was applied. It is
61
+ * decoded with the manifest contract, so fields this SDK does not know are dropped.
62
+ */
63
+ export const readCatalog = (input) => Effect.gen(function* () {
64
+ const row = yield* readCatalogRow(input.sql, { forUpdate: false });
65
+ if (row === undefined) {
66
+ return undefined;
67
+ }
68
+ const parsed = yield* Effect.try({
69
+ try: () => JSON.parse(row.manifest),
70
+ catch: (cause) => new CatalogInvalid({ message: "The _ontology manifest is not JSON.", cause }),
71
+ });
72
+ const manifest = yield* decodeManifest(parsed).pipe(Effect.mapError((cause) => new CatalogInvalid({
73
+ message: "The _ontology manifest does not match the contract.",
74
+ cause,
75
+ })));
76
+ if (manifest.hash !== row.hash ||
77
+ manifestHash(parsed) !== row.hash) {
78
+ return yield* new CatalogInvalid({
79
+ message: "The _ontology hash does not match the manifest it records.",
80
+ cause: { recordedHash: row.hash, manifestHash: manifest.hash },
81
+ });
82
+ }
83
+ return manifest;
84
+ }).pipe(Effect.withSpan("ontology.migrate.readCatalog"));
85
+ /**
86
+ * The storage the catalog records as kept: what removals retained, which declaring the entity or
87
+ * @legacy ontology.pre-upgrade-database-tolerance
88
+ * field again restores. An earlier SDK's catalog records none, and its `_ontology` table has no
89
+ * `retained` column; older SDKs neither read nor write it.
90
+ */
91
+ export const readRetainedStorage = (input) => Effect.gen(function* () {
92
+ const presence = yield* input.sql
93
+ .unsafe(`SELECT to_regclass($1) IS NOT NULL AS present`, [CATALOG])
94
+ .pipe(Effect.flatMap(Schema.decodeUnknownEffect(Schema.Array(Presence))));
95
+ if (presence[0]?.present !== true) {
96
+ return NO_RETAINED_STORAGE;
97
+ }
98
+ const rows = yield* input.sql
99
+ .unsafe(`SELECT (to_jsonb(c) -> 'retained')::text AS "retained" FROM ${CATALOG} c WHERE c."id"`)
100
+ .pipe(Effect.flatMap(Schema.decodeUnknownEffect(Schema.Array(RetainedRow))));
101
+ const text = rows[0]?.retained;
102
+ if (text === null || text === undefined || text === "null") {
103
+ return NO_RETAINED_STORAGE;
104
+ }
105
+ const parsed = yield* Effect.try({
106
+ try: () => JSON.parse(text),
107
+ catch: (cause) => new CatalogInvalid({ message: "The _ontology kept storage is not JSON.", cause }),
108
+ });
109
+ return yield* Schema.decodeUnknownEffect(RetainedStorage)(parsed).pipe(Effect.mapError((cause) => new CatalogInvalid({
110
+ message: "The _ontology kept storage does not match the contract.",
111
+ cause,
112
+ })));
113
+ }).pipe(Effect.catchTag("SchemaError", (cause) => Effect.fail(new CatalogInvalid({ message: "The _ontology catalog has an unexpected shape.", cause }))), Effect.withSpan("ontology.migrate.readRetainedStorage"));
114
+ /**
115
+ * The names in the current schema, for `planMigration`'s `existingStorage`: relations and types,
116
+ * which share one namespace, and the columns of each table. Names starting with `_`, which no
117
+ * entity's storage uses, are left out.
118
+ */
119
+ export const readStorageNames = (input) => Effect.gen(function* () {
120
+ const names = yield* input.sql.unsafe(`SELECT c.relname AS "name" FROM pg_catalog.pg_class c
121
+ WHERE c.relnamespace = current_schema()::regnamespace AND left(c.relname, 1) <> '_'
122
+ UNION
123
+ SELECT t.typname FROM pg_catalog.pg_type t
124
+ WHERE t.typnamespace = current_schema()::regnamespace AND t.typcategory <> 'A'
125
+ AND left(t.typname, 1) <> '_'`);
126
+ const columns = yield* input.sql.unsafe(`SELECT c.relname AS "table", a.attname AS "column"
127
+ FROM pg_catalog.pg_attribute a JOIN pg_catalog.pg_class c ON c.oid = a.attrelid
128
+ WHERE c.relnamespace = current_schema()::regnamespace AND c.relkind IN ('r', 'p')
129
+ AND left(c.relname, 1) <> '_' AND a.attnum > 0 AND NOT a.attisdropped
130
+ ORDER BY 1, a.attnum`);
131
+ const byTable = {};
132
+ for (const { table, column } of columns) {
133
+ const list = Object.hasOwn(byTable, table) ? byTable[table] : undefined;
134
+ if (list === undefined) {
135
+ byTable[table] = [column];
136
+ }
137
+ else {
138
+ list.push(column);
139
+ }
140
+ }
141
+ return { names: [...new Set(names.map((row) => row.name))].sort(), columns: byTable };
142
+ }).pipe(Effect.withSpan("ontology.migrate.readStorageNames"));
143
+ const verifyCatalog = (sql, plan, options) => Effect.gen(function* () {
144
+ const row = yield* readCatalogRow(sql, options);
145
+ if (row?.hash !== plan.currentHash) {
146
+ return yield* new CatalogMismatch({
147
+ message: "The database's applied ontology is not the one the plan starts from; plan the migration again.",
148
+ ...(plan.currentHash === undefined ? {} : { expectedHash: plan.currentHash }),
149
+ ...(row === undefined ? {} : { actualHash: row.hash }),
150
+ });
151
+ }
152
+ // A plan made without the record leaves it as it is.
153
+ if (plan.retained === undefined) {
154
+ return;
155
+ }
156
+ const retained = yield* readRetainedStorage({ sql });
157
+ if (retainedStorageJson(retained) !== retainedStorageJson(plan.retained.current)) {
158
+ return yield* new CatalogMismatch({
159
+ message: "The storage the database keeps is not what the plan starts from; plan the migration again.",
160
+ ...(plan.currentHash === undefined ? {} : { expectedHash: plan.currentHash }),
161
+ ...(row === undefined ? {} : { actualHash: row.hash }),
162
+ });
163
+ }
164
+ });
165
+ /**
166
+ * Records the kept storage the plan leaves. The column is added the first time there is any to
167
+ * record, so that a database without kept storage keeps the catalog an earlier SDK created.
168
+ */
169
+ const recordRetained = (sql, plan) => Effect.gen(function* () {
170
+ if (plan.retained === undefined) {
171
+ return;
172
+ }
173
+ const json = plan.retained.target.entities.length === 0 ? null : retainedStorageJson(plan.retained.target);
174
+ const [row] = yield* sql.unsafe(`SELECT to_jsonb(c) ? 'retained' AS "present" FROM ${CATALOG} c WHERE c."id"`);
175
+ if (row?.present !== true && json === null) {
176
+ return;
177
+ }
178
+ if (row?.present !== true) {
179
+ yield* sql.unsafe(`ALTER TABLE ${CATALOG} ADD COLUMN IF NOT EXISTS "retained" jsonb`);
180
+ }
181
+ yield* sql.unsafe(`UPDATE ${CATALOG} SET "retained" = $1::jsonb WHERE "id"`, [json]);
182
+ });
183
+ const runStep = (sql, step, stepIndex) => Effect.forEach(step.sql, (statement) => sql.unsafe(statement).unprepared, { discard: true }).pipe(Effect.mapError((cause) => new MigrationFailed({
184
+ message: `Migration step ${stepIndex + 1} failed: ${step.description}`,
185
+ stepIndex,
186
+ step: step.description,
187
+ cause,
188
+ })));
189
+ /**
190
+ * Reconciles the workflow users with the target's workflows, inside the migration's transaction so
191
+ * that only the deploy that recorded the target decides them.
192
+ */
193
+ const reconcileWorkflows = (plan, sql, workspaceId) => workspaceId === undefined
194
+ ? Effect.void
195
+ : reconcileWorkflowUsers(principalsOntology(plan.target), { workspaceId }).pipe(Effect.provideService(SqlClient.SqlClient, sql));
196
+ /**
197
+ * Applies a plan. Non-transactional steps run first, each statement on its own; they only add enum
198
+ * values and build indexes concurrently, and are safe to run again after a failure. Every other step
199
+ * then runs in one transaction with `statement_timeout` and `lock_timeout` set, which also verifies
200
+ * that the catalog still records the manifest the plan starts from and finally records the target. A
201
+ * failure rolls the transaction back and leaves the applied version in place. With `workspaceId`,
202
+ * the same transaction then reconciles the workflow users with the target's workflows. A no-op plan
203
+ * writes nothing else when the runtime schema is also current; with `workspaceId` it still
204
+ * reconciles the workflow users, under the migration lock while the catalog records its target.
205
+ */
206
+ export const applyMigration = (plan, options) => Effect.gen(function* () {
207
+ const { sql } = options;
208
+ if (plan.refusals.length > 0) {
209
+ return yield* new MigrationRefused({
210
+ message: `The migration plan has ${plan.refusals.length} refusal(s); nothing was applied.`,
211
+ refusals: plan.refusals,
212
+ });
213
+ }
214
+ // @legacy ontology.workflow-cutover-artifacts
215
+ // Ontology SDKs 0.86.0 to 0.88.0 read the journal row before the catalog; lock in their order.
216
+ const lockWorkflowAdmission = Effect.gen(function* () {
217
+ const [presence] = yield* sql.unsafe("SELECT to_regclass('_workflow_admission') IS NOT NULL AS present");
218
+ if (presence?.present) {
219
+ yield* sql.unsafe("SELECT id FROM _workflow_admission WHERE id FOR UPDATE");
220
+ }
221
+ });
222
+ const statementTimeout = Duration.toMillis(options.statementTimeout ?? DEFAULT_STATEMENT_TIMEOUT);
223
+ const lockTimeout = Duration.toMillis(options.lockTimeout ?? DEFAULT_LOCK_TIMEOUT);
224
+ const configureTimeouts = Effect.gen(function* () {
225
+ yield* sql.unsafe(`SELECT set_config('statement_timeout', $1, true)`, [
226
+ String(statementTimeout),
227
+ ]);
228
+ yield* sql.unsafe(`SELECT set_config('lock_timeout', $1, true)`, [String(lockTimeout)]);
229
+ });
230
+ const [presence] = yield* sql.unsafe(`SELECT to_regclass('_ontology_replication') IS NOT NULL AS present,
231
+ to_regclass('_ontology_replication_targets') IS NOT NULL AS targets`);
232
+ if (presence?.present) {
233
+ const targetPresent = presence.targets && isNoopMigration(plan)
234
+ ? "EXISTS (SELECT 1 FROM _ontology_replication_targets WHERE generation = active_generation)"
235
+ : "false";
236
+ const [state] = yield* sql.unsafe(`SELECT version, enabled, ${targetPresent} AS target_present FROM _ontology_replication WHERE id`);
237
+ if (state?.enabled &&
238
+ state.version >= 6 &&
239
+ (yield* requestShadowSupersession(sql, plan.target.hash))) {
240
+ return yield* new MigrationRefused({
241
+ message: "replication_publication_pending",
242
+ refusals: [
243
+ {
244
+ code: "replication-publication-pending",
245
+ path: "replication.publication",
246
+ message: "replication_publication_pending",
247
+ },
248
+ ],
249
+ });
250
+ }
251
+ if (isNoopMigration(plan) &&
252
+ state?.version === REPLICATION_SCHEMA_VERSION &&
253
+ (!state.enabled || state.target_present)) {
254
+ if (options.workspaceId !== undefined || syncsIdentities(plan)) {
255
+ // Under the migration lock, and only while the catalog still records this target.
256
+ yield* sql.withTransaction(Effect.gen(function* () {
257
+ yield* configureTimeouts;
258
+ yield* sql.unsafe(`SELECT pg_advisory_xact_lock(hashtextextended($1, 0))`, [
259
+ MIGRATION_LOCK,
260
+ ]);
261
+ // Drain admitted writers before catalog, identity and workflow-user locks, even
262
+ // without DDL.
263
+ yield* lockReplicationLifecycle(sql);
264
+ yield* lockWorkflowAdmission;
265
+ yield* verifyCatalog(sql, plan, { forUpdate: true });
266
+ // An earlier SDK may have served or migrated the database since: copy what it wrote.
267
+ if (syncsIdentities(plan)) {
268
+ // @legacy identities.legacy-stores-dual-write
269
+ yield* syncUserIdentities(sql);
270
+ }
271
+ yield* reconcileWorkflows(plan, sql, options.workspaceId);
272
+ yield* recordWorkflowCatalog(sql, plan.target);
273
+ }));
274
+ }
275
+ return { hash: plan.target.hash, appliedSteps: 0, changed: false };
276
+ }
277
+ }
278
+ yield* verifyCatalog(sql, plan, { forUpdate: false });
279
+ for (const [stepIndex, step] of plan.steps.entries()) {
280
+ if (!step.transactional) {
281
+ yield* runStep(sql, step, stepIndex);
282
+ }
283
+ }
284
+ yield* sql.withTransaction(Effect.gen(function* () {
285
+ yield* configureTimeouts;
286
+ yield* sql.unsafe(`SELECT pg_advisory_xact_lock(hashtextextended($1, 0))`, [
287
+ MIGRATION_LOCK,
288
+ ]);
289
+ // Recheck after serializing migrations: an earlier migration may have created the table.
290
+ const [replication] = yield* sql.unsafe("SELECT to_regclass('_ontology_replication') IS NOT NULL AS present");
291
+ if (replication?.present) {
292
+ yield* lockReplicationSchema(sql);
293
+ }
294
+ // Writers authorize workflows/files after lifecycle admission. Match that catalog order.
295
+ yield* lockWorkflowAdmission;
296
+ yield* verifyCatalog(sql, plan, { forUpdate: true });
297
+ const previousManifest = yield* readCatalog({ sql });
298
+ let refresh;
299
+ let active;
300
+ let exclusions;
301
+ if (replication?.present) {
302
+ const [state] = yield* sql.unsafe("SELECT * FROM _ontology_replication WHERE id FOR UPDATE");
303
+ if (state && previousManifest) {
304
+ exclusions = yield* Effect.try({
305
+ try: () => migrationReplicationExclusions(previousManifest, plan.target, state.exclusions ?? []),
306
+ catch: (cause) => new CatalogInvalid({ message: "The replication exclusions are invalid.", cause }),
307
+ });
308
+ }
309
+ if (state?.enabled) {
310
+ refresh = yield* Effect.try({
311
+ try: () => resolveReplicationSelection(plan.target, effectiveReplicationExclusions(plan.target, exclusions ?? state.exclusions ?? [])),
312
+ catch: (cause) => new CatalogInvalid({ message: "The replication exclusions are invalid.", cause }),
313
+ });
314
+ const [target] = presence.targets
315
+ ? yield* sql.unsafe("SELECT * FROM _ontology_replication_targets WHERE generation = $1::uuid", [state.active_generation])
316
+ : [];
317
+ if (target &&
318
+ (yield* dropsServingReplicationStorage(sql, {
319
+ current: previousManifest,
320
+ target,
321
+ version: state.version,
322
+ retained: plan.retained?.current,
323
+ steps: plan.steps,
324
+ }))) {
325
+ return yield* new MigrationRefused({
326
+ message: "replication_source_compatibility_required",
327
+ refusals: [
328
+ {
329
+ code: "drop-refused",
330
+ path: "replication.compatibility",
331
+ message: "replication_source_compatibility_required",
332
+ },
333
+ ],
334
+ });
335
+ }
336
+ active = target;
337
+ // A runtime-only upgrade retains an existing explicit projection.
338
+ if (target?.manifest.hash === plan.target.hash) {
339
+ refresh = target.selection;
340
+ }
341
+ // Both writer protocols are fenced. Capture and schema changes commit on one stream.
342
+ yield* sql.unsafe("UPDATE _ontology_replication SET enabled = false WHERE id");
343
+ }
344
+ }
345
+ // Install metadata before destructive steps so pending envelopes and stable import/scan
346
+ // cursors can survive storage changes. Capture stays fenced until everything commits.
347
+ for (const statement of REPLICATION_DDL) {
348
+ yield* sql.unsafe(statement).unprepared;
349
+ }
350
+ yield* sql.unsafe("UPDATE _ontology_replication SET version = $1 WHERE id", [
351
+ REPLICATION_SCHEMA_VERSION,
352
+ ]);
353
+ yield* prepareReplicationEvolution(sql);
354
+ if (active) {
355
+ yield* enableShadowCapture(sql, active, replicationScanScopes(active));
356
+ }
357
+ if (plan.steps.some((step) => step.kind === "dropEntities")) {
358
+ for (const entity of previousManifest?.entities ?? []) {
359
+ if (!entity.builtIn &&
360
+ !entity.source &&
361
+ !plan.target.entities.some((item) => item.id === entity.id)) {
362
+ yield* retainReplicationHistory(sql, historyTableName(entity.name));
363
+ }
364
+ }
365
+ }
366
+ for (const [stepIndex, step] of plan.steps.entries()) {
367
+ if (step.transactional) {
368
+ yield* runStep(sql, step, stepIndex);
369
+ }
370
+ }
371
+ // Once the entity's table and the legacy stores exist: copy what an earlier SDK wrote.
372
+ if (syncsIdentities(plan)) {
373
+ yield* syncUserIdentities(sql).pipe(Effect.mapError((cause) => new MigrationFailed({
374
+ message: `Migration step ${plan.steps.length + 1} failed: ${IDENTITY_SYNC}`,
375
+ stepIndex: plan.steps.length,
376
+ step: IDENTITY_SYNC,
377
+ cause,
378
+ })));
379
+ }
380
+ for (const statement of replicationEntityDdl(plan.target, previousManifest)) {
381
+ yield* sql.unsafe(statement).unprepared;
382
+ }
383
+ // References survive entity/history table renames, including receipts for paused generations
384
+ // and the history of an entity restored under a new name.
385
+ for (const entity of plan.target.entities) {
386
+ const previous = previousManifest?.entities.find((item) => item.id === entity.id)?.name ??
387
+ plan.retained?.current.entities.find((item) => item.id === entity.id && item.removed)
388
+ ?.name;
389
+ if (previous !== undefined && previous !== entity.name) {
390
+ yield* renameReplicationHistory(sql, historyTableName(previous), historyTableName(entity.name));
391
+ }
392
+ }
393
+ yield* sql.unsafe("UPDATE _ontology_replication SET version = $1 WHERE id", [
394
+ REPLICATION_SCHEMA_VERSION,
395
+ ]);
396
+ if (exclusions !== undefined) {
397
+ yield* sql.unsafe("UPDATE _ontology_replication SET exclusions = $1::jsonb WHERE id", [
398
+ JSON.stringify(exclusions),
399
+ ]);
400
+ }
401
+ yield* sql.unsafe("ALTER TABLE _ontology_replication VALIDATE CONSTRAINT _ontology_replication_protocol_floor");
402
+ yield* sql.unsafe("ALTER TABLE _ontology_replication VALIDATE CONSTRAINT _ontology_replication_schema_floor_v5");
403
+ yield* sql.unsafe("ALTER TABLE _ontology_replication VALIDATE CONSTRAINT _ontology_replication_schema_floor_v6");
404
+ yield* sql.unsafe(`
405
+ INSERT INTO ${CATALOG} ("id", "version", "hash", "manifest")
406
+ VALUES (true, $1, $2, $3::jsonb)
407
+ ON CONFLICT ("id") DO UPDATE SET
408
+ "version" = excluded."version",
409
+ "hash" = excluded."hash",
410
+ "manifest" = excluded."manifest",
411
+ "applied_at" = now()
412
+ `, [plan.target.version, plan.target.hash, canonicalJson(encodeManifest(plan.target))]);
413
+ yield* recordRetained(sql, plan);
414
+ if (refresh !== undefined) {
415
+ if (active) {
416
+ const fills = yield* migratedReplicationFills(sql, active, plan.target, refresh, plan.retained?.current);
417
+ yield* refreshReplicationProjection(sql, active, { ...active, manifest: plan.target, selection: refresh, fills }, plan.retained?.current).pipe(Effect.catchTag("ReplicationBaselineFailed", (cause) => Effect.fail(new MigrationRefused({
418
+ message: "replication_publication_pending",
419
+ refusals: [
420
+ {
421
+ code: "replication-publication-pending",
422
+ path: "replication.publication",
423
+ message: "replication_publication_pending",
424
+ },
425
+ ],
426
+ cause,
427
+ }))));
428
+ yield* refreshShadowCapturePolicy(sql);
429
+ yield* sql.unsafe("UPDATE _ontology_replication SET enabled=true WHERE id");
430
+ }
431
+ else {
432
+ // Missing capture metadata is observable damage, so recover from authoritative rows
433
+ // under a fresh incarnation instead of asking the workspace to disable capture.
434
+ yield* prepareReplicationBaseline(sql, {
435
+ generation: randomUUID(),
436
+ manifest: plan.target,
437
+ selection: refresh,
438
+ exclusions: exclusions ?? [],
439
+ newSource: true,
440
+ }).pipe(Effect.mapError((cause) => new CatalogInvalid({
441
+ message: "Replication initialization could not be prepared.",
442
+ cause,
443
+ })));
444
+ }
445
+ }
446
+ yield* sql.unsafe("UPDATE _ontology_replication SET requested_manifest_hash=NULL,requested_manifest_until=NULL WHERE id");
447
+ yield* reconcileWorkflows(plan, sql, options.workspaceId);
448
+ yield* recordWorkflowCatalog(sql, plan.target);
449
+ }));
450
+ return { hash: plan.target.hash, appliedSteps: plan.steps.length, changed: true };
451
+ }).pipe(Effect.withSpan("ontology.migrate.apply", {
452
+ attributes: { "ontology.target_hash": plan.target.hash, "ontology.steps": plan.steps.length },
453
+ }));
454
+ /**
455
+ * Reads the catalog, plans the migration to the target and applies it. Run it on a Neon branch of the
456
+ * workspace database first as a dry run, then on production: the plan is made against each database's
457
+ * own catalog.
458
+ */
459
+ /** The runtime's tables, beside the catalog and the entity tables. */
460
+ export const RUNTIME_TABLES = [
461
+ ...FEDERATION_TABLES,
462
+ "_ontology_replication_scans",
463
+ "_ontology_replication_epochs",
464
+ "_ontology_replication_segments",
465
+ "_ontology_replication_control_jobs",
466
+ ACTION_ATTRIBUTION_TABLE,
467
+ USER_ROLES_TABLE,
468
+ API_KEYS_TABLE,
469
+ ...OAUTH_TABLES,
470
+ ...AGENT_TABLES,
471
+ ATTACHMENTS_TABLE,
472
+ WORKFLOW_STARTS_TABLE,
473
+ "_workflow_admission",
474
+ AGENT_TASKS_TABLE,
475
+ SIGN_IN_EMAILS_TABLE,
476
+ ];
477
+ /**
478
+ * The runtime tables the database has, for `planMigration`'s `existingTables`: a database that an
479
+ * earlier SDK migrated lacks the tables added since.
480
+ * A grants table without app-session binding is reported incomplete so the idempotent OAuth DDL
481
+ * also upgrades an unchanged manifest, and so is an attachments table whose source check predates
482
+ * one of {@link ATTACHMENT_SOURCES}, which the idempotent attachment DDL widens.
483
+ */
484
+ export const readRuntimeTables = (input) => input.sql
485
+ .unsafe(`SELECT "tablename" AS "name" FROM "pg_catalog"."pg_tables" ` +
486
+ `WHERE "schemaname" = current_schema() ` +
487
+ `AND "tablename" IN (${RUNTIME_TABLES.map(quoteLiteral).join(", ")}) ` +
488
+ `AND ("tablename" <> '_oauth_grants' OR EXISTS (` +
489
+ `SELECT 1 FROM information_schema.columns WHERE table_schema = current_schema() ` +
490
+ `AND table_name = '_oauth_grants' AND column_name = 'identity_id')) ` +
491
+ `AND ("tablename" <> ${quoteLiteral(ATTACHMENTS_TABLE)} OR EXISTS (` +
492
+ `SELECT 1 FROM pg_catalog.pg_constraint c ` +
493
+ `JOIN pg_catalog.pg_class t ON t.oid = c.conrelid ` +
494
+ `JOIN pg_catalog.pg_namespace n ON n.oid = t.relnamespace ` +
495
+ `WHERE n.nspname = current_schema() AND t.relname = ${quoteLiteral(ATTACHMENTS_TABLE)} ` +
496
+ `AND c.conname = ${quoteLiteral(ATTACHMENT_SOURCE_CHECK)} ` +
497
+ ATTACHMENT_SOURCES.map((source) => `AND pg_catalog.pg_get_constraintdef(c.oid) LIKE ${quoteLiteral(`%'${source}'%`)} `).join("") +
498
+ `))`)
499
+ .pipe(Effect.map((rows) => new Set(rows.map((row) => row.name))));
500
+ /** Only valid, complete covering indexes satisfy the upgrade; failed builds are retried. */
501
+ export const readHistoryActivityIndexes = (input) => input.sql
502
+ .unsafe(`SELECT c.relname AS name FROM pg_catalog.pg_index i
503
+ JOIN pg_catalog.pg_class c ON c.oid = i.indexrelid
504
+ WHERE i.indisvalid AND i.indisready AND i.indnatts = 2 AND i.indpred IS NULL
505
+ AND pg_catalog.pg_table_is_visible(c.oid)
506
+ AND pg_catalog.pg_get_indexdef(i.indexrelid, 1, true) = 'at'
507
+ AND pg_catalog.pg_get_indexdef(i.indexrelid, 2, true) = 'principal_id'`)
508
+ .pipe(Effect.map((rows) => new Set(rows.map((row) => row.name))));
509
+ export const migrate = (input) => Effect.gen(function* () {
510
+ const current = yield* readCatalog({ sql: input.sql });
511
+ const retained = yield* readRetainedStorage({ sql: input.sql });
512
+ const existingTables = yield* readRuntimeTables({ sql: input.sql });
513
+ const existingHistoryActivityIndexes = yield* readHistoryActivityIndexes({ sql: input.sql });
514
+ const existingStorage = yield* readStorageNames({ sql: input.sql });
515
+ const plan = planMigration({
516
+ current,
517
+ retained,
518
+ existingHistoryActivityIndexes,
519
+ existingStorage,
520
+ target: input.target,
521
+ existingTables,
522
+ ...(input.options === undefined ? {} : { options: input.options }),
523
+ });
524
+ const result = yield* applyMigration(plan, input);
525
+ return { plan, result };
526
+ });
@@ -0,0 +1,46 @@
1
+ import { Schema } from "effect";
2
+ declare const MigrationRefused_base: Schema.Class<MigrationRefused, Schema.TaggedStruct<"MigrationRefused", {
3
+ readonly message: Schema.String;
4
+ readonly refusals: Schema.$Array<Schema.Struct<{
5
+ readonly code: Schema.Literals<readonly ["invalid-manifest", "type-change", "relationship-change", "drop-refused", "name-collision", "identifier-too-long", "rename-conflict", "replication-rebuild-required", "replication-publication-pending"]>;
6
+ readonly path: Schema.String;
7
+ readonly message: Schema.String;
8
+ }>>;
9
+ readonly cause: Schema.optionalKey<Schema.Unknown>;
10
+ }>, import("effect/Cause").YieldableError>;
11
+ /** The plan has refusals; nothing was applied. */
12
+ export declare class MigrationRefused extends MigrationRefused_base {
13
+ }
14
+ declare const CatalogMismatch_base: Schema.Class<CatalogMismatch, Schema.TaggedStruct<"CatalogMismatch", {
15
+ readonly message: Schema.String;
16
+ readonly expectedHash: Schema.optionalKey<Schema.String>;
17
+ readonly actualHash: Schema.optionalKey<Schema.String>;
18
+ }>, import("effect/Cause").YieldableError>;
19
+ /**
20
+ * The applied manifest is not the one the plan was made from: another migration ran in between, or the
21
+ * plan was made against another database. Nothing was applied.
22
+ */
23
+ export declare class CatalogMismatch extends CatalogMismatch_base {
24
+ }
25
+ declare const CatalogInvalid_base: Schema.Class<CatalogInvalid, Schema.TaggedStruct<"CatalogInvalid", {
26
+ readonly message: Schema.String;
27
+ readonly cause: Schema.Unknown;
28
+ }>, import("effect/Cause").YieldableError>;
29
+ /** The `_ontology` row cannot be read as a manifest. */
30
+ export declare class CatalogInvalid extends CatalogInvalid_base {
31
+ }
32
+ declare const MigrationFailed_base: Schema.Class<MigrationFailed, Schema.TaggedStruct<"MigrationFailed", {
33
+ readonly message: Schema.String;
34
+ /** The position of the failed step in `plan.steps`. */
35
+ readonly stepIndex: Schema.Number;
36
+ readonly step: Schema.String;
37
+ readonly cause: Schema.Unknown;
38
+ }>, import("effect/Cause").YieldableError>;
39
+ /**
40
+ * A step failed. A failed transactional step rolls the whole transaction back; non-transactional steps
41
+ * that ran before it stay applied and are safe to run again. The message names the step only; the
42
+ * database's own explanation, which may quote stored values, is kept in `cause`.
43
+ */
44
+ export declare class MigrationFailed extends MigrationFailed_base {
45
+ }
46
+ export {};
@@ -0,0 +1,38 @@
1
+ import { Schema } from "effect";
2
+ import { MigrationRefusal } from "./model.js";
3
+ /** The plan has refusals; nothing was applied. */
4
+ export class MigrationRefused extends Schema.TaggedError()("MigrationRefused", {
5
+ message: Schema.String,
6
+ refusals: Schema.Array(MigrationRefusal),
7
+ cause: Schema.optionalKey(Schema.Unknown),
8
+ }) {
9
+ }
10
+ /**
11
+ * The applied manifest is not the one the plan was made from: another migration ran in between, or the
12
+ * plan was made against another database. Nothing was applied.
13
+ */
14
+ export class CatalogMismatch extends Schema.TaggedError()("CatalogMismatch", {
15
+ message: Schema.String,
16
+ expectedHash: Schema.optionalKey(Schema.String),
17
+ actualHash: Schema.optionalKey(Schema.String),
18
+ }) {
19
+ }
20
+ /** The `_ontology` row cannot be read as a manifest. */
21
+ export class CatalogInvalid extends Schema.TaggedError()("CatalogInvalid", {
22
+ message: Schema.String,
23
+ cause: Schema.Unknown,
24
+ }) {
25
+ }
26
+ /**
27
+ * A step failed. A failed transactional step rolls the whole transaction back; non-transactional steps
28
+ * that ran before it stay applied and are safe to run again. The message names the step only; the
29
+ * database's own explanation, which may quote stored values, is kept in `cause`.
30
+ */
31
+ export class MigrationFailed extends Schema.TaggedError()("MigrationFailed", {
32
+ message: Schema.String,
33
+ /** The position of the failed step in `plan.steps`. */
34
+ stepIndex: Schema.Number,
35
+ step: Schema.String,
36
+ cause: Schema.Unknown,
37
+ }) {
38
+ }
@@ -0,0 +1,10 @@
1
+ export { applyMigration, migrate, readCatalog, readRetainedStorage, readRuntimeTables, readHistoryActivityIndexes, readStorageNames, RUNTIME_TABLES, } from "./apply.js";
2
+ export type { ApplyMigrationError, ApplyMigrationOptions, CatalogInput, MigrateInput, MigrationResult, } from "./apply.js";
3
+ export { CatalogInvalid, CatalogMismatch, MigrationFailed, MigrationRefused } from "./errors.js";
4
+ export { isNoopMigration, MIGRATION_REFUSAL_CODES, MIGRATION_STEP_CLASSIFICATIONS, MIGRATION_STEP_KINDS, MigrationPlan, MigrationRefusal, MigrationStep, RetainedEntity, RetainedStorage, } from "./model.js";
5
+ export type { MigrationRefusalCode, MigrationStepClassification, MigrationStepKind, } from "./model.js";
6
+ export { planMigration } from "./plan.js";
7
+ export { preparePreviewDatabase } from "./preview.js";
8
+ export type { MigrationOptions, PlanMigrationInput, StorageNames } from "./plan.js";
9
+ /** The physical mapping: table, column, enum, index and constraint names, and the DDL builders. */
10
+ export * as OntologyStorage from "./storage.js";
@@ -0,0 +1,7 @@
1
+ export { applyMigration, migrate, readCatalog, readRetainedStorage, readRuntimeTables, readHistoryActivityIndexes, readStorageNames, RUNTIME_TABLES, } from "./apply.js";
2
+ export { CatalogInvalid, CatalogMismatch, MigrationFailed, MigrationRefused } from "./errors.js";
3
+ export { isNoopMigration, MIGRATION_REFUSAL_CODES, MIGRATION_STEP_CLASSIFICATIONS, MIGRATION_STEP_KINDS, MigrationPlan, MigrationRefusal, MigrationStep, RetainedEntity, RetainedStorage, } from "./model.js";
4
+ export { planMigration } from "./plan.js";
5
+ export { preparePreviewDatabase } from "./preview.js";
6
+ /** The physical mapping: table, column, enum, index and constraint names, and the DDL builders. */
7
+ export * as OntologyStorage from "./storage.js";