@cosmicdrift/kumiko-framework 0.418.0 → 0.420.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 (36) hide show
  1. package/agents/api/framework-engine.md +4 -0
  2. package/agents/api/framework-ui-types.md +18 -1
  3. package/agents/api/renderer-web.md +6 -0
  4. package/agents/api/types.md +10 -1
  5. package/agents/api.md +2 -2
  6. package/agents/boot-rules.md +10 -0
  7. package/agents/examples/pdf-letterhead.md +473 -0
  8. package/agents/examples.md +1 -0
  9. package/agents/features.md +11 -0
  10. package/agents/widgets.md +1 -0
  11. package/dist/crypto/subject-resolver.d.ts +1 -0
  12. package/dist/crypto/subject-resolver.js +8 -2
  13. package/dist/db/queries/backfill-pii.js +29 -3
  14. package/dist/engine/boot-validator/action-form-preview-rules.d.ts +5 -0
  15. package/dist/engine/boot-validator/action-form-preview-rules.js +5 -0
  16. package/dist/engine/boot-validator/action-form-preview.js +13 -0
  17. package/dist/engine/boot-validator/boot-phases-app.js +2 -0
  18. package/dist/engine/boot-validator/boot-rules.d.ts +26 -0
  19. package/dist/engine/boot-validator/boot-rules.js +2 -0
  20. package/dist/engine/boot-validator/page-help-rules.d.ts +17 -0
  21. package/dist/engine/boot-validator/page-help-rules.js +17 -0
  22. package/dist/engine/boot-validator/page-help.d.ts +2 -0
  23. package/dist/engine/boot-validator/page-help.js +109 -0
  24. package/dist/engine/boot-validator/screens-actions.d.ts +5 -0
  25. package/dist/engine/boot-validator/screens-actions.js +15 -6
  26. package/dist/engine/boot-validator/screens-forms-rules.d.ts +5 -0
  27. package/dist/engine/boot-validator/screens-forms-rules.js +5 -0
  28. package/dist/engine/boot-validator/screens-forms.js +13 -1
  29. package/dist/engine/boot-validator/url-prefill-fields.js +5 -11
  30. package/dist/engine/registry-ingest.js +11 -0
  31. package/dist/i18n/required-surface-keys.d.ts +2 -0
  32. package/dist/i18n/required-surface-keys.js +11 -1
  33. package/dist/migrations/pii-event-backfill.js +4 -1
  34. package/dist/ui-types/index.d.ts +1 -1
  35. package/package.json +3 -3
  36. package/src/changes.json +18 -0
@@ -0,0 +1,473 @@
1
+ <!-- Generated by `bun run gen:agent-docs` from samples/recipes/pdf-letterhead. Do not edit. -->
2
+
3
+ # pdf-letterhead
4
+
5
+ A PDF letterhead as a layout with its own appearance and company-data footer, a letter with an address frame, and the transfer of the layout to templates (apply-layout, publish-templates).
6
+
7
+ ## README
8
+
9
+ # PDF Letterhead
10
+
11
+ A PDF layout with its own look, a letter with an address frame, and the transfer of the layout to templates.
12
+
13
+ ## What it shows
14
+
15
+ - A system `pdf-layout` with a header, a footer in three columns (a borderless table) that prints the company placeholders `companyAddress`, `companyIban` and `companyBic`, and appearance in `meta`: font, size, table style and page margins in mm.
16
+ - A `document-pdf` letter with an address frame (`data-frame`, preset `address`) at the DIN 5008 form B window position, and a text style (`data-text-style`) on a run of text.
17
+ - Company placeholders read the tenant's own settings (`tenant:config:company-*`); the validate query lists the ones a tenant has left empty.
18
+ - `apply-layout` hands the layout to chosen templates as drafts (mode `selected`) or makes it the tenant default (mode `all`, no copies); `publish-templates` activates the drafts together; the usage query lists which templates use the layout.
19
+
20
+ ## Source
21
+
22
+ `src/letterhead.ts` holds the layout, the letter and the tenant-editable list; the app passes the list to `createTemplateResolverFeature({ tenantEditable })`.
23
+
24
+ ## Tests
25
+
26
+ Needs a running Postgres and `TEST_DATABASE_URL` set (e.g. `postgres://postgres:postgres@127.0.0.1:5432/postgres`, see `demo/.env.example`).
27
+
28
+ ```bash
29
+ cd samples/recipes/pdf-letterhead
30
+ bun test
31
+ ```
32
+
33
+ ## Source files
34
+
35
+ ### src/__tests__/letterhead.integration.test.ts
36
+
37
+ ```ts
38
+ // A letterhead from layout to letter, through the real write pipeline over HTTP: the system layout
39
+ // carries its own look and company-data footer, the tenant's letter keeps its address frame, and
40
+ // apply-layout / publish-templates hand the layout to the letter.
41
+
42
+ import { afterAll, beforeAll, describe, expect, test } from "bun:test";
43
+ import {
44
+ configValuesTable,
45
+ createConfigAccessorFactory,
46
+ createConfigFeature,
47
+ createConfigResolver,
48
+ } from "@cosmicdrift/kumiko-bundled-features/config";
49
+ import { createRendererFoundationFeature } from "@cosmicdrift/kumiko-bundled-features/renderer-foundation";
50
+ import {
51
+ createTemplateResolverFeature,
52
+ DEFAULT_PDF_LAYOUT_SLUG_CONFIG_KEY,
53
+ TemplateResolverHandlers,
54
+ TemplateResolverQueries,
55
+ templateResourceEntity,
56
+ } from "@cosmicdrift/kumiko-bundled-features/template-resolver";
57
+ import {
58
+ createTenantFeature,
59
+ tenantEntity,
60
+ tenantMembershipsTable,
61
+ } from "@cosmicdrift/kumiko-bundled-features/tenant";
62
+ import { createUserFeature, userEntity } from "@cosmicdrift/kumiko-bundled-features/user";
63
+ import {
64
+ createFilesFeature,
65
+ createInMemoryFileProvider,
66
+ } from "@cosmicdrift/kumiko-framework/files";
67
+ import { createTestUser, TestUsers, testTenantId } from "@cosmicdrift/kumiko-framework/seeding";
68
+ import {
69
+ createRendererPuppeteerClientFeature,
70
+ RendererPuppeteerClientQueries,
71
+ renderedPdfEntity,
72
+ } from "@cosmicdrift/kumiko-renderer-puppeteer-client";
73
+ import {
74
+ setupTestStack,
75
+ type TestStack,
76
+ unsafeCreateEntityTable,
77
+ unsafePushTables,
78
+ } from "@cosmicdrift/kumiko-testing/stack";
79
+ import {
80
+ LETTER_HTML,
81
+ LETTER_LOCALE,
82
+ LETTER_SLUG,
83
+ LETTERHEAD_LAYOUT_HTML,
84
+ LETTERHEAD_LAYOUT_META,
85
+ LETTERHEAD_LAYOUT_SLUG,
86
+ REBUILT_HEADER_BLOCKS,
87
+ REBUILT_LAYOUT_NAME,
88
+ REBUILT_LAYOUT_SLUG,
89
+ REBUILT_LETTER_BLOCKS,
90
+ REBUILT_LETTER_SLUG,
91
+ TENANT_EDITABLE,
92
+ } from "../letterhead";
93
+
94
+ const admin = createTestUser({ id: 1, roles: ["TenantAdmin"], tenantId: testTenantId(1) });
95
+ const LETTER_REF = { slug: LETTER_SLUG, kind: "document-pdf", locale: LETTER_LOCALE } as const;
96
+
97
+ let stack: TestStack;
98
+ let letterId: string;
99
+
100
+ beforeAll(async () => {
101
+ stack = await setupTestStack({
102
+ features: [
103
+ createFilesFeature(),
104
+ createConfigFeature(),
105
+ createUserFeature(),
106
+ createTenantFeature(),
107
+ createTemplateResolverFeature({ tenantEditable: [...TENANT_EDITABLE] }),
108
+ createRendererFoundationFeature(),
109
+ createRendererPuppeteerClientFeature(),
110
+ ],
111
+ files: { storageProvider: createInMemoryFileProvider() },
112
+ extraContext: ({ registry }) => {
113
+ const resolver = createConfigResolver();
114
+ return {
115
+ configResolver: resolver,
116
+ configAccessorFactory: createConfigAccessorFactory(registry, resolver),
117
+ };
118
+ },
119
+ });
120
+ await unsafeCreateEntityTable(stack.db, userEntity);
121
+ await unsafeCreateEntityTable(stack.db, tenantEntity);
122
+ await unsafeCreateEntityTable(stack.db, templateResourceEntity);
123
+ await unsafeCreateEntityTable(stack.db, renderedPdfEntity, "rendered-pdf");
124
+ await unsafePushTables(stack.db, { configValuesTable, tenantMembershipsTable });
125
+
126
+ await stack.http.writeOk(
127
+ TemplateResolverHandlers.upsertSystem,
128
+ {
129
+ slug: LETTERHEAD_LAYOUT_SLUG,
130
+ kind: "pdf-layout",
131
+ locale: LETTER_LOCALE,
132
+ content: LETTERHEAD_LAYOUT_HTML,
133
+ contentFormat: "html",
134
+ meta: LETTERHEAD_LAYOUT_META,
135
+ variableSchema: {},
136
+ linkedResources: {},
137
+ },
138
+ TestUsers.systemAdmin,
139
+ );
140
+ const stored = await stack.http.writeOk<{ id: string }>(
141
+ TemplateResolverHandlers.upsertTenant,
142
+ {
143
+ ...LETTER_REF,
144
+ content: LETTER_HTML,
145
+ contentFormat: "html",
146
+ status: "active",
147
+ variableSchema: { recipientName: { type: "text" } },
148
+ },
149
+ admin,
150
+ );
151
+ letterId = stored.id;
152
+ });
153
+
154
+ afterAll(async () => {
155
+ await stack.cleanup();
156
+ });
157
+
158
+ describe("pdf-letterhead", () => {
159
+ test("the letter keeps its address frame and text style as written", async () => {
160
+ const letter = await stack.http.queryOk<{ content: string }>(
161
+ TemplateResolverQueries.findById,
162
+ { id: letterId },
163
+ admin,
164
+ );
165
+ expect(letter.content).toContain('data-frame-preset="address"');
166
+ expect(letter.content).toContain('data-size-pt="14"');
167
+ });
168
+
169
+ test("the footer asks for company data the tenant has not entered", async () => {
170
+ await stack.http.writeOk(
171
+ "config:write:set",
172
+ { key: "tenant:config:company-iban", value: "DE89 3704 0044 0532 0130 00" },
173
+ admin,
174
+ );
175
+ const result = await stack.http.queryOk<{ emptyCompanyData: string[] }>(
176
+ TemplateResolverQueries.validate,
177
+ {
178
+ ...LETTER_REF,
179
+ content: LETTERHEAD_LAYOUT_HTML,
180
+ contentFormat: "html",
181
+ meta: {},
182
+ },
183
+ admin,
184
+ );
185
+ expect(result.emptyCompanyData).toContain("companyBic");
186
+ expect(result.emptyCompanyData).not.toContain("companyIban");
187
+ });
188
+
189
+ test("apply-layout hands the layout to the letter, publish-templates activates it", async () => {
190
+ const applied = await stack.http.writeOk<{ applied: { slug: string }[]; skipped: unknown[] }>(
191
+ TemplateResolverHandlers.applyLayout,
192
+ {
193
+ layoutSlug: LETTERHEAD_LAYOUT_SLUG,
194
+ target: { mode: "selected", templates: [{ slug: LETTER_SLUG, locale: LETTER_LOCALE }] },
195
+ },
196
+ admin,
197
+ );
198
+ expect(applied.applied.map((entry) => entry.slug)).toEqual([LETTER_SLUG]);
199
+ expect(applied.skipped).toEqual([]);
200
+
201
+ const published = await stack.http.writeOk<{
202
+ published: { slug: string }[];
203
+ failed: unknown[];
204
+ }>(TemplateResolverHandlers.publishTemplates, { templates: [LETTER_REF] }, admin);
205
+ expect(published.published.map((entry) => entry.slug)).toEqual([LETTER_SLUG]);
206
+
207
+ const usage = await stack.http.queryOk<{
208
+ usedByTemplates: { slug: string; hasOwnLayout: boolean }[];
209
+ }>(TemplateResolverQueries.usage, { slug: LETTERHEAD_LAYOUT_SLUG, kind: "pdf-layout" }, admin);
210
+ expect(usage.usedByTemplates).toMatchObject([{ slug: LETTER_SLUG, hasOwnLayout: true }]);
211
+ });
212
+
213
+ test("mode all makes the layout the tenant default without touching the letter", async () => {
214
+ await stack.http.writeOk(
215
+ TemplateResolverHandlers.applyLayout,
216
+ { layoutSlug: LETTERHEAD_LAYOUT_SLUG, target: { mode: "all" } },
217
+ admin,
218
+ );
219
+ const values = await stack.http.queryOk<Record<string, { value?: unknown }>>(
220
+ "config:query:values",
221
+ { keys: [DEFAULT_PDF_LAYOUT_SLUG_CONFIG_KEY] },
222
+ admin,
223
+ );
224
+ expect(values[DEFAULT_PDF_LAYOUT_SLUG_CONFIG_KEY]?.value).toBe(LETTERHEAD_LAYOUT_SLUG);
225
+ });
226
+
227
+ test("create-layout and patch-draft rebuild a letterhead and a letter from structured blocks", async () => {
228
+ type Blocks = {
229
+ base: { scope: string; version: number };
230
+ blocks: { type: string; text?: string; each?: string }[];
231
+ };
232
+ const layout = await stack.http.writeOk<{ base: Blocks["base"] }>(
233
+ TemplateResolverHandlers.createLayout,
234
+ { name: REBUILT_LAYOUT_NAME, title: "Briefkopf Musterfirma", locale: LETTER_LOCALE },
235
+ admin,
236
+ );
237
+ await stack.http.writeOk(
238
+ TemplateResolverHandlers.patchDraft,
239
+ {
240
+ slug: REBUILT_LAYOUT_SLUG,
241
+ kind: "pdf-layout",
242
+ region: "header",
243
+ locale: LETTER_LOCALE,
244
+ base: layout.base,
245
+ ops: [{ op: "replaceBody", blocks: REBUILT_HEADER_BLOCKS }],
246
+ },
247
+ admin,
248
+ );
249
+ const header = await stack.http.queryOk<Blocks>(
250
+ TemplateResolverQueries.documentBlocks,
251
+ { slug: REBUILT_LAYOUT_SLUG, kind: "pdf-layout", region: "header", locale: LETTER_LOCALE },
252
+ admin,
253
+ );
254
+ expect(header.blocks.map((block) => block.text)).toEqual([
255
+ "Musterfirma GmbH",
256
+ "Musterstraße 1, 12345 Musterstadt",
257
+ ]);
258
+
259
+ await stack.http.writeOk(
260
+ TemplateResolverHandlers.upsertTenant,
261
+ {
262
+ slug: REBUILT_LETTER_SLUG,
263
+ kind: "document-pdf",
264
+ locale: LETTER_LOCALE,
265
+ content: "<p>Platzhalter</p>",
266
+ contentFormat: "html",
267
+ variableSchema: {
268
+ invoiceNumber: { type: "text" },
269
+ positions: { type: "list", item: { label: { type: "text" }, amount: { type: "text" } } },
270
+ },
271
+ },
272
+ admin,
273
+ );
274
+ const letterRef = { slug: REBUILT_LETTER_SLUG, kind: "document-pdf", locale: LETTER_LOCALE };
275
+ const before = await stack.http.queryOk<Blocks>(
276
+ TemplateResolverQueries.documentBlocks,
277
+ letterRef,
278
+ admin,
279
+ );
280
+ await stack.http.writeOk(
281
+ TemplateResolverHandlers.patchDraft,
282
+ {
283
+ ...letterRef,
284
+ base: before.base,
285
+ ops: [
286
+ { op: "replaceBody", blocks: REBUILT_LETTER_BLOCKS },
287
+ { op: "setMeta", meta: { layoutSlug: REBUILT_LAYOUT_SLUG } },
288
+ ],
289
+ },
290
+ admin,
291
+ );
292
+ const after = await stack.http.queryOk<Blocks & { meta: Record<string, unknown> }>(
293
+ TemplateResolverQueries.documentBlocks,
294
+ letterRef,
295
+ admin,
296
+ );
297
+ expect(after.blocks.map((block) => block.type)).toEqual(["frame", "heading", "repeat"]);
298
+ expect(after.blocks[0]?.text).toBe("Max Mustermann\nBeispielweg 2");
299
+ expect(after.meta["layoutSlug"]).toBe(REBUILT_LAYOUT_SLUG);
300
+ });
301
+ });
302
+
303
+ describe("pdf-letterhead preview-png", () => {
304
+ const SERVICE_TOKEN = "recipe-service-token-0123456789abcdef";
305
+ const ONE_PIXEL_PNG =
306
+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==";
307
+ const PNG_MAGIC = [0x89, 0x50, 0x4e, 0x47];
308
+ const renderedHtml: string[] = [];
309
+ const envKeys = ["PUPPETEER_SERVICE_URL", "PUPPETEER_AUTH_TOKEN", "PUPPETEER_CLIENT_MAX_RETRIES"];
310
+ const savedEnv = new Map<string, string | undefined>();
311
+
312
+ // Stands in for puppeteer-service so the recipe runs without Chromium or poppler.
313
+ const service = Bun.serve({
314
+ port: 0,
315
+ async fetch(request) {
316
+ const { pathname } = new URL(request.url);
317
+ if (request.headers.get("Authorization") !== `Bearer ${SERVICE_TOKEN}`) {
318
+ return new Response("unauthorized", { status: 401 });
319
+ }
320
+ if (pathname === "/render") {
321
+ renderedHtml.push(JSON.stringify(await request.json()));
322
+ return new Response("%PDF-1.4\n1 0 obj<< /Type /Pages /Kids [] /Count 1 >>endobj\n%%EOF", {
323
+ headers: { "Content-Type": "application/pdf" },
324
+ });
325
+ }
326
+ if (pathname === "/rasterize") {
327
+ const page = { mimeType: "image/png", data: ONE_PIXEL_PNG, widthPx: 1, heightPx: 1 };
328
+ return Response.json({ pages: [page], images: [] });
329
+ }
330
+ return new Response("not found", { status: 404 });
331
+ },
332
+ });
333
+
334
+ beforeAll(() => {
335
+ for (const key of envKeys) savedEnv.set(key, process.env[key]);
336
+ process.env["PUPPETEER_SERVICE_URL"] = `http://127.0.0.1:${service.port}`;
337
+ process.env["PUPPETEER_AUTH_TOKEN"] = SERVICE_TOKEN;
338
+ process.env["PUPPETEER_CLIENT_MAX_RETRIES"] = "0";
339
+ });
340
+
341
+ afterAll(async () => {
342
+ for (const [key, value] of savedEnv) {
343
+ if (value === undefined) delete process.env[key];
344
+ else process.env[key] = value;
345
+ }
346
+ await service.stop(true);
347
+ });
348
+
349
+ test("the rebuilt letterhead is printed and comes back as a PNG page the agent can look at", async () => {
350
+ await stack.http.writeOk(
351
+ TemplateResolverHandlers.publishTemplates,
352
+ { templates: [{ slug: REBUILT_LAYOUT_SLUG, kind: "pdf-layout", locale: LETTER_LOCALE }] },
353
+ admin,
354
+ );
355
+ const preview = await stack.http.queryOk<{
356
+ pages: { widthPx: number; heightPx: number }[];
357
+ agentImages: { mimeType: string; data: string }[];
358
+ }>(
359
+ RendererPuppeteerClientQueries.previewPng,
360
+ {
361
+ slug: REBUILT_LETTER_SLUG,
362
+ locale: LETTER_LOCALE,
363
+ content: "<p>Sehr geehrte Damen und Herren</p>",
364
+ meta: { layoutSlug: REBUILT_LAYOUT_SLUG },
365
+ },
366
+ admin,
367
+ );
368
+
369
+ expect(renderedHtml.join("")).toContain("Musterfirma GmbH");
370
+ expect(preview.pages).toHaveLength(1);
371
+ expect(preview.agentImages).toHaveLength(1);
372
+ const bytes = Buffer.from(preview.agentImages[0]?.data ?? "", "base64");
373
+ expect([...bytes.subarray(0, 4)]).toEqual(PNG_MAGIC);
374
+ });
375
+ });
376
+ ```
377
+
378
+ ### src/letterhead.ts
379
+
380
+ ```ts
381
+ // The pieces an app ships for a letterhead: a system layout with its own look, a letter that places
382
+ // the recipient in the DIN address window, and the list of templates tenants may edit.
383
+
384
+ import {
385
+ TENANT_LAYOUT_SLUG_PREFIX,
386
+ type TenantEditableTemplate,
387
+ } from "@cosmicdrift/kumiko-bundled-features/template-resolver";
388
+
389
+ export const LETTERHEAD_LAYOUT_SLUG = "letterhead";
390
+ export const LETTER_SLUG = "letter";
391
+ export const LETTER_LOCALE = "de";
392
+
393
+ // Company placeholders read the tenant's own settings (tenant:config:company-*); a tenant that
394
+ // left one empty is told so by the validate query instead of getting an empty line in the PDF.
395
+ export const LETTERHEAD_LAYOUT_HTML = [
396
+ '<div data-header><p data-align="center"><strong>Hausverwaltung am Sund</strong></p></div>',
397
+ "<div data-content></div>",
398
+ "<div data-signature></div>",
399
+ [
400
+ '<div data-footer><table data-borders="none"><tbody><tr>',
401
+ '<td><p data-size="small"><span data-variable="companyAddress"></span></p></td>',
402
+ '<td><p data-size="small"><span data-variable="companyIban"></span></p></td>',
403
+ '<td><p data-size="small"><span data-variable="companyBic"></span></p></td>',
404
+ "</tr></tbody></table></div>",
405
+ ].join(""),
406
+ ].join("");
407
+
408
+ export const LETTERHEAD_LAYOUT_META = {
409
+ fontFamily: "times",
410
+ fontSizePt: 11,
411
+ tableStyle: "lines",
412
+ margins: { top: 36, right: 24, bottom: 28, left: 30 },
413
+ } as const;
414
+
415
+ // DIN 5008 form B: the frame sits at the window position, 85 x 45 mm at 20 / 45 mm.
416
+ export const LETTER_HTML = [
417
+ '<div data-frame data-x="20" data-y="45" data-width="85" data-height="45" data-frame-preset="address"><p><span data-variable="recipientName"></span></p></div>',
418
+ '<p><span data-text-style data-size-pt="14" data-font="times">Guten Tag,</span></p>',
419
+ "<p>anbei erhalten Sie die Unterlagen.</p>",
420
+ ].join("");
421
+
422
+ // What an AI assistant sends through create-layout and patch-draft to rebuild an uploaded letter:
423
+ // structured blocks only, never HTML. Names and addresses are made up.
424
+ export const REBUILT_LAYOUT_NAME = "rebuilt-letterhead";
425
+ export const REBUILT_LAYOUT_SLUG = `${TENANT_LAYOUT_SLUG_PREFIX}${REBUILT_LAYOUT_NAME}`;
426
+ export const REBUILT_LETTER_SLUG = "rebuilt-letter";
427
+
428
+ export const REBUILT_HEADER_BLOCKS = [
429
+ {
430
+ type: "paragraph",
431
+ align: "right",
432
+ runs: [{ text: "Musterfirma GmbH", bold: true, sizePt: 14, color: "#1f5468" }],
433
+ },
434
+ { type: "paragraph", align: "right", text: "Musterstraße 1, 12345 Musterstadt" },
435
+ ] as const;
436
+
437
+ export const REBUILT_LETTER_BLOCKS = [
438
+ {
439
+ type: "frame",
440
+ xMm: 20,
441
+ yMm: 45,
442
+ widthMm: 85,
443
+ heightMm: 45,
444
+ preset: "address",
445
+ blocks: [
446
+ { type: "paragraph", text: "Max Mustermann" },
447
+ { type: "paragraph", text: "Beispielweg 2" },
448
+ ],
449
+ },
450
+ { type: "heading", level: 2, text: "Rechnung {{invoiceNumber}}" },
451
+ {
452
+ type: "table",
453
+ columnWidthsPx: [320, 120],
454
+ header: {
455
+ cells: [
456
+ { text: "Leistung", background: "#eeeeee" },
457
+ { text: "Betrag", align: "right" },
458
+ ],
459
+ },
460
+ rows: [],
461
+ repeat: {
462
+ each: "positions",
463
+ row: { cells: [{ text: "{{label}}" }, { text: "{{amount}}", align: "right" }] },
464
+ },
465
+ },
466
+ ] as const;
467
+
468
+ export const TENANT_EDITABLE: readonly TenantEditableTemplate[] = [
469
+ { kind: "pdf-layout", slug: LETTERHEAD_LAYOUT_SLUG, access: { roles: ["TenantAdmin"] } },
470
+ { kind: "document-pdf", slug: LETTER_SLUG, access: { roles: ["TenantAdmin"] } },
471
+ { kind: "document-pdf", slug: REBUILT_LETTER_SLUG, access: { roles: ["TenantAdmin"] } },
472
+ ];
473
+ ```
@@ -60,6 +60,7 @@
60
60
  | `notes-history-basic` | Append-only note history — who wrote what, when — attached to any entity without changing it. | `examples/notes-history-basic.md` |
61
61
  | `ownership` | Entity- and Field-level Row-Ownership: from() helper, Straddle-safe multi-role checks, Field-level Read/Write filtering. | `examples/ownership.md` |
62
62
  | `pdf-audit-export` | Exports an audit table as a PDF: a write handler renders rows with renderTablePdf and uploads the bytes before the transaction (uploadFileBytesBeforeTransaction) and stores them as a FileRef (createFileRefFromUploadedBytes). | `examples/pdf-audit-export.md` |
63
+ | `pdf-letterhead` | A PDF letterhead as a layout with its own appearance and company-data footer, a letter with an address frame, and the transfer of the layout to templates (apply-layout, publish-templates). | `examples/pdf-letterhead.md` |
63
64
  | `pipeline-basics` | M.1 Tier-1 step-vocabulary showcase: every step in one inventory-management feature (aggregate.{create,update,appendEvent}, read.{findOne,findMany}, branch, forEach, compute, return, unsafeProjection{Upsert,Delete}). | `examples/pipeline-basics.md` |
64
65
  | `prod-boot-options` | runProdApp boot options: mail, kmsMode, fileStorage, demoMode and signal handling declared as options instead of hand-wired in bin/main.ts. | `examples/prod-boot-options.md` |
65
66
  | `public-share-token` | Generic share-token entity: mint hash-stored token, anonymous read-by-token with IP rate-limit. | `examples/public-share-token.md` |
@@ -740,6 +740,7 @@ Config keys:
740
740
 
741
741
  | Key | Type | Scope | Default |
742
742
  | --- | --- | --- | --- |
743
+ | `default-pdf-layout-slug` | text | tenant | `` |
743
744
  | `resource-max-bytes` | number | system | `2097152` |
744
745
 
745
746
  ## template-resolver-user-data
@@ -762,7 +763,17 @@ Config keys:
762
763
 
763
764
  | Key | Type | Scope | Default |
764
765
  | --- | --- | --- | --- |
766
+ | `company-address` | text | tenant | `` |
767
+ | `company-bank` | text | tenant | `` |
768
+ | `company-bic` | text | tenant | `` |
769
+ | `company-email` | text | tenant | `` |
770
+ | `company-iban` | text | tenant | `` |
771
+ | `company-management` | text | tenant | `` |
765
772
  | `company-name` | text | tenant | `` |
773
+ | `company-phone` | text | tenant | `` |
774
+ | `company-register` | text | tenant | `` |
775
+ | `company-vat-id` | text | tenant | `` |
776
+ | `company-website` | text | tenant | `` |
766
777
  | `locale` | select | tenant | `de` |
767
778
  | `max-users` | number | system | `50` |
768
779
  | `price-model` | select | system | `basic` |
package/agents/widgets.md CHANGED
@@ -51,6 +51,7 @@ Value exports of `@cosmicdrift/kumiko-renderer/web`.
51
51
  | `EditorLocaleSwitch` | |
52
52
  | `EditorModeSwitch` | |
53
53
  | `EditorPanel` | |
54
+ | `EditorToolbarPill` | |
54
55
  | `EditorWorkbench` | |
55
56
  | `EmptyState` | Empty state with an optional icon and CTA, using the dashed-box style of entityList empty states as a standalone widget for custom screens. |
56
57
  | `ErrorState` | Error state based on the Banner primitive, with a retry button. |
@@ -13,6 +13,7 @@ export interface ResolveSubjectOptions {
13
13
  readonly ignoreWhenAbsent?: boolean;
14
14
  }
15
15
  export declare function nonEmptyString(value: unknown): string | null;
16
+ export declare function usableOwnerId(value: unknown): string | null;
16
17
  /**
17
18
  * Maps a pii-annotated field to the subject whose key encrypts it.
18
19
  * Returns null for fields without any PII annotation (stored plaintext).
@@ -1,7 +1,8 @@
1
1
  import { normalizeEventPiiSubject } from "@cosmicdrift/kumiko-types/handlers";
2
2
  import { isFileField } from "../engine/field-helpers.js";
3
3
  import { isSelfPiiField } from "./is-self-pii-field.js";
4
- import { RECORD_ENTITY_PATTERN } from "./kms-adapter.js";
4
+ import { PII_ERASED_SENTINEL, RECORD_ENTITY_PATTERN } from "./kms-adapter.js";
5
+ import { isPiiCiphertext } from "./pii-ciphertext-format.js";
5
6
  // Thrown when a field IS pii-annotated but the row can't name its subject —
6
7
  // that must surface as an error, not fall back to plaintext.
7
8
  export class SubjectResolutionError extends Error {
@@ -15,6 +16,11 @@ export class SubjectResolutionError extends Error {
15
16
  export function nonEmptyString(value) {
16
17
  return typeof value === "string" && value.length > 0 ? value : null;
17
18
  }
19
+ // A stored ciphertext or the erased sentinel in an owner column is not a user id.
20
+ export function usableOwnerId(value) {
21
+ const id = nonEmptyString(value);
22
+ return id === null || id === PII_ERASED_SENTINEL || isPiiCiphertext(id) ? null : id;
23
+ }
18
24
  function rowIdAsString(row) {
19
25
  const id = row["id"];
20
26
  return nonEmptyString(id) ?? (typeof id === "number" ? String(id) : null);
@@ -32,7 +38,7 @@ function resolveRecordSubject(fieldName, row, opts) {
32
38
  }
33
39
  function resolveUserOwnedSubject(userOwned, fieldName, row, opts) {
34
40
  const { ownerField } = userOwned;
35
- const userId = nonEmptyString(row[ownerField]) ?? nonEmptyString(opts.ownerFallback?.[ownerField]);
41
+ const userId = usableOwnerId(row[ownerField]) ?? usableOwnerId(opts.ownerFallback?.[ownerField]);
36
42
  if (userId !== null)
37
43
  return { kind: "user", userId };
38
44
  if (opts.ignoreWhenAbsent !== true) {
@@ -66,7 +66,7 @@ import { configuredEventPiiCatalog } from "../../crypto/event-pii.js";
66
66
  import { isLocalKeyKmsAdapter, KeyErasedError, KeyNotFoundError, } from "../../crypto/kms-adapter.js";
67
67
  import { isPlainUserOwnedField } from "../../crypto/owner-transition-rekey.js";
68
68
  import { configuredPiiSubjectKms, decryptPiiValueForSubject, encryptPiiJsonValueForSubject, encryptPiiValueForSubject, isPiiCiphertext, PII_ERASED_SENTINEL, piiCiphertextSubject, } from "../../crypto/pii-field-encryption.js";
69
- import { collectPiiEncryptedFields, nonEmptyString, resolveEventSubject, resolveSubjectForField, SubjectResolutionError, } from "../../crypto/subject-resolver.js";
69
+ import { collectPiiEncryptedFields, resolveEventSubject, resolveSubjectForField, SubjectResolutionError, usableOwnerId, } from "../../crypto/subject-resolver.js";
70
70
  import { resolveTableName } from "../entity-table-meta.js";
71
71
  import { asRawClient } from "../query.js";
72
72
  import { tableExists } from "../schema-inspection.js";
@@ -517,6 +517,8 @@ async function rekeyTenantKeyedValue(deps, target) {
517
517
  const fieldDef = entity.fields[field];
518
518
  if (fieldDef === undefined || !isPlainUserOwnedField(fieldDef))
519
519
  return { kind: "unchanged" };
520
+ if (fieldDef.userOwned.ownerField === field)
521
+ return rekeySelfOwnedValue(deps, target);
520
522
  const keyedUnder = ciphertextSubjectOrNull(ciphertext);
521
523
  const userSubject = keyedUnder?.kind === "tenant" && keyedUnder.tenantId === target.tenantId
522
524
  ? rekeyTargetOfTenantKeyedValue(target)
@@ -529,6 +531,30 @@ async function rekeyTenantKeyedValue(deps, target) {
529
531
  (target.isSupersededHistory || (await deps.hasNewerValueOfField(field)))) {
530
532
  return { kind: "unchanged" };
531
533
  }
534
+ return moveUnderUserSubject(deps, userSubject, ciphertext, field, () => decryptPiiValueForSubject(deps.subjectKms, ciphertext, deps.kmsCtx, field));
535
+ }
536
+ // The field is its own owner: the key follows the value, so no event history or
537
+ // projection decides it, and a stored ciphertext must never be read as the owner id.
538
+ async function rekeySelfOwnedValue(deps, target) {
539
+ const { field, ciphertext } = target;
540
+ const keyedUnder = ciphertextSubjectOrNull(ciphertext);
541
+ if (keyedUnder === null)
542
+ return { kind: "unchanged" };
543
+ const ownTenantKey = keyedUnder.kind === "tenant" && keyedUnder.tenantId === target.tenantId;
544
+ if (!ownTenantKey && keyedUnder.kind !== "user")
545
+ return { kind: "unchanged" };
546
+ const plaintext = await decryptPiiValueForSubject(deps.subjectKms, ciphertext, deps.kmsCtx, field);
547
+ if (plaintext === PII_ERASED_SENTINEL)
548
+ return { kind: "erased" };
549
+ const ownerId = usableOwnerId(plaintext);
550
+ if (ownerId === null)
551
+ return { kind: "unchanged" };
552
+ if (keyedUnder.kind === "user" && keyedUnder.userId === ownerId)
553
+ return { kind: "unchanged" };
554
+ return moveUnderUserSubject(deps, { kind: "user", userId: ownerId }, ciphertext, field, async () => plaintext);
555
+ }
556
+ // Forgotten and dryRun are decided before the plaintext is read.
557
+ async function moveUnderUserSubject(deps, userSubject, ciphertext, field, readPlaintext) {
532
558
  if (await deps.isForgottenSubject(userSubject))
533
559
  return { kind: "erased" };
534
560
  if (deps.dryRun) {
@@ -536,7 +562,7 @@ async function rekeyTenantKeyedValue(deps, target) {
536
562
  ? { kind: "erased" }
537
563
  : { kind: "rekeyed", value: ciphertext };
538
564
  }
539
- const plaintext = await decryptPiiValueForSubject(deps.subjectKms, ciphertext, deps.kmsCtx, field);
565
+ const plaintext = await readPlaintext();
540
566
  if (plaintext === PII_ERASED_SENTINEL)
541
567
  return { kind: "erased" };
542
568
  try {
@@ -563,7 +589,7 @@ function rekeyTargetOfTenantKeyedValue(target) {
563
589
  // projection of the event's own tenant is authoritative here: the payload of
564
590
  // an old created event still names the owner the row had back then.
565
591
  function currentProjectionOwnerIfOther(target, ownerField, keyedUserId) {
566
- const owner = nonEmptyString(target.projectionOwnerRow?.[ownerField]);
592
+ const owner = usableOwnerId(target.projectionOwnerRow?.[ownerField]);
567
593
  return owner === null || owner === keyedUserId ? null : { kind: "user", userId: owner };
568
594
  }
569
595
  // Only the row's own tenant key or a user key counts: another tenant's key is
@@ -14,6 +14,11 @@ export declare const ACTION_FORM_PREVIEW_RULES: {
14
14
  readonly summary: "preview.list names the result field of its rows and at least one column.";
15
15
  readonly fix: "Set list.field to the array in the query result and list the columns to show.";
16
16
  };
17
+ readonly sectionUnknown: {
18
+ readonly id: "action-form-preview/section-unknown";
19
+ readonly summary: "preview.section names a fields section of the layout.";
20
+ readonly fix: "Give a layout section that id, or drop section to show the preview below the form.";
21
+ };
17
22
  readonly empty: {
18
23
  readonly id: "action-form-preview/empty";
19
24
  readonly summary: "A preview shows facts or a list.";
@@ -14,6 +14,11 @@ export const ACTION_FORM_PREVIEW_RULES = {
14
14
  summary: "preview.list names the result field of its rows and at least one column.",
15
15
  fix: "Set list.field to the array in the query result and list the columns to show.",
16
16
  },
17
+ sectionUnknown: {
18
+ id: "action-form-preview/section-unknown",
19
+ summary: "preview.section names a fields section of the layout.",
20
+ fix: "Give a layout section that id, or drop section to show the preview below the form.",
21
+ },
17
22
  empty: {
18
23
  id: "action-form-preview/empty",
19
24
  summary: "A preview shows facts or a list.",
@@ -1,3 +1,4 @@
1
+ import { isFieldsEditSection } from "../screen-helpers.js";
1
2
  import { ACTION_FORM_PREVIEW_RULES } from "./action-form-preview-rules.js";
2
3
  import { bootRuleError } from "./boot-rule.js";
3
4
  function isBlank(value) {
@@ -12,6 +13,17 @@ function validateSentFields(where, preview, fieldNames) {
12
13
  });
13
14
  }
14
15
  }
16
+ function validateSection(where, preview, screen) {
17
+ // skip: no placement, the panel stays below the form
18
+ if (preview.section === undefined)
19
+ return;
20
+ const sectionIds = screen.layout.sections.flatMap((section) => isFieldsEditSection(section) && section.id !== undefined ? [section.id] : []);
21
+ if (sectionIds.includes(preview.section))
22
+ return;
23
+ throw bootRuleError(ACTION_FORM_PREVIEW_RULES.sectionUnknown, {
24
+ message: `${where} section "${preview.section}" is no fields section id of the layout. Section ids: ${sectionIds.join(", ") || "(none)"}.`,
25
+ });
26
+ }
15
27
  function validateFacts(where, facts) {
16
28
  for (const fact of facts) {
17
29
  if (!isBlank(fact.label))
@@ -42,6 +54,7 @@ export function validateActionFormPreview(featureName, screenId, screen, fieldNa
42
54
  return;
43
55
  const where = `[Feature ${featureName}] Screen "${screenId}" (actionForm) preview`;
44
56
  validateSentFields(where, preview, fieldNames);
57
+ validateSection(where, preview, screen);
45
58
  const facts = preview.facts ?? [];
46
59
  if (facts.length === 0 && preview.list === undefined) {
47
60
  throw bootRuleError(ACTION_FORM_PREVIEW_RULES.empty, {