@cosmicdrift/kumiko-framework 0.406.0 → 0.410.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 (212) hide show
  1. package/AGENTS.md +4 -2
  2. package/agents/api/framework-db.md +1 -0
  3. package/agents/api/framework-engine.md +17 -2
  4. package/agents/api/framework-ui-types.md +15 -0
  5. package/agents/api/renderer-web.md +156 -2
  6. package/agents/api/types.md +113 -71
  7. package/agents/api.md +4 -4
  8. package/agents/boot-rules.md +744 -0
  9. package/agents/examples/anonymous-access.md +23 -1
  10. package/agents/examples/contact.md +173 -0
  11. package/agents/examples/delivery-notifications.md +34 -1
  12. package/agents/examples/record-detail-layout.md +13 -2
  13. package/agents/examples/search.md +65 -3
  14. package/agents/examples/secrets-demo.md +96 -2
  15. package/agents/examples/tenant-inactivity.md +138 -0
  16. package/agents/examples.md +2 -0
  17. package/agents/features-index.md +4 -0
  18. package/agents/features.md +25 -1
  19. package/agents/widgets.md +12 -1
  20. package/dist/api/export/export-rows.js +1 -0
  21. package/dist/compliance/index.d.ts +1 -1
  22. package/dist/db/event-store-executor-read-where.js +15 -5
  23. package/dist/db/index.d.ts +1 -1
  24. package/dist/db/index.js +1 -1
  25. package/dist/db/migrate-generator.js +3 -1
  26. package/dist/db/queries/event-consumer.js +11 -7
  27. package/dist/db/queries/event-store.d.ts +2 -1
  28. package/dist/db/queries/event-store.js +25 -6
  29. package/dist/db/queries/rls-boot-catalog.js +3 -1
  30. package/dist/db/queries/session-advisory-lock.d.ts +7 -0
  31. package/dist/db/queries/session-advisory-lock.js +23 -0
  32. package/dist/db/query.js +7 -10
  33. package/dist/db/row-level-security-connection.js +4 -2
  34. package/dist/engine/access.js +5 -1
  35. package/dist/engine/active-membership.js +1 -0
  36. package/dist/engine/boot-validator/access-declarations.js +76 -33
  37. package/dist/engine/boot-validator/action-wiring.js +8 -6
  38. package/dist/engine/boot-validator/agent-effect-rules.d.ts +12 -0
  39. package/dist/engine/boot-validator/agent-effect-rules.js +12 -0
  40. package/dist/engine/boot-validator/agent-effect.d.ts +2 -0
  41. package/dist/engine/boot-validator/agent-effect.js +20 -0
  42. package/dist/engine/boot-validator/boot-context.js +5 -1
  43. package/dist/engine/boot-validator/boot-environment-rules.d.ts +12 -0
  44. package/dist/engine/boot-validator/boot-environment-rules.js +12 -0
  45. package/dist/engine/boot-validator/boot-phases-app.js +5 -1
  46. package/dist/engine/boot-validator/boot-phases.js +3 -1
  47. package/dist/engine/boot-validator/boot-rules.d.ts +2624 -0
  48. package/dist/engine/boot-validator/boot-rules.js +58 -0
  49. package/dist/engine/boot-validator/bundled-lists-table.js +23 -9
  50. package/dist/engine/boot-validator/config-deps.js +71 -23
  51. package/dist/engine/boot-validator/config-edit-action-rules.d.ts +17 -0
  52. package/dist/engine/boot-validator/config-edit-action-rules.js +17 -0
  53. package/dist/engine/boot-validator/config-key-rules.d.ts +117 -0
  54. package/dist/engine/boot-validator/config-key-rules.js +117 -0
  55. package/dist/engine/boot-validator/custom-screen-write-qns.js +6 -2
  56. package/dist/engine/boot-validator/derived-sql-fields-rules.d.ts +77 -0
  57. package/dist/engine/boot-validator/derived-sql-fields-rules.js +77 -0
  58. package/dist/engine/boot-validator/derived-sql-fields.js +53 -17
  59. package/dist/engine/boot-validator/detail-screens.js +10 -4
  60. package/dist/engine/boot-validator/entity-declaration-rules.d.ts +92 -0
  61. package/dist/engine/boot-validator/entity-declaration-rules.js +92 -0
  62. package/dist/engine/boot-validator/entity-handler-access-rules.d.ts +102 -0
  63. package/dist/engine/boot-validator/entity-handler-access-rules.js +102 -0
  64. package/dist/engine/boot-validator/entity-handler.d.ts +0 -7
  65. package/dist/engine/boot-validator/entity-handler.js +259 -355
  66. package/dist/engine/boot-validator/entity-image-variants.d.ts +2 -0
  67. package/dist/engine/boot-validator/entity-image-variants.js +91 -0
  68. package/dist/engine/boot-validator/entity-list-aggregate-options.js +8 -2
  69. package/dist/engine/boot-validator/entity-reference-embedded-rules.d.ts +117 -0
  70. package/dist/engine/boot-validator/entity-reference-embedded-rules.js +117 -0
  71. package/dist/engine/boot-validator/entity-select-image-rules.d.ts +122 -0
  72. package/dist/engine/boot-validator/entity-select-image-rules.js +122 -0
  73. package/dist/engine/boot-validator/entity-select.d.ts +8 -0
  74. package/dist/engine/boot-validator/entity-select.js +197 -0
  75. package/dist/engine/boot-validator/entity-structure-rules.d.ts +107 -0
  76. package/dist/engine/boot-validator/entity-structure-rules.js +107 -0
  77. package/dist/engine/boot-validator/field-conditions-rules.d.ts +92 -0
  78. package/dist/engine/boot-validator/field-conditions-rules.js +92 -0
  79. package/dist/engine/boot-validator/field-conditions.js +67 -22
  80. package/dist/engine/boot-validator/form-derivations-rules.d.ts +77 -0
  81. package/dist/engine/boot-validator/form-derivations-rules.js +77 -0
  82. package/dist/engine/boot-validator/form-derivations.js +52 -18
  83. package/dist/engine/boot-validator/global-tenancy.js +13 -7
  84. package/dist/engine/boot-validator/handler-declaration-rules.d.ts +77 -0
  85. package/dist/engine/boot-validator/handler-declaration-rules.js +77 -0
  86. package/dist/engine/boot-validator/handler-field-references-rules.d.ts +22 -0
  87. package/dist/engine/boot-validator/handler-field-references-rules.js +22 -0
  88. package/dist/engine/boot-validator/handler-field-references.js +14 -6
  89. package/dist/engine/boot-validator/list-bulk-actions-rules.d.ts +42 -0
  90. package/dist/engine/boot-validator/list-bulk-actions-rules.js +42 -0
  91. package/dist/engine/boot-validator/list-bulk-actions.js +29 -11
  92. package/dist/engine/boot-validator/list-column-layout.js +22 -10
  93. package/dist/engine/boot-validator/list-query-rules.d.ts +107 -0
  94. package/dist/engine/boot-validator/list-query-rules.js +107 -0
  95. package/dist/engine/boot-validator/list-table-aggregate-options.js +43 -15
  96. package/dist/engine/boot-validator/list-table-aggregate-query.js +7 -3
  97. package/dist/engine/boot-validator/list-table-aggregate-rules.d.ts +82 -0
  98. package/dist/engine/boot-validator/list-table-aggregate-rules.js +82 -0
  99. package/dist/engine/boot-validator/list-table-export-options.js +19 -7
  100. package/dist/engine/boot-validator/list-table-options.js +33 -13
  101. package/dist/engine/boot-validator/list-table-reject-unknown-keys.js +6 -2
  102. package/dist/engine/boot-validator/list-table-rules.d.ts +132 -0
  103. package/dist/engine/boot-validator/list-table-rules.js +132 -0
  104. package/dist/engine/boot-validator/nav-rules.d.ts +42 -0
  105. package/dist/engine/boot-validator/nav-rules.js +42 -0
  106. package/dist/engine/boot-validator/nav.js +33 -17
  107. package/dist/engine/boot-validator/ownership-rules.d.ts +27 -0
  108. package/dist/engine/boot-validator/ownership-rules.js +27 -0
  109. package/dist/engine/boot-validator/ownership.js +28 -12
  110. package/dist/engine/boot-validator/parent-ref.js +32 -20
  111. package/dist/engine/boot-validator/projection-list-screens.js +76 -35
  112. package/dist/engine/boot-validator/query-output-columns.js +9 -3
  113. package/dist/engine/boot-validator/query-refs.js +20 -10
  114. package/dist/engine/boot-validator/query-rules.d.ts +37 -0
  115. package/dist/engine/boot-validator/query-rules.js +37 -0
  116. package/dist/engine/boot-validator/read-gate.js +14 -10
  117. package/dist/engine/boot-validator/record-owned.js +5 -1
  118. package/dist/engine/boot-validator/related-list-table-rules.js +17 -7
  119. package/dist/engine/boot-validator/screens-actions-rules.d.ts +185 -0
  120. package/dist/engine/boot-validator/screens-actions-rules.js +185 -0
  121. package/dist/engine/boot-validator/screens-actions.js +169 -93
  122. package/dist/engine/boot-validator/screens-dashboard-chart-rules.d.ts +87 -0
  123. package/dist/engine/boot-validator/screens-dashboard-chart-rules.js +87 -0
  124. package/dist/engine/boot-validator/screens-dashboard-rules.d.ts +227 -0
  125. package/dist/engine/boot-validator/screens-dashboard-rules.js +227 -0
  126. package/dist/engine/boot-validator/screens-dashboard.js +222 -85
  127. package/dist/engine/boot-validator/screens-forms-layout-rules.d.ts +122 -0
  128. package/dist/engine/boot-validator/screens-forms-layout-rules.js +122 -0
  129. package/dist/engine/boot-validator/screens-forms-rules.d.ts +152 -0
  130. package/dist/engine/boot-validator/screens-forms-rules.js +152 -0
  131. package/dist/engine/boot-validator/screens-forms.js +240 -112
  132. package/dist/engine/boot-validator/screens-kind-config-edit.js +72 -16
  133. package/dist/engine/boot-validator/screens-kind-entity-edit.js +15 -7
  134. package/dist/engine/boot-validator/screens-kind-entity-list.js +57 -32
  135. package/dist/engine/boot-validator/screens-kind-projection-detail-rules.d.ts +92 -0
  136. package/dist/engine/boot-validator/screens-kind-projection-detail-rules.js +92 -0
  137. package/dist/engine/boot-validator/screens-kind-projection-detail.js +85 -47
  138. package/dist/engine/boot-validator/screens-kind-rules.d.ts +137 -0
  139. package/dist/engine/boot-validator/screens-kind-rules.js +137 -0
  140. package/dist/engine/boot-validator/screens-kind-secret-mint.js +18 -8
  141. package/dist/engine/boot-validator/screens-kind-shared.js +40 -22
  142. package/dist/engine/boot-validator/screens-lists-rules.d.ts +82 -0
  143. package/dist/engine/boot-validator/screens-lists-rules.js +82 -0
  144. package/dist/engine/boot-validator/screens-lists.js +90 -45
  145. package/dist/engine/boot-validator/screens-rules.d.ts +57 -0
  146. package/dist/engine/boot-validator/screens-rules.js +57 -0
  147. package/dist/engine/boot-validator/screens.js +17 -12
  148. package/dist/engine/boot-validator/transaction-phases.js +12 -4
  149. package/dist/engine/boot-validator/transfer-graph.js +17 -11
  150. package/dist/engine/boot-validator/url-prefill-fields.js +9 -5
  151. package/dist/engine/boot-validator/workspaces.js +11 -5
  152. package/dist/engine/boot-validator/zod-shape.js +6 -2
  153. package/dist/engine/entity-handlers.d.ts +1 -0
  154. package/dist/engine/entity-handlers.js +3 -0
  155. package/dist/engine/entity-list-runtime-options.js +23 -29
  156. package/dist/engine/extensions/tenant-data.d.ts +3 -0
  157. package/dist/engine/factories.d.ts +1 -1
  158. package/dist/engine/factories.js +4 -3
  159. package/dist/engine/index.d.ts +4 -2
  160. package/dist/engine/index.js +2 -0
  161. package/dist/engine/project-app-schema-for-roles.js +29 -14
  162. package/dist/engine/registry-facade.js +7 -8
  163. package/dist/engine/registry-validate.js +5 -1
  164. package/dist/engine/soft-delete-cleanup.d.ts +1 -0
  165. package/dist/engine/soft-delete-cleanup.js +5 -0
  166. package/dist/engine/steps/describe-workflow-step-error.js +1 -0
  167. package/dist/es-ops/operations-schema.d.ts +1 -1
  168. package/dist/event-store/ensure-dead-letter-table.d.ts +2 -0
  169. package/dist/event-store/ensure-dead-letter-table.js +10 -0
  170. package/dist/event-store/rebuild-dead-letter.js +2 -8
  171. package/dist/event-store/upcaster-dead-letter.js +2 -8
  172. package/dist/files/copy-pending-file-refs-to-tenant.d.ts +28 -0
  173. package/dist/files/copy-pending-file-refs-to-tenant.js +87 -0
  174. package/dist/files/file-routes.d.ts +1 -1
  175. package/dist/files/file-routes.js +21 -6
  176. package/dist/files/index.d.ts +2 -0
  177. package/dist/files/index.js +1 -0
  178. package/dist/i18n/required-surface-keys.js +1 -0
  179. package/dist/jobs/job-runner-helpers.js +1 -0
  180. package/dist/jobs/job-runner.js +7 -12
  181. package/dist/logging/utils.js +30 -60
  182. package/dist/observability/metrics-handle.js +10 -21
  183. package/dist/pipeline/cascade-handler.js +7 -6
  184. package/dist/pipeline/dispatch-query.js +18 -5
  185. package/dist/pipeline/dispatch-shared.d.ts +1 -0
  186. package/dist/pipeline/dispatch-shared.js +3 -1
  187. package/dist/pipeline/dispatch-write.js +10 -12
  188. package/dist/pipeline/dispatcher.js +12 -14
  189. package/dist/pipeline/event-dispatcher-admin.js +9 -8
  190. package/dist/pipeline/event-dispatcher-delivery.d.ts +19 -1
  191. package/dist/pipeline/event-dispatcher-delivery.js +121 -29
  192. package/dist/pipeline/event-dispatcher.d.ts +5 -1
  193. package/dist/pipeline/event-dispatcher.js +28 -21
  194. package/dist/pipeline/handler-context-phase-denials.js +2 -0
  195. package/dist/pipeline/multi-stream-apply-context.js +12 -20
  196. package/dist/pipeline/system-hooks.d.ts +4 -1
  197. package/dist/pipeline/system-hooks.js +79 -6
  198. package/dist/pipeline/system-identity-switch.js +10 -7
  199. package/dist/search/build-search-snippet.d.ts +9 -0
  200. package/dist/search/build-search-snippet.js +40 -0
  201. package/dist/search/index.d.ts +1 -0
  202. package/dist/search/index.js +1 -0
  203. package/dist/search/meilisearch-adapter.d.ts +32 -0
  204. package/dist/search/meilisearch-adapter.js +153 -56
  205. package/dist/search/meilisearch-chunking.d.ts +21 -0
  206. package/dist/search/meilisearch-chunking.js +96 -0
  207. package/dist/search/reindex-entity.d.ts +1 -0
  208. package/dist/search/reindex-entity.js +97 -52
  209. package/dist/ui-types/index.d.ts +1 -1
  210. package/dist/upgrade-cli.js +3 -14
  211. package/package.json +3 -3
  212. package/src/changes.json +79 -0
@@ -0,0 +1,138 @@
1
+ <!-- Generated by `bun run gen:agent-docs` from samples/recipes/tenant-inactivity. Do not edit. -->
2
+
3
+ # tenant-inactivity
4
+
5
+ tenant-inactivity: warn abandoned free accounts, then file the regular tenant-lifecycle deletion request; tier-based exemption and a keep-account link.
6
+
7
+ ## README
8
+
9
+ # Sample: Tenant Inactivity
10
+
11
+ Opt-in deletion of abandoned free accounts. Mount `createTenantInactivityFeature` next to `sessions`, `tenant-lifecycle` and `delivery`; a daily job tracks the last activity per tenant, warns the tenant owners by mail and finally files the normal deletion request.
12
+
13
+ ## What you learn here
14
+
15
+ - **One rule for everybody, or one per tier**: `{ rule }` applies to every tenant; `{ resolveTier, rulesByTier }` returns `null` for a tier to exempt it (paid plans).
16
+ - **Warning cycle**: with `warnings: [{ days: 30 }, { days: 7 }]` the owners get one mail 30 and one 7 days before the deadline. On the deadline the job calls the same core as the owner's `request-destruction` handler, so the wait period comes from the compliance profile and the owner can still cancel.
17
+ - **Activity restarts the cycle**: a new session counts, and so does the keep-account link in the mail (`keepAccountTokenSecret` signs it; without a secret the mail links to `keepAccountUrl` only). Other apps of the same account report through `activitySources`; `fetchRemoteAppLastActivity` reads the opt-in `lastActivityProbeSecret` route of a remote sessions feature.
18
+ - **No write per request**: the state is only written by the daily job; the state query (`tenant-inactivity:query:state`) shows `exempt`, `lastActivityAt`, `warningsSent`, `nextStep` and `nextStepAt`.
19
+
20
+ ## Feature composition
21
+
22
+ ```
23
+ sessions, tenant, tenant-lifecycle, delivery (required)
24
+ tenant-inactivity <- this sample
25
+ ```
26
+
27
+ ## Tests
28
+
29
+ `src/__tests__/feature.integration.test.ts` runs the job against a manual clock and reads the outlook through the state query. The full mail and deletion flow is covered in `bundled-features/src/tenant-inactivity/__tests__`.
30
+
31
+ ## Source files
32
+
33
+ ### src/__tests__/feature.integration.test.ts
34
+
35
+ ```ts
36
+ import { afterAll, beforeAll, describe, expect, test } from "bun:test";
37
+ import { createAuthEmailPasswordFeature } from "@cosmicdrift/kumiko-bundled-features/auth-email-password";
38
+ import { createAuthFoundationFeature } from "@cosmicdrift/kumiko-bundled-features/auth-foundation";
39
+ import { createComplianceProfilesFeature } from "@cosmicdrift/kumiko-bundled-features/compliance-profiles";
40
+ import {
41
+ configValuesTable,
42
+ createConfigFeature,
43
+ createConfigResolver,
44
+ } from "@cosmicdrift/kumiko-bundled-features/config";
45
+ import {
46
+ createDeliveryFeature,
47
+ createDeliveryTestContext,
48
+ } from "@cosmicdrift/kumiko-bundled-features/delivery";
49
+ import {
50
+ createSessionCallbacks,
51
+ createSessionsFeature,
52
+ type SessionCallbacks,
53
+ } from "@cosmicdrift/kumiko-bundled-features/sessions";
54
+ import {
55
+ sessionCallbacksFromLateBound,
56
+ withMintedSession,
57
+ } from "@cosmicdrift/kumiko-bundled-features/sessions/testing";
58
+ import { createTenantFeature, TenantHandlers } from "@cosmicdrift/kumiko-bundled-features/tenant";
59
+ import { createTenantInactivityFeature } from "@cosmicdrift/kumiko-bundled-features/tenant-inactivity";
60
+ import { createTenantLifecycleFeature } from "@cosmicdrift/kumiko-bundled-features/tenant-lifecycle";
61
+ import { createUserFeature } from "@cosmicdrift/kumiko-bundled-features/user";
62
+ import { SYSTEM_TENANT_ID } from "@cosmicdrift/kumiko-framework/engine";
63
+ import { TestUsers } from "@cosmicdrift/kumiko-framework/seeding";
64
+ import { createLateBoundHolder, createManualClock } from "@cosmicdrift/kumiko-testing/helpers";
65
+ import {
66
+ setupTestStack,
67
+ type TestStack,
68
+ unsafePushTables,
69
+ } from "@cosmicdrift/kumiko-testing/stack";
70
+ import { Temporal } from "@cosmicdrift/kumiko-types/temporal";
71
+
72
+ const START = Temporal.Instant.from("2030-01-15T10:00:00Z");
73
+ const clock = createManualClock(START);
74
+ const callbacks = createLateBoundHolder<SessionCallbacks>("session-callbacks");
75
+
76
+ let stack: TestStack;
77
+
78
+ beforeAll(async () => {
79
+ const bound = sessionCallbacksFromLateBound(callbacks);
80
+ stack = await setupTestStack({
81
+ features: [
82
+ createConfigFeature(),
83
+ createTenantFeature(),
84
+ createUserFeature(),
85
+ createComplianceProfilesFeature(),
86
+ createDeliveryFeature(),
87
+ createAuthFoundationFeature(),
88
+ createAuthEmailPasswordFeature(),
89
+ createSessionsFeature({ clock }),
90
+ createTenantLifecycleFeature(),
91
+ createTenantInactivityFeature({
92
+ rule: { after: { months: 12 }, warnings: [{ days: 30 }, { days: 7 }] },
93
+ keepAccountUrl: "https://app.example.test/keep-account",
94
+ }),
95
+ ],
96
+ extraContext: (deps) => ({
97
+ ...createDeliveryTestContext(deps),
98
+ configResolver: createConfigResolver({ cipher: undefined }),
99
+ clock,
100
+ }),
101
+ authConfig: { ...bound.asAuthConfig(), membershipQuery: "tenant:query:memberships" },
102
+ jobs: { consumerLane: "worker" },
103
+ });
104
+ callbacks.set(createSessionCallbacks({ db: stack.db, clock }));
105
+ await unsafePushTables(stack.db, { configValuesTable });
106
+ });
107
+
108
+ afterAll(async () => {
109
+ await stack.cleanup();
110
+ });
111
+
112
+ describe("tenant-inactivity recipe", () => {
113
+ test("the daily job plans the first warning from the last activity", async () => {
114
+ const creator = sessionCallbacksFromLateBound(callbacks).asAuthConfig().sessionCreator;
115
+ if (!creator) throw new Error("no sessionCreator");
116
+ const systemAdmin = () =>
117
+ withMintedSession(creator, { ...TestUsers.systemAdmin, tenantId: SYSTEM_TENANT_ID });
118
+ await stack.http.writeOk(
119
+ TenantHandlers.create,
120
+ { id: TestUsers.admin.tenantId, key: "acme", name: "Acme Corp" },
121
+ await systemAdmin(),
122
+ );
123
+
124
+ await stack.jobRunner?.dispatch("tenant-inactivity:job:check-inactive-tenants", {});
125
+ await stack.drainJobs();
126
+
127
+ const outlook = await stack.http.queryOk<Record<string, unknown>>(
128
+ "tenant-inactivity:query:state",
129
+ { tenantIdOverride: TestUsers.admin.tenantId },
130
+ await systemAdmin(),
131
+ );
132
+ const deadline = START.toZonedDateTimeISO("UTC").add({ months: 12 }).toInstant();
133
+ expect(outlook["exempt"]).toBe(false);
134
+ expect(outlook["nextStep"]).toBe("warning");
135
+ expect(outlook["nextStepAt"]).toBe(deadline.subtract({ hours: 30 * 24 }).toString());
136
+ });
137
+ });
138
+ ```
@@ -19,6 +19,7 @@
19
19
  | `chat-channels` | Chat channels. Delivery notifications to Slack, minus the browser tab. | `examples/chat-channels.md` |
20
20
  | `compliance-profiles-demo` | Two-tenant demo: EU + Swiss compliance profiles deliver different authority contacts, languages, and grace periods through the same App-code. | `examples/compliance-profiles-demo.md` |
21
21
  | `compose-stacks` | compose*Stack helpers for auth, security, GDPR and SaaS billing, and the runProdApp check that names a stack whose boot option is missing. | `examples/compose-stacks.md` |
22
+ | `contact` | Public contact form backend: the contact bundled feature with its required companions (delivery, user-data-rights, files) and the anonymous browser client. | `examples/contact.md` |
22
23
  | `cross-feature-events` | Feature appends a typed domain event via ctx.events.append; a r.multiStreamProjection reacts asynchronously. | `examples/cross-feature-events.md` |
23
24
  | `crypto-shredding-hr` | Crypto-shredding: PII fields encrypted per subject key; forgetting the subject erases the key and every field it protected. | `examples/crypto-shredding-hr.md` |
24
25
  | `currencies-global` | Shared money fields across tenants. Commas still matter. | `examples/currencies-global.md` |
@@ -73,6 +74,7 @@
73
74
  | `session-revocation` | createSessionCallbacks + sessionChecker — server-side session revocation via JWT jti. | `examples/session-revocation.md` |
74
75
  | `state-machine` | Enforced entity state transitions. No more illegal state changes. | `examples/state-machine.md` |
75
76
  | `tags-basic` | Tag and group any entity without changing it — host-agnostic, event-sourced. | `examples/tags-basic.md` |
77
+ | `tenant-inactivity` | tenant-inactivity: warn abandoned free accounts, then file the regular tenant-lifecycle deletion request; tier-based exemption and a keep-account link. | `examples/tenant-inactivity.md` |
76
78
  | `tenant-isolation` | Multi-tenant separation. Your data stays your data. | `examples/tenant-isolation.md` |
77
79
  | `tenant-settings` | Tenant-Settings: per-tenant Currency + Locale defaults, auto-filled into a money field / locale field on create instead of a hard-coded literal. | `examples/tenant-settings.md` |
78
80
  | `tier-admin` | Manually grant a tier to a tenant without a billing purchase — the SystemAdmin operator flow and how the resolver cache stays in sync. | `examples/tier-admin.md` |
@@ -48,6 +48,8 @@ One entry per feature a package ships: purpose, import of its factory, required
48
48
  `import { createComplianceProfilesOpsFeature } from "@cosmicdrift/kumiko-bundled-features/compliance-profiles-ops"`; requires `compliance-profiles`, `tenant`
49
49
  - `config`: Stores per-tenant (and optionally per-user) configuration values with a multi-layer cascade: user-row → tenant-row → system-row → app-override (deploy-time `AppConfigOverrides`) → computed → feature default.
50
50
  `import { createConfigFeature } from "@cosmicdrift/kumiko-bundled-features/config"`
51
+ - `contact`: Contact inbox: an anonymous browser client (GET /contact/client.js) submits questions, contact requests, bug reports and wishes behind a honeypot, a minimum submit time and a single-use proof-of-work challenge; signed-in users file reports from the admin.
52
+ `import { createContactFeature } from "@cosmicdrift/kumiko-bundled-features/contact"`; requires `config`, `delivery`, `user-data-rights`, `files`, `notes-history`
51
53
  - `crypto-shredding`: Operator-level crypto-shredding trigger.
52
54
  `import { createCryptoShreddingFeature } from "@cosmicdrift/kumiko-bundled-features/crypto-shredding"`
53
55
  - `custom-fields`: Tenant- and system-scoped custom field definitions with generic value storage on any host entity.
@@ -158,6 +160,8 @@ One entry per feature a package ships: purpose, import of its factory, required
158
160
  `import { createTenantFeature } from "@cosmicdrift/kumiko-bundled-features/tenant"`; requires `config`; config without default `smtp-host`, `smtp-pass`
159
161
  - `tenant-handover`: Try-before-signup ownership handover: claims the rows of a declared-transferable entity graph (root plus its parentRef-linked children) from an anonymous/public tenant into the caller's own tenant, legitimized by a row-bound grant the anonymous flow minted.
160
162
  `import { createTenantHandoverFeature } from "@cosmicdrift/kumiko-bundled-features/tenant-handover"`
163
+ - `tenant-inactivity`: Deletes abandoned free accounts: warns the tenant owners before the deadline, then files the regular tenant-lifecycle deletion request.
164
+ `import { createTenantInactivityFeature } from "@cosmicdrift/kumiko-bundled-features/tenant-inactivity"`; requires `sessions`, `tenant`, `tenant-lifecycle`, `delivery`
161
165
  - `tenant-lifecycle`: Tenant-destroy lifecycle: request/cancel destruction with compliance-profile grace, auth 410 gate for teardown states, cron trigger after grace, and staged destroy runner (extension fan-out, subject-key erase, tenant tombstone).
162
166
  `import { createTenantLifecycleFeature } from "@cosmicdrift/kumiko-bundled-features/tenant-lifecycle"`; requires `tenant`, `compliance-profiles`
163
167
  - `tenant-settings`: Per-tenant Currency + Locale defaults, exposed as two config keys (tenant-settings:config:currency, tenant-settings:config:locale) that surface in the self-populating Settings-Hub via `mask`.
@@ -194,6 +194,22 @@ Stores per-tenant (and optionally per-user) configuration values with a multi-la
194
194
 
195
195
  Category: infrastructure
196
196
 
197
+ ## contact
198
+
199
+ Contact inbox: an anonymous browser client (GET /contact/client.js) submits questions, contact requests, bug reports and wishes behind a honeypot, a minimum submit time and a single-use proof-of-work challenge; signed-in users file reports from the admin. Every request is stored platform-wide and every SystemAdmin is notified by mail, optionally also in a Telegram chat (option `telegram`, off by default); the notification names only the kind, the app and a link, never name, address, phone, subject or message, because mail and Telegram cannot be shredded. SystemAdmins reply by mail (Reply-To set, attachments, quoting the original) and mark requests done; a website sender gets a fixed acknowledgement, a signed-in reporter a copy and an in-app note. Personal data is crypto-shredding-ready and the EXT_USER_DATA hooks export and erase a user's requests.
200
+
201
+ Category: communication
202
+
203
+ Requires: `config`, `delivery`, `user-data-rights`, `files`, `notes-history`
204
+
205
+ Optional requires: `channel-telegram`
206
+
207
+ Config keys:
208
+
209
+ | Key | Type | Scope | Default |
210
+ | --- | --- | --- | --- |
211
+ | `reply-to` | text | system | `` |
212
+
197
213
  ## crypto-shredding
198
214
 
199
215
  Operator-level crypto-shredding trigger. `forget-subject` erases a user or tenant subject key in the configured KMS adapter, making every PII field encrypted under it permanently unreadable (reads render the `[[erased]]` sentinel), and appends a `subject-forgotten` audit event. Requires a KMS adapter (`runProdApp({ kms })`). The automated Art.-17 deletion pipeline in `user-data-rights` erases keys itself; this command covers manual forgets (authority requests, operator recovery, tenant destroy).
@@ -725,6 +741,14 @@ Try-before-signup ownership handover: claims the rows of a declared-transferable
725
741
 
726
742
  Category: identity
727
743
 
744
+ ## tenant-inactivity
745
+
746
+ Deletes abandoned free accounts: warns the tenant owners before the deadline, then files the regular tenant-lifecycle deletion request. Activity or the keep-account link restarts the period; tiers without a rule are exempt.
747
+
748
+ Category: compliance
749
+
750
+ Requires: `sessions`, `tenant`, `tenant-lifecycle`, `delivery`
751
+
728
752
  ## tenant-lifecycle
729
753
 
730
754
  Tenant-destroy lifecycle: request/cancel destruction with compliance-profile grace, auth 410 gate for teardown states, cron trigger after grace, and staged destroy runner (extension fan-out, subject-key erase, tenant tombstone).
@@ -733,7 +757,7 @@ Category: compliance
733
757
 
734
758
  Requires: `tenant`, `compliance-profiles`
735
759
 
736
- Optional requires: `sessions`
760
+ Optional requires: `sessions`, `data-retention`
737
761
 
738
762
  Exposes APIs: `tenantLifecycle.runDestroySweep`
739
763
 
package/agents/widgets.md CHANGED
@@ -9,14 +9,18 @@ Value exports of `@cosmicdrift/kumiko-renderer/web`.
9
9
  | Name | Description |
10
10
  | --- | --- |
11
11
  | `ActionMenu` | |
12
+ | `AiSurface` | Light blue area that marks content as AI-generated. |
12
13
  | `AiTextArea` | Multi-line variant of {@link AiTextField}. |
13
14
  | `AiTextField` | Single-line AI text field — ghost-text completion + correct/translate/ rewrite toolbar. |
14
15
  | `AppLayout` | |
16
+ | `AttachmentCard` | Full-width attachment row with a thumbnail box, name, second line and an "open original" link or button. |
17
+ | `AttachmentChip` | File chip with icon, name and a second line; renders as link, button or plain box depending on href/onOpen. |
15
18
  | `Avatar` | |
16
19
  | `BareFormProvider` | |
17
20
  | `BooleanField` | Checkbox/Switch = Field(layout:"inline") + Input(kind:"boolean"). |
18
21
  | `Card` | |
19
22
  | `ChoiceCards` | Card-styled radio group for mutually exclusive choices that need a description or price line. |
23
+ | `ClampedText` | Clamps content to `lines`; the toggle shows only while the content actually overflows. |
20
24
  | `CollapsibleSection` | Collapsible section using native <details> with React-controlled state; otherwise the open attribute resets to its initial value on every parent re-render. |
21
25
  | `ComparisonTable` | Transposed comparison table: row = metric, column = variant, with the best column optionally highlighted for each metric. |
22
26
  | `DateField` | Date field = Field + Input(kind:"date"), ISO yyyy-mm-dd. |
@@ -49,14 +53,17 @@ Value exports of `@cosmicdrift/kumiko-renderer/web`.
49
53
  | `LiveEventsProvider` | |
50
54
  | `LoadingState` | Loading state with skeleton rows styled like cards; `rows` controls the height. |
51
55
  | `LocaleProvider` | |
56
+ | `MessageReader` | Mail thread with an optional tab per attachment; the tab bar only exists when there are attachment tabs. |
57
+ | `MessageThread` | Mail conversation, oldest first: older messages fold to one line, the last one is open on a sheet. |
52
58
  | `MiniStat` | Compact metric tile (without an icon) — for dense KPI grids. |
59
+ | `MobileTopBar` | Phone-only bar for focused screens: the shell header is hidden there, so the screen brings its own. |
53
60
  | `ModeSwitch` | Segmented control for mutually exclusive modes—the prominent alternative to the buried <select>. |
54
61
  | `MoneyField` | |
55
62
  | `NavProvider` | |
56
63
  | `NavTree` | |
57
64
  | `NumberField` | Number field = Field + Input(kind:"number"); avoids repeating the id/name/value/onChange wiring at each screen. |
58
65
  | `PageSection` | |
59
- | `PdfPreview` | |
66
+ | `PdfPreview` | PDF pages rendered with pdf.js; pages render lazily as they scroll into view. |
60
67
  | `PercentField` | |
61
68
  | `PhotoSlots` | Guided photo capture: one tile per requested shot in a two-column grid, each its own camera/gallery picker, filled tiles show the thumbnail. |
62
69
  | `PlainContentEditor` | |
@@ -80,6 +87,8 @@ Value exports of `@cosmicdrift/kumiko-renderer/web`.
80
87
  | `ScreenWidthProvider` | |
81
88
  | `SectionCard` | Section with a title and optional action slot (range switcher, filter) — replaces repeated `<section className={CARD}>…<h2>` blocks in custom screens. |
82
89
  | `SelectField` | Select field = Field + Input(kind:"select"). |
90
+ | `SenderFrame` | Sand frame with one white sheet inside, for content that mimics a letter or mail. |
91
+ | `SenderSheet` | The white sheet alone, for a frame that holds several sheets (PDF pages, thumbnails). |
83
92
  | `SideBySideTable` | Small read-only grid with real table semantics (`th scope`) whose cells are arbitrary React nodes — for side-by-side comparisons like "from the document" vs. |
84
93
  | `Sidebar` | |
85
94
  | `SidebarBrand` | |
@@ -95,6 +104,7 @@ Value exports of `@cosmicdrift/kumiko-renderer/web`.
95
104
  | `StatusBadge` | Pill badge with a status dot. |
96
105
  | `StatusBarChart` | Status bar strip (e.g. 90-day uptime): variable-height bars with gradient fade + tick line on top; the last entry gets a "now" accent stripe. |
97
106
  | `StepBar` | Wizard step overview — numbered chips with a connector line between them. |
107
+ | `StepList` | Ordered plan of steps with status icons, progress header and per-step actions. |
98
108
  | `TextField` | Text field = Field + Input(kind:"text"). |
99
109
  | `TextareaField` | Multi-line text field = Field + Input(kind:"textarea"). |
100
110
  | `ThemeMenuItem` | Theme toggle as a dropdown entry, for a user menu that carries the shell controls. |
@@ -127,6 +137,7 @@ Value exports of `@cosmicdrift/kumiko-renderer/web`.
127
137
  | `usePrimitives` | |
128
138
  | `useQuery` | |
129
139
  | `useResolvers` | |
140
+ | `useShellFocusMode` | Screen side: call while the screen is mounted to get the focused shell. |
130
141
  | `useStore` | |
131
142
  | `useStoreSelector` | |
132
143
  | `useToast` | |
@@ -10,6 +10,7 @@ const CLIENT_CONTROLLED_PAGING_KEYS = [
10
10
  "totalCount",
11
11
  "aggregate",
12
12
  "includeDeleted",
13
+ "onlyDeleted",
13
14
  "filter",
14
15
  ];
15
16
  export function sanitizeExportPayload(clientPayload, plan) {
@@ -1,6 +1,6 @@
1
1
  export { addDurationSpec, subtractRetentionSpec, } from "./duration-spec.ts";
2
2
  export { complianceProfileOverrideSchema } from "./override-schema.ts";
3
- export type { ComplianceProfile, ComplianceProfileKey, ComplianceProfileOverride, DurationSpec, EffectiveComplianceProfile, } from "./profiles.ts";
3
+ export type { ComplianceProfile, ComplianceProfileKey, ComplianceProfileOverride, DurationSpec, EffectiveComplianceProfile, RetentionSpec, } from "./profiles.ts";
4
4
  export { COMPLIANCE_PROFILES, resolveComplianceProfile, SELECTABLE_PROFILE_KEYS, } from "./profiles.ts";
5
5
  export type { SubProcessor } from "./sub-processors.ts";
6
6
  export { getActiveSubProcessors, getPlannedSubProcessors, KUMIKO_SUB_PROCESSORS, } from "./sub-processors.ts";
@@ -1,18 +1,19 @@
1
1
  import { buildOwnershipClause, normalizeAccessEntry, } from "../engine/ownership.js";
2
2
  import { SYSTEM_TENANT_ID } from "../engine/types/identifiers.js";
3
+ import { ValidationError } from "../errors/index.js";
3
4
  import { appendShiftedClause, applyListFilter, collectListFilters, deriveParentNarrowTypes, } from "./event-store-executor-read-filter.js";
4
5
  import { applyListSearch } from "./event-store-executor-read-search.js";
5
6
  import { resolveReadOwnership } from "./read-ownership.js";
6
7
  import { physicalColumnName } from "./table-builder.js";
7
8
  import { schemaTableName } from "./table-introspection.js";
8
9
  // Replicates TenantDb's readWhere semantics for the raw list SQL.
9
- function appendTenantAndSoftDeleteScope(where, ctx, db, includeDeleted) {
10
+ function appendTenantAndSoftDeleteScope(where, ctx, db, trash) {
10
11
  if (ctx.table["tenantId"] !== undefined && db.mode === "tenant") {
11
12
  where.params.push(db.tenantId, SYSTEM_TENANT_ID);
12
13
  where.whereSql.push(`${where.colSql("tenantId")} IN ($${where.params.length - 1}, $${where.params.length})`);
13
14
  }
14
- if (ctx.softDelete && ctx.table["isDeleted"] && !includeDeleted) {
15
- where.whereSql.push(`${where.colSql("isDeleted")} = FALSE`);
15
+ if (ctx.softDelete && ctx.table["isDeleted"] && trash !== "withDeleted") {
16
+ where.whereSql.push(`${where.colSql("isDeleted")} = ${trash === "onlyDeleted" ? "TRUE" : "FALSE"}`);
16
17
  }
17
18
  }
18
19
  // Field-level read access gates filtering, sorting and aggregating the same way it
@@ -30,7 +31,16 @@ export function createFieldReadClause(ctx, user) {
30
31
  export async function buildListWhere(ctx, payload, user, db, runtimeOptions) {
31
32
  const { table, entity, entityName, searchAdapter, streamTenantFor } = ctx;
32
33
  const tableName = String(schemaTableName(table));
33
- const includeDeleted = runtimeOptions?.includeDeleted === true;
34
+ const onlyDeleted = runtimeOptions?.onlyDeleted === true;
35
+ if (onlyDeleted && !ctx.softDelete) {
36
+ throw new ValidationError({
37
+ fields: [
38
+ { path: "onlyDeleted", code: "not_soft_delete", i18nKey: "errors.validation.onlyDeleted" },
39
+ ],
40
+ });
41
+ }
42
+ // The parent-visibility gate lifts its deleted-host predicate for a trash list the same way.
43
+ const includeDeleted = onlyDeleted || runtimeOptions?.includeDeleted === true;
34
44
  // Decide before touching search or the DB: an `empty` ownership skips both paths.
35
45
  const ownership = resolveReadOwnership(ctx, tableName, user, db, runtimeOptions?.parentVisibility, {
36
46
  includeDeleted,
@@ -65,7 +75,7 @@ export async function buildListWhere(ctx, payload, user, db, runtimeOptions) {
65
75
  return { kind: "empty" };
66
76
  searchTruncated = search.searchTruncated;
67
77
  }
68
- appendTenantAndSoftDeleteScope(where, ctx, db, includeDeleted);
78
+ appendTenantAndSoftDeleteScope(where, ctx, db, onlyDeleted ? "onlyDeleted" : includeDeleted ? "withDeleted" : "live");
69
79
  if (ownership.kind === "sql")
70
80
  appendShiftedClause(where, ownership);
71
81
  for (const f of collectListFilters(payload)) {
@@ -28,7 +28,7 @@ export { readDatabaseNow } from "./queries/database-now.ts";
28
28
  export { listEventTenantIds } from "./queries/event-tenants.ts";
29
29
  export { toPostgresArrayLiteral } from "./queries/postgres-array-literal.ts";
30
30
  export { executeRawQuery } from "./queries/raw-sql.ts";
31
- export { withSessionAdvisoryLock } from "./queries/session-advisory-lock.ts";
31
+ export { tryWithSessionAdvisoryLock, withSessionAdvisoryLock, } from "./queries/session-advisory-lock.ts";
32
32
  export type { JsonTextMatch, SelectOptions, WhereObject, } from "./query.ts";
33
33
  export { aggregateWhere, asEntityTableMeta, asRawClient, countWhere, deleteMany, deleteManyBatched, fetchOne, incrementCounter, insertMany, insertOnConflictDoNothing, insertOne, requireEntityTableMeta, runInSavepointIfSupported, runnerCanBeginTransaction, selectInnerJoin, selectMany, transaction, unsafeReadRetrying, updateMany, upsertByPk, upsertOnConflict, } from "./query.ts";
34
34
  export { seedReferenceData } from "./reference-data.ts";
package/dist/db/index.js CHANGED
@@ -24,7 +24,7 @@ export { readDatabaseNow } from "./queries/database-now.js";
24
24
  export { listEventTenantIds } from "./queries/event-tenants.js";
25
25
  export { toPostgresArrayLiteral } from "./queries/postgres-array-literal.js";
26
26
  export { executeRawQuery } from "./queries/raw-sql.js";
27
- export { withSessionAdvisoryLock } from "./queries/session-advisory-lock.js";
27
+ export { tryWithSessionAdvisoryLock, withSessionAdvisoryLock, } from "./queries/session-advisory-lock.js";
28
28
  export { aggregateWhere, asEntityTableMeta, asRawClient, countWhere, deleteMany, deleteManyBatched, fetchOne, incrementCounter, insertMany, insertOnConflictDoNothing, insertOne, requireEntityTableMeta, runInSavepointIfSupported, runnerCanBeginTransaction, selectInnerJoin, selectMany, transaction, unsafeReadRetrying, updateMany, upsertByPk, upsertOnConflict, } from "./query.js";
29
29
  export { seedReferenceData } from "./reference-data.js";
30
30
  export { renderTablesDdl } from "./render-ddl.js";
@@ -383,7 +383,9 @@ export function assertUniqueTableNames(metas) {
383
383
  const duplicates = [...counts].filter(([, count]) => count > 1);
384
384
  if (duplicates.length > 0) {
385
385
  throw new Error(duplicates
386
- .map(([tableName, count]) => `ENTITY_METAS lists table "${tableName}" ${count} times — the migration diff would silently use only one definition. collectTableMetas(features) already includes every table a feature registers (r.storeTable, entities, projections); remove the duplicate entry for "${tableName}" (a hand-added meta, or two features registering the same table).`)
386
+ .map(
387
+ // guard:dup-ok one template-literal line per row; only the shape matches other renderers
388
+ ([tableName, count]) => `ENTITY_METAS lists table "${tableName}" ${count} times — the migration diff would silently use only one definition. collectTableMetas(features) already includes every table a feature registers (r.storeTable, entities, projections); remove the duplicate entry for "${tableName}" (a hand-added meta, or two features registering the same table).`)
387
389
  .join("\n"));
388
390
  }
389
391
  }
@@ -12,6 +12,7 @@ export async function selectSnapshotXmin(db) {
12
12
  throw new Error("selectSnapshotXmin: no row returned");
13
13
  return xmin;
14
14
  }
15
+ // guard:dup-ok symmetric twin of selectSnapshotXmin; a shared helper would only add indirection
15
16
  export async function selectSnapshotXmax(db) {
16
17
  const rows = await asRawClient(db).unsafe(`SELECT pg_snapshot_xmax(pg_current_snapshot())::text AS xmax`);
17
18
  const xmax = rows[0]?.xmax;
@@ -127,10 +128,15 @@ export async function selectProvablyIdleConsumerPairs(db, names, instanceIds, de
127
128
  )`, [toPostgresArrayLiteral(names), toPostgresArrayLiteral(instanceIds), deadStatus]);
128
129
  return rows.map((r) => ({ name: r.name, instanceId: r.instance_id }));
129
130
  }
130
- export async function selectConsumerForUpdateSkipLocked(db, name, instanceId) {
131
- const rows = await asRawClient(db).unsafe(`SELECT * FROM "kumiko_event_consumers" WHERE "name" = $1 AND "instance_id" = $2 FOR UPDATE SKIP LOCKED`, [name, instanceId]);
131
+ // Raw because the callers need row locks (FOR UPDATE [SKIP LOCKED]) or RETURNING *; the SQL is
132
+ // always a fixed literal with name/instanceId bound as $1/$2, never interpolated.
133
+ async function firstConsumerRow(db, sql, name, instanceId) {
134
+ const rows = await asRawClient(db).unsafe(sql, [name, instanceId]);
132
135
  return rows[0];
133
136
  }
137
+ export async function selectConsumerForUpdateSkipLocked(db, name, instanceId) {
138
+ return firstConsumerRow(db, `SELECT * FROM "kumiko_event_consumers" WHERE "name" = $1 AND "instance_id" = $2 FOR UPDATE SKIP LOCKED`, name, instanceId);
139
+ }
134
140
  export async function markConsumerProcessing(db, name, instanceId) {
135
141
  await asRawClient(db).unsafe(`UPDATE "kumiko_event_consumers" SET "status" = 'processing', "updated_at" = now()
136
142
  WHERE "name" = $1 AND "instance_id" = $2`, [name, instanceId]);
@@ -230,8 +236,7 @@ export async function resetConsumerForMspRebuild(db, name, instanceId) {
230
236
  "updated_at" = now()`, [name, instanceId]);
231
237
  }
232
238
  export async function selectConsumerForUpdate(db, name, instanceId) {
233
- const rows = await asRawClient(db).unsafe(`SELECT * FROM "kumiko_event_consumers" WHERE "name" = $1 AND "instance_id" = $2 FOR UPDATE`, [name, instanceId]);
234
- return rows[0];
239
+ return firstConsumerRow(db, `SELECT * FROM "kumiko_event_consumers" WHERE "name" = $1 AND "instance_id" = $2 FOR UPDATE`, name, instanceId);
235
240
  }
236
241
  export async function updateConsumerRebuildCursor(db, name, instanceId, lastProcessedEventId, pendingGaps) {
237
242
  await asRawClient(db).unsafe(`UPDATE "kumiko_event_consumers" SET
@@ -255,15 +260,14 @@ export async function markConsumerRebuildFailed(db, name, instanceId, errorMessa
255
260
  // so the caller can enforce a lifetime cap on automatic revivals; manual
256
261
  // restartConsumer()/enableConsumer() reset it back to 0.
257
262
  export async function rearmDeadConsumer(db, name, instanceId) {
258
- const rows = await asRawClient(db).unsafe(`UPDATE "kumiko_event_consumers" SET
263
+ return firstConsumerRow(db, `UPDATE "kumiko_event_consumers" SET
259
264
  "status" = 'idle',
260
265
  "attempts" = 0,
261
266
  "last_error" = NULL,
262
267
  "rearm_count" = "rearm_count" + 1,
263
268
  "updated_at" = now()
264
269
  WHERE "name" = $1 AND "instance_id" = $2
265
- RETURNING *`, [name, instanceId]);
266
- return rows[0];
270
+ RETURNING *`, name, instanceId);
267
271
  }
268
272
  // skipPoisonEvent's pending-gap branch: the poison is a pending id below the
269
273
  // cursor, so it's removed from pending_gaps directly instead of advancing
@@ -58,5 +58,6 @@ export type PendingIdRange = {
58
58
  readonly from: bigint;
59
59
  readonly to: bigint;
60
60
  };
61
- export declare function selectPendingAndNewEventRows(db: AnyDb, cursor: bigint, pendingRanges: readonly PendingIdRange[], batchSize: number): Promise<ReadonlyArray<Record<string, unknown>>>;
61
+ export declare function selectPendingAndNewEventRows(db: AnyDb, cursor: bigint, pendingRanges: readonly PendingIdRange[], batchSize: number, pendingLimit: number): Promise<ReadonlyArray<Record<string, unknown>>>;
62
+ export declare function selectTenantIdsInRangesAbove(db: AnyDb, pendingRanges: readonly PendingIdRange[], aboveId: bigint): Promise<ReadonlySet<string>>;
62
63
  export declare function selectSmallestVisibleIdInRanges(db: AnyDb, pendingRanges: readonly PendingIdRange[]): Promise<bigint | null>;
@@ -279,18 +279,21 @@ export async function upsertArchivedStream(db, params) {
279
279
  // consumer is still watching as pending gaps (ids invisible on an earlier
280
280
  // turn that may have become visible since). Raw SQL — the typed builder's
281
281
  // WhereObject is an AND of fields, it can't express this OR.
282
- export async function selectPendingAndNewEventRows(db, cursor, pendingRanges, batchSize) {
282
+ export async function selectPendingAndNewEventRows(db, cursor, pendingRanges, batchSize, pendingLimit) {
283
283
  if (pendingRanges.length === 0) {
284
284
  return unsafeReadRetrying(db, `SELECT * FROM "kumiko_events" WHERE "id" > $1 ORDER BY "id" ASC LIMIT $2`, [cursor, batchSize]);
285
285
  }
286
286
  return unsafeReadRetrying(db,
287
287
  // UNION ALL of two primary-key range scans: an `id > $1 OR EXISTS (…)`
288
288
  // predicate can't use the index and would seq-scan kumiko_events per turn.
289
- // Ranges sit below $1, so the branches never overlap.
290
- `(SELECT e.* FROM unnest($2::bigint[], $3::bigint[]) AS g(f, t)
291
- CROSS JOIN LATERAL (
292
- SELECT * FROM "kumiko_events" WHERE "id" BETWEEN g.f AND g.t ORDER BY "id" ASC LIMIT $4
293
- ) e)
289
+ // Ranges sit below $1, so the branches never overlap. The pending branch is capped at $5
290
+ // so ids a consumer keeps holding can never take the whole batch from newer events.
291
+ `(SELECT p.* FROM (
292
+ SELECT e.* FROM unnest($2::bigint[], $3::bigint[]) AS g(f, t)
293
+ CROSS JOIN LATERAL (
294
+ SELECT * FROM "kumiko_events" WHERE "id" BETWEEN g.f AND g.t ORDER BY "id" ASC LIMIT $5
295
+ ) e
296
+ ) p ORDER BY p."id" ASC LIMIT $5)
294
297
  UNION ALL
295
298
  (SELECT * FROM "kumiko_events" WHERE "id" > $1 ORDER BY "id" ASC LIMIT $4)
296
299
  ORDER BY "id" ASC LIMIT $4`, [
@@ -298,7 +301,23 @@ export async function selectPendingAndNewEventRows(db, cursor, pendingRanges, ba
298
301
  toPostgresArrayLiteral(pendingRanges.map((r) => r.from)),
299
302
  toPostgresArrayLiteral(pendingRanges.map((r) => r.to)),
300
303
  batchSize,
304
+ pendingLimit,
305
+ ]);
306
+ }
307
+ // Tenants with an event inside a pending range above `aboveId`: the pending events a capped
308
+ // fetch left out, whose tenants must not see newer events before them.
309
+ export async function selectTenantIdsInRangesAbove(db, pendingRanges, aboveId) {
310
+ if (pendingRanges.length === 0)
311
+ return new Set();
312
+ const rows = await unsafeReadRetrying(db, `SELECT DISTINCT e."tenant_id" FROM unnest($1::bigint[], $2::bigint[]) AS g(f, t)
313
+ CROSS JOIN LATERAL (
314
+ SELECT "tenant_id" FROM "kumiko_events" WHERE "id" BETWEEN GREATEST(g.f, $3) AND g.t
315
+ ) e`, [
316
+ toPostgresArrayLiteral(pendingRanges.map((r) => r.from)),
317
+ toPostgresArrayLiteral(pendingRanges.map((r) => r.to)),
318
+ aboveId + 1n,
301
319
  ]);
320
+ return new Set(rows.map((row) => row.tenant_id));
302
321
  }
303
322
  // Smallest committed-and-visible id inside any pending range — lets
304
323
  // skipPoisonEvent (event-dispatcher-admin.ts) tell a live poison apart from
@@ -23,7 +23,9 @@ export async function readTenantTablesRowLevelSecurity(db) {
23
23
  AND EXISTS (SELECT 1 FROM pg_attribute a
24
24
  WHERE a.attrelid = c.oid AND a.attname = 'tenant_id' AND a.attnum > 0 AND NOT a.attisdropped)
25
25
  ORDER BY c.relname COLLATE "C"`, [TENANT_ISOLATION_POLICY, SYSTEM_TENANT_READ_POLICY]);
26
- return rows.map((row) => ({
26
+ return rows.map(
27
+ // guard:dup-ok catalog row to snapshot field mapping; only the object-literal shape matches other mappers
28
+ (row) => ({
27
29
  tableName: row.relname,
28
30
  enabled: row.relrowsecurity,
29
31
  forced: row.relforcerowsecurity,
@@ -1,2 +1,9 @@
1
1
  import type { AnyDb } from "../query.ts";
2
2
  export declare function withSessionAdvisoryLock<T>(db: AnyDb, key: number, fn: () => Promise<T>): Promise<T>;
3
+ export type TryAdvisoryLockResult<T> = {
4
+ readonly acquired: true;
5
+ readonly value: T;
6
+ } | {
7
+ readonly acquired: false;
8
+ };
9
+ export declare function tryWithSessionAdvisoryLock<T>(db: AnyDb, key: number, fn: () => Promise<T>): Promise<TryAdvisoryLockResult<T>>;
@@ -21,3 +21,26 @@ export async function withSessionAdvisoryLock(db, key, fn) {
21
21
  await conn.release();
22
22
  }
23
23
  }
24
+ // Same session scoping as withSessionAdvisoryLock, but a peer holding the lock makes the
25
+ // caller skip instead of wait: for work that only needs to run once across replicas.
26
+ export async function tryWithSessionAdvisoryLock(db, key, fn) {
27
+ const client = asRawClient(db);
28
+ if (typeof client.reserve !== "function") {
29
+ throw new Error("tryWithSessionAdvisoryLock: db has no .reserve() (need a Bun.SQL pool)");
30
+ }
31
+ const conn = await client.reserve();
32
+ try {
33
+ const rows = await conn.unsafe(`SELECT pg_try_advisory_lock($1) AS "locked"`, [key]);
34
+ if (rows[0]?.locked !== true)
35
+ return { acquired: false };
36
+ try {
37
+ return { acquired: true, value: await fn() };
38
+ }
39
+ finally {
40
+ await conn.unsafe(`SELECT pg_advisory_unlock($1)`, [key]).catch(() => undefined);
41
+ }
42
+ }
43
+ finally {
44
+ await conn.release();
45
+ }
46
+ }
package/dist/db/query.js CHANGED
@@ -729,22 +729,19 @@ export async function deleteManyBatched(db, table, where, options) {
729
729
  }
730
730
  return { deleted, batches };
731
731
  }
732
- export async function transaction(db, fn) {
732
+ function beginnableClientOrThrow(db, caller) {
733
733
  const raw = asRawClient(db);
734
734
  if (!hasBegin(raw)) {
735
735
  throw new InternalError({
736
- message: "transaction: runner has no begin() — already inside a transaction or savepoint.",
736
+ message: `${caller}: runner has no begin() — already inside a transaction or savepoint.`,
737
737
  });
738
738
  }
739
- return raw.begin(fn);
739
+ return raw;
740
+ }
741
+ export async function transaction(db, fn) {
742
+ return beginnableClientOrThrow(db, "transaction").begin(fn);
740
743
  }
741
744
  // A tx/savepoint handle has no begin(); fail closed instead of nesting silently or TypeError-ing.
742
745
  export async function runInNewTransaction(db, fn) {
743
- const raw = asRawClient(db);
744
- if (!hasBegin(raw)) {
745
- throw new InternalError({
746
- message: "runInNewTransaction: runner has no begin() — already inside a transaction or savepoint.",
747
- });
748
- }
749
- return raw.begin(fn);
746
+ return beginnableClientOrThrow(db, "runInNewTransaction").begin(fn);
750
747
  }
@@ -75,11 +75,13 @@ function transactionHandleProxy(handle, state) {
75
75
  if (typeof value !== "function")
76
76
  return value;
77
77
  if (UNSUPPORTED_ON_ENFORCED_HANDLE.has(prop)) {
78
- return () => {
78
+ return (
79
+ // guard:dup-ok a throw-only stub; the message is its whole content
80
+ () => {
79
81
  throw new InternalError({
80
82
  message: `row-level security: ${String(prop)} is not supported on an enforced transaction handle`,
81
83
  });
82
- };
84
+ });
83
85
  }
84
86
  if (prop === "unsafe" || prop === "file") {
85
87
  return (...args) => alignedStatement(target, state, () => callMethod(target, prop, args));
@@ -1,4 +1,4 @@
1
- import { isOpenToAllGranted } from "@cosmicdrift/kumiko-types/handlers";
1
+ import { isAnySignedInGranted, isOpenToAllGranted } from "@cosmicdrift/kumiko-types/handlers";
2
2
  import { ANONYMOUS_ROLE } from "./system-user.js";
3
3
  // Default-deny: a handler without an explicit AccessRule is unreachable. To
4
4
  // grant access a handler must either list allowed roles or opt into
@@ -11,6 +11,8 @@ import { ANONYMOUS_ROLE } from "./system-user.js";
11
11
  // list `anonymous` in `roles` (e.g. `roles: ["anonymous", "customer"]`).
12
12
  // Without this guard, enabling `anonymousAccess` on the server would silently
13
13
  // turn every existing `openToAll: true` handler into a public endpoint.
14
+ // `anySignedIn` widens such a public rule to every signed-in caller instead of
15
+ // the listed roles only.
14
16
  export function hasAccess(user, access) {
15
17
  if (!access)
16
18
  return false;
@@ -21,5 +23,7 @@ export function hasAccess(user, access) {
21
23
  }
22
24
  if (access.roles.length === 0)
23
25
  return false;
26
+ if (isAnySignedInGranted(access) && !user.roles.includes(ANONYMOUS_ROLE))
27
+ return true;
24
28
  return access.roles.some((role) => user.roles.includes(role));
25
29
  }