@cosmicdrift/kumiko-samples 0.406.0 → 0.409.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 (238) hide show
  1. package/package.json +1 -1
  2. package/packages/bundled-features/package.json +26 -4
  3. package/packages/bundled-features/src/account-security/feature.ts +9 -1
  4. package/packages/bundled-features/src/admin-shell/changes.json +6 -0
  5. package/packages/bundled-features/src/admin-shell/feature.ts +4 -1
  6. package/packages/bundled-features/src/agent-tools/agent-manifest.ts +1 -0
  7. package/packages/bundled-features/src/agent-tools/changes.json +6 -0
  8. package/packages/bundled-features/src/agent-tools/tool-catalog.ts +1 -0
  9. package/packages/bundled-features/src/agent-tools/types.ts +4 -0
  10. package/packages/bundled-features/src/audit/event-classification.ts +1 -0
  11. package/packages/bundled-features/src/auth-email-password/bootstrap.ts +1 -0
  12. package/packages/bundled-features/src/auth-email-password/errors.ts +18 -66
  13. package/packages/bundled-features/src/auth-email-password/web/auth-client.ts +30 -64
  14. package/packages/bundled-features/src/auth-email-password/web/auth-redirect.ts +2 -2
  15. package/packages/bundled-features/src/auth-email-password/web/confirm-account-unlock-screen.tsx +20 -66
  16. package/packages/bundled-features/src/auth-email-password/web/index.ts +1 -0
  17. package/packages/bundled-features/src/auth-email-password/web/read-path-param.ts +8 -0
  18. package/packages/bundled-features/src/auth-email-password/web/return-path.ts +3 -2
  19. package/packages/bundled-features/src/auth-email-password/web/token-confirm-screen.tsx +97 -0
  20. package/packages/bundled-features/src/auth-email-password/web/verify-email-screen.tsx +20 -68
  21. package/packages/bundled-features/src/auth-foundation/boot-checks.ts +22 -15
  22. package/packages/bundled-features/src/auth-foundation/boot-rules.ts +33 -0
  23. package/packages/bundled-features/src/auth-mfa/errors.ts +12 -42
  24. package/packages/bundled-features/src/auth-mfa/feature-exports.ts +6 -45
  25. package/packages/bundled-features/src/auth-mfa/feature.ts +8 -19
  26. package/packages/bundled-features/src/auth-mfa/web/mfa-client.ts +19 -33
  27. package/packages/bundled-features/src/billing-foundation/consumer-protection/termination-notify.ts +1 -0
  28. package/packages/bundled-features/src/billing-foundation/web/plan-price.ts +20 -7
  29. package/packages/bundled-features/src/cap-counter/stock-cap-guard.ts +1 -0
  30. package/packages/bundled-features/src/channel-in-app/changes.json +7 -0
  31. package/packages/bundled-features/src/channel-in-app/feature.ts +2 -0
  32. package/packages/bundled-features/src/channel-in-app/handlers/read-state-by-keys.query.ts +35 -0
  33. package/packages/bundled-features/src/channel-in-app/in-app-channel.ts +1 -0
  34. package/packages/bundled-features/src/channel-in-app/tables.ts +5 -1
  35. package/packages/bundled-features/src/contact/challenge.ts +41 -0
  36. package/packages/bundled-features/src/contact/changes.json +27 -0
  37. package/packages/bundled-features/src/contact/client/contact-client-source.ts +203 -0
  38. package/packages/bundled-features/src/contact/entity.ts +168 -0
  39. package/packages/bundled-features/src/contact/feature.ts +171 -0
  40. package/packages/bundled-features/src/contact/handlers/access.ts +17 -0
  41. package/packages/bundled-features/src/contact/handlers/attempts.ts +76 -0
  42. package/packages/bundled-features/src/contact/handlers/challenge.query.ts +44 -0
  43. package/packages/bundled-features/src/contact/handlers/forward-request.write.ts +98 -0
  44. package/packages/bundled-features/src/contact/handlers/mark-done.write.ts +40 -0
  45. package/packages/bundled-features/src/contact/handlers/notify-reporter-in-app.write.ts +48 -0
  46. package/packages/bundled-features/src/contact/handlers/open-count.query.ts +15 -0
  47. package/packages/bundled-features/src/contact/handlers/open-count.ts +17 -0
  48. package/packages/bundled-features/src/contact/handlers/replies.query.ts +29 -0
  49. package/packages/bundled-features/src/contact/handlers/reply.write.ts +197 -0
  50. package/packages/bundled-features/src/contact/handlers/report.write.ts +126 -0
  51. package/packages/bundled-features/src/contact/handlers/request-delivery.query.ts +143 -0
  52. package/packages/bundled-features/src/contact/handlers/request-detail.query.ts +50 -0
  53. package/packages/bundled-features/src/contact/handlers/request-list.query.ts +14 -0
  54. package/packages/bundled-features/src/contact/handlers/send-reply-mail.write.ts +124 -0
  55. package/packages/bundled-features/src/contact/handlers/send-test.write.ts +45 -0
  56. package/packages/bundled-features/src/contact/handlers/submit.write.ts +194 -0
  57. package/packages/bundled-features/src/contact/handlers/take-over-uploads.ts +47 -0
  58. package/packages/bundled-features/src/contact/i18n.ts +189 -0
  59. package/packages/bundled-features/src/contact/index.ts +29 -0
  60. package/packages/bundled-features/src/contact/lib.ts +176 -0
  61. package/packages/bundled-features/src/contact/mail.ts +401 -0
  62. package/packages/bundled-features/src/contact/options.ts +95 -0
  63. package/packages/bundled-features/src/contact/panels.ts +28 -0
  64. package/packages/bundled-features/src/contact/payloads.ts +106 -0
  65. package/packages/bundled-features/src/contact/pow.ts +22 -0
  66. package/packages/bundled-features/src/contact/screens.ts +506 -0
  67. package/packages/bundled-features/src/contact/subject.ts +13 -0
  68. package/packages/bundled-features/src/contact/user-agent.ts +39 -0
  69. package/packages/bundled-features/src/contact/user-data-hooks.ts +180 -0
  70. package/packages/bundled-features/src/contact/web/constants.ts +160 -0
  71. package/packages/bundled-features/src/contact/web/index.ts +29 -0
  72. package/packages/bundled-features/src/crypto-shredding/handlers/forget-subject.write.ts +5 -16
  73. package/packages/bundled-features/src/data-retention/changes.json +6 -0
  74. package/packages/bundled-features/src/data-retention/feature.ts +16 -2
  75. package/packages/bundled-features/src/data-retention/index.ts +5 -0
  76. package/packages/bundled-features/src/data-retention/run-retention-cleanup.ts +138 -41
  77. package/packages/bundled-features/src/data-retention/tenant-destruction-hold.ts +196 -0
  78. package/packages/bundled-features/src/delivery/address-opt-out.ts +1 -0
  79. package/packages/bundled-features/src/delivery/changes.json +7 -0
  80. package/packages/bundled-features/src/delivery/channel-context.ts +2 -0
  81. package/packages/bundled-features/src/delivery/delivery-service.ts +29 -5
  82. package/packages/bundled-features/src/delivery/events.ts +2 -0
  83. package/packages/bundled-features/src/delivery/feature.ts +3 -2
  84. package/packages/bundled-features/src/delivery/handlers/attempts-by-keys.query.ts +55 -0
  85. package/packages/bundled-features/src/delivery/handlers/log.query.ts +1 -1
  86. package/packages/bundled-features/src/delivery/jobs.ts +5 -0
  87. package/packages/bundled-features/src/delivery/tables.ts +13 -2
  88. package/packages/bundled-features/src/delivery/types.ts +3 -0
  89. package/packages/bundled-features/src/delivery/unsubscribe-page.ts +2 -0
  90. package/packages/bundled-features/src/delivery/web/delivery-channel-cell.tsx +1 -1
  91. package/packages/bundled-features/src/delivery/web/delivery-error-cell.tsx +1 -1
  92. package/packages/bundled-features/src/delivery/web/delivery-status-cell.tsx +1 -1
  93. package/packages/bundled-features/src/delivery/web/delivery-time-cell.tsx +3 -2
  94. package/packages/bundled-features/src/delivery/web/delivery-type-cell.tsx +1 -1
  95. package/packages/bundled-features/src/delivery/web/public-names.ts +1 -0
  96. package/packages/bundled-features/src/document-ingest-foundation/boot-checks.ts +14 -9
  97. package/packages/bundled-features/src/document-ingest-foundation/boot-rules.ts +22 -0
  98. package/packages/bundled-features/src/document-ingest-foundation/changes.json +6 -0
  99. package/packages/bundled-features/src/document-ingest-foundation/events.ts +17 -0
  100. package/packages/bundled-features/src/document-ingest-foundation/feature.ts +39 -1
  101. package/packages/bundled-features/src/document-ingest-foundation/index.ts +10 -0
  102. package/packages/bundled-features/src/document-ingest-foundation/report-ingest-progress.ts +43 -0
  103. package/packages/bundled-features/src/document-ingest-foundation/tables.ts +43 -0
  104. package/packages/bundled-features/src/files-tenant-data/changes.json +6 -0
  105. package/packages/bundled-features/src/files-tenant-data/hooks.ts +4 -1
  106. package/packages/bundled-features/src/folders/web/folder-manager.tsx +8 -9
  107. package/packages/bundled-features/src/folders/web/folder-section.tsx +1 -1
  108. package/packages/bundled-features/src/form-draft-user-data/index.ts +2 -0
  109. package/packages/bundled-features/src/inbound-mail-foundation/changes.json +13 -0
  110. package/packages/bundled-features/src/inbound-mail-foundation/entities.ts +2 -0
  111. package/packages/bundled-features/src/inbound-mail-foundation/events.ts +2 -0
  112. package/packages/bundled-features/src/inbound-mail-foundation/feature.ts +6 -6
  113. package/packages/bundled-features/src/inbound-mail-foundation/handlers/attach-message-content.write.ts +7 -0
  114. package/packages/bundled-features/src/inbound-mail-foundation/handlers/ingest-message.write.ts +6 -0
  115. package/packages/bundled-features/src/inbound-mail-foundation/handlers/list-messages.query.ts +6 -2
  116. package/packages/bundled-features/src/inbound-mail-foundation/handlers/message-content.query.ts +3 -0
  117. package/packages/bundled-features/src/inbound-mail-foundation/handlers/message-content.ts +19 -0
  118. package/packages/bundled-features/src/inbound-mail-foundation/projection.ts +2 -0
  119. package/packages/bundled-features/src/inbound-mail-foundation/sanitize-inbound-html.ts +150 -0
  120. package/packages/bundled-features/src/inbound-mail-foundation/types.ts +1 -0
  121. package/packages/bundled-features/src/jobs/job-run-logger.ts +24 -25
  122. package/packages/bundled-features/src/ledger/handlers/reports.query.ts +46 -31
  123. package/packages/bundled-features/src/ledger/recurring.ts +1 -0
  124. package/packages/bundled-features/src/notes-history/web/notes-section.tsx +3 -1
  125. package/packages/bundled-features/src/personal-access-tokens/feature.ts +9 -17
  126. package/packages/bundled-features/src/personal-access-tokens/handlers/create.write.ts +2 -7
  127. package/packages/bundled-features/src/secrets/changes.json +6 -0
  128. package/packages/bundled-features/src/secrets/handlers/delete.write.ts +8 -4
  129. package/packages/bundled-features/src/secrets/handlers/list.query.ts +6 -3
  130. package/packages/bundled-features/src/secrets/handlers/set.write.ts +9 -4
  131. package/packages/bundled-features/src/secrets/secret-scope.ts +33 -0
  132. package/packages/bundled-features/src/sessions/changes.json +6 -0
  133. package/packages/bundled-features/src/sessions/feature.ts +21 -18
  134. package/packages/bundled-features/src/sessions/handlers/last-activity-probe.query.ts +53 -0
  135. package/packages/bundled-features/src/sessions/handlers/last-activity-probe.route.ts +39 -0
  136. package/packages/bundled-features/src/sessions/screens.ts +1 -0
  137. package/packages/bundled-features/src/sessions/session-callbacks.ts +13 -12
  138. package/packages/bundled-features/src/sessions/web/i18n.ts +4 -1
  139. package/packages/bundled-features/src/shared/assert-billing-live.ts +14 -0
  140. package/packages/bundled-features/src/shared/collect-extension-options.ts +12 -0
  141. package/packages/bundled-features/src/shared/index.ts +16 -0
  142. package/packages/bundled-features/src/shared/late-bound-slot.ts +19 -0
  143. package/packages/bundled-features/src/shared/mail-locale-templates.ts +7 -1
  144. package/packages/bundled-features/src/shared/price-env-shape.ts +44 -0
  145. package/packages/bundled-features/src/shared/purge-row-file-refs.ts +1 -1
  146. package/packages/bundled-features/src/shared/read-feature-export-fn.ts +16 -0
  147. package/packages/bundled-features/src/shared/signup-handover.ts +3 -4
  148. package/packages/bundled-features/src/shared/tenant-destruction-hold.ts +49 -0
  149. package/packages/bundled-features/src/shared/unprocessable.ts +19 -0
  150. package/packages/bundled-features/src/shared/web/index.ts +3 -0
  151. package/packages/bundled-features/src/subscription-paddle/feature.ts +7 -15
  152. package/packages/bundled-features/src/subscription-paddle/runtime.ts +4 -7
  153. package/packages/bundled-features/src/subscription-stripe/feature.ts +7 -15
  154. package/packages/bundled-features/src/subscription-stripe/runtime.ts +4 -7
  155. package/packages/bundled-features/src/tags/entity.ts +1 -0
  156. package/packages/bundled-features/src/tags/web/tag-chip.tsx +14 -0
  157. package/packages/bundled-features/src/tags/web/tag-filter.tsx +4 -5
  158. package/packages/bundled-features/src/tags/web/tag-manager.tsx +1 -1
  159. package/packages/bundled-features/src/tags/web/tag-section.tsx +3 -6
  160. package/packages/bundled-features/src/tags/web/tags-cell.tsx +4 -5
  161. package/packages/bundled-features/src/template-resolver/compile-document-body.ts +27 -15
  162. package/packages/bundled-features/src/template-resolver/handlers/by-tenant.query.ts +11 -8
  163. package/packages/bundled-features/src/template-resolver/handlers/discard-draft.write.ts +1 -0
  164. package/packages/bundled-features/src/template-resolver/handlers/overview.query.ts +1 -0
  165. package/packages/bundled-features/src/template-resolver/handlers/send-test.write.ts +5 -5
  166. package/packages/bundled-features/src/template-resolver/handlers/toggle-status.write.ts +3 -0
  167. package/packages/bundled-features/src/template-resolver/linked-resources.ts +11 -6
  168. package/packages/bundled-features/src/template-resolver/store-template-resource.ts +15 -12
  169. package/packages/bundled-features/src/template-resolver/web/document-images.ts +6 -6
  170. package/packages/bundled-features/src/template-resolver/web/document-insert-fields.tsx +41 -36
  171. package/packages/bundled-features/src/template-resolver/web/document-schema.ts +11 -12
  172. package/packages/bundled-features/src/template-resolver/web/tiptap-attribute-parse-rule.ts +19 -0
  173. package/packages/bundled-features/src/tenant/i18n.ts +3 -0
  174. package/packages/bundled-features/src/tenant/schema/tenant.ts +1 -0
  175. package/packages/bundled-features/src/tenant/web/member-roles-cell.tsx +1 -1
  176. package/packages/bundled-features/src/tenant/web/member-status-cell.tsx +1 -1
  177. package/packages/bundled-features/src/tenant-inactivity/changes.json +8 -0
  178. package/packages/bundled-features/src/tenant-inactivity/check-inactive-tenants.ts +260 -0
  179. package/packages/bundled-features/src/tenant-inactivity/constants.ts +12 -0
  180. package/packages/bundled-features/src/tenant-inactivity/email-templates.ts +24 -0
  181. package/packages/bundled-features/src/tenant-inactivity/feature.ts +66 -0
  182. package/packages/bundled-features/src/tenant-inactivity/handlers/inactivity-state.query.ts +49 -0
  183. package/packages/bundled-features/src/tenant-inactivity/handlers/keep-account.write.ts +56 -0
  184. package/packages/bundled-features/src/tenant-inactivity/inactivity-plan.ts +187 -0
  185. package/packages/bundled-features/src/tenant-inactivity/index.ts +5 -0
  186. package/packages/bundled-features/src/tenant-inactivity/keep-token.ts +44 -0
  187. package/packages/bundled-features/src/tenant-inactivity/mail-notifications.ts +62 -0
  188. package/packages/bundled-features/src/tenant-inactivity/options.ts +38 -0
  189. package/packages/bundled-features/src/tenant-inactivity/remote-activity.ts +32 -0
  190. package/packages/bundled-features/src/tenant-inactivity/state-store.ts +71 -0
  191. package/packages/bundled-features/src/tenant-inactivity/state-table.ts +50 -0
  192. package/packages/bundled-features/src/tenant-lifecycle/boot-checks.ts +8 -6
  193. package/packages/bundled-features/src/tenant-lifecycle/boot-rules.ts +16 -0
  194. package/packages/bundled-features/src/tenant-lifecycle/changes.json +18 -0
  195. package/packages/bundled-features/src/tenant-lifecycle/feature.ts +24 -1
  196. package/packages/bundled-features/src/tenant-lifecycle/handlers/request-destruction.write.ts +12 -87
  197. package/packages/bundled-features/src/tenant-lifecycle/index.ts +4 -0
  198. package/packages/bundled-features/src/tenant-lifecycle/request-tenant-destruction.ts +108 -0
  199. package/packages/bundled-features/src/tenant-lifecycle/retention-config-destroy-hooks.ts +62 -0
  200. package/packages/bundled-features/src/tenant-lifecycle/run-tenant-destroy.ts +58 -5
  201. package/packages/bundled-features/src/tenant-lifecycle/stages.ts +31 -2
  202. package/packages/bundled-features/src/tenant-lifecycle/testing.ts +1 -1
  203. package/packages/bundled-features/src/tier-engine/caps-for-tier-from-map.ts +16 -0
  204. package/packages/bundled-features/src/tier-engine/changes.json +6 -0
  205. package/packages/bundled-features/src/tier-engine/compose-app.ts +21 -20
  206. package/packages/bundled-features/src/tier-engine/index.ts +1 -0
  207. package/packages/bundled-features/src/user-data-rights/feature.ts +2 -0
  208. package/packages/bundled-features/src/user-data-rights/run-forget-cleanup.ts +2 -0
  209. package/packages/bundled-features/src/user-data-rights/web/privacy-center-screen.tsx +1 -1
  210. package/packages/bundled-features/src/user-data-rights/zip-path.ts +1 -0
  211. package/packages/bundled-features/src/user-data-rights-defaults/hooks/config-value.userdata-hook.ts +8 -27
  212. package/packages/bundled-features/src/user-data-rights-defaults/hooks/delivery-attempt.userdata-hook.ts +11 -8
  213. package/packages/bundled-features/src/user-data-rights-defaults/hooks/forget-own-rows-delete-hook.ts +42 -0
  214. package/packages/bundled-features/src/user-data-rights-defaults/hooks/notification-preference.userdata-hook.ts +8 -27
  215. package/packages/bundled-features/src/user-profile/handlers/change-email.write.ts +2 -6
  216. package/packages/bundled-features/src/user-profile/web/profile-screen.tsx +2 -3
  217. package/samples/apps/styleguide/src/features/widgets/i18n.ts +6 -0
  218. package/samples/apps/styleguide/src/features/widgets/web/InboxReaderExamples.tsx +158 -0
  219. package/samples/apps/styleguide/src/features/widgets/web/Widgets.tsx +2 -0
  220. package/samples/apps/styleguide/src/features/widgets/web/sample-pdf.ts +28 -0
  221. package/samples/apps/use-all-bundled/feature-manifest.json +134 -2
  222. package/samples/apps/use-all-bundled/kumiko/migrations/0063_contact.rebuild.json +4 -0
  223. package/samples/apps/use-all-bundled/package.json +1 -0
  224. package/samples/apps/use-all-bundled/playwright.config.ts +2 -0
  225. package/samples/apps/use-all-bundled/src/app/client.tsx +3 -0
  226. package/samples/apps/use-all-bundled/src/app/screens-feature.ts +46 -2
  227. package/samples/apps/use-all-bundled/src/run-config.ts +38 -4
  228. package/samples/recipes/contact/README.md +46 -0
  229. package/samples/recipes/contact/package.json +12 -0
  230. package/samples/recipes/contact/src/feature.ts +27 -0
  231. package/samples/recipes/delivery-notifications/src/feature.ts +3 -0
  232. package/samples/recipes/record-detail-layout/src/feature.ts +9 -1
  233. package/samples/recipes/search/README.md +2 -0
  234. package/samples/recipes/search/src/feature.ts +27 -2
  235. package/samples/recipes/secrets-demo/README.md +1 -0
  236. package/samples/recipes/secrets-demo/src/feature.ts +56 -0
  237. package/samples/recipes/tenant-inactivity/README.md +21 -0
  238. package/samples/recipes/tenant-inactivity/package.json +12 -0
@@ -1,4 +1,5 @@
1
1
  import {
2
+ bootRuleError,
2
3
  EXT_EXTERNAL_RESOURCE,
3
4
  EXT_INFRA_RESOURCE,
4
5
  EXT_SEARCH_ADAPTER,
@@ -11,6 +12,7 @@ import {
11
12
  } from "@cosmicdrift/kumiko-framework/engine";
12
13
  import { createFallbackLogger } from "@cosmicdrift/kumiko-framework/logging";
13
14
  import { entitiesOf } from "../shared/index.ts";
15
+ import { TENANT_LIFECYCLE_BOOT_RULES } from "./boot-rules.ts";
14
16
 
15
17
  const log = createFallbackLogger("kumiko:boot");
16
18
 
@@ -46,9 +48,9 @@ export function validateTenantDataHookCoverage(features: readonly FeatureDefinit
46
48
  .filter(([, field]) => hasTenantOwned(field))
47
49
  .map(([name]) => name);
48
50
  if (tenantSubjectFields.length === 0) continue;
49
- throw new Error(
50
- `[kumiko:boot] Entity "${entityName}" (feature "${feature.name}") has tenant-subject fields (${tenantSubjectFields.join(", ")}) but no feature registers an EXT_TENANT_DATA destroy hook for it — tenant destroy never erases this data. Register r.useExtension(EXT_TENANT_DATA, "${entityName}", { destroy }) or a documented no-op if crypto-shredding covers it.`,
51
- );
51
+ throw bootRuleError(TENANT_LIFECYCLE_BOOT_RULES.tenantSubjectWithoutDestroyHook, {
52
+ message: `[kumiko:boot] Entity "${entityName}" (feature "${feature.name}") has tenant-subject fields (${tenantSubjectFields.join(", ")}) but no feature registers an EXT_TENANT_DATA destroy hook for it — tenant destroy never erases this data. Register r.useExtension(EXT_TENANT_DATA, "${entityName}", { destroy }) or a documented no-op if crypto-shredding covers it.`,
53
+ });
52
54
  }
53
55
  }
54
56
  }
@@ -74,9 +76,9 @@ export function validateTenantDestroyHookShapes(features: readonly FeatureDefini
74
76
  : isTenantResourceExtensionHooks(usage.options);
75
77
  if (isValid) continue;
76
78
  const requiredFn = isTenantData ? "destroy" : "destroyTenant";
77
- throw new Error(
78
- `[kumiko:boot] ${usage.extensionName} registration for "${usage.entityName}" (feature "${feature.name}") has no ${requiredFn} function — tenant destroy would fail at this stage.`,
79
- );
79
+ throw bootRuleError(TENANT_LIFECYCLE_BOOT_RULES.destroyFunctionMissing, {
80
+ message: `[kumiko:boot] ${usage.extensionName} registration for "${usage.entityName}" (feature "${feature.name}") has no ${requiredFn} function — tenant destroy would fail at this stage.`,
81
+ });
80
82
  }
81
83
  }
82
84
  }
@@ -0,0 +1,16 @@
1
+ import type { BootRuleTable } from "@cosmicdrift/kumiko-framework/engine";
2
+
3
+ export const TENANT_LIFECYCLE_BOOT_RULES = {
4
+ tenantSubjectWithoutDestroyHook: {
5
+ id: "tenant-lifecycle/tenant-subject-without-destroy-hook",
6
+ summary:
7
+ "An entity with tenant-subject fields has an EXT_TENANT_DATA destroy hook, so tenant destroy erases its data.",
8
+ fix: 'Register r.useExtension(EXT_TENANT_DATA, "<entity>", { destroy }) or a documented no-op if crypto-shredding covers it.',
9
+ },
10
+ destroyFunctionMissing: {
11
+ id: "tenant-lifecycle/destroy-function-missing",
12
+ summary:
13
+ "A tenant data or tenant resource extension registration provides its destroy function, otherwise tenant destroy fails at that stage.",
14
+ fix: "Provide destroy (EXT_TENANT_DATA) or destroyTenant (tenant resource extensions) in the registration options.",
15
+ },
16
+ } as const satisfies BootRuleTable;
@@ -1,4 +1,22 @@
1
1
  [
2
+ {
3
+ "version": "0.408.0",
4
+ "type": "improvement",
5
+ "title": "Shared lookup for single-provider extension points",
6
+ "detail": "findSignupHandoverProvider and findTenantDestructionHoldProvider now go through one internal helper that returns the first registered usage whose options match the provider shape. Usages with other options are still skipped, and the result is undefined when none matches."
7
+ },
8
+ {
9
+ "version": "0.407.0",
10
+ "type": "improvement",
11
+ "title": "Tenants with blockDelete rows park in destroyHeld",
12
+ "detail": "When a destroying tenant owns rows of an entity with strategy blockDelete (entity default, preset, profile or per-tenant override), the destruction pauses before the tenant row in the new tenant status destroyHeld instead of deleting those rows. The sweep ignores destroyHeld tenants and hasTenantDestructionWork does not count them. The daily data-retention cleanup hard-deletes the held rows once their keepFor has passed, including their files, and then moves the tenant back to destroying in the same run. Code that switches exhaustively over the tenant status must handle destroyHeld; it is a transient state between destroying and destroyed and never the final one. The tenant's compliance profile and retention overrides are erased in the tenant-row phase through EXT_TENANT_DATA hooks, so they survive while the tenant is held."
13
+ },
14
+ {
15
+ "version": "0.407.0",
16
+ "type": "improvement",
17
+ "title": "requestTenantDestruction extracted",
18
+ "detail": "The core of the request-destruction handler is exported as requestTenantDestruction({ tenantId, actor, now, db, runner, registry, revokeSessions }) so other features, such as tenant-inactivity, file the same deletion request. The handler behavior is unchanged."
19
+ },
2
20
  {
3
21
  "version": "0.406.0",
4
22
  "type": "improvement",
@@ -9,6 +9,7 @@ import {
9
9
  type FeatureDefinition,
10
10
  type TenantLifecycleStatusPlugin,
11
11
  } from "@cosmicdrift/kumiko-framework/engine";
12
+ import { EXT_TENANT_DESTRUCTION_HOLD } from "../shared/index.ts";
12
13
  import {
13
14
  validateTenantDataHookCoverage,
14
15
  validateTenantDestroyHookShapes,
@@ -40,10 +41,17 @@ import {
40
41
  } from "./events.ts";
41
42
  import { cancelDestructionWrite } from "./handlers/cancel-destruction.write.ts";
42
43
  import { requestDestructionWrite } from "./handlers/request-destruction.write.ts";
44
+ import {
45
+ COMPLIANCE_PROFILE_ENTITY_NAME,
46
+ complianceProfileTenantDestroyHook,
47
+ RETENTION_OVERRIDE_ENTITY_NAME,
48
+ retentionOverrideTenantDestroyHook,
49
+ } from "./retention-config-destroy-hooks.ts";
43
50
  import {
44
51
  hasTenantDestructionWork,
45
52
  resolveTenantLifecycleGate,
46
53
  runTenantDestructionSweep,
54
+ tenantDestructionHoldProvider,
47
55
  } from "./run-tenant-destroy.ts";
48
56
 
49
57
  const tenantLifecycleStatusPlugin: TenantLifecycleStatusPlugin = {
@@ -64,7 +72,7 @@ export function createTenantLifecycleFeature(): FeatureDefinition {
64
72
  recommended: false,
65
73
  });
66
74
  r.requires({ features: ["tenant", "compliance-profiles"] });
67
- r.optionalRequires("sessions");
75
+ r.optionalRequires("sessions", "data-retention");
68
76
  r.usesApi("compliance.forTenant");
69
77
 
70
78
  r.extendsRegistrar(EXT_TENANT_DATA, {});
@@ -73,6 +81,21 @@ export function createTenantLifecycleFeature(): FeatureDefinition {
73
81
  r.extendsRegistrar(EXT_STORAGE_PROVIDER, {});
74
82
  r.extendsRegistrar(EXT_INFRA_RESOURCE, {});
75
83
 
84
+ // Self-extension: data-retention hands a parked tenant back through this, see shared/tenant-destruction-hold.ts.
85
+ r.extendsRegistrar(EXT_TENANT_DESTRUCTION_HOLD, {});
86
+ r.useExtension(EXT_TENANT_DESTRUCTION_HOLD, "tenant-lifecycle", tenantDestructionHoldProvider);
87
+
88
+ // Registered here because the hosts of these entities cannot require tenant-lifecycle (cycle,
89
+ // resp. standalone use); the override hook no-ops without data-retention.
90
+ r.useExtension(EXT_TENANT_DATA, COMPLIANCE_PROFILE_ENTITY_NAME, {
91
+ destroy: complianceProfileTenantDestroyHook,
92
+ phase: "tenant-row",
93
+ });
94
+ r.useExtension(EXT_TENANT_DATA, RETENTION_OVERRIDE_ENTITY_NAME, {
95
+ destroy: retentionOverrideTenantDestroyHook,
96
+ phase: "tenant-row",
97
+ });
98
+
76
99
  // Self-extension, same pattern as `user`/EXT_PRINCIPAL_STATUS — declares
77
100
  // AND fulfils tenantLifecycleStatus so teardown state is visible with no per-app wiring.
78
101
  r.extendsRegistrar(EXT_TENANT_LIFECYCLE_STATUS, {});
@@ -1,22 +1,6 @@
1
- import { addDurationSpec } from "@cosmicdrift/kumiko-framework/compliance";
2
- import { createEventStoreExecutor, fetchOne } from "@cosmicdrift/kumiko-framework/db";
3
- import { defineWriteHandler, SYSTEM_TENANT_ID } from "@cosmicdrift/kumiko-framework/engine";
4
- import { UnprocessableError, writeFailure } from "@cosmicdrift/kumiko-framework/errors";
5
- import { appendDomainEventCore } from "@cosmicdrift/kumiko-framework/pipeline";
6
- import { getTemporal } from "@cosmicdrift/kumiko-framework/time";
1
+ import { defineWriteHandler } from "@cosmicdrift/kumiko-framework/engine";
7
2
  import * as z from "zod";
8
- import { resolveProfileForTenant } from "../../compliance-profiles/index.ts";
9
- import { type TenantLifecycleStatus, tenantEntity, tenantTable } from "../../tenant/index.ts";
10
- import { DESTRUCTION_REQUESTED_EVENT_QN, TENANT_LIFECYCLE_FEATURE } from "../constants.ts";
11
- import { revokeTenantSessions } from "../lib/revoke-tenant-sessions.ts";
12
- import { invalidateTenantLifecycleGate } from "../lifecycle-gate.ts";
13
-
14
- const crud = createEventStoreExecutor(tenantTable, tenantEntity, { entityName: "tenant" });
15
-
16
- type TenantLifecycleRow = {
17
- status: TenantLifecycleStatus;
18
- gracePeriodEnd: Temporal.Instant | null;
19
- };
3
+ import { requestTenantDestruction } from "../request-tenant-destruction.ts";
20
4
 
21
5
  const REQUEST_DESTRUCTION_TENANT_ROW_REASON =
22
6
  "reads the caller's tenant row (a global row on the system tenant), its compliance profile, appends to the tenant stream on the system tenant and revokes its sessions via DbRunner helpers";
@@ -32,73 +16,14 @@ export const requestDestructionWrite = defineWriteHandler({
32
16
  grants: ["unsafeRaw"],
33
17
  reason: REQUEST_DESTRUCTION_TENANT_ROW_REASON,
34
18
  },
35
- handler: async (event, ctx) => {
36
- const tenantId = event.user.tenantId;
37
- const runner = ctx.db.unsafeRaw();
38
- const row = await fetchOne<TenantLifecycleRow>(runner, tenantTable, { id: tenantId });
39
- if (!row) {
40
- return writeFailure(new UnprocessableError("tenant_not_found", { details: { tenantId } }));
41
- }
42
- if (row.status !== "active") {
43
- return writeFailure(
44
- new UnprocessableError("tenant_not_active", {
45
- details: { status: row.status },
46
- }),
47
- );
48
- }
49
-
50
- const { profile } = await resolveProfileForTenant({ db: runner, tenantId });
51
- const T = getTemporal();
52
- const gracePeriodEnd = addDurationSpec(T.Now.instant(), profile.tenantDestroyGracePeriod);
53
-
54
- const update = await crud.update(
55
- {
56
- id: tenantId,
57
- changes: {
58
- status: "destroyRequested",
59
- destroyRequestedAt: T.Now.instant(),
60
- destroyRequestedBy: event.user.id,
61
- gracePeriodEnd,
62
- },
63
- },
64
- event.user,
65
- ctx.db,
66
- { skipOptimisticLock: true },
67
- );
68
- if (!update.isSuccess) return update;
69
- invalidateTenantLifecycleGate(tenantId);
70
-
71
- await appendDomainEventCore(
72
- {
73
- registry: ctx.registry,
74
- db: runner,
75
- tenantId: SYSTEM_TENANT_ID,
76
- userId: String(event.user.id),
77
- callSiteLabel: "tenant-lifecycle request-destruction",
78
- callerFeature: TENANT_LIFECYCLE_FEATURE,
79
- },
80
- {
81
- aggregateId: tenantId,
82
- aggregateType: "tenant",
83
- type: DESTRUCTION_REQUESTED_EVENT_QN,
84
- payload: {
85
- requestedBy: event.user.id,
86
- gracePeriodEnd: gracePeriodEnd.toString(),
87
- },
88
- },
89
- );
90
-
91
- if (await ctx.hasFeature("sessions")) {
92
- await revokeTenantSessions(runner, tenantId);
93
- }
94
-
95
- return {
96
- isSuccess: true as const,
97
- data: {
98
- tenantId,
99
- status: "destroyRequested" as const,
100
- gracePeriodEnd: gracePeriodEnd.toString(),
101
- },
102
- };
103
- },
19
+ handler: async (event, ctx) =>
20
+ requestTenantDestruction({
21
+ tenantId: event.user.tenantId,
22
+ actor: event.user,
23
+ now: ctx.tz.now(),
24
+ db: ctx.db,
25
+ runner: ctx.db.unsafeRaw(),
26
+ registry: ctx.registry,
27
+ revokeSessions: await ctx.hasFeature("sessions"),
28
+ }),
104
29
  });
@@ -11,4 +11,8 @@ export {
11
11
  TenantLifecycleHandlers,
12
12
  } from "./constants.ts";
13
13
  export { createTenantLifecycleFeature } from "./feature.ts";
14
+ export {
15
+ type RequestTenantDestructionArgs,
16
+ requestTenantDestruction,
17
+ } from "./request-tenant-destruction.ts";
14
18
  export { resolveTenantLifecycleGate } from "./run-tenant-destroy.ts";
@@ -0,0 +1,108 @@
1
+ import { addDurationSpec } from "@cosmicdrift/kumiko-framework/compliance";
2
+ import {
3
+ createEventStoreExecutor,
4
+ type DbRunner,
5
+ fetchOne,
6
+ type TenantDb,
7
+ } from "@cosmicdrift/kumiko-framework/db";
8
+ import {
9
+ type Registry,
10
+ type SessionUser,
11
+ SYSTEM_TENANT_ID,
12
+ type TenantId,
13
+ } from "@cosmicdrift/kumiko-framework/engine";
14
+ import { UnprocessableError, writeFailure } from "@cosmicdrift/kumiko-framework/errors";
15
+ import { appendDomainEventCore } from "@cosmicdrift/kumiko-framework/pipeline";
16
+ import type { Temporal } from "@cosmicdrift/kumiko-types/temporal";
17
+ import { resolveProfileForTenant } from "../compliance-profiles/index.ts";
18
+ import { type TenantLifecycleStatus, tenantEntity, tenantTable } from "../tenant/index.ts";
19
+ import { DESTRUCTION_REQUESTED_EVENT_QN, TENANT_LIFECYCLE_FEATURE } from "./constants.ts";
20
+ import { revokeTenantSessions } from "./lib/revoke-tenant-sessions.ts";
21
+ import { invalidateTenantLifecycleGate } from "./lifecycle-gate.ts";
22
+
23
+ const crud = createEventStoreExecutor(tenantTable, tenantEntity, { entityName: "tenant" });
24
+
25
+ type TenantLifecycleRow = {
26
+ status: TenantLifecycleStatus;
27
+ gracePeriodEnd: Temporal.Instant | null;
28
+ };
29
+
30
+ export type RequestTenantDestructionArgs = {
31
+ readonly tenantId: TenantId;
32
+ readonly actor: SessionUser;
33
+ readonly now: Temporal.Instant;
34
+ readonly db: TenantDb;
35
+ readonly runner: DbRunner;
36
+ readonly registry: Registry;
37
+ readonly revokeSessions: boolean;
38
+ };
39
+
40
+ // Shared by the owner-facing request-destruction handler and by system callers such as
41
+ // tenant-inactivity, so both start the same compliance-profile grace period.
42
+ export async function requestTenantDestruction(args: RequestTenantDestructionArgs) {
43
+ const { tenantId, actor, now, db, runner, registry } = args;
44
+ const row = await fetchOne<TenantLifecycleRow>(runner, tenantTable, { id: tenantId });
45
+ if (!row) {
46
+ return writeFailure(new UnprocessableError("tenant_not_found", { details: { tenantId } }));
47
+ }
48
+ if (row.status !== "active") {
49
+ return writeFailure(
50
+ new UnprocessableError("tenant_not_active", {
51
+ details: { status: row.status },
52
+ }),
53
+ );
54
+ }
55
+
56
+ const { profile } = await resolveProfileForTenant({ db: runner, tenantId });
57
+ const gracePeriodEnd = addDurationSpec(now, profile.tenantDestroyGracePeriod);
58
+
59
+ const update = await crud.update(
60
+ {
61
+ id: tenantId,
62
+ changes: {
63
+ status: "destroyRequested",
64
+ destroyRequestedAt: now,
65
+ destroyRequestedBy: actor.id,
66
+ gracePeriodEnd,
67
+ },
68
+ },
69
+ actor,
70
+ db,
71
+ { skipOptimisticLock: true },
72
+ );
73
+ if (!update.isSuccess) return update;
74
+ invalidateTenantLifecycleGate(tenantId);
75
+
76
+ await appendDomainEventCore(
77
+ {
78
+ registry,
79
+ db: runner,
80
+ tenantId: SYSTEM_TENANT_ID,
81
+ userId: String(actor.id),
82
+ callSiteLabel: "tenant-lifecycle request-destruction",
83
+ callerFeature: TENANT_LIFECYCLE_FEATURE,
84
+ },
85
+ {
86
+ aggregateId: tenantId,
87
+ aggregateType: "tenant",
88
+ type: DESTRUCTION_REQUESTED_EVENT_QN,
89
+ payload: {
90
+ requestedBy: actor.id,
91
+ gracePeriodEnd: gracePeriodEnd.toString(),
92
+ },
93
+ },
94
+ );
95
+
96
+ if (args.revokeSessions) {
97
+ await revokeTenantSessions(runner, tenantId);
98
+ }
99
+
100
+ return {
101
+ isSuccess: true as const,
102
+ data: {
103
+ tenantId,
104
+ status: "destroyRequested" as const,
105
+ gracePeriodEnd: gracePeriodEnd.toString(),
106
+ },
107
+ };
108
+ }
@@ -0,0 +1,62 @@
1
+ // The tenant's retention configuration (compliance profile, retention overrides) decides which
2
+ // entities are blockDelete-held. It is erased in the "tenant-row" phase, after the hold check, because
3
+ // deleting it earlier would change the hold predicate while the tenant still waits on held rows.
4
+
5
+ import { createEventStoreExecutor } from "@cosmicdrift/kumiko-framework/db";
6
+ import {
7
+ createSystemUser,
8
+ type EntityDefinition,
9
+ type TenantDataHookCtx,
10
+ } from "@cosmicdrift/kumiko-framework/engine";
11
+ import {
12
+ tenantComplianceProfileEntity,
13
+ tenantComplianceProfileTable,
14
+ } from "../compliance-profiles/index.ts";
15
+ import {
16
+ tenantRetentionOverrideEntity,
17
+ tenantRetentionOverrideTable,
18
+ } from "../data-retention/index.ts";
19
+
20
+ export const COMPLIANCE_PROFILE_ENTITY_NAME = "tenant-compliance-profile";
21
+ export const RETENTION_OVERRIDE_ENTITY_NAME = "tenant-retention-override";
22
+
23
+ type ExecutorTable = Parameters<typeof createEventStoreExecutor>[0];
24
+
25
+ async function forgetAllTenantRows(
26
+ ctx: TenantDataHookCtx,
27
+ table: ExecutorTable,
28
+ entity: EntityDefinition,
29
+ entityName: string,
30
+ ): Promise<void> {
31
+ const executor = createEventStoreExecutor(table, entity, { entityName });
32
+ const user = createSystemUser(ctx.tenantId);
33
+ const rows = await ctx.db.selectMany<{ id: string }>(table, { tenantId: ctx.tenantId });
34
+ for (const row of rows) {
35
+ const forgotten = await executor.forget({ id: row.id }, user, ctx.db);
36
+ if (!forgotten.isSuccess) {
37
+ throw new Error(
38
+ `tenant-lifecycle: failed to forget ${entityName} ${row.id} for tenant ${ctx.tenantId}: ${forgotten.error.message}`,
39
+ );
40
+ }
41
+ }
42
+ }
43
+
44
+ export async function complianceProfileTenantDestroyHook(ctx: TenantDataHookCtx): Promise<void> {
45
+ await forgetAllTenantRows(
46
+ ctx,
47
+ tenantComplianceProfileTable,
48
+ tenantComplianceProfileEntity,
49
+ COMPLIANCE_PROFILE_ENTITY_NAME,
50
+ );
51
+ }
52
+
53
+ export async function retentionOverrideTenantDestroyHook(ctx: TenantDataHookCtx): Promise<void> {
54
+ // skip: data-retention is optional, without it the override table does not exist
55
+ if (!ctx.registry.getEntity(RETENTION_OVERRIDE_ENTITY_NAME)) return;
56
+ await forgetAllTenantRows(
57
+ ctx,
58
+ tenantRetentionOverrideTable,
59
+ tenantRetentionOverrideEntity,
60
+ RETENTION_OVERRIDE_ENTITY_NAME,
61
+ );
62
+ }
@@ -3,6 +3,7 @@ import type { DbRunner, TenantDb, WhereObject } from "@cosmicdrift/kumiko-framew
3
3
  import {
4
4
  createEventStoreExecutor,
5
5
  createTenantDb,
6
+ fetchOne,
6
7
  selectMany,
7
8
  WritePurposes,
8
9
  } from "@cosmicdrift/kumiko-framework/db";
@@ -23,7 +24,9 @@ import type { FileProviderResolver } from "@cosmicdrift/kumiko-framework/files";
23
24
  import type { Logger } from "@cosmicdrift/kumiko-framework/logging";
24
25
  import type { SearchAdapter } from "@cosmicdrift/kumiko-framework/search";
25
26
  import { getTemporal } from "@cosmicdrift/kumiko-framework/time";
26
- import { tenantEntity, tenantTable } from "../tenant/index.ts";
27
+ import { tenantHasBlockDeleteRows } from "../data-retention/index.ts";
28
+ import type { TenantDestructionHoldProvider } from "../shared/index.ts";
29
+ import { type TenantLifecycleStatus, tenantEntity, tenantTable } from "../tenant/index.ts";
27
30
  import {
28
31
  DESTRUCTION_STAGE_MAX_PENDING_MS,
29
32
  DESTRUCTION_STAGE_MIN_SLICE_MS,
@@ -202,7 +205,11 @@ async function appendTenantStageEventIdempotent(
202
205
  return lastEventVersion(events);
203
206
  }
204
207
 
205
- async function markTenantDestroyFailed(db: DbRunner, tenantId: TenantId): Promise<void> {
208
+ async function setTenantLifecycleStatus(
209
+ db: DbRunner,
210
+ tenantId: TenantId,
211
+ status: TenantLifecycleStatus,
212
+ ): Promise<void> {
206
213
  const user = createSystemUser(tenantId);
207
214
  const scopedDb = createTenantDb({
208
215
  db,
@@ -213,7 +220,7 @@ async function markTenantDestroyFailed(db: DbRunner, tenantId: TenantId): Promis
213
220
  await tenantCrud.update(
214
221
  {
215
222
  id: tenantId,
216
- changes: { status: "destroyFailed" },
223
+ changes: { status },
217
224
  },
218
225
  user,
219
226
  scopedDb,
@@ -222,6 +229,17 @@ async function markTenantDestroyFailed(db: DbRunner, tenantId: TenantId): Promis
222
229
  invalidateTenantLifecycleGate(tenantId);
223
230
  }
224
231
 
232
+ // True while the tenant still owns rows whose blockDelete retention has not run out.
233
+ async function tenantOwnsRetentionHeldRows(args: {
234
+ readonly db: DbRunner;
235
+ readonly registry: Registry;
236
+ readonly tenantId: TenantId;
237
+ readonly now: Temporal.Instant;
238
+ }): Promise<boolean> {
239
+ if (!args.registry.features.has("data-retention")) return false;
240
+ return await tenantHasBlockDeleteRows(args);
241
+ }
242
+
225
243
  async function haltPipelineOnAbandon(args: {
226
244
  readonly db: DbRunner;
227
245
  readonly tenantId: TenantId;
@@ -252,7 +270,7 @@ async function haltPipelineOnAbandon(args: {
252
270
  { stage: args.stage, error: args.error, failedAt: failedAt.toString() },
253
271
  versionAfterAbandon,
254
272
  );
255
- await markTenantDestroyFailed(args.db, args.tenantId);
273
+ await setTenantLifecycleStatus(args.db, args.tenantId, "destroyFailed");
256
274
  }
257
275
 
258
276
  async function maybeAppendDestructionCompleted(
@@ -285,6 +303,7 @@ type StageTickResult = {
285
303
  readonly halted?: boolean;
286
304
  readonly progressed?: boolean;
287
305
  readonly pending?: boolean;
306
+ readonly held?: boolean;
288
307
  };
289
308
 
290
309
  // `version` differs per caller: the catch path appends against the pre-run
@@ -379,6 +398,20 @@ export async function runNextDestructionStage(args: {
379
398
  return { done: isDestructionPipelineComplete(completed) };
380
399
  }
381
400
 
401
+ // Parking is no stage attempt: no stage-started event, no attempt count, no failure.
402
+ if (
403
+ next.name === "tenant-row" &&
404
+ (await tenantOwnsRetentionHeldRows({
405
+ db: args.db,
406
+ registry: args.registry,
407
+ tenantId: args.tenantId,
408
+ now,
409
+ }))
410
+ ) {
411
+ await setTenantLifecycleStatus(args.db, args.tenantId, "destroyHeld");
412
+ return { done: false, held: true };
413
+ }
414
+
382
415
  const priorAttempts = attemptsByStage.get(next.name) ?? 0;
383
416
  const attempt = priorAttempts + 1;
384
417
  const ctx: DestructionStageCtx = {
@@ -392,6 +425,7 @@ export async function runNextDestructionStage(args: {
392
425
  escapeHatchAuditLog: args.escapeHatchAuditLog,
393
426
  actor: args.actor,
394
427
  deadlineAt: args.deadlineAt ?? Date.now() + DESTRUCTION_STAGE_TICK_BUDGET_MS,
428
+ now,
395
429
  };
396
430
 
397
431
  let version = lastEventVersion(events);
@@ -482,6 +516,25 @@ export async function hasTenantDestructionWork(
482
516
  return due > 0 || destroying > 0;
483
517
  }
484
518
 
519
+ // A destroyHeld tenant is not sweep work: the daily retention run releases it once its last held row
520
+ // is gone, and the sweep then runs tenant-row as a fresh first attempt.
521
+ export const tenantDestructionHoldProvider: TenantDestructionHoldProvider = {
522
+ async isParked({ db, tenantId }) {
523
+ return (await tenantStatusOf(db, tenantId)) === "destroyHeld";
524
+ },
525
+ async releaseIfFree({ db, registry, tenantId, now }) {
526
+ if ((await tenantStatusOf(db, tenantId)) !== "destroyHeld") return false;
527
+ if (await tenantOwnsRetentionHeldRows({ db, registry, tenantId, now })) return false;
528
+ await setTenantLifecycleStatus(db, tenantId, "destroying");
529
+ return true;
530
+ },
531
+ };
532
+
533
+ async function tenantStatusOf(db: DbRunner, tenantId: TenantId): Promise<string | undefined> {
534
+ const row = await fetchOne<{ status: string }>(db, tenantTable, { id: tenantId });
535
+ return row?.status;
536
+ }
537
+
485
538
  /** Cron entry: start destruction for tenants past grace, then advance stages. */
486
539
  export async function runTenantDestructionSweep(args: {
487
540
  readonly db: DbRunner;
@@ -559,7 +612,7 @@ export async function runTenantDestructionSweep(args: {
559
612
  escapeHatchAuditLog: args.escapeHatchAuditLog,
560
613
  actor: args.actor,
561
614
  });
562
- if (!result.error && !result.halted) advanced++;
615
+ if (!result.error && !result.halted && !result.held) advanced++;
563
616
  } catch (err) {
564
617
  // Isolate the failure to this tenant — an uncaught throw here must not
565
618
  // abort the whole sweep tick and starve every other "destroying" tenant
@@ -1,3 +1,4 @@
1
+ /// <reference types="temporal-polyfill/global" preserve="true" />
1
2
  import {
2
3
  configuredPiiSubjectKms,
3
4
  type SubjectId,
@@ -23,6 +24,7 @@ import {
23
24
  isTenantDataExtensionHooks,
24
25
  isTenantResourceExtensionHooks,
25
26
  type Registry,
27
+ type TenantDataDestroyPhase,
26
28
  type TenantDataHookCtx,
27
29
  type TenantDestroyHookResult,
28
30
  type TenantId,
@@ -39,6 +41,10 @@ import {
39
41
  type SearchAdapter,
40
42
  } from "@cosmicdrift/kumiko-framework/search";
41
43
  import { getTemporal } from "@cosmicdrift/kumiko-framework/time";
44
+ import {
45
+ type DestructionHold,
46
+ holdBlockDeleteRowsForDestruction,
47
+ } from "../data-retention/index.ts";
42
48
  import {
43
49
  tenantEntity,
44
50
  tenantMembershipEntity,
@@ -67,6 +73,8 @@ export type DestructionStageCtx = {
67
73
  readonly actor?: string;
68
74
  // Epoch ms the stage must hand back by returning { done: false }.
69
75
  readonly deadlineAt: number;
76
+ // Sweep clock, so retention cut-offs follow the injected clock instead of wall time.
77
+ readonly now: Temporal.Instant;
70
78
  };
71
79
 
72
80
  export type StageRunOutcome = {
@@ -131,15 +139,33 @@ async function runExtensionDestroyHooks(
131
139
  return total.outcome();
132
140
  }
133
141
 
134
- async function runTenantDataHooks(ctx: DestructionStageCtx): Promise<StageRunOutcome> {
142
+ const NOTHING_HELD: DestructionHold = { entityNames: new Set(), fileRefIds: new Set() };
143
+
144
+ async function runTenantDataHooks(
145
+ ctx: DestructionStageCtx,
146
+ phase: TenantDataDestroyPhase,
147
+ ): Promise<StageRunOutcome> {
135
148
  const usages = ctx.registry.getExtensionUsages(EXT_TENANT_DATA);
136
149
  const total = newOutcomeAccumulator();
150
+ // Rows inside a blockDelete keepFor must outlive the account; their hook is skipped, the rows are
151
+ // anonymized and the fileRefs they point at are handed to the other hooks. Recomputed every tick.
152
+ const hold =
153
+ phase === "app-data" && ctx.registry.features.has("data-retention")
154
+ ? await holdBlockDeleteRowsForDestruction({
155
+ db: ctx.db,
156
+ registry: ctx.registry,
157
+ tenantId: ctx.tenantId,
158
+ now: ctx.now,
159
+ })
160
+ : NOTHING_HELD;
137
161
  for (const usage of usages) {
138
162
  if (!isTenantDataExtensionHooks(usage.options)) {
139
163
  throw new Error(
140
164
  `${EXT_TENANT_DATA} registration for "${usage.entityName}" has no destroy function`,
141
165
  );
142
166
  }
167
+ if ((usage.options["phase"] ?? "app-data") !== phase) continue;
168
+ if (hold.entityNames.has(usage.entityName)) continue;
143
169
  const destroy = usage.options.destroy;
144
170
  const reason = extensionUsageEscapeHatchReason(usage);
145
171
  const report = createEscapeHatchReporter({
@@ -162,6 +188,7 @@ async function runTenantDataHooks(ctx: DestructionStageCtx): Promise<StageRunOut
162
188
  tenantId: ctx.tenantId,
163
189
  deadlineAt: ctx.deadlineAt,
164
190
  fileProviderResolver: ctx.fileProviderResolver,
191
+ heldFileRefIds: hold.fileRefIds,
165
192
  log: ctx.log,
166
193
  };
167
194
  total.add(await destroy(hookCtx));
@@ -245,6 +272,8 @@ async function purgeTenantCache(ctx: DestructionStageCtx): Promise<StageRunOutco
245
272
  }
246
273
 
247
274
  async function tombstoneTenantRow(ctx: DestructionStageCtx): Promise<StageRunOutcome> {
275
+ const lateHooks = await runTenantDataHooks(ctx, "tenant-row");
276
+ if (!lateHooks.done) return lateHooks;
248
277
  const now = getTemporal().Now.instant();
249
278
  const user = createSystemUser(ctx.tenantId);
250
279
  const db = createTenantDb({
@@ -315,7 +344,7 @@ export const DESTRUCTION_STAGES: readonly DestructionStage[] = [
315
344
  {
316
345
  name: "app-data",
317
346
  maxAttempts: 3,
318
- run: runTenantDataHooks,
347
+ run: (ctx) => runTenantDataHooks(ctx, "app-data"),
319
348
  },
320
349
  {
321
350
  name: "subject-keys",
@@ -51,7 +51,7 @@ export async function driveDestructionToCompletion(
51
51
  });
52
52
  const rows = await selectMany(db, tenantTable, { id: tenantId });
53
53
  status = String(rows[0]?.["status"]);
54
- if (status === "destroyed" || status === "destroyFailed") break;
54
+ if (status === "destroyed" || status === "destroyFailed" || status === "destroyHeld") break;
55
55
  }
56
56
  return status;
57
57
  }