@cosmicdrift/kumiko-framework 0.414.0 → 0.416.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 (115) hide show
  1. package/agents/api/framework-engine.md +46 -8
  2. package/agents/api/framework-errors.md +1 -1
  3. package/agents/api/framework-ui-types.md +69 -4
  4. package/agents/api/renderer-web.md +27 -4
  5. package/agents/api/types.md +68 -16
  6. package/agents/api.md +2 -2
  7. package/agents/boot-rules.md +39 -7
  8. package/agents/examples/crypto-shredding-hr.md +63 -1
  9. package/agents/examples/embedded.md +24 -1
  10. package/agents/examples/handbook-knowledge.md +129 -0
  11. package/agents/examples/record-detail-layout.md +113 -7
  12. package/agents/examples/signature.md +186 -0
  13. package/agents/examples/writeform-section.md +1 -0
  14. package/agents/examples.md +2 -0
  15. package/agents/features-index.md +4 -0
  16. package/agents/features.md +14 -0
  17. package/agents/widgets.md +7 -0
  18. package/dist/api/request-context-internals.d.ts +2 -0
  19. package/dist/api/request-context-scopes.js +9 -2
  20. package/dist/api/request-context.js +1 -1
  21. package/dist/api/routes.js +4 -4
  22. package/dist/api/server-event-dispatcher.js +3 -0
  23. package/dist/api/server-routes.js +2 -0
  24. package/dist/db/parent-ref-clause.js +31 -3
  25. package/dist/db/parent-ref-global-hosts.d.ts +4 -1
  26. package/dist/db/parent-ref-global-hosts.js +50 -12
  27. package/dist/db/queries/rls-boot-catalog.js +5 -6
  28. package/dist/db/queries/rls-shape.d.ts +1 -0
  29. package/dist/db/queries/rls-shape.js +21 -6
  30. package/dist/db/table-builder.js +3 -1
  31. package/dist/engine/boot-validator/boot-phases.js +5 -0
  32. package/dist/engine/boot-validator/boot-rules.d.ts +144 -9
  33. package/dist/engine/boot-validator/card-meta-overflow-rules.d.ts +2 -2
  34. package/dist/engine/boot-validator/card-meta-overflow-rules.js +2 -2
  35. package/dist/engine/boot-validator/card-meta-overflow.js +7 -5
  36. package/dist/engine/boot-validator/cross-tenant-file-read.d.ts +3 -0
  37. package/dist/engine/boot-validator/cross-tenant-file-read.js +19 -0
  38. package/dist/engine/boot-validator/entity-declaration-rules.d.ts +10 -0
  39. package/dist/engine/boot-validator/entity-declaration-rules.js +10 -0
  40. package/dist/engine/boot-validator/entity-list-screens.js +2 -7
  41. package/dist/engine/boot-validator/list-row-guidance-rules.d.ts +17 -2
  42. package/dist/engine/boot-validator/list-row-guidance-rules.js +17 -2
  43. package/dist/engine/boot-validator/list-row-guidance.d.ts +7 -0
  44. package/dist/engine/boot-validator/list-row-guidance.js +45 -1
  45. package/dist/engine/boot-validator/list-sort-summary-rules.d.ts +2 -2
  46. package/dist/engine/boot-validator/list-sort-summary-rules.js +2 -2
  47. package/dist/engine/boot-validator/list-sort-summary.js +31 -20
  48. package/dist/engine/boot-validator/list-toolbar-options.js +3 -4
  49. package/dist/engine/boot-validator/named-filter-rules.d.ts +10 -0
  50. package/dist/engine/boot-validator/named-filter-rules.js +10 -0
  51. package/dist/engine/boot-validator/projection-list-screens.js +5 -4
  52. package/dist/engine/boot-validator/query-output-columns.js +18 -0
  53. package/dist/engine/boot-validator/query-output-guidance.js +3 -0
  54. package/dist/engine/boot-validator/query-refs.js +14 -1
  55. package/dist/engine/boot-validator/relative-time-format.d.ts +1 -0
  56. package/dist/engine/boot-validator/relative-time-format.js +51 -0
  57. package/dist/engine/boot-validator/screens-actions-rules.d.ts +16 -1
  58. package/dist/engine/boot-validator/screens-actions-rules.js +16 -1
  59. package/dist/engine/boot-validator/screens-actions.js +56 -16
  60. package/dist/engine/boot-validator/screens-dashboard-narrow.d.ts +2 -1
  61. package/dist/engine/boot-validator/screens-dashboard-narrow.js +43 -4
  62. package/dist/engine/boot-validator/screens-dashboard-rules.d.ts +12 -2
  63. package/dist/engine/boot-validator/screens-dashboard-rules.js +12 -2
  64. package/dist/engine/boot-validator/screens-dashboard.js +2 -1
  65. package/dist/engine/boot-validator/screens-forms-layout-rules.d.ts +5 -0
  66. package/dist/engine/boot-validator/screens-forms-layout-rules.js +5 -0
  67. package/dist/engine/boot-validator/screens-forms-rules.d.ts +60 -0
  68. package/dist/engine/boot-validator/screens-forms-rules.js +60 -0
  69. package/dist/engine/boot-validator/screens-forms.d.ts +1 -1
  70. package/dist/engine/boot-validator/screens-forms.js +108 -2
  71. package/dist/engine/boot-validator/screens-kind-config-edit.js +1 -0
  72. package/dist/engine/boot-validator/screens-kind-projection-detail-rules.d.ts +5 -0
  73. package/dist/engine/boot-validator/screens-kind-projection-detail-rules.js +5 -0
  74. package/dist/engine/boot-validator/screens-kind-projection-detail.js +30 -0
  75. package/dist/engine/boot-validator/screens-lists-rules.d.ts +5 -0
  76. package/dist/engine/boot-validator/screens-lists-rules.js +5 -0
  77. package/dist/engine/boot-validator/screens-lists.js +4 -1
  78. package/dist/engine/build-config-feature-schema.js +5 -35
  79. package/dist/engine/config-access-rules.d.ts +3 -0
  80. package/dist/engine/config-access-rules.js +34 -0
  81. package/dist/engine/factories.d.ts +2 -0
  82. package/dist/engine/named-filter-roles.js +6 -14
  83. package/dist/engine/project-app-schema-for-roles.js +2 -0
  84. package/dist/engine/schema-builder.js +3 -1
  85. package/dist/engine/soft-delete-cleanup.js +2 -0
  86. package/dist/errors/reasons.d.ts +1 -0
  87. package/dist/errors/reasons.js +4 -0
  88. package/dist/files/file-routes.d.ts +2 -0
  89. package/dist/files/file-routes.js +85 -22
  90. package/dist/files/foreign-tenant-file-read.d.ts +13 -0
  91. package/dist/files/foreign-tenant-file-read.js +64 -0
  92. package/dist/i18n/required-surface-keys.js +28 -7
  93. package/dist/jobs/job-runner-execution.js +3 -0
  94. package/dist/jobs/job-runner-types.d.ts +1 -0
  95. package/dist/jobs/job-runner.js +8 -0
  96. package/dist/pipeline/context-services.d.ts +1 -1
  97. package/dist/pipeline/context-services.js +1 -1
  98. package/dist/pipeline/event-dispatcher-delivery.js +3 -0
  99. package/dist/pipeline/event-dispatcher.d.ts +2 -0
  100. package/dist/pipeline/handler-context-phase-denials.js +1 -1
  101. package/dist/pipeline/irreversible-operation-gate.js +36 -10
  102. package/dist/search/meilisearch-adapter-internals.d.ts +2 -0
  103. package/dist/search/meilisearch-adapter-internals.js +5 -0
  104. package/dist/search/meilisearch-adapter.d.ts +1 -0
  105. package/dist/search/meilisearch-adapter.js +3 -2
  106. package/dist/ui-types/card-column-roles.d.ts +2 -0
  107. package/dist/ui-types/card-column-roles.js +15 -0
  108. package/dist/ui-types/index.d.ts +2 -2
  109. package/dist/ui-types/index.js +1 -1
  110. package/package.json +3 -3
  111. package/presets/biome-plugins/no-date-api.grit +3 -1
  112. package/presets/biome-plugins/no-direct-fetch.grit +1 -1
  113. package/presets/biome-plugins/unsafe-json-parse.grit +7 -1
  114. package/presets/biome-rules.json +12 -10
  115. package/src/changes.json +99 -0
@@ -0,0 +1,186 @@
1
+ <!-- Generated by `bun run gen:agent-docs` from samples/recipes/signature. Do not edit. -->
2
+
3
+ # signature
4
+
5
+ The signature bundled feature: a request for several signers, a signing link that is delivered by the app, and a completed PDF with a signature page.
6
+
7
+ ## README
8
+
9
+ # Signature
10
+
11
+ Several people sign one PDF of the tenant, in person on a display or through a link. The last
12
+ signature moves the request to `all-signed`; a job renders a signature page, appends it to the
13
+ unchanged original and completes the request.
14
+
15
+ ## What it shows
16
+
17
+ - **Feature** - `createSignatureFeature({ retention, linkSecret, renderHtmlToPdf, deliverLink, signaturePageUrl })`.
18
+ Needs `files` and `user-data-rights` (exports and erases signer data); the test mounts user-data-rights with its own dependencies.
19
+ - **deliverLink** - `issue-link` hands the signing link to the app (mail) and returns only
20
+ `{ signerId, linkSentAt }`: whoever may issue a link must not be able to sign with it.
21
+ - **renderHtmlToPdf** - injected; in an app it is the client of `@cosmicdrift/kumiko-renderer-puppeteer-client`.
22
+ - **Test** - `setupTestStack` and HTTP: request, issue-link, anonymous sign-by-link, sweep job, completed.
23
+
24
+ ## Files
25
+
26
+ ```
27
+ src/feature.ts the feature with a link outbox and a stand-in printer
28
+ src/__tests__/feature.integration.test.ts request to completed request over HTTP
29
+ ```
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 { createAuthFoundationFeature } from "@cosmicdrift/kumiko-bundled-features/auth-foundation";
38
+ import { createComplianceProfilesFeature } from "@cosmicdrift/kumiko-bundled-features/compliance-profiles";
39
+ import { createDataRetentionFeature } from "@cosmicdrift/kumiko-bundled-features/data-retention";
40
+ import { createSessionsFeature } from "@cosmicdrift/kumiko-bundled-features/sessions";
41
+ import { createUserFeature } from "@cosmicdrift/kumiko-bundled-features/user";
42
+ import { createUserDataRightsFeature } from "@cosmicdrift/kumiko-bundled-features/user-data-rights";
43
+ import { createEventStoreExecutor, createTenantDb } from "@cosmicdrift/kumiko-framework/db";
44
+ import { createSystemUser, SYSTEM_TENANT_ID } from "@cosmicdrift/kumiko-framework/engine";
45
+ import {
46
+ createFilesFeature,
47
+ createInMemoryFileProvider,
48
+ fileRefEntity,
49
+ fileRefsTable,
50
+ } from "@cosmicdrift/kumiko-framework/files";
51
+ import { createTestUser, testTenantId } from "@cosmicdrift/kumiko-framework/seeding";
52
+ import { setupTestStack, type TestStack } from "@cosmicdrift/kumiko-testing/stack";
53
+ import { PDFDocument } from "pdf-lib";
54
+ import { deliveredLinks, signatureFeature } from "../feature";
55
+
56
+ const TENANT = testTenantId(1);
57
+ const admin = createTestUser({ roles: ["TenantAdmin"], tenantId: TENANT });
58
+ const SIGNATURE_PNG =
59
+ "iVBORw0KGgoAAAANSUhEUgAAACgAAAAQCAYAAABk1z2tAAAANklEQVR4nGNgYGD4j4QHJUB24KB0LC4HDjqHgsCoY0dDdTS9jmas0SJrtGwdrbVGq9f/yCUBAOaodYsn7bfwAAAAAElFTkSuQmCC";
60
+
61
+ const provider = createInMemoryFileProvider();
62
+ let stack: TestStack;
63
+
64
+ beforeAll(async () => {
65
+ stack = await setupTestStack({
66
+ features: [
67
+ createUserFeature(),
68
+ createAuthFoundationFeature(),
69
+ createSessionsFeature(),
70
+ createDataRetentionFeature(),
71
+ createComplianceProfilesFeature(),
72
+ createUserDataRightsFeature(),
73
+ createFilesFeature(),
74
+ signatureFeature,
75
+ ],
76
+ files: { storageProvider: provider },
77
+ jobs: { consumerLane: "worker", getActiveTenantIds: async () => [TENANT] },
78
+ anonymousAccess: { defaultTenantId: SYSTEM_TENANT_ID },
79
+ });
80
+ });
81
+
82
+ afterAll(async () => {
83
+ await stack.cleanup();
84
+ });
85
+
86
+ async function seedContract(): Promise<string> {
87
+ const bytes = await (async () => {
88
+ const pdf = await PDFDocument.create();
89
+ pdf.addPage();
90
+ return pdf.save();
91
+ })();
92
+ const storageKey = `${TENANT}/contract.pdf`;
93
+ await provider.write(storageKey, bytes, "application/pdf");
94
+ const db = createTenantDb({
95
+ db: stack.db,
96
+ tenantId: TENANT,
97
+ mode: "system",
98
+ reason: "recipe seeds the document the request refers to",
99
+ });
100
+ const created = await createEventStoreExecutor(fileRefsTable, fileRefEntity, {
101
+ entityName: "fileRef",
102
+ }).create(
103
+ { storageKey, fileName: "contract.pdf", mimeType: "application/pdf", size: bytes.length },
104
+ createSystemUser(TENANT),
105
+ db,
106
+ );
107
+ if (!created.isSuccess) throw new Error(created.error.message);
108
+ return String(created.data.id);
109
+ }
110
+
111
+ describe("signature recipe", () => {
112
+ test("a link is delivered, never returned, and the last signature completes the request", async () => {
113
+ const { requestId, signerIds } = await stack.http.writeOk<{
114
+ requestId: string;
115
+ signerIds: string[];
116
+ }>(
117
+ "signature:write:request",
118
+ {
119
+ documentFileId: await seedContract(),
120
+ title: "Rental agreement",
121
+ subjectType: "lease",
122
+ subjectId: "lease-1",
123
+ signers: [{ name: "Ada", email: "ada@example.test" }],
124
+ },
125
+ admin,
126
+ );
127
+ const signerId = signerIds[0] as string;
128
+
129
+ const issued = await stack.http.writeOk<Record<string, unknown>>(
130
+ "signature:write:issue-link",
131
+ { signerId },
132
+ admin,
133
+ );
134
+ expect(Object.keys(issued).sort()).toEqual(["linkSentAt", "signerId"]);
135
+
136
+ const url = deliveredLinks.get(signerId) ?? "";
137
+ expect(url.startsWith("https://app.example/sign#")).toBe(true);
138
+ const signed = await stack.http.raw("POST", "/api/write", {
139
+ type: "signature:write:sign-by-link",
140
+ payload: { token: url.slice(url.indexOf("#") + 1), imagePngBase64: SIGNATURE_PNG },
141
+ });
142
+ expect(signed.status).toBe(200);
143
+
144
+ await stack.jobRunner?.dispatch("signature:job:sweep", { tenantId: TENANT });
145
+ await stack.drainJobs();
146
+
147
+ const request = await stack.http.queryOk<{ status: string }>(
148
+ "signature:query:signature-request:detail",
149
+ { id: requestId },
150
+ admin,
151
+ );
152
+ expect(request.status).toBe("completed");
153
+ });
154
+ });
155
+ ```
156
+
157
+ ### src/feature.ts
158
+
159
+ ```ts
160
+ import { createSignatureFeature } from "@cosmicdrift/kumiko-bundled-features/signature";
161
+ import { PDFDocument } from "pdf-lib";
162
+
163
+ // In an app `deliverLink` sends a mail to the signer. The recipe keeps the links in a map so the
164
+ // test can open them: the link is never part of a handler result.
165
+ export const deliveredLinks = new Map<string, string>();
166
+
167
+ // In an app this is `renderHtmlToPdf` from @cosmicdrift/kumiko-renderer-puppeteer-client, which
168
+ // needs the print service; the recipe prints a blank page instead.
169
+ async function printSignaturePage(): Promise<Uint8Array> {
170
+ const pdf = await PDFDocument.create();
171
+ pdf.addPage();
172
+ return pdf.save();
173
+ }
174
+
175
+ export const SIGNATURE_LINK_SECRET = "signature-recipe-link-secret-0123456789";
176
+
177
+ export const signatureFeature = createSignatureFeature({
178
+ retention: { keepFor: "10y" },
179
+ linkSecret: SIGNATURE_LINK_SECRET,
180
+ renderHtmlToPdf: printSignaturePage,
181
+ signaturePageUrl: "https://app.example/sign",
182
+ deliverLink: async (_ctx, { signerId, url }) => {
183
+ deliveredLinks.set(signerId, url);
184
+ },
185
+ });
186
+ ```
@@ -651,6 +651,7 @@ describe("writeform-section sample — registration", () => {
651
651
  editSection === undefined ||
652
652
  editSection.kind === "extension" ||
653
653
  editSection.kind === "relatedList" ||
654
+ editSection.kind === "stepList" ||
654
655
  detailSection?.kind !== "writeForm"
655
656
  ) {
656
657
  throw new Error("expected an entityEdit fields section and a writeForm section");
@@ -42,6 +42,7 @@
42
42
  | `field-access` | Field-level access control. When entity-level roles aren't granular enough. | `examples/field-access.md` |
43
43
  | `files-post-processing` | The three ways to generate an image variant: declarative field variants, imperative ctx.services.derivatives.variant() with region-blur, and the public route behind a default-deny predicate. | `examples/files-post-processing.md` |
44
44
  | `golden-path` | The smallest complete feature: entity, write handler, event, projection, screen and an integration test. | `examples/golden-path.md` |
45
+ | `handbook-knowledge` | The handbook-knowledge bundled feature: a fixed handbook JSON served to the AI assistant as list-pages and read-page query tools. | `examples/handbook-knowledge.md` |
45
46
  | `helpdesk` | Public contact form backend: the helpdesk bundled feature with its required companions (delivery, user-data-rights, files) and the anonymous browser client. | `examples/helpdesk.md` |
46
47
  | `host-routing` | createHostRoutingFeature + createHostDispatch — tenant per subdomain, per-host HTML and CSP, locale redirect, shared by runProdApp and the dev server. | `examples/host-routing.md` |
47
48
  | `i18n` | Feature-scoped translations. 'Hallo' and 'Hello' in the same app. | `examples/i18n.md` |
@@ -74,6 +75,7 @@
74
75
  | `security-baseline` | composeSecurityStack(): sessions, crypto-shredding, rate-limiting, audit — plus the NODE_ENV=production boot warning when one is missing. | `examples/security-baseline.md` |
75
76
  | `seed-migration` | ES-Operations seed-migrations — file-based diff-and-apply für Aggregate-Updates die idempotent-Seeder nicht erfassen. | `examples/seed-migration.md` |
76
77
  | `session-revocation` | createSessionCallbacks + sessionChecker — server-side session revocation via JWT jti. | `examples/session-revocation.md` |
78
+ | `signature` | The signature bundled feature: a request for several signers, a signing link that is delivered by the app, and a completed PDF with a signature page. | `examples/signature.md` |
77
79
  | `state-machine` | Enforced entity state transitions. No more illegal state changes. | `examples/state-machine.md` |
78
80
  | `tags-basic` | Tag and group any entity without changing it — host-agnostic, event-sourced. | `examples/tags-basic.md` |
79
81
  | `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` |
@@ -90,6 +90,8 @@ One entry per feature a package ships: purpose, import of its factory, required
90
90
  `import { createFormDraftFeature } from "@cosmicdrift/kumiko-bundled-features/form-draft"`
91
91
  - `form-draft-user-data`: GDPR (Art.
92
92
  `import { createFormDraftUserDataFeature } from "@cosmicdrift/kumiko-bundled-features/form-draft-user-data"`; requires `user-data-rights`
93
+ - `handbook-knowledge`: Gives the AI agent the app's handbook as two read-only query tools: `list-pages` returns the catalog of task and screen pages with the questions each answers, `read-page` returns one page in the caller's language with a fallback to the default language and a fixed length cap.
94
+ `import { createHandbookKnowledgeFeature } from "@cosmicdrift/kumiko-bundled-features/handbook-knowledge"`
93
95
  - `helpdesk`: Helpdesk inbox: an anonymous browser client (GET /helpdesk/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.
94
96
  `import { createHelpdeskFeature } from "@cosmicdrift/kumiko-bundled-features/helpdesk"`; requires `config`, `delivery`, `user-data-rights`, `files`, `notes-history`
95
97
  - `host-routing`: Host- and path-based tenant routing: an authoritative tenant resolver from the subdomain (tenantBy host), a tenant existence check against enabled, active tenants, and the tenant-key query behind createHostDispatch, which picks the HTML file, CSP, locale redirect or 404 per host for runProdApp's hostDispatch.
@@ -144,6 +146,8 @@ One entry per feature a package ships: purpose, import of its factory, required
144
146
  `import { createSeoFeature } from "@cosmicdrift/kumiko-bundled-features/seo"`; requires `config`
145
147
  - `sessions`: Tracks signed-in clients in the `store_user_sessions` table (one row per JWT, keyed by the `sid`/`jti` claim) and exposes handlers for `mine` (list your sessions), `revoke`, and `revokeAllOthers`.
146
148
  `import { createSessionsFeature } from "@cosmicdrift/kumiko-bundled-features/sessions"`; requires `user`, `auth-foundation`
149
+ - `signature`: Signature requests: a signed-in user asks several people to sign one PDF of the tenant.
150
+ `import { createSignatureFeature } from "@cosmicdrift/kumiko-bundled-features/signature"`; requires `files`, `user-data-rights`
147
151
  - `step-dispatcher`: Internal system feature that drains deferred Tier-2 side-effects (currently `webhook.send` and `mail.send`) after their originating transaction commits.
148
152
  `import { createStepDispatcherFeature } from "@cosmicdrift/kumiko-bundled-features/step-dispatcher"`; requires `secrets`
149
153
  - `subscription-mollie`: Mollie payment provider plugin for `billing-foundation`, covering the DACH/EU mid-market use case.
@@ -397,6 +397,12 @@ Requires: `user-data-rights`
397
397
 
398
398
  Optional requires: `form-draft`
399
399
 
400
+ ## handbook-knowledge
401
+
402
+ Gives the AI agent the app's handbook as two read-only query tools: `list-pages` returns the catalog of task and screen pages with the questions each answers, `read-page` returns one page in the caller's language with a fallback to the default language and a fixed length cap. The pages come from a build-time JSON (`kumiko handbuch knowledge`), so no table, projection or search index is involved and the handbook text stays public content.
403
+
404
+ Category: ai
405
+
400
406
  ## helpdesk
401
407
 
402
408
  Helpdesk inbox: an anonymous browser client (GET /helpdesk/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.
@@ -660,6 +666,14 @@ Requires: `user`, `auth-foundation`
660
666
 
661
667
  Exposes APIs: `sessions.revokeAllForUser`
662
668
 
669
+ ## signature
670
+
671
+ Signature requests: a signed-in user asks several people to sign one PDF of the tenant. Each signer draws a signature on a display in person or through a link in the URL fragment (14 days, limited opens, revocable, single-use, one answer for every rejection). The last signature moves the request to all-signed; a job renders a signature page through the injected print function, appends it to the unchanged original and completes the request. Events completed, declined and expired report the outcome; signer name, email, image, IP and user agent are personal data.
672
+
673
+ Category: data
674
+
675
+ Requires: `files`, `user-data-rights`
676
+
663
677
  ## step-dispatcher
664
678
 
665
679
  Internal system feature that drains deferred Tier-2 side-effects (currently `webhook.send` and `mail.send`) after their originating transaction commits. An `r.multiStreamProjection` on the `kumiko:system:step.dispatch-requested` system event enqueues one `step-dispatcher:job:deliver` BullMQ job per dispatch (Redis carries only the stream id and tenant, never the request payload). The job performs the actual HTTP or mail delivery and appends `kumiko:system:step.dispatched` or `kumiko:system:step.dispatch-failed` back onto the same stream, so the outcome is recorded in the event log without a separate status table. Transient failures (network error, timeout, 5xx, 408, 429, any mail adapter failure) are retried 3 times with exponential backoff; the outcome is recorded after the final attempt and the payload key is erased only then. A request that still has no outcome after 24 hours (job stalled or lost, or its final attempt could not record one) is closed by the daily `step-dispatcher:job:sweep-abandoned` cron (it pages through all such requests; requests that already have an outcome are not swept) with a generic `dispatch-failed` event and its payload key is erased. Permanent failures (invalid url, blocked host, other 4xx, unavailable auth secret) are recorded immediately. At most 2 deliveries per tenant run at once (`maxPerTenant` with `onLimit: "defer"`), so a slow receiver of one tenant does not delay other tenants. Requires a job runner (Redis) and a worker consuming the job's default `worker` lane; without a job runner the projection fails loudly. Mount this feature explicitly via `createStepDispatcherFeature()` in your app's feature list alongside any features that use `r.step.webhook.send` or `r.step.mail.send`. Requires the `secrets` feature (`createSecretsFeature()`) to be mounted — `webhook.send` auth resolves per-tenant through it, under `step-dispatcher:webhook-auth.<name>`. Every `webhook.send` request carries `Idempotency-Key: <dispatch stream id>`, stable across retries and redeliveries of the same dispatch request; an explicit `Idempotency-Key` in `headers` takes precedence.
package/agents/widgets.md CHANGED
@@ -29,6 +29,12 @@ Value exports of `@cosmicdrift/kumiko-renderer/web`.
29
29
  | `DetailList` | Read-only key-value list for detail views (dimmed label on the left, value on the right). |
30
30
  | `DispatcherProvider` | |
31
31
  | `Drawer` | Slide-in panel beside a list (e.g. mail reader next to the inbox) — thin wrapper over the Sheet primitive with header/body/footer slots so screens skip per-route Radix boilerplate. |
32
+ | `DrawnFilter` | |
33
+ | `DrawnPanel` | |
34
+ | `DrawnPencil` | |
35
+ | `DrawnSearch` | |
36
+ | `DrawnSparkles` | |
37
+ | `DrawnWand` | |
32
38
  | `DropdownMenu` | |
33
39
  | `DropdownMenuCheckboxItem` | |
34
40
  | `DropdownMenuContent` | |
@@ -177,6 +183,7 @@ Value exports of `@cosmicdrift/kumiko-renderer/web`.
177
183
  | `buildFileUploadFormData` | |
178
184
  | `buildNavRegistrySlice` | |
179
185
  | `buildNavRegistrySliceForApp` | |
186
+ | `clearNavCollapseState` | Forgets the collapsed containers and the revealed screen; logout calls it so the next user starts expanded. |
180
187
  | `clearRememberedListState` | Forgets all remembered list state and the identity marker. |
181
188
  | `cn` | Standard shadcn helper: `clsx` combines conditional classes, while `tailwind-merge` resolves conflicts (for example, `px-2 px-4` → `px-4`). |
182
189
  | `createBrowserDraftStorage` | Default DraftStorage when createKumikoApp boots without one. |
@@ -1,4 +1,5 @@
1
1
  import { AsyncLocalStorage } from "node:async_hooks";
2
+ import type { IrreversibleWithoutEntryHandler } from "@cosmicdrift/kumiko-types/config";
2
3
  import type { WriteOrigin } from "@cosmicdrift/kumiko-types/event-store-types";
3
4
  import type { AgentRisk } from "@cosmicdrift/kumiko-types/handlers";
4
5
  import type { ErrorDocsConfig } from "../errors/docs-url.ts";
@@ -23,6 +24,7 @@ export type RequestContextData = {
23
24
  };
24
25
  readonly chargedRateLimitBuckets?: Set<string>;
25
26
  readonly agentToolCall?: true;
27
+ readonly irreversibleWithoutEntryHandler?: IrreversibleWithoutEntryHandler;
26
28
  };
27
29
  export declare const storage: AsyncLocalStorage<RequestContextData>;
28
30
  export declare function setRequestIdentity(identity: {
@@ -50,11 +50,18 @@ export function runWithOrigin(origin, fn) {
50
50
  export function isAgentToolCallScope() {
51
51
  return requestContext.get()?.agentToolCall === true;
52
52
  }
53
+ function withoutIrreversibleExemption(data) {
54
+ const { irreversibleWithoutEntryHandler: _irreversibleWithoutEntryHandler, ...rest } = data;
55
+ return rest;
56
+ }
53
57
  // An ungated origin never mints a scope: seeds and boot writes keep their missing context.
58
+ // Hooks and nested dispatches run through here too, so a job's or consumer's irreversible-operation
59
+ // exception ends at this boundary and is never inherited by them.
54
60
  export function runWithWriteOrigin(origin, fn) {
55
- const current = requestContext.get();
61
+ const scope = requestContext.get();
62
+ const current = scope && withoutIrreversibleExemption(scope);
56
63
  if (!isPersonalDataGated(origin)) {
57
- if (!current?.writeOrigin)
64
+ if (!current || (!scope?.writeOrigin && !scope?.irreversibleWithoutEntryHandler))
58
65
  return fn();
59
66
  const { writeOrigin: _writeOrigin, ...rest } = current;
60
67
  return requestContext.run(rest, fn);
@@ -46,7 +46,7 @@ export const requestContext = {
46
46
  export function runAsAgentToolCallEntry(fn) {
47
47
  const current = requestContext.get();
48
48
  const requestId = current?.requestId ?? requestContext.generateId();
49
- const { entryHandler: _entryHandler, ...rest } = current ?? {};
49
+ const { entryHandler: _entryHandler, irreversibleWithoutEntryHandler: _irreversibleWithoutEntryHandler, ...rest } = current ?? {};
50
50
  return requestContext.run({
51
51
  ...rest,
52
52
  requestId,
@@ -28,13 +28,13 @@ const CLIENT_CLOSED_REQUEST_STATUS = 499;
28
28
  export function createApiRoutes(dispatcher, options = {}) {
29
29
  const heartbeatMs = options.sseHeartbeatMs ?? SSE_HEARTBEAT_INTERVAL_MS;
30
30
  const api = new Hono();
31
- // Before any body is read, so even an answer to a broken body carries the app clock. Whole
32
- // milliseconds in ISO form: Temporal's toString() can run to nanoseconds, which Date.parse on
33
- // Hermes/JSC does not define.
31
+ // Stamped after the handler ran, so the client's skew estimate is not behind by the handler's
32
+ // runtime. Whole milliseconds in ISO form: Temporal's toString() can run to nanoseconds, which
33
+ // Date.parse on Hermes/JSC does not define.
34
34
  api.use("*", async (c, next) => {
35
+ await next();
35
36
  const nowMs = options.clock?.now().epochMilliseconds ?? Date.now();
36
37
  c.header(APP_NOW_HEADER_NAME, new Date(nowMs).toISOString());
37
- await next();
38
38
  });
39
39
  api.post(Routes.write, async (c) => {
40
40
  const user = getUser(c);
@@ -153,6 +153,9 @@ function buildMultiStreamProjectionConsumer(msp, deps) {
153
153
  // Carry the MSP's declared cursor-seed through to the consumer. Default
154
154
  // (beginning) is applied inside insertConsumerIfAbsent.
155
155
  ...(msp.startFrom && { startFrom: msp.startFrom }),
156
+ ...(msp.irreversibleWithoutEntryHandler && {
157
+ irreversibleWithoutEntryHandler: msp.irreversibleWithoutEntryHandler,
158
+ }),
156
159
  handler: async (event, ctx) => {
157
160
  const applyFn = msp.apply[event.type];
158
161
  // skip: this MSP doesn't care about this event type — fast path,
@@ -1,6 +1,7 @@
1
1
  import { createProjectingTenantDb } from "../db/tenant-db.js";
2
2
  import { isAnonymousSessionUser } from "../engine/system-user.js";
3
3
  import { createFileRoutes, readFilesRouteOptions } from "../files/file-routes.js";
4
+ import { createForeignTenantFileReadCheck } from "../files/foreign-tenant-file-read.js";
4
5
  import { createRecordReadCheck } from "../files/record-read-check.js";
5
6
  import { createRecordWriteCheck } from "../files/record-write-check.js";
6
7
  import { createRateLimitResolver } from "../rate-limit/index.js";
@@ -93,6 +94,7 @@ export function mountFileRoutes(app, wiring) {
93
94
  ...(fileRateLimitResolver ? { rateLimitResolver: fileRateLimitResolver } : {}),
94
95
  clientIpResolver: wiring.clientIpResolver,
95
96
  canReadRecord,
97
+ canReadForeignTenantFile: createForeignTenantFileReadCheck(options.registry, dispatcher.query),
96
98
  canWriteRecord: createRecordWriteCheck({
97
99
  registry: options.registry,
98
100
  canReadRecord,
@@ -1,7 +1,7 @@
1
1
  import { buildOwnershipClause } from "../engine/ownership.js";
2
2
  import { SYSTEM_TENANT_ID, UUID_SHAPE_PATTERN } from "../engine/types/identifiers.js";
3
3
  import { buildEntityTable, physicalColumnName } from "./table-builder.js";
4
- import { schemaTableName } from "./table-introspection.js";
4
+ import { asEntityTableMeta, schemaTableName } from "./table-introspection.js";
5
5
  import { isGlobalTenancyTable } from "./tenant-db-runner.js";
6
6
  const candidateStaticsCache = new WeakMap();
7
7
  function candidateStaticsFor(candidateName, candidate, resolveTable) {
@@ -103,9 +103,11 @@ function collectGateBranches(candidates, mode, gate) {
103
103
  let shared;
104
104
  const branches = [];
105
105
  for (const [candidateName, candidate] of candidates) {
106
- const isHiddenGlobalHost = gate.globalHostsHidden && candidate.tenancy === "global";
107
- if (mode === "globalHostsOnly" && !isHiddenGlobalHost)
106
+ const isHiddenGlobalHost = isHiddenGlobalHostCandidate(candidateName, candidate, gate);
107
+ if (mode === "globalHostsOnly" &&
108
+ isExcludedFromHostOnlyCheck(candidate, isHiddenGlobalHost, gate)) {
108
109
  continue;
110
+ }
109
111
  const resolvesHostIds = mode === "statement" && isHiddenGlobalHost;
110
112
  const pendingShared = resolvesHostIds || shared !== undefined
111
113
  ? undefined
@@ -139,6 +141,32 @@ function collectGateBranches(candidates, mode, gate) {
139
141
  }
140
142
  return { branches, params };
141
143
  }
144
+ function isHiddenGlobalHostCandidate(candidateName, candidate, gate) {
145
+ return (gate.globalHostsHidden &&
146
+ candidate.tenancy === "global" &&
147
+ !tableReadsSystemRows(candidateStaticsFor(candidateName, candidate, gate.option.resolveTable)));
148
+ }
149
+ function isExcludedFromHostOnlyCheck(candidate, isHiddenGlobalHost, gate) {
150
+ return !isHiddenGlobalHost || hostReadRuleNeedsRowLevelSecurity(candidate, gate.user);
151
+ }
152
+ // The registry table carries the flag for implicitly classified reference data too, which the
153
+ // entity definition alone does not say; such a host is visible to the tenant-scoped EXISTS arm.
154
+ function tableReadsSystemRows(statics) {
155
+ return asEntityTableMeta(statics.table)?.systemRowsReadable === true;
156
+ }
157
+ // The system-scope host check has no row level security as a second layer, so a where-rule
158
+ // subquery over a tenant table would see other tenants' rows; such a host opens no arm (fail closed).
159
+ function hostReadRuleNeedsRowLevelSecurity(candidate, user) {
160
+ const readRules = candidate.access?.read;
161
+ if (readRules === undefined)
162
+ return false;
163
+ const applicable = user.roles.flatMap((role) => {
164
+ const rule = readRules[role];
165
+ return rule === undefined ? [] : [rule];
166
+ });
167
+ return (!applicable.includes("all") &&
168
+ applicable.some((rule) => rule !== "all" && rule.kind === "where"));
169
+ }
142
170
  function planSharedBinding(db, boundSoFar) {
143
171
  if (db.mode !== "tenant") {
144
172
  return { values: [UUID_SHAPE_PATTERN], uuidIdx: boundSoFar + 1, tenantIdx: undefined };
@@ -4,6 +4,7 @@ import type { EntityId } from "@cosmicdrift/kumiko-types/identifiers";
4
4
  import type { SessionUser } from "../engine/types/index.ts";
5
5
  import type { Table } from "./event-store-executor-context.ts";
6
6
  import type { TenantDb } from "./tenant-db.ts";
7
+ export declare const MAX_RESOLVED_GLOBAL_HOST_IDS = 5000;
7
8
  export type GlobalHostRowScope = {
8
9
  readonly kind: "row";
9
10
  readonly rowId: EntityId;
@@ -17,4 +18,6 @@ export declare function withGlobalParentHosts(ctx: {
17
18
  }, user: SessionUser, db: TenantDb, option: ParentVisibilityOption | undefined, gate: {
18
19
  readonly includeDeleted: boolean;
19
20
  readonly narrowTypes: ReadonlySet<string> | undefined;
20
- }, rowScope: GlobalHostRowScope): Promise<ParentVisibilityOption | undefined>;
21
+ }, rowScope: GlobalHostRowScope, options?: {
22
+ readonly maxResolvedHostIds?: number;
23
+ }): Promise<ParentVisibilityOption | undefined>;
@@ -1,13 +1,16 @@
1
+ import { createFallbackLogger } from "../logging/utils.js";
1
2
  import { buildParentRefGate, readsGlobalHostsUnderTenantScope } from "./parent-ref-clause.js";
2
3
  import { executeRawQueryRead } from "./queries/raw-sql.js";
3
4
  import { systemScopedRunner } from "./row-level-security-scope.js";
4
5
  import { physicalColumnName } from "./table-builder.js";
5
6
  import { schemaTableName } from "./table-introspection.js";
6
7
  import { tenantDbRunner } from "./tenant-db-runner.js";
8
+ const log = createFallbackLogger("parent-ref-global-hosts");
9
+ export const MAX_RESOLVED_GLOBAL_HOST_IDS = 5000;
7
10
  // The gated statement runs under the tenant scope, where a global host's EXISTS sees no row. The
8
11
  // same host check runs here in the system scope, limited to the caller's join rows by an explicit
9
12
  // tenant filter, and only host ids leave it; the gated statement keeps its own row level security.
10
- export async function withGlobalParentHosts(ctx, user, db, option, gate, rowScope) {
13
+ export async function withGlobalParentHosts(ctx, user, db, option, gate, rowScope, options) {
11
14
  const { entity, table } = ctx;
12
15
  const parentRef = entity.parentRef;
13
16
  if (option === undefined || parentRef === undefined || db.mode !== "tenant")
@@ -22,7 +25,44 @@ export async function withGlobalParentHosts(ctx, user, db, option, gate, rowScop
22
25
  if (rowScope.kind === "list" && rowScope.pinnedHostIds?.size === 0) {
23
26
  return { ...option, globalHostIds: new Map() };
24
27
  }
25
- const params = [...hostCheck.params, db.tenantId];
28
+ const isUnpinnedList = rowScope.kind === "list" && rowScope.pinnedHostIds === undefined;
29
+ // Correlating the gated statement with the host check would need a SECURITY DEFINER function,
30
+ // so an unpinned list resolves ids up front and this cap is the deliberate bound on that set.
31
+ const maxHostIds = options?.maxResolvedHostIds ?? MAX_RESOLVED_GLOBAL_HOST_IDS;
32
+ const query = buildHostQuery({
33
+ parentRef,
34
+ table,
35
+ joinTableName,
36
+ hostCheck,
37
+ tenantId: db.tenantId,
38
+ rowScope,
39
+ includeDeleted: gate.includeDeleted,
40
+ rowLimit: isUnpinnedList ? maxHostIds + 1 : undefined,
41
+ });
42
+ const rows = await executeRawQueryRead(systemScopedRunner(tenantDbRunner(db), "parent-ref gate checks global hosts, whose rows carry the system tenant, for the caller's own join rows"), query.sqlText, query.params);
43
+ if (isUnpinnedList && rows.length > maxHostIds) {
44
+ log.warn("global host ids of an unpinned list exceed the cap; the global host arm is left out", {
45
+ table: joinTableName,
46
+ limit: maxHostIds,
47
+ });
48
+ return { ...option, globalHostIds: new Map() };
49
+ }
50
+ return { ...option, globalHostIds: groupHostIdsByType(rows) };
51
+ }
52
+ function groupHostIdsByType(rows) {
53
+ const globalHostIds = new Map();
54
+ for (const row of rows) {
55
+ const ids = globalHostIds.get(row.entityType);
56
+ if (ids === undefined)
57
+ globalHostIds.set(row.entityType, [row.entityId]);
58
+ else
59
+ ids.push(row.entityId);
60
+ }
61
+ return globalHostIds;
62
+ }
63
+ function buildHostQuery(input) {
64
+ const { parentRef, table, joinTableName, hostCheck, rowScope } = input;
65
+ const params = [...hostCheck.params, input.tenantId];
26
66
  const column = (field) => `"${joinTableName}"."${physicalColumnName(table, field)}"`;
27
67
  const whereParts = [`${column("tenantId")} = $${params.length}`, hostCheck.sqlText];
28
68
  if (rowScope.kind === "row") {
@@ -33,15 +73,13 @@ export async function withGlobalParentHosts(ctx, user, db, option, gate, rowScop
33
73
  params.push([...rowScope.pinnedHostIds]);
34
74
  whereParts.push(`${column(parentRef.entityIdField)}::text = ANY($${params.length}::text[])`);
35
75
  }
36
- const rows = await executeRawQueryRead(systemScopedRunner(tenantDbRunner(db), "parent-ref gate checks global hosts, whose rows carry the system tenant, for the caller's own join rows"), `SELECT DISTINCT ${column(parentRef.entityTypeField)}::text AS "entityType", ${column(parentRef.entityIdField)}::text AS "entityId" ` +
37
- `FROM "${joinTableName}" WHERE ${whereParts.join(" AND ")}`, params);
38
- const globalHostIds = new Map();
39
- for (const row of rows) {
40
- const ids = globalHostIds.get(row.entityType);
41
- if (ids === undefined)
42
- globalHostIds.set(row.entityType, [row.entityId]);
43
- else
44
- ids.push(row.entityId);
76
+ if (input.rowLimit !== undefined && !input.includeDeleted && table["isDeleted"] !== undefined) {
77
+ whereParts.push(`${column("isDeleted")} = FALSE`);
45
78
  }
46
- return { ...option, globalHostIds };
79
+ const limitClause = input.rowLimit === undefined ? "" : ` LIMIT ${input.rowLimit}`;
80
+ return {
81
+ sqlText: `SELECT DISTINCT ${column(parentRef.entityTypeField)}::text AS "entityType", ${column(parentRef.entityIdField)}::text AS "entityId" ` +
82
+ `FROM "${joinTableName}" WHERE ${whereParts.join(" AND ")}${limitClause}`,
83
+ params,
84
+ };
47
85
  }
@@ -1,6 +1,6 @@
1
1
  import { asRawClient } from "../query.js";
2
2
  import { SYSTEM_TENANT_READ_POLICY, TENANT_ISOLATION_POLICY } from "../render-rls-ddl.js";
3
- import { isFrameworkIsolationIntact, readRowLevelSecurityShape } from "./rls-shape.js";
3
+ import { isFrameworkIsolationIntact, readRowLevelSecurityShapes } from "./rls-shape.js";
4
4
  export async function readConnectedRoleAttributes(db) {
5
5
  const rows = await asRawClient(db).unsafe(`SELECT rolname, rolsuper, rolbypassrls FROM pg_roles WHERE rolname = current_user`);
6
6
  const row = rows[0];
@@ -24,10 +24,9 @@ export async function readTenantTablesRowLevelSecurity(db) {
24
24
  AND EXISTS (SELECT 1 FROM pg_attribute a
25
25
  WHERE a.attrelid = c.oid AND a.attname = 'tenant_id' AND a.attnum > 0 AND NOT a.attisdropped)
26
26
  ORDER BY c.relname COLLATE "C"`, [TENANT_ISOLATION_POLICY, SYSTEM_TENANT_READ_POLICY]);
27
- return Promise.all(rows.map(async (row) => {
28
- const shape = row.has_isolation
29
- ? await readRowLevelSecurityShape(db, row.relname)
30
- : undefined;
27
+ const shapes = await readRowLevelSecurityShapes(db, rows.filter((row) => row.has_isolation).map((row) => row.relname));
28
+ return rows.map((row) => {
29
+ const shape = shapes.get(row.relname);
31
30
  return {
32
31
  tableName: row.relname,
33
32
  enabled: row.relrowsecurity,
@@ -36,7 +35,7 @@ export async function readTenantTablesRowLevelSecurity(db) {
36
35
  isolationAltered: shape !== undefined && !isFrameworkIsolationIntact(shape),
37
36
  hasSystemReadPolicy: row.has_system_read,
38
37
  };
39
- }));
38
+ });
40
39
  }
41
40
  export async function readTablesWithRowLevelSecurityEnabled(db) {
42
41
  const rows = await asRawClient(db).unsafe(`SELECT c.relname FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
@@ -7,5 +7,6 @@ export type RowLevelSecurityShape = {
7
7
  readonly appliesToPublic: boolean;
8
8
  })[];
9
9
  };
10
+ export declare function readRowLevelSecurityShapes(db: AnyDb, tableNames: readonly string[]): Promise<ReadonlyMap<string, RowLevelSecurityShape>>;
10
11
  export declare function readRowLevelSecurityShape(db: AnyDb, tableName: string): Promise<RowLevelSecurityShape | undefined>;
11
12
  export declare function isFrameworkIsolationIntact(shape: RowLevelSecurityShape): boolean;
@@ -17,12 +17,7 @@ function commandOf(code) {
17
17
  throw new Error(`unknown pg_policy.polcmd code "${code}"`);
18
18
  return command;
19
19
  }
20
- export async function readRowLevelSecurityShape(db, tableName) {
21
- const rows = await asRawClient(db).unsafe(`SELECT c.relrowsecurity, c.relforcerowsecurity, p.polname, p.polpermissive, p.polcmd::text AS polcmd, (p.polroles = '{0}'::oid[]) AS polpublic
22
- FROM pg_class c
23
- JOIN pg_namespace n ON n.oid = c.relnamespace
24
- LEFT JOIN pg_policy p ON p.polrelid = c.oid
25
- WHERE n.nspname = 'public' AND c.relname = $1`, [tableName]);
20
+ function shapeOfRows(rows) {
26
21
  const first = rows[0];
27
22
  if (first === undefined)
28
23
  return undefined;
@@ -41,6 +36,26 @@ export async function readRowLevelSecurityShape(db, tableName) {
41
36
  });
42
37
  return { enabled: first.relrowsecurity, forced: first.relforcerowsecurity, policies };
43
38
  }
39
+ export async function readRowLevelSecurityShapes(db, tableNames) {
40
+ const shapes = new Map();
41
+ if (tableNames.length === 0)
42
+ return shapes;
43
+ const rows = await asRawClient(db).unsafe(`SELECT c.relname, c.relrowsecurity, c.relforcerowsecurity, p.polname, p.polpermissive, p.polcmd::text AS polcmd, (p.polroles = '{0}'::oid[]) AS polpublic
44
+ FROM pg_class c
45
+ JOIN pg_namespace n ON n.oid = c.relnamespace
46
+ LEFT JOIN pg_policy p ON p.polrelid = c.oid
47
+ WHERE n.nspname = 'public' AND c.relname = ANY($1::text[])`, [tableNames]);
48
+ const rowsByTable = Map.groupBy(rows, (row) => row.relname);
49
+ for (const [tableName, tableRows] of rowsByTable) {
50
+ const shape = shapeOfRows(tableRows);
51
+ if (shape !== undefined)
52
+ shapes.set(tableName, shape);
53
+ }
54
+ return shapes;
55
+ }
56
+ export async function readRowLevelSecurityShape(db, tableName) {
57
+ return (await readRowLevelSecurityShapes(db, [tableName])).get(tableName);
58
+ }
44
59
  // Shared by the rebuild guard and the boot check, so both judge a hand-edited policy alike.
45
60
  export function isFrameworkIsolationIntact(shape) {
46
61
  const isolation = shape.policies.find((policy) => policy.name === TENANT_ISOLATION_POLICY);
@@ -103,7 +103,9 @@ const COLUMN_EMITTERS = {
103
103
  embedded: (name, snakeName, field) => ({
104
104
  [name]: field.multiple === true ? emptyJsonbArray(snakeName) : emptyJsonbObject(snakeName),
105
105
  }),
106
- jsonb: (name, snakeName) => ({ [name]: emptyJsonbObject(snakeName) }),
106
+ jsonb: (name, snakeName, field) => ({
107
+ [name]: field.emptyValue === "array" ? emptyJsonbArray(snakeName) : emptyJsonbObject(snakeName),
108
+ }),
107
109
  date: singleColumnNotNullWhenRequired(plainDate),
108
110
  timestamp: singleColumnNotNullWhenRequired(instant),
109
111
  tz: singleColumnNotNullWhenRequired(text),