@cosmicdrift/kumiko-framework 0.413.1 → 0.415.0

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 (479) hide show
  1. package/AGENTS.md +5 -2
  2. package/agents/api/framework-db.md +14 -3
  3. package/agents/api/framework-engine.md +69 -13
  4. package/agents/api/framework-errors.md +1 -1
  5. package/agents/api/framework-event-store.md +14 -0
  6. package/agents/api/framework-ui-types.md +158 -21
  7. package/agents/api/renderer-web.md +112 -11
  8. package/agents/api/testing-helpers.md +3 -2
  9. package/agents/api/testing-stack.md +3 -0
  10. package/agents/api/types.md +248 -24
  11. package/agents/api.md +7 -7
  12. package/agents/boot-rules.md +66 -10
  13. package/agents/examples/api-docs.md +2 -6
  14. package/agents/examples/auth-mfa.md +57 -10
  15. package/agents/examples/chat-channels.md +2 -0
  16. package/agents/examples/crypto-shredding-hr.md +63 -1
  17. package/agents/examples/currencies-global.md +1 -0
  18. package/agents/examples/env-composition.md +7 -11
  19. package/agents/examples/managed-pages.md +90 -1
  20. package/agents/examples/pwa-shell.md +210 -0
  21. package/agents/examples/rate-limiting.md +3 -3
  22. package/agents/examples/record-detail-layout.md +1643 -67
  23. package/agents/examples/workflow-engine.md +16 -12
  24. package/agents/examples.md +1 -0
  25. package/agents/features-index.md +4 -2
  26. package/agents/features.md +22 -7
  27. package/agents/widgets.md +26 -1
  28. package/dist/api/api-constants.d.ts +1 -0
  29. package/dist/api/api-constants.js +4 -0
  30. package/dist/api/auth-middleware.js +4 -3
  31. package/dist/api/auth-routes-shared.js +2 -1
  32. package/dist/api/entity-read-access.d.ts +1 -0
  33. package/dist/api/entity-read-access.js +18 -0
  34. package/dist/api/export/export-route.d.ts +6 -1
  35. package/dist/api/export/export-route.js +27 -1
  36. package/dist/api/export/export-rows.js +19 -3
  37. package/dist/api/request-context-internals.d.ts +2 -0
  38. package/dist/api/request-context-scopes.js +9 -2
  39. package/dist/api/request-context.js +1 -1
  40. package/dist/api/routes.d.ts +2 -0
  41. package/dist/api/routes.js +9 -1
  42. package/dist/api/server-event-dispatcher.js +3 -0
  43. package/dist/api/server-extra-routes.js +2 -1
  44. package/dist/api/server-feature-http-routes.d.ts +9 -0
  45. package/dist/api/server-feature-http-routes.js +109 -0
  46. package/dist/api/server-middleware.js +2 -19
  47. package/dist/api/server-pat-rate-limit-guard.d.ts +3 -0
  48. package/dist/api/server-pat-rate-limit-guard.js +19 -0
  49. package/dist/api/server-rate-limit-wiring.d.ts +10 -0
  50. package/dist/api/server-rate-limit-wiring.js +37 -0
  51. package/dist/api/server-routes.d.ts +4 -12
  52. package/dist/api/server-routes.js +12 -171
  53. package/dist/api/server-schema-route.d.ts +3 -0
  54. package/dist/api/server-schema-route.js +58 -0
  55. package/dist/api/server-wiring.js +2 -37
  56. package/dist/api/server.js +3 -1
  57. package/dist/compliance/override-schema.js +5 -5
  58. package/dist/compliance/sub-processors.js +10 -1
  59. package/dist/crypto/index.d.ts +1 -1
  60. package/dist/crypto/index.js +1 -1
  61. package/dist/crypto/pii-field-encryption.d.ts +2 -0
  62. package/dist/crypto/pii-field-encryption.js +16 -1
  63. package/dist/db/apply-entity-event.js +4 -0
  64. package/dist/db/bun-sql-connection-codes.d.ts +1 -0
  65. package/dist/db/bun-sql-connection-codes.js +7 -0
  66. package/dist/db/collect-table-metas.js +4 -1
  67. package/dist/db/config-seed.js +1 -1
  68. package/dist/db/derived-field-sql.js +15 -13
  69. package/dist/db/derived-related-sql.d.ts +2 -2
  70. package/dist/db/derived-related-sql.js +4 -2
  71. package/dist/db/dialect.d.ts +3 -0
  72. package/dist/db/dialect.js +1 -3
  73. package/dist/db/driver-row-coercion.js +2 -2
  74. package/dist/db/driver-value-preparation.js +1 -1
  75. package/dist/db/eagerload.js +15 -12
  76. package/dist/db/entity-table-meta.d.ts +2 -0
  77. package/dist/db/entity-table-meta.js +7 -0
  78. package/dist/db/event-store-executor-context.js +13 -8
  79. package/dist/db/event-store-executor-read-aggregate-currencies.js +2 -2
  80. package/dist/db/event-store-executor-read-aggregate.js +2 -2
  81. package/dist/db/event-store-executor-read-filter.d.ts +4 -0
  82. package/dist/db/event-store-executor-read-filter.js +28 -11
  83. package/dist/db/event-store-executor-read-search.d.ts +1 -0
  84. package/dist/db/event-store-executor-read-search.js +6 -6
  85. package/dist/db/event-store-executor-read-sort.js +3 -3
  86. package/dist/db/event-store-executor-read-where.js +14 -5
  87. package/dist/db/event-store-executor-read.js +7 -7
  88. package/dist/db/event-store-executor-write.js +50 -95
  89. package/dist/db/executor-managed-tables.js +4 -1
  90. package/dist/db/index.d.ts +4 -2
  91. package/dist/db/index.js +4 -2
  92. package/dist/db/known-table-names.d.ts +1 -0
  93. package/dist/db/known-table-names.js +7 -5
  94. package/dist/db/list-aggregate-labels.d.ts +1 -0
  95. package/dist/db/list-aggregate-labels.js +9 -1
  96. package/dist/db/migrate-generator.js +23 -4
  97. package/dist/db/migrate-rls-diff.d.ts +1 -0
  98. package/dist/db/migrate-rls-diff.js +15 -1
  99. package/dist/db/migrate-runner.js +2 -2
  100. package/dist/db/money.d.ts +1 -1
  101. package/dist/db/money.js +1 -4
  102. package/dist/db/parent-ref-clause.d.ts +6 -2
  103. package/dist/db/parent-ref-clause.js +105 -24
  104. package/dist/db/parent-ref-global-hosts.d.ts +23 -0
  105. package/dist/db/parent-ref-global-hosts.js +85 -0
  106. package/dist/db/production-schema-command-hint.d.ts +1 -0
  107. package/dist/db/production-schema-command-hint.js +3 -0
  108. package/dist/db/queries/backfill-pii.js +55 -29
  109. package/dist/db/queries/ddl.js +13 -2
  110. package/dist/db/queries/event-store-open-streams.d.ts +15 -0
  111. package/dist/db/queries/event-store-open-streams.js +33 -0
  112. package/dist/db/queries/event-store-payload-scrub.d.ts +5 -0
  113. package/dist/db/queries/event-store-payload-scrub.js +11 -0
  114. package/dist/db/queries/event-store.js +0 -1
  115. package/dist/db/queries/raw-sql.js +0 -1
  116. package/dist/db/queries/rebuild-rls-guard.d.ts +2 -1
  117. package/dist/db/queries/rebuild-rls-guard.js +24 -11
  118. package/dist/db/queries/rls-boot-catalog.d.ts +1 -0
  119. package/dist/db/queries/rls-boot-catalog.js +13 -9
  120. package/dist/db/queries/rls-shape.d.ts +3 -1
  121. package/dist/db/queries/rls-shape.js +31 -6
  122. package/dist/db/queries/session-advisory-lock.js +2 -1
  123. package/dist/db/queries/test-stack.js +7 -7
  124. package/dist/db/query.js +16 -11
  125. package/dist/db/rebuild-marker.js +11 -2
  126. package/dist/db/render-rls-ddl.d.ts +2 -0
  127. package/dist/db/render-rls-ddl.js +16 -11
  128. package/dist/db/replay-migration-sql.js +1 -1
  129. package/dist/db/row-level-security-boot-check.js +18 -5
  130. package/dist/db/row-level-security-connection.js +25 -12
  131. package/dist/db/row-level-security-scope.d.ts +2 -1
  132. package/dist/db/row-level-security-scope.js +9 -5
  133. package/dist/db/sql-identifier.d.ts +1 -0
  134. package/dist/db/sql-identifier.js +3 -0
  135. package/dist/db/system-tenant-read-db.d.ts +5 -0
  136. package/dist/db/system-tenant-read-db.js +28 -0
  137. package/dist/db/table-builder.d.ts +3 -1
  138. package/dist/db/table-builder.js +18 -8
  139. package/dist/db/table-info.d.ts +1 -2
  140. package/dist/db/table-introspection.d.ts +3 -0
  141. package/dist/db/table-introspection.js +6 -0
  142. package/dist/db/table-push.d.ts +1 -0
  143. package/dist/db/table-push.js +7 -1
  144. package/dist/db/tenant-db-runner.d.ts +3 -0
  145. package/dist/db/tenant-db-runner.js +19 -1
  146. package/dist/db/transaction-serialization.d.ts +1 -0
  147. package/dist/db/transaction-serialization.js +20 -3
  148. package/dist/db/where-clause.js +11 -2
  149. package/dist/db/write-ownership-failures.d.ts +25 -0
  150. package/dist/db/write-ownership-failures.js +82 -0
  151. package/dist/engine/boot-validator/boot-check.js +7 -1
  152. package/dist/engine/boot-validator/boot-phases-app.js +5 -5
  153. package/dist/engine/boot-validator/boot-phases.js +3 -2
  154. package/dist/engine/boot-validator/boot-rules.d.ts +305 -28
  155. package/dist/engine/boot-validator/boot-rules.js +4 -0
  156. package/dist/engine/boot-validator/bundled-lists-table.js +2 -2
  157. package/dist/engine/boot-validator/card-meta-overflow-rules.d.ts +2 -2
  158. package/dist/engine/boot-validator/card-meta-overflow-rules.js +2 -2
  159. package/dist/engine/boot-validator/card-meta-overflow.js +8 -5
  160. package/dist/engine/boot-validator/config-deps.d.ts +0 -1
  161. package/dist/engine/boot-validator/config-deps.js +0 -28
  162. package/dist/engine/boot-validator/config-key-rules.d.ts +0 -15
  163. package/dist/engine/boot-validator/config-key-rules.js +0 -15
  164. package/dist/engine/boot-validator/dashboard-screen-target.d.ts +22 -0
  165. package/dist/engine/boot-validator/dashboard-screen-target.js +20 -0
  166. package/dist/engine/boot-validator/dashboard-stat-navigate.d.ts +1 -0
  167. package/dist/engine/boot-validator/dashboard-stat-navigate.js +25 -17
  168. package/dist/engine/boot-validator/definition-webhook-events-rules.d.ts +5 -0
  169. package/dist/engine/boot-validator/definition-webhook-events-rules.js +5 -0
  170. package/dist/engine/boot-validator/derived-sql-fields.js +1 -2
  171. package/dist/engine/boot-validator/entity-declaration-rules.d.ts +5 -0
  172. package/dist/engine/boot-validator/entity-declaration-rules.js +5 -0
  173. package/dist/engine/boot-validator/entity-list-screens.d.ts +1 -0
  174. package/dist/engine/boot-validator/entity-list-screens.js +35 -13
  175. package/dist/engine/boot-validator/entity-structure-rules.d.ts +5 -0
  176. package/dist/engine/boot-validator/entity-structure-rules.js +5 -0
  177. package/dist/engine/boot-validator/list-column-layout.js +10 -6
  178. package/dist/engine/boot-validator/list-row-guidance-rules.d.ts +67 -0
  179. package/dist/engine/boot-validator/list-row-guidance-rules.js +67 -0
  180. package/dist/engine/boot-validator/list-row-guidance.d.ts +20 -0
  181. package/dist/engine/boot-validator/list-row-guidance.js +143 -0
  182. package/dist/engine/boot-validator/list-sort-summary-rules.d.ts +42 -0
  183. package/dist/engine/boot-validator/list-sort-summary-rules.js +42 -0
  184. package/dist/engine/boot-validator/list-sort-summary.d.ts +5 -0
  185. package/dist/engine/boot-validator/list-sort-summary.js +160 -0
  186. package/dist/engine/boot-validator/list-table-options.js +15 -1
  187. package/dist/engine/boot-validator/list-table-rules.d.ts +10 -5
  188. package/dist/engine/boot-validator/list-table-rules.js +10 -5
  189. package/dist/engine/boot-validator/list-toolbar-options.d.ts +10 -0
  190. package/dist/engine/boot-validator/list-toolbar-options.js +30 -0
  191. package/dist/engine/boot-validator/named-filter-rules.d.ts +42 -2
  192. package/dist/engine/boot-validator/named-filter-rules.js +42 -2
  193. package/dist/engine/boot-validator/ownership.js +10 -1
  194. package/dist/engine/boot-validator/parent-ref.js +87 -50
  195. package/dist/engine/boot-validator/projection-list-screens.d.ts +1 -0
  196. package/dist/engine/boot-validator/projection-list-screens.js +32 -1
  197. package/dist/engine/boot-validator/query-output-columns.js +62 -9
  198. package/dist/engine/boot-validator/query-output-guidance.d.ts +7 -0
  199. package/dist/engine/boot-validator/query-output-guidance.js +40 -0
  200. package/dist/engine/boot-validator/query-refs.js +34 -1
  201. package/dist/engine/boot-validator/row-decoration.d.ts +11 -0
  202. package/dist/engine/boot-validator/row-decoration.js +16 -0
  203. package/dist/engine/boot-validator/screens-actions.js +1 -1
  204. package/dist/engine/boot-validator/screens-dashboard-links.d.ts +10 -0
  205. package/dist/engine/boot-validator/screens-dashboard-links.js +36 -0
  206. package/dist/engine/boot-validator/screens-dashboard-narrow.d.ts +4 -0
  207. package/dist/engine/boot-validator/screens-dashboard-narrow.js +211 -0
  208. package/dist/engine/boot-validator/screens-dashboard-rules.d.ts +84 -4
  209. package/dist/engine/boot-validator/screens-dashboard-rules.js +84 -4
  210. package/dist/engine/boot-validator/screens-dashboard.js +29 -7
  211. package/dist/engine/boot-validator/screens-kind-entity-list.js +32 -27
  212. package/dist/engine/boot-validator/screens-kind-projection-detail-guidance.d.ts +3 -0
  213. package/dist/engine/boot-validator/screens-kind-projection-detail-guidance.js +46 -0
  214. package/dist/engine/boot-validator/screens-kind-projection-detail-rules.d.ts +20 -0
  215. package/dist/engine/boot-validator/screens-kind-projection-detail-rules.js +20 -0
  216. package/dist/engine/boot-validator/screens-kind-projection-detail.js +2 -0
  217. package/dist/engine/boot-validator/screens-kind-projection-list.js +4 -0
  218. package/dist/engine/boot-validator/screens-kind-rules.d.ts +25 -0
  219. package/dist/engine/boot-validator/screens-kind-rules.js +25 -0
  220. package/dist/engine/boot-validator/screens-lists.d.ts +8 -2
  221. package/dist/engine/boot-validator/screens-lists.js +19 -3
  222. package/dist/engine/boot-validator/screens.js +1 -1
  223. package/dist/engine/boot-validator/sort-nulls.d.ts +2 -0
  224. package/dist/engine/boot-validator/sort-nulls.js +15 -0
  225. package/dist/engine/boot-validator/zod-shape.d.ts +2 -1
  226. package/dist/engine/boot-validator/zod-shape.js +19 -1
  227. package/dist/engine/build-app-schema.js +4 -0
  228. package/dist/engine/config-helpers.d.ts +1 -2
  229. package/dist/engine/config-helpers.js +6 -7
  230. package/dist/engine/define-feature.js +1 -0
  231. package/dist/engine/define-handler.d.ts +1 -0
  232. package/dist/engine/define-handler.js +4 -2
  233. package/dist/engine/definition-violations.js +2 -2
  234. package/dist/engine/entity-handlers.js +3 -8
  235. package/dist/engine/entity-list-runtime-options.js +9 -8
  236. package/dist/engine/factories.d.ts +2 -0
  237. package/dist/engine/feature-config-events-jobs.js +1 -0
  238. package/dist/engine/feature-entity-handlers.js +5 -2
  239. package/dist/engine/field-access.d.ts +1 -1
  240. package/dist/engine/field-access.js +7 -10
  241. package/dist/engine/find-entity.js +3 -3
  242. package/dist/engine/form-derivations.js +3 -3
  243. package/dist/engine/index.d.ts +3 -3
  244. package/dist/engine/index.js +2 -2
  245. package/dist/engine/named-filter-roles.d.ts +3 -0
  246. package/dist/engine/named-filter-roles.js +15 -0
  247. package/dist/engine/pipeline.js +0 -1
  248. package/dist/engine/project-app-schema-for-roles.js +17 -2
  249. package/dist/engine/qualified-name.js +0 -1
  250. package/dist/engine/registry-facade.js +1 -2
  251. package/dist/engine/registry-state.d.ts +1 -1
  252. package/dist/engine/registry-state.js +5 -2
  253. package/dist/engine/registry-validate.js +2 -1
  254. package/dist/engine/resolve-named-list-filters.js +5 -2
  255. package/dist/engine/schema-builder.js +9 -11
  256. package/dist/engine/screen-helpers.d.ts +12 -0
  257. package/dist/engine/screen-helpers.js +17 -1
  258. package/dist/engine/soft-delete-cleanup.js +3 -5
  259. package/dist/engine/state-machine.js +0 -1
  260. package/dist/engine/steps/_database-clock.d.ts +2 -0
  261. package/dist/engine/steps/_database-clock.js +6 -0
  262. package/dist/engine/steps/compute.js +1 -1
  263. package/dist/engine/steps/retry.js +5 -1
  264. package/dist/engine/steps/return.js +0 -1
  265. package/dist/engine/steps/wait-for-event.js +2 -1
  266. package/dist/engine/steps/wait.js +2 -1
  267. package/dist/engine/system-user.d.ts +2 -2
  268. package/dist/engine/system-user.js +2 -2
  269. package/dist/engine/types/handlers.d.ts +1 -1
  270. package/dist/engine/types/handlers.js +1 -1
  271. package/dist/engine/types/screen.d.ts +1 -1
  272. package/dist/engine/types/screen.js +1 -1
  273. package/dist/engine/webhook-contracts.d.ts +2 -3
  274. package/dist/engine/webhook-contracts.js +2 -25
  275. package/dist/engine/webhook-events.js +48 -29
  276. package/dist/engine/webhook-payload-strictness.d.ts +7 -0
  277. package/dist/engine/webhook-payload-strictness.js +53 -0
  278. package/dist/env/_zod-introspect.d.ts +1 -0
  279. package/dist/env/dry-run.d.ts +1 -1
  280. package/dist/env/dry-run.js +1 -1
  281. package/dist/env/field-meta.d.ts +4 -0
  282. package/dist/env/field-meta.js +67 -0
  283. package/dist/env/field-rules.d.ts +9 -0
  284. package/dist/env/field-rules.js +46 -0
  285. package/dist/env/index.d.ts +3 -3
  286. package/dist/env/index.js +16 -71
  287. package/dist/env/internals.d.ts +3 -0
  288. package/dist/env/internals.js +1 -2
  289. package/dist/env/required-env.d.ts +3 -1
  290. package/dist/env/required-env.js +5 -2
  291. package/dist/errors/reasons.d.ts +1 -0
  292. package/dist/errors/reasons.js +4 -0
  293. package/dist/errors/serialize.js +2 -2
  294. package/dist/errors/write-error-info.js +0 -2
  295. package/dist/es-ops/operations-schema.js +18 -7
  296. package/dist/event-store/admin-api.js +3 -3
  297. package/dist/event-store/event-store.js +0 -3
  298. package/dist/event-store/index.d.ts +1 -0
  299. package/dist/event-store/index.js +1 -0
  300. package/dist/event-store/transfer.js +1 -1
  301. package/dist/files/assert-file-refs-belong-to-tenant.d.ts +2 -1
  302. package/dist/files/assert-file-refs-belong-to-tenant.js +15 -13
  303. package/dist/files/bind-pending-file-refs.d.ts +3 -1
  304. package/dist/files/bind-pending-file-refs.js +54 -27
  305. package/dist/files/copy-pending-file-refs-to-tenant.js +7 -3
  306. package/dist/files/create-file-ref.d.ts +4 -1
  307. package/dist/files/create-file-ref.js +14 -3
  308. package/dist/files/default-file-guard.js +4 -1
  309. package/dist/files/file-claim.d.ts +6 -0
  310. package/dist/files/file-claim.js +17 -0
  311. package/dist/files/file-field-slots.d.ts +2 -0
  312. package/dist/files/file-field-slots.js +28 -0
  313. package/dist/files/file-ref-entity.d.ts +3 -0
  314. package/dist/files/file-ref-entity.js +2 -0
  315. package/dist/files/file-ref-table.d.ts +3 -0
  316. package/dist/files/file-routes.d.ts +4 -1
  317. package/dist/files/file-routes.js +80 -16
  318. package/dist/files/in-memory-provider.d.ts +1 -1
  319. package/dist/files/in-memory-provider.js +2 -1
  320. package/dist/files/index.d.ts +1 -1
  321. package/dist/files/index.js +1 -1
  322. package/dist/files/invalid-file-ref-error.d.ts +2 -0
  323. package/dist/files/invalid-file-ref-error.js +15 -0
  324. package/dist/files/local-provider.js +9 -2
  325. package/dist/files/provider-resolver.js +1 -1
  326. package/dist/files/rebind-file-ref.d.ts +3 -2
  327. package/dist/files/rebind-file-ref.js +24 -18
  328. package/dist/files/resolve-file-handles.d.ts +13 -0
  329. package/dist/files/resolve-file-handles.js +57 -0
  330. package/dist/files/storage-tracking.d.ts +1 -1
  331. package/dist/files/storage-tracking.js +5 -2
  332. package/dist/files/sweep-stale-pending-file-refs.js +10 -4
  333. package/dist/files/types.d.ts +4 -0
  334. package/dist/files/types.js +10 -0
  335. package/dist/files/upload-field-resolution.d.ts +1 -0
  336. package/dist/files/upload-field-resolution.js +16 -2
  337. package/dist/files/upload-ledger.js +1 -1
  338. package/dist/i18n/required-surface-guidance-keys.d.ts +3 -0
  339. package/dist/i18n/required-surface-guidance-keys.js +9 -0
  340. package/dist/i18n/required-surface-keys.js +21 -5
  341. package/dist/internal/boot-rule-table-expectations.d.ts +2 -0
  342. package/dist/internal/boot-rule-table-expectations.js +29 -0
  343. package/dist/internal/row-level-security.d.ts +1 -0
  344. package/dist/internal/row-level-security.js +1 -0
  345. package/dist/internal/testing.d.ts +1 -0
  346. package/dist/internal/testing.js +1 -0
  347. package/dist/jobs/index.d.ts +1 -0
  348. package/dist/jobs/index.js +1 -0
  349. package/dist/jobs/job-load-events.d.ts +10 -0
  350. package/dist/jobs/job-load-events.js +12 -0
  351. package/dist/jobs/job-runner-context.js +6 -158
  352. package/dist/jobs/job-runner-dispatch.d.ts +7 -0
  353. package/dist/jobs/job-runner-dispatch.js +57 -0
  354. package/dist/jobs/job-runner-event-triggers.js +18 -9
  355. package/dist/jobs/job-runner-execution.js +5 -2
  356. package/dist/jobs/job-runner-facets.d.ts +48 -0
  357. package/dist/jobs/job-runner-facets.js +156 -0
  358. package/dist/jobs/job-runner-gates.js +19 -11
  359. package/dist/jobs/job-runner-helpers.d.ts +5 -1
  360. package/dist/jobs/job-runner-helpers.js +18 -3
  361. package/dist/jobs/job-runner-scope.d.ts +1 -0
  362. package/dist/jobs/job-runner-scope.js +2 -0
  363. package/dist/jobs/job-runner-tenant-cap-lock.d.ts +2 -0
  364. package/dist/jobs/job-runner-tenant-cap-lock.js +30 -0
  365. package/dist/jobs/job-runner-types.d.ts +1 -0
  366. package/dist/jobs/job-runner.js +39 -70
  367. package/dist/jobs/obliterate-job-queues.d.ts +6 -0
  368. package/dist/jobs/obliterate-job-queues.js +23 -0
  369. package/dist/lifecycle/lifecycle.js +1 -1
  370. package/dist/migrations/event-header-scrub.d.ts +11 -0
  371. package/dist/migrations/event-header-scrub.js +33 -0
  372. package/dist/migrations/event-payload-scrub.d.ts +1 -1
  373. package/dist/migrations/event-payload-scrub.js +36 -4
  374. package/dist/migrations/index.d.ts +1 -0
  375. package/dist/migrations/index.js +2 -0
  376. package/dist/migrations/kumiko-drift.d.ts +5 -2
  377. package/dist/migrations/kumiko-drift.js +51 -14
  378. package/dist/migrations/pending-rebuilds.js +4 -5
  379. package/dist/observability/sensitive-filter.js +0 -12
  380. package/dist/pipeline/aggregate-type-removal.js +17 -4
  381. package/dist/pipeline/context-services.d.ts +2 -0
  382. package/dist/pipeline/context-services.js +5 -2
  383. package/dist/pipeline/dispatch-batch.js +4 -3
  384. package/dist/pipeline/dispatch-context-helpers.d.ts +11 -0
  385. package/dist/pipeline/dispatch-context-helpers.js +58 -0
  386. package/dist/pipeline/dispatch-nested-write.d.ts +7 -0
  387. package/dist/pipeline/dispatch-nested-write.js +119 -0
  388. package/dist/pipeline/dispatch-query.js +10 -3
  389. package/dist/pipeline/dispatch-scope.js +4 -3
  390. package/dist/pipeline/dispatch-shared.d.ts +2 -6
  391. package/dist/pipeline/dispatch-shared.js +6 -38
  392. package/dist/pipeline/dispatch-write.d.ts +0 -1
  393. package/dist/pipeline/dispatch-write.js +3 -302
  394. package/dist/pipeline/dispatcher-utils.js +6 -0
  395. package/dist/pipeline/effective-system-scope.d.ts +3 -0
  396. package/dist/pipeline/effective-system-scope.js +22 -0
  397. package/dist/pipeline/event-dispatcher-delivery.d.ts +1 -0
  398. package/dist/pipeline/event-dispatcher-delivery.js +20 -9
  399. package/dist/pipeline/event-dispatcher.d.ts +6 -1
  400. package/dist/pipeline/event-dispatcher.js +6 -7
  401. package/dist/pipeline/handler-context-auth.d.ts +3 -2
  402. package/dist/pipeline/handler-context-auth.js +3 -4
  403. package/dist/pipeline/handler-context-db.js +11 -4
  404. package/dist/pipeline/handler-context-dispatch.js +2 -2
  405. package/dist/pipeline/handler-context-events.d.ts +8 -3
  406. package/dist/pipeline/handler-context-events.js +20 -65
  407. package/dist/pipeline/handler-context-member-resolution.js +16 -8
  408. package/dist/pipeline/handler-context-notify.d.ts +1 -0
  409. package/dist/pipeline/handler-context-notify.js +2 -0
  410. package/dist/pipeline/handler-context-phase-denials.js +3 -2
  411. package/dist/pipeline/handler-context-projection.d.ts +3 -0
  412. package/dist/pipeline/handler-context-projection.js +39 -0
  413. package/dist/pipeline/handler-context-scope.d.ts +1 -1
  414. package/dist/pipeline/handler-context-scope.js +14 -2
  415. package/dist/pipeline/index.d.ts +1 -1
  416. package/dist/pipeline/index.js +1 -1
  417. package/dist/pipeline/irreversible-operation-gate.js +36 -10
  418. package/dist/pipeline/lifecycle-pipeline.d.ts +1 -0
  419. package/dist/pipeline/lifecycle-pipeline.js +7 -4
  420. package/dist/pipeline/member-reader.js +4 -2
  421. package/dist/pipeline/msp-rebuild.js +1 -1
  422. package/dist/pipeline/nested-write-parent-guard.d.ts +5 -0
  423. package/dist/pipeline/nested-write-parent-guard.js +81 -0
  424. package/dist/pipeline/projection-rebuild.d.ts +2 -0
  425. package/dist/pipeline/projection-rebuild.js +16 -7
  426. package/dist/pipeline/projection-state.js +4 -6
  427. package/dist/pipeline/system-hooks.js +36 -6
  428. package/dist/pipeline/write-result-masking.js +31 -3
  429. package/dist/pipeline/write-transition-guard.d.ts +7 -0
  430. package/dist/pipeline/write-transition-guard.js +95 -0
  431. package/dist/schema-cli/shared.d.ts +2 -0
  432. package/dist/schema-cli/shared.js +4 -2
  433. package/dist/schema-cli/validate-command.js +43 -28
  434. package/dist/search/meilisearch-adapter-internals.d.ts +2 -0
  435. package/dist/search/meilisearch-adapter-internals.js +5 -0
  436. package/dist/search/meilisearch-adapter.d.ts +1 -0
  437. package/dist/search/meilisearch-adapter.js +17 -11
  438. package/dist/search/reindex-entity.d.ts +2 -0
  439. package/dist/search/reindex-entity.js +32 -4
  440. package/dist/search/reindex-tenants-search.js +20 -4
  441. package/dist/time/tz-context.js +1 -1
  442. package/dist/ui-types/card-column-roles.d.ts +6 -0
  443. package/dist/ui-types/card-column-roles.js +21 -3
  444. package/dist/ui-types/index.d.ts +3 -3
  445. package/dist/ui-types/index.js +2 -2
  446. package/dist/utils/ids.js +0 -1
  447. package/dist/utils/index.d.ts +1 -0
  448. package/dist/utils/index.js +1 -0
  449. package/dist/utils/return-path-limit.d.ts +1 -0
  450. package/dist/utils/return-path-limit.js +1 -0
  451. package/package.json +5 -3
  452. package/presets/biome-app.json +39 -21
  453. package/presets/biome-plugins/admin-api.grit +10 -0
  454. package/presets/biome-plugins/error-reasons.grit +53 -0
  455. package/presets/biome-plugins/es-literal-writes-tests.grit +18 -0
  456. package/presets/biome-plugins/es-literal-writes.grit +22 -0
  457. package/presets/biome-plugins/i18n-locale-terminology-de.grit +15 -0
  458. package/presets/biome-plugins/i18n-locale-terminology-romance.grit +10 -0
  459. package/presets/biome-plugins/no-create-test-dispatcher.grit +5 -0
  460. package/presets/biome-plugins/no-css-properties-type.grit +7 -0
  461. package/presets/biome-plugins/no-date-api.grit +11 -0
  462. package/presets/biome-plugins/no-direct-fetch.grit +16 -0
  463. package/presets/biome-plugins/no-direct-fs.grit +16 -0
  464. package/presets/biome-plugins/no-external-font-cdn-css.grit +9 -0
  465. package/presets/biome-plugins/no-external-font-cdn.grit +12 -0
  466. package/presets/biome-plugins/no-raw-hooks.grit +10 -0
  467. package/presets/biome-plugins/no-same-folder-barrel-import.grit +11 -0
  468. package/presets/biome-plugins/no-screen-container-classes.grit +7 -0
  469. package/presets/biome-plugins/no-skipped-or-retried-tests.grit +34 -0
  470. package/presets/biome-plugins/no-temporal-polyfill-require.grit +10 -0
  471. package/presets/biome-plugins/raw-html-in-web.grit +40 -0
  472. package/presets/biome-plugins/raw-ui-in-app.grit +142 -0
  473. package/presets/biome-plugins/restricted-event-store-symbols.grit +18 -0
  474. package/presets/biome-plugins/test-title.grit +20 -0
  475. package/presets/biome-plugins/unsafe-json-parse.grit +12 -0
  476. package/presets/biome-rules.json +467 -0
  477. package/src/changes.json +366 -0
  478. package/dist/engine/minor-units.d.ts +0 -2
  479. package/dist/engine/minor-units.js +0 -8
@@ -18,11 +18,11 @@ import { errorCodeOf, isPlainObject } from "@cosmicdrift/kumiko-types/type-guard
18
18
  import { compareByCodepoint } from "../utils/compare.js";
19
19
  import { describeIndexChange, renderAddColumn, renderColumnChange, whereSqlEqual, } from "./migrate-change-render.js";
20
20
  import { diffPrimaryKey, renderPrimaryKeyChange, } from "./migrate-primary-key.js";
21
- import { diffRowLevelSecurity, renderRowLevelSecurityChanges, } from "./migrate-rls-diff.js";
21
+ import { diffRowLevelSecurity, renderPolicyDropsBeforeTenantColumnChange, renderRowLevelSecurityChanges, } from "./migrate-rls-diff.js";
22
22
  import { renderIndex, renderTableDdl } from "./render-ddl.js";
23
- import { isTableRowLevelSecurityRecord, rowLevelSecurityByTable, } from "./render-rls-ddl.js";
23
+ import { isTableRowLevelSecurityRecord, rowLevelSecurityByTable, TENANT_COLUMN, } from "./render-rls-ddl.js";
24
24
  import { findRetiredTableDrops } from "./retired-framework-tables.js";
25
- import { quoteIdent } from "./sql-identifier.js";
25
+ import { quoteIdent, quoteLiteral } from "./sql-identifier.js";
26
26
  const SNAPSHOT_VERSION = 1;
27
27
  function isSnapshot(value) {
28
28
  return (isPlainObject(value) &&
@@ -303,6 +303,17 @@ function renderChangedIndex(td, idxChange) {
303
303
  renderIndex(td.tableName, nextIdxMeta),
304
304
  ];
305
305
  }
306
+ // The guard line deliberately lacks the `DESTRUCTIVE:` marker: replay expands that marker up to the
307
+ // first `;`, which would cut the DO block apart.
308
+ function renderDroppedColumn(tableName, colName) {
309
+ const table = quoteIdent(tableName);
310
+ const column = quoteIdent(colName);
311
+ const message = quoteLiteral(`${tableName}.${colName} is not empty`);
312
+ return [
313
+ `-- DO $$ BEGIN IF EXISTS (SELECT 1 FROM ${table} WHERE ${column} IS NOT NULL) THEN RAISE EXCEPTION ${message}; END IF; END $$; -- guard: uncomment together with the drop below`,
314
+ `-- DESTRUCTIVE: ALTER TABLE ${table} DROP COLUMN ${column}; -- uncomment + ensure backup`,
315
+ ];
316
+ }
306
317
  function renderInPlaceTableChanges(td) {
307
318
  return [
308
319
  ...td.newColumns.map((col) => renderAddColumn(td.tableName, col)),
@@ -311,7 +322,7 @@ function renderInPlaceTableChanges(td) {
311
322
  ...td.newIndexes.map((idx) => renderIndex(td.tableName, idx)),
312
323
  ...td.changedIndexes.flatMap((idxChange) => renderChangedIndex(td, idxChange)),
313
324
  ...td.droppedIndexes.map((name) => `-- (review) DROP INDEX IF EXISTS ${quoteIdent(name)};`),
314
- ...td.droppedColumns.map((colName) => `-- DESTRUCTIVE: ALTER TABLE ${quoteIdent(td.tableName)} DROP COLUMN ${quoteIdent(colName)}; -- uncomment + ensure backup`),
325
+ ...td.droppedColumns.flatMap((colName) => renderDroppedColumn(td.tableName, colName)),
315
326
  "",
316
327
  ];
317
328
  }
@@ -347,6 +358,13 @@ function renderRetiredDrops(retiredDrops) {
347
358
  "",
348
359
  ];
349
360
  }
361
+ function tablesChangingTenantColumn(changedTables) {
362
+ return new Set(changedTables
363
+ .filter((td) => !isRecreatedManagedTable(td) &&
364
+ (td.droppedColumns.includes(TENANT_COLUMN) ||
365
+ td.changedColumns.some((change) => change.name === TENANT_COLUMN && change.typeChanged !== undefined)))
366
+ .map((td) => td.tableName));
367
+ }
350
368
  // Render the diff as a SQL-file content with header-comment + grouped
351
369
  // statements. Destructive operations (DROP TABLE/COLUMN, DROP INDEX where
352
370
  // the index serves performance) are emitted as commented-out statements
@@ -357,6 +375,7 @@ export function renderMigrationSql(diff, options) {
357
375
  const lines = [
358
376
  ...renderMigrationHeader(options),
359
377
  ...renderNewTables(diff.newTables),
378
+ ...renderPolicyDropsBeforeTenantColumnChange(rowLevelSecurityChanges, tablesChangingTenantColumn(diff.changedTables)),
360
379
  ...renderChangedTables(diff.changedTables),
361
380
  ...renderRowLevelSecurityChanges(options.rowLevelSecurityChanges),
362
381
  ...renderDroppedTables(diff.droppedTables),
@@ -17,4 +17,5 @@ type RowLevelSecuritySnapshotView = {
17
17
  };
18
18
  export declare function diffRowLevelSecurity(previous: RowLevelSecuritySnapshotView | null, next: RowLevelSecuritySnapshotView, recreatedTables: ReadonlySet<string>): RowLevelSecurityChange[];
19
19
  export declare function renderRowLevelSecurityChanges(changes?: readonly RowLevelSecurityChange[]): string[];
20
+ export declare function renderPolicyDropsBeforeTenantColumnChange(changes: readonly RowLevelSecurityChange[] | undefined, tablesChangingTenantColumn: ReadonlySet<string>): string[];
20
21
  export {};
@@ -1,6 +1,6 @@
1
1
  // Row level security part of the migration generator: diffs the per-table policy
2
2
  // specs between two snapshots and renders the resulting DDL section.
3
- import { isSameTableRowLevelSecurity, renderDisableRowLevelSecurity, renderEnableRowLevelSecurity, } from "./render-rls-ddl.js";
3
+ import { isSameTableRowLevelSecurity, renderDisableRowLevelSecurity, renderDropPolicy, renderEnableRowLevelSecurity, } from "./render-rls-ddl.js";
4
4
  import { quoteIdent } from "./sql-identifier.js";
5
5
  function specOf(view, tableName) {
6
6
  const byTable = view?.rowLevelSecurity;
@@ -59,3 +59,17 @@ export function renderRowLevelSecurityChanges(changes = []) {
59
59
  "",
60
60
  ];
61
61
  }
62
+ // Postgres refuses ALTER COLUMN TYPE / DROP COLUMN on a column a policy still references, so the
63
+ // previous policies must go before the in-place table changes; the section after them recreates them.
64
+ export function renderPolicyDropsBeforeTenantColumnChange(changes = [], tablesChangingTenantColumn) {
65
+ const statements = changes.flatMap((change) => {
66
+ if (!tablesChangingTenantColumn.has(change.tableName) || change.previous === undefined) {
67
+ return [];
68
+ }
69
+ const tableSql = quoteIdent(change.tableName);
70
+ return change.previous.policies.map((policy) => renderDropPolicy(tableSql, policy.name));
71
+ });
72
+ if (statements.length === 0)
73
+ return [];
74
+ return ["-- === Row level security (pre) ===", ...statements, ""];
75
+ }
@@ -19,7 +19,7 @@ import { join } from "node:path";
19
19
  import { propertyOf } from "@cosmicdrift/kumiko-types/type-guards";
20
20
  import { applyRowLevelSecurityScope } from "./queries/rls-scope.js";
21
21
  import { asRawClient, hasBegin, } from "./query.js";
22
- import { SYSTEM_ROW_LEVEL_SECURITY_SCOPE } from "./row-level-security-scope.js";
22
+ import { systemRowLevelSecurityScope } from "./row-level-security-scope.js";
23
23
  // Advisory-lock key (random 32-bit integer, stable). Prevents two Pods
24
24
  // booting at the same time from both running migrate apply (the second
25
25
  // blocks until the first finishes).
@@ -264,7 +264,7 @@ export async function runMigrations(db, migrations) {
264
264
  await conn.unsafe("BEGIN");
265
265
  try {
266
266
  // Transaction-local, so the next migration's BEGIN starts clean; migrations rewrite every tenant's rows.
267
- await applyRowLevelSecurityScope(conn, SYSTEM_ROW_LEVEL_SECURITY_SCOPE);
267
+ await applyRowLevelSecurityScope(conn, systemRowLevelSecurityScope("migration run"));
268
268
  for (const stmt of m.statements) {
269
269
  await conn.unsafe(stmt);
270
270
  }
@@ -1,5 +1,5 @@
1
1
  import type { EntityDefinition } from "@cosmicdrift/kumiko-types/fields";
2
- import { toMinorUnits } from "../engine/minor-units.ts";
2
+ import { toMinorUnits } from "@cosmicdrift/kumiko-types/minor-units";
3
3
  export declare const FRAMEWORK_DEFAULT_CURRENCY: "EUR";
4
4
  export { toMinorUnits };
5
5
  export declare function moneyPayloadToMinorUnits(raw: unknown): number | undefined;
package/dist/db/money.js CHANGED
@@ -31,12 +31,9 @@ import { DEFAULT_CURRENCIES } from "../engine/field-helpers.js";
31
31
  // Unlike locatedTimestamp, we retain the field name `<name>` as the
32
32
  // amount column (legacy DB convention for money — `SUM(buying_price)` remains
33
33
  // idiomatic). `<name>Currency` is the additional column.
34
- import { MINOR_UNIT_SCALE, toMinorUnits } from "../engine/minor-units.js";
34
+ import { toMajorUnits, toMinorUnits } from "@cosmicdrift/kumiko-types/minor-units";
35
35
  export const FRAMEWORK_DEFAULT_CURRENCY = DEFAULT_CURRENCIES[0]; // "EUR"
36
36
  export { toMinorUnits };
37
- function toMajorUnits(amountScaled) {
38
- return amountScaled / MINOR_UNIT_SCALE;
39
- }
40
37
  // One money field's write payload — `{ amount, currency }` or a bare number
41
38
  // (both MAJOR units, see file header) — reduced to minor units. This is the
42
39
  // counterpart a write-handler needs when comparing a top-level money field
@@ -5,8 +5,12 @@ import type { SessionUser } from "../engine/types/index.ts";
5
5
  import type { Table } from "./event-store-executor-context.ts";
6
6
  import type { TenantDb } from "./tenant-db.ts";
7
7
  export type { ParentVisibilityOption } from "@cosmicdrift/kumiko-types/event-store-executor-types";
8
- export declare function buildParentRefClause(entity: EntityDefinition, table: Table, tableName: string, user: SessionUser, db: TenantDb, option: ParentVisibilityOption | undefined, opts: {
8
+ type ParentRefGateOptions = {
9
9
  readonly includeDeleted?: boolean;
10
10
  readonly narrowTypes?: ReadonlySet<string>;
11
11
  readonly requireReadHandler?: boolean;
12
- }): OwnershipClause;
12
+ };
13
+ export type ParentRefGateMode = "statement" | "globalHostsOnly";
14
+ export declare function buildParentRefClause(entity: EntityDefinition, table: Table, tableName: string, user: SessionUser, db: TenantDb, option: ParentVisibilityOption | undefined, opts: ParentRefGateOptions): OwnershipClause;
15
+ export declare function readsGlobalHostsUnderTenantScope(db: TenantDb, joinTable: Table): boolean;
16
+ export declare function buildParentRefGate(entity: EntityDefinition, table: Table, tableName: string, user: SessionUser, db: TenantDb, option: ParentVisibilityOption | undefined, opts: ParentRefGateOptions, mode: ParentRefGateMode): OwnershipClause;
@@ -1,7 +1,8 @@
1
1
  import { buildOwnershipClause } from "../engine/ownership.js";
2
2
  import { SYSTEM_TENANT_ID, UUID_SHAPE_PATTERN } from "../engine/types/identifiers.js";
3
3
  import { buildEntityTable, physicalColumnName } from "./table-builder.js";
4
- import { schemaTableName } from "./table-introspection.js";
4
+ import { asEntityTableMeta, schemaTableName } from "./table-introspection.js";
5
+ import { isGlobalTenancyTable } from "./tenant-db-runner.js";
5
6
  const candidateStaticsCache = new WeakMap();
6
7
  function candidateStaticsFor(candidateName, candidate, resolveTable) {
7
8
  if (resolveTable !== undefined)
@@ -49,6 +50,14 @@ function selectCandidates(parentRef, option, narrowTypes, requireReadHandler) {
49
50
  return candidates;
50
51
  }
51
52
  export function buildParentRefClause(entity, table, tableName, user, db, option, opts) {
53
+ return buildParentRefGate(entity, table, tableName, user, db, option, opts, "statement");
54
+ }
55
+ // A tenant-scoped statement reads a global host table under row level security, which hides the
56
+ // system tenant rows a global host lives on; a join table that is global itself runs in the system scope.
57
+ export function readsGlobalHostsUnderTenantScope(db, joinTable) {
58
+ return db.mode === "tenant" && !isGlobalTenancyTable(joinTable);
59
+ }
60
+ export function buildParentRefGate(entity, table, tableName, user, db, option, opts, mode) {
52
61
  const parentRef = entity.parentRef;
53
62
  if (parentRef === undefined)
54
63
  return { kind: "pass" };
@@ -70,40 +79,112 @@ export function buildParentRefClause(entity, table, tableName, user, db, option,
70
79
  const candidates = selectCandidates(parentRef, option, opts.narrowTypes, opts.requireReadHandler === true);
71
80
  if (candidates.length === 0)
72
81
  return { kind: "empty" };
73
- // The uuid shape and the tenant ids are bound once and shared by every
74
- // branch. The shape is a parameter rather than a literal because shiftParams
75
- // rewrites `$<digits>` anywhere in the text, including inside a string.
76
- const params = [UUID_SHAPE_PATTERN];
77
- const uuidIdx = params.length;
78
- let tenantIdx;
79
- if (db.mode === "tenant") {
80
- params.push(db.tenantId, SYSTEM_TENANT_ID);
81
- tenantIdx = [params.length - 1, params.length];
82
- }
82
+ const { branches, params } = collectGateBranches(candidates, mode, {
83
+ db,
84
+ user,
85
+ option,
86
+ joinTableName: tableName,
87
+ typeCol,
88
+ idCol,
89
+ includeDeleted: opts.includeDeleted === true,
90
+ globalHostsHidden: readsGlobalHostsUnderTenantScope(db, table),
91
+ });
92
+ if (branches.length === 0)
93
+ return { kind: "empty" };
94
+ return { kind: "sql", sqlText: `(${branches.join(" OR ")})`, params };
95
+ }
96
+ function collectGateBranches(candidates, mode, gate) {
97
+ // The uuid shape and the tenant ids are bound once, together with the first kept
98
+ // EXISTS branch, and shared by every later one: Postgres rejects a statement with
99
+ // a parameter it cannot type, which an unused one is. The shape is a parameter
100
+ // rather than a literal because shiftParams rewrites `$<digits>` anywhere in the
101
+ // text, including inside a string.
102
+ const params = [];
103
+ let shared;
83
104
  const branches = [];
84
105
  for (const [candidateName, candidate] of candidates) {
85
- const branch = buildCandidateBranch(candidateName, candidate, user, {
86
- joinTableName: tableName,
87
- typeCol,
88
- idCol,
89
- uuidIdx,
90
- tenantIdx,
91
- includeDeleted: opts.includeDeleted === true,
106
+ const isHiddenGlobalHost = isHiddenGlobalHostCandidate(candidateName, candidate, gate);
107
+ if (mode === "globalHostsOnly" &&
108
+ isExcludedFromHostOnlyCheck(candidate, isHiddenGlobalHost, gate)) {
109
+ continue;
110
+ }
111
+ const resolvesHostIds = mode === "statement" && isHiddenGlobalHost;
112
+ const pendingShared = resolvesHostIds || shared !== undefined
113
+ ? undefined
114
+ : planSharedBinding(gate.db, params.length);
115
+ const binding = pendingShared ?? shared;
116
+ const branchContext = {
117
+ joinTableName: gate.joinTableName,
118
+ typeCol: gate.typeCol,
119
+ idCol: gate.idCol,
120
+ uuidIdx: binding?.uuidIdx ?? 0,
121
+ tenantIdx: binding?.tenantIdx,
122
+ includeDeleted: gate.includeDeleted,
92
123
  // Ownership params are laid out right after the branch's own host-type
93
124
  // placeholder. Nothing reaches the shared `params` until the branch is
94
125
  // kept, so a dropped branch reserves no index and can't shift the
95
126
  // positional binding of the branches after it.
96
- typeParamIdx: params.length + 1,
97
- resolveTable: option.resolveTable,
98
- });
127
+ typeParamIdx: params.length + (pendingShared?.values.length ?? 0) + 1,
128
+ resolveTable: gate.option.resolveTable,
129
+ };
130
+ const branch = resolvesHostIds
131
+ ? buildResolvedHostBranch(gate.option.globalHostIds?.get(candidateName), branchContext)
132
+ : buildCandidateBranch(candidateName, candidate, gate.user, branchContext);
99
133
  if (branch === undefined)
100
134
  continue;
135
+ if (pendingShared !== undefined) {
136
+ params.push(...pendingShared.values);
137
+ shared = pendingShared;
138
+ }
101
139
  params.push(candidateName, ...branch.params);
102
140
  branches.push(branch.sqlText);
103
141
  }
104
- if (branches.length === 0)
105
- return { kind: "empty" };
106
- return { kind: "sql", sqlText: `(${branches.join(" OR ")})`, params };
142
+ return { branches, params };
143
+ }
144
+ function isHiddenGlobalHostCandidate(candidateName, candidate, gate) {
145
+ return (gate.globalHostsHidden &&
146
+ candidate.tenancy === "global" &&
147
+ !tableReadsSystemRows(candidateStaticsFor(candidateName, candidate, gate.option.resolveTable)));
148
+ }
149
+ function isExcludedFromHostOnlyCheck(candidate, isHiddenGlobalHost, gate) {
150
+ return !isHiddenGlobalHost || hostReadRuleNeedsRowLevelSecurity(candidate, gate.user);
151
+ }
152
+ // The registry table carries the flag for implicitly classified reference data too, which the
153
+ // entity definition alone does not say; such a host is visible to the tenant-scoped EXISTS arm.
154
+ function tableReadsSystemRows(statics) {
155
+ return asEntityTableMeta(statics.table)?.systemRowsReadable === true;
156
+ }
157
+ // The system-scope host check has no row level security as a second layer, so a where-rule
158
+ // subquery over a tenant table would see other tenants' rows; such a host opens no arm (fail closed).
159
+ function hostReadRuleNeedsRowLevelSecurity(candidate, user) {
160
+ const readRules = candidate.access?.read;
161
+ if (readRules === undefined)
162
+ return false;
163
+ const applicable = user.roles.flatMap((role) => {
164
+ const rule = readRules[role];
165
+ return rule === undefined ? [] : [rule];
166
+ });
167
+ return (!applicable.includes("all") &&
168
+ applicable.some((rule) => rule !== "all" && rule.kind === "where"));
169
+ }
170
+ function planSharedBinding(db, boundSoFar) {
171
+ if (db.mode !== "tenant") {
172
+ return { values: [UUID_SHAPE_PATTERN], uuidIdx: boundSoFar + 1, tenantIdx: undefined };
173
+ }
174
+ return {
175
+ values: [UUID_SHAPE_PATTERN, db.tenantId, SYSTEM_TENANT_ID],
176
+ uuidIdx: boundSoFar + 1,
177
+ tenantIdx: [boundSoFar + 2, boundSoFar + 3],
178
+ };
179
+ }
180
+ // Unresolved ids leave the arm out: a host the statement cannot check is never treated as readable.
181
+ function buildResolvedHostBranch(hostIds, ctx) {
182
+ if (hostIds === undefined || hostIds.length === 0)
183
+ return undefined;
184
+ return {
185
+ sqlText: `("${ctx.joinTableName}"."${ctx.typeCol}" = $${ctx.typeParamIdx} AND "${ctx.joinTableName}"."${ctx.idCol}"::text = ANY($${ctx.typeParamIdx + 1}::text[]))`,
186
+ params: [hostIds],
187
+ };
107
188
  }
108
189
  // One `entity_type = $n AND EXISTS (...)` arm, or undefined when the host's own
109
190
  // read ownership can never match — an unsatisfiable arm is dropped rather than
@@ -0,0 +1,23 @@
1
+ import type { ParentVisibilityOption } from "@cosmicdrift/kumiko-types/event-store-executor-types";
2
+ import type { EntityDefinition } from "@cosmicdrift/kumiko-types/fields";
3
+ import type { EntityId } from "@cosmicdrift/kumiko-types/identifiers";
4
+ import type { SessionUser } from "../engine/types/index.ts";
5
+ import type { Table } from "./event-store-executor-context.ts";
6
+ import type { TenantDb } from "./tenant-db.ts";
7
+ export declare const MAX_RESOLVED_GLOBAL_HOST_IDS = 5000;
8
+ export type GlobalHostRowScope = {
9
+ readonly kind: "row";
10
+ readonly rowId: EntityId;
11
+ } | {
12
+ readonly kind: "list";
13
+ readonly pinnedHostIds: ReadonlySet<string> | undefined;
14
+ };
15
+ export declare function withGlobalParentHosts(ctx: {
16
+ readonly entity: EntityDefinition;
17
+ readonly table: Table;
18
+ }, user: SessionUser, db: TenantDb, option: ParentVisibilityOption | undefined, gate: {
19
+ readonly includeDeleted: boolean;
20
+ readonly narrowTypes: ReadonlySet<string> | undefined;
21
+ }, rowScope: GlobalHostRowScope, options?: {
22
+ readonly maxResolvedHostIds?: number;
23
+ }): Promise<ParentVisibilityOption | undefined>;
@@ -0,0 +1,85 @@
1
+ import { createFallbackLogger } from "../logging/utils.js";
2
+ import { buildParentRefGate, readsGlobalHostsUnderTenantScope } from "./parent-ref-clause.js";
3
+ import { executeRawQueryRead } from "./queries/raw-sql.js";
4
+ import { systemScopedRunner } from "./row-level-security-scope.js";
5
+ import { physicalColumnName } from "./table-builder.js";
6
+ import { schemaTableName } from "./table-introspection.js";
7
+ import { tenantDbRunner } from "./tenant-db-runner.js";
8
+ const log = createFallbackLogger("parent-ref-global-hosts");
9
+ export const MAX_RESOLVED_GLOBAL_HOST_IDS = 5000;
10
+ // The gated statement runs under the tenant scope, where a global host's EXISTS sees no row. The
11
+ // same host check runs here in the system scope, limited to the caller's join rows by an explicit
12
+ // tenant filter, and only host ids leave it; the gated statement keeps its own row level security.
13
+ export async function withGlobalParentHosts(ctx, user, db, option, gate, rowScope, options) {
14
+ const { entity, table } = ctx;
15
+ const parentRef = entity.parentRef;
16
+ if (option === undefined || parentRef === undefined || db.mode !== "tenant")
17
+ return option;
18
+ if (!readsGlobalHostsUnderTenantScope(db, table) || table["tenantId"] === undefined) {
19
+ return option;
20
+ }
21
+ const joinTableName = String(schemaTableName(table));
22
+ const hostCheck = buildParentRefGate(entity, table, joinTableName, user, db, option, gate, "globalHostsOnly");
23
+ if (hostCheck.kind !== "sql")
24
+ return option;
25
+ if (rowScope.kind === "list" && rowScope.pinnedHostIds?.size === 0) {
26
+ return { ...option, globalHostIds: new Map() };
27
+ }
28
+ const isUnpinnedList = rowScope.kind === "list" && rowScope.pinnedHostIds === undefined;
29
+ // Correlating the gated statement with the host check would need a SECURITY DEFINER function,
30
+ // so an unpinned list resolves ids up front and this cap is the deliberate bound on that set.
31
+ const maxHostIds = options?.maxResolvedHostIds ?? MAX_RESOLVED_GLOBAL_HOST_IDS;
32
+ const query = buildHostQuery({
33
+ parentRef,
34
+ table,
35
+ joinTableName,
36
+ hostCheck,
37
+ tenantId: db.tenantId,
38
+ rowScope,
39
+ includeDeleted: gate.includeDeleted,
40
+ rowLimit: isUnpinnedList ? maxHostIds + 1 : undefined,
41
+ });
42
+ const rows = await executeRawQueryRead(systemScopedRunner(tenantDbRunner(db), "parent-ref gate checks global hosts, whose rows carry the system tenant, for the caller's own join rows"), query.sqlText, query.params);
43
+ if (isUnpinnedList && rows.length > maxHostIds) {
44
+ log.warn("global host ids of an unpinned list exceed the cap; the global host arm is left out", {
45
+ table: joinTableName,
46
+ limit: maxHostIds,
47
+ });
48
+ return { ...option, globalHostIds: new Map() };
49
+ }
50
+ return { ...option, globalHostIds: groupHostIdsByType(rows) };
51
+ }
52
+ function groupHostIdsByType(rows) {
53
+ const globalHostIds = new Map();
54
+ for (const row of rows) {
55
+ const ids = globalHostIds.get(row.entityType);
56
+ if (ids === undefined)
57
+ globalHostIds.set(row.entityType, [row.entityId]);
58
+ else
59
+ ids.push(row.entityId);
60
+ }
61
+ return globalHostIds;
62
+ }
63
+ function buildHostQuery(input) {
64
+ const { parentRef, table, joinTableName, hostCheck, rowScope } = input;
65
+ const params = [...hostCheck.params, input.tenantId];
66
+ const column = (field) => `"${joinTableName}"."${physicalColumnName(table, field)}"`;
67
+ const whereParts = [`${column("tenantId")} = $${params.length}`, hostCheck.sqlText];
68
+ if (rowScope.kind === "row") {
69
+ params.push(rowScope.rowId);
70
+ whereParts.push(`${column("id")} = $${params.length}`);
71
+ }
72
+ else if (rowScope.pinnedHostIds !== undefined) {
73
+ params.push([...rowScope.pinnedHostIds]);
74
+ whereParts.push(`${column(parentRef.entityIdField)}::text = ANY($${params.length}::text[])`);
75
+ }
76
+ if (input.rowLimit !== undefined && !input.includeDeleted && table["isDeleted"] !== undefined) {
77
+ whereParts.push(`${column("isDeleted")} = FALSE`);
78
+ }
79
+ const limitClause = input.rowLimit === undefined ? "" : ` LIMIT ${input.rowLimit}`;
80
+ return {
81
+ sqlText: `SELECT DISTINCT ${column(parentRef.entityTypeField)}::text AS "entityType", ${column(parentRef.entityIdField)}::text AS "entityId" ` +
82
+ `FROM "${joinTableName}" WHERE ${whereParts.join(" AND ")}${limitClause}`,
83
+ params,
84
+ };
85
+ }
@@ -0,0 +1 @@
1
+ export declare const PRODUCTION_SCHEMA_COMMAND_HINT = "In the production image run `bun /app/kumiko.js schema <subcommand>` instead of `bun kumiko-schema <subcommand>`.";
@@ -0,0 +1,3 @@
1
+ // The `kumiko-schema` bin ships with dev-server and is absent from the production image, whose
2
+ // standalone bundle only understands `kumiko schema …`; boot errors fire in both places.
3
+ export const PRODUCTION_SCHEMA_COMMAND_HINT = "In the production image run `bun /app/kumiko.js schema <subcommand>` instead of `bun kumiko-schema <subcommand>`.";
@@ -45,7 +45,10 @@
45
45
  // tenant-keyed ciphertext of a userOwned field moves under the user the
46
46
  // strict chain (stages 1+2, never whenAbsent) names; user-keyed ciphertext
47
47
  // moves under the projection's current owner when that is another user (an
48
- // owner change made before owner transitions re-keyed the value). An owner
48
+ // owner change made before owner transitions re-keyed the value). Only the latest
49
+ // event that carries the field moves: older events were written for the previous
50
+ // owner, and a newer event means the live path already re-keyed the value, so a
51
+ // forget of the previous owner must keep erasing the older ones. An owner
49
52
  // cleared again (owner → none) is not recoverable from the projection: such
50
53
  // values stay tenant-keyed, unlike the live path that keeps the last owner.
51
54
  // For whenAbsent: "self" fields the same stage moves tenant-keyed ciphertext
@@ -130,6 +133,36 @@ async function backfillAllEventBatches(db, registry, options) {
130
133
  }
131
134
  return { ...total, failures };
132
135
  }
136
+ function failureReason(e) {
137
+ const reason = e instanceof Error ? e.message : String(e);
138
+ if (!(e instanceof SubjectResolutionError))
139
+ return reason;
140
+ return (`${reason} (retry with { resolveOwnerFromProjection: true } to resolve the owner ` +
141
+ "from the entity's projection table, and/or { eraseUnresolvableSubjects: true } to " +
142
+ "erase fields whose subject stays unresolvable)");
143
+ }
144
+ function selectEventBatch(raw, aggregateTypes, catalogTypes, options, batchSize) {
145
+ if (options.eventIds) {
146
+ return raw.unsafe(`SELECT "id", "aggregate_id", "aggregate_type", "tenant_id", "type", "payload"
147
+ FROM "kumiko_events"
148
+ WHERE ("aggregate_type" = ANY($1::text[]) OR "type" = ANY($2::text[])) AND "id" = ANY($3::bigint[])
149
+ ORDER BY "id" ASC`, [
150
+ toPostgresArrayLiteral(aggregateTypes),
151
+ toPostgresArrayLiteral(catalogTypes),
152
+ toPostgresArrayLiteral([...options.eventIds]),
153
+ ]);
154
+ }
155
+ return raw.unsafe(`SELECT "id", "aggregate_id", "aggregate_type", "tenant_id", "type", "payload"
156
+ FROM "kumiko_events"
157
+ WHERE ("aggregate_type" = ANY($1::text[]) OR "type" = ANY($2::text[])) AND "id" > $3::bigint
158
+ ORDER BY "id" ASC
159
+ LIMIT $4`, [
160
+ toPostgresArrayLiteral(aggregateTypes),
161
+ toPostgresArrayLiteral(catalogTypes),
162
+ String(options.afterEventId ?? 0),
163
+ batchSize,
164
+ ]);
165
+ }
133
166
  // Processes exactly one batch. Snapshots of the batch's touched aggregates are
134
167
  // dropped inside the same call so an abort between batches never leaves a
135
168
  // snapshot that caches plaintext for an already-encrypted stream.
@@ -164,25 +197,7 @@ export async function backfillEventPiiEncryptionBatch(db, registry, options = {}
164
197
  });
165
198
  if (aggregateTypes.length === 0 && catalogTypes.length === 0)
166
199
  return emptyBatch();
167
- const rows = await (options.eventIds
168
- ? raw.unsafe(`SELECT "id", "aggregate_id", "aggregate_type", "tenant_id", "type", "payload"
169
- FROM "kumiko_events"
170
- WHERE ("aggregate_type" = ANY($1::text[]) OR "type" = ANY($2::text[])) AND "id" = ANY($3::bigint[])
171
- ORDER BY "id" ASC`, [
172
- toPostgresArrayLiteral(aggregateTypes),
173
- toPostgresArrayLiteral(catalogTypes),
174
- toPostgresArrayLiteral([...options.eventIds]),
175
- ])
176
- : raw.unsafe(`SELECT "id", "aggregate_id", "aggregate_type", "tenant_id", "type", "payload"
177
- FROM "kumiko_events"
178
- WHERE ("aggregate_type" = ANY($1::text[]) OR "type" = ANY($2::text[])) AND "id" > $3::bigint
179
- ORDER BY "id" ASC
180
- LIMIT $4`, [
181
- toPostgresArrayLiteral(aggregateTypes),
182
- toPostgresArrayLiteral(catalogTypes),
183
- String(options.afterEventId ?? 0),
184
- batchSize,
185
- ]));
200
+ const rows = await selectEventBatch(raw, aggregateTypes, catalogTypes, options, batchSize);
186
201
  const last = rows[rows.length - 1];
187
202
  if (last === undefined)
188
203
  return emptyBatch();
@@ -214,16 +229,8 @@ export async function backfillEventPiiEncryptionBatch(db, registry, options = {}
214
229
  touchedEventTypes.add(row.type);
215
230
  }
216
231
  catch (e) {
217
- const reason = e instanceof Error ? e.message : String(e);
218
232
  firstFailedEventId ??= String(row.id);
219
- result.failures.push({
220
- eventId: String(row.id),
221
- reason: e instanceof SubjectResolutionError
222
- ? `${reason} (retry with { resolveOwnerFromProjection: true } to resolve the owner ` +
223
- "from the entity's projection table, and/or { eraseUnresolvableSubjects: true } to " +
224
- "erase fields whose subject stays unresolvable)"
225
- : reason,
226
- });
233
+ result.failures.push({ eventId: String(row.id), reason: failureReason(e) });
227
234
  }
228
235
  }
229
236
  // Snapshots may cache the plaintext state of touched aggregates.
@@ -389,6 +396,7 @@ export async function backfillEventPiiEncryptionBatch(db, registry, options = {}
389
396
  kmsCtx,
390
397
  dryRun: options.dryRun === true,
391
398
  isForgottenSubject: (subject) => isForgottenSubject(subject, row.aggregate_id),
399
+ hasNewerValueOfField: (fieldName) => aggregateHasNewerValueOfField(row, fieldName),
392
400
  predictOutcome: predictEncryptOutcome,
393
401
  }, {
394
402
  entity,
@@ -399,6 +407,7 @@ export async function backfillEventPiiEncryptionBatch(db, registry, options = {}
399
407
  subjectSource,
400
408
  ownerFallback,
401
409
  projectionOwnerRow,
410
+ isSupersededHistory: section === payload["previous"] && isRecord(payload["changes"]),
402
411
  });
403
412
  if (rekey.kind === "rekeyed") {
404
413
  section[field] = rekey.value;
@@ -460,6 +469,19 @@ export async function backfillEventPiiEncryptionBatch(db, registry, options = {}
460
469
  }
461
470
  return subject.kind === "user" && forgottenAggregates.has(subject.userId);
462
471
  }
472
+ // A later event that sets the field (`changes`, or the flat payload of a created event). An
473
+ // explicit null counts: it replaced the value this event carries, so that value is stale.
474
+ async function aggregateHasNewerValueOfField(event, fieldName) {
475
+ const rows = await raw.unsafe(`SELECT 1 AS found FROM "kumiko_events"
476
+ WHERE "aggregate_id" = $1 AND "tenant_id" = $2 AND "id" > $3::bigint
477
+ AND (
478
+ jsonb_exists("payload" -> 'changes', $4::text)
479
+ OR ("payload" -> 'changes' IS NULL AND "payload" -> 'previous' IS NULL
480
+ AND jsonb_exists("payload", $4::text))
481
+ )
482
+ LIMIT 1`, [event.aggregate_id, event.tenant_id, event.id, fieldName]);
483
+ return rows.length > 0;
484
+ }
463
485
  // A tenant destroyed before its name was record-owned never had a record key
464
486
  // to erase, and destroy tombstones the row instead of emitting *.forgotten —
465
487
  // read_tenants.destroyed_at is the only durable marker.
@@ -503,6 +525,10 @@ async function rekeyTenantKeyedValue(deps, target) {
503
525
  : null;
504
526
  if (userSubject === null)
505
527
  return { kind: "unchanged" };
528
+ if (keyedUnder?.kind === "user" &&
529
+ (target.isSupersededHistory || (await deps.hasNewerValueOfField(field)))) {
530
+ return { kind: "unchanged" };
531
+ }
506
532
  if (await deps.isForgottenSubject(userSubject))
507
533
  return { kind: "erased" };
508
534
  if (deps.dryRun) {
@@ -1,5 +1,5 @@
1
1
  import { asRawClient, transaction } from "../query.js";
2
- import { renderTableRowLevelSecurityDdl, tenantRowLevelSecurityFor } from "../render-rls-ddl.js";
2
+ import { renderDropPolicy, renderTableRowLevelSecurityDdl, SYSTEM_TENANT_READ_POLICY, tenantRowLevelSecurityFor, } from "../render-rls-ddl.js";
3
3
  import { quoteIdent } from "../sql-identifier.js";
4
4
  import { readRowLevelSecurityShape } from "./rls-shape.js";
5
5
  import { quoteTableIdent } from "./table-ops.js";
@@ -23,12 +23,19 @@ export async function createIndexIfNotExists(db, indexKind, indexName, tableName
23
23
  const where = whereSql !== undefined ? ` WHERE ${whereSql}` : "";
24
24
  await asRawClient(db).unsafe(`CREATE ${indexKind} IF NOT EXISTS ${quoteTableIdent(indexName)} ON ${quoteTableIdent(tableName)} (${columnList})${where}`);
25
25
  }
26
+ function expectsSystemReadPolicy(meta) {
27
+ return (tenantRowLevelSecurityFor(meta)?.policies.some((policy) => policy.name === SYSTEM_TENANT_READ_POLICY) === true);
28
+ }
26
29
  // Policy texts are not compared: a hand-edited kumiko policy is the operator's to keep, and the
27
30
  // catalog check of the boot path reports it. Foreign policies are ignored.
28
31
  function hasKumikoRowLevelSecurity(state, meta) {
29
32
  const spec = tenantRowLevelSecurityFor(meta);
30
33
  if (state === undefined || spec === undefined || !state.enabled || !state.forced)
31
34
  return false;
35
+ if (!expectsSystemReadPolicy(meta) &&
36
+ state.policies.some((actual) => actual.name === SYSTEM_TENANT_READ_POLICY)) {
37
+ return false;
38
+ }
32
39
  return spec.policies.every((expected) => state.policies.some((actual) => actual.name === expected.name &&
33
40
  actual.kind === expected.kind &&
34
41
  actual.command === expected.command));
@@ -49,7 +56,11 @@ export async function applyTableRowLevelSecurity(db, meta) {
49
56
  if (hasKumikoRowLevelSecurity(await readRowLevelSecurityShape(tx, meta.tableName), meta)) {
50
57
  return;
51
58
  }
52
- for (const statement of statements)
59
+ // A policy the table no longer qualifies for (marker removed) would survive the re-create below.
60
+ const staleSystemRead = expectsSystemReadPolicy(meta)
61
+ ? []
62
+ : [renderDropPolicy(quoteIdent(meta.tableName), SYSTEM_TENANT_READ_POLICY)];
63
+ for (const statement of [...staleSystemRead, ...statements])
53
64
  await tx.unsafe(statement);
54
65
  });
55
66
  }
@@ -0,0 +1,15 @@
1
+ import type { DbRunner } from "../connection.ts";
2
+ export type OpenStreamsArgs = {
3
+ readonly aggregateType: string;
4
+ readonly startedType: string;
5
+ readonly closingTypes: readonly string[];
6
+ readonly startedBeforeIso: string;
7
+ readonly limit: number;
8
+ readonly afterId?: string;
9
+ };
10
+ export type OpenStream = {
11
+ readonly id: string;
12
+ readonly tenantId: string;
13
+ readonly aggregateId: string;
14
+ };
15
+ export declare function selectOpenStreamsStartedBefore(db: DbRunner, args: OpenStreamsArgs): Promise<readonly OpenStream[]>;