@cosmicdrift/kumiko-framework 0.414.0 → 0.415.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/agents/api/framework-engine.md +9 -3
  2. package/agents/api/framework-errors.md +1 -1
  3. package/agents/api/framework-ui-types.md +10 -1
  4. package/agents/api/renderer-web.md +20 -3
  5. package/agents/api/types.md +47 -14
  6. package/agents/api.md +2 -2
  7. package/agents/boot-rules.md +7 -5
  8. package/agents/examples/crypto-shredding-hr.md +63 -1
  9. package/agents/examples/record-detail-layout.md +113 -7
  10. package/agents/widgets.md +7 -0
  11. package/dist/api/request-context-internals.d.ts +2 -0
  12. package/dist/api/request-context-scopes.js +9 -2
  13. package/dist/api/request-context.js +1 -1
  14. package/dist/api/routes.js +4 -4
  15. package/dist/api/server-event-dispatcher.js +3 -0
  16. package/dist/db/parent-ref-clause.js +31 -3
  17. package/dist/db/parent-ref-global-hosts.d.ts +4 -1
  18. package/dist/db/parent-ref-global-hosts.js +50 -12
  19. package/dist/db/queries/rls-boot-catalog.js +5 -6
  20. package/dist/db/queries/rls-shape.d.ts +1 -0
  21. package/dist/db/queries/rls-shape.js +21 -6
  22. package/dist/engine/boot-validator/boot-rules.d.ts +16 -6
  23. package/dist/engine/boot-validator/card-meta-overflow-rules.d.ts +2 -2
  24. package/dist/engine/boot-validator/card-meta-overflow-rules.js +2 -2
  25. package/dist/engine/boot-validator/card-meta-overflow.js +7 -5
  26. package/dist/engine/boot-validator/entity-list-screens.js +2 -7
  27. package/dist/engine/boot-validator/list-row-guidance-rules.d.ts +2 -2
  28. package/dist/engine/boot-validator/list-row-guidance-rules.js +2 -2
  29. package/dist/engine/boot-validator/list-row-guidance.js +15 -1
  30. package/dist/engine/boot-validator/list-sort-summary-rules.d.ts +2 -2
  31. package/dist/engine/boot-validator/list-sort-summary-rules.js +2 -2
  32. package/dist/engine/boot-validator/list-sort-summary.js +31 -20
  33. package/dist/engine/boot-validator/list-toolbar-options.js +3 -4
  34. package/dist/engine/boot-validator/named-filter-rules.d.ts +10 -0
  35. package/dist/engine/boot-validator/named-filter-rules.js +10 -0
  36. package/dist/engine/boot-validator/projection-list-screens.js +5 -4
  37. package/dist/engine/boot-validator/query-output-guidance.js +1 -0
  38. package/dist/engine/boot-validator/query-refs.js +10 -0
  39. package/dist/engine/boot-validator/screens-actions.js +1 -1
  40. package/dist/engine/named-filter-roles.js +6 -14
  41. package/dist/engine/schema-builder.js +3 -1
  42. package/dist/engine/soft-delete-cleanup.js +2 -0
  43. package/dist/errors/reasons.d.ts +1 -0
  44. package/dist/errors/reasons.js +4 -0
  45. package/dist/i18n/required-surface-keys.js +2 -1
  46. package/dist/jobs/job-runner-execution.js +3 -0
  47. package/dist/jobs/job-runner-types.d.ts +1 -0
  48. package/dist/jobs/job-runner.js +8 -0
  49. package/dist/pipeline/context-services.d.ts +1 -1
  50. package/dist/pipeline/context-services.js +1 -1
  51. package/dist/pipeline/event-dispatcher-delivery.js +3 -0
  52. package/dist/pipeline/event-dispatcher.d.ts +2 -0
  53. package/dist/pipeline/handler-context-phase-denials.js +1 -1
  54. package/dist/pipeline/irreversible-operation-gate.js +36 -10
  55. package/dist/search/meilisearch-adapter-internals.d.ts +2 -0
  56. package/dist/search/meilisearch-adapter-internals.js +5 -0
  57. package/dist/search/meilisearch-adapter.d.ts +1 -0
  58. package/dist/search/meilisearch-adapter.js +3 -2
  59. package/dist/ui-types/card-column-roles.d.ts +2 -0
  60. package/dist/ui-types/card-column-roles.js +15 -0
  61. package/dist/ui-types/index.d.ts +2 -2
  62. package/dist/ui-types/index.js +1 -1
  63. package/package.json +3 -3
  64. package/presets/biome-plugins/no-date-api.grit +3 -1
  65. package/presets/biome-plugins/no-direct-fetch.grit +1 -1
  66. package/presets/biome-plugins/unsafe-json-parse.grit +7 -1
  67. package/presets/biome-rules.json +12 -10
  68. package/src/changes.json +57 -0
@@ -81,6 +81,17 @@ deletion grace period.
81
81
  projection rebuild recomputes it from the (now undecryptable) ciphertext
82
82
  to `NULL`.
83
83
 
84
+ ## Irreversible operations in jobs
85
+
86
+ `forget`, hard deletes, `kms.eraseKey` and writes to `readAsInstruction` fields are gated: they run only from a
87
+ handler marked `agent: { risk: "high" }`. A job or an event consumer has no handler entry, so it must declare
88
+ `irreversibleWithoutEntryHandler` on `r.job` or `r.multiStreamProjection`, or the gate refuses with
89
+ `irreversible_operation_without_entry_handler`. The value names why no entry handler exists:
90
+ `rebuildable-derived-data` (the data is derived and a rebuild recreates it), `high-risk-or-cron-pipeline`
91
+ (a maintenance pipeline that is high-risk by design, like `purge-archived-comments`) or
92
+ `per-dispatch-record-key` (the key belongs to one dispatch record). Hooks and routes never inherit the
93
+ declaration; they dispatch a `risk: "high"` handler instead.
94
+
84
95
  ## Source files
85
96
 
86
97
  ### src/__tests__/feature.integration.test.ts
@@ -114,6 +125,7 @@ import {
114
125
  resetBlindIndexKeyForTests,
115
126
  resetPiiSubjectKmsForTests,
116
127
  resetTestTables,
128
+ waitFor,
117
129
  } from "@cosmicdrift/kumiko-testing/helpers";
118
130
  import {
119
131
  setupTestStack,
@@ -128,7 +140,7 @@ let kms: InMemoryKmsAdapter;
128
140
  const admin = TestUsers.admin;
129
141
 
130
142
  beforeAll(async () => {
131
- stack = await setupTestStack({ features: [hrFeature] });
143
+ stack = await setupTestStack({ features: [hrFeature], jobs: { consumerLane: "worker" } });
132
144
  await unsafeCreateEntityTable(stack.db, employeeEntity);
133
145
  await unsafeCreateEntityTable(stack.db, hrCommentEntity);
134
146
  await createEventsTable(stack.db);
@@ -210,6 +222,29 @@ describe("crypto-shredding-hr", () => {
210
222
  expect(rows[0]?.body).toStartWith(`${PII_CIPHERTEXT_PREFIX}user:${employeeId}:`);
211
223
  });
212
224
 
225
+ test("purge-archived-comments job forgets the comment row; its declaration lets the cron run past the gate", async () => {
226
+ const employeeId = await createEmployee();
227
+ const comment = await stack.http.writeOk<SaveContext>(
228
+ "hr:write:hr-comment:create",
229
+ { employeeId, body: "archived note", authorName: "Manager X" },
230
+ admin,
231
+ );
232
+ const commentId = String(comment.id);
233
+
234
+ await stack.jobRunner?.dispatch("hr:job:purge-archived-comments", {
235
+ commentIds: [commentId],
236
+ tenantId: admin.tenantId,
237
+ });
238
+
239
+ await waitFor(async () => {
240
+ const rows = await asRawClient(stack.db).unsafe(
241
+ "SELECT id FROM read_hr_comments WHERE id = $1",
242
+ [commentId],
243
+ );
244
+ expect(rows).toHaveLength(0);
245
+ });
246
+ });
247
+
213
248
  test("forget: eraseKey renders [[erased]] for the employee AND comments about them", async () => {
214
249
  const employeeId = await createEmployee();
215
250
  await stack.http.writeOk<SaveContext>(
@@ -278,7 +313,9 @@ describe("crypto-shredding-hr — blind-index lookups", () => {
278
313
  ### src/feature.ts
279
314
 
280
315
  ```ts
316
+ import { buildEntityTable, createEventStoreExecutor } from "@cosmicdrift/kumiko-framework/db";
281
317
  import { createEntity, createTextField, defineFeature } from "@cosmicdrift/kumiko-framework/engine";
318
+ import * as z from "zod";
282
319
 
283
320
  export const employeeEntity = createEntity({
284
321
  table: "read_hr_employees",
@@ -300,6 +337,13 @@ export const hrCommentEntity = createEntity({
300
337
  softDelete: true,
301
338
  });
302
339
 
340
+ const hrCommentTable = buildEntityTable("hr-comment", hrCommentEntity);
341
+ const hrCommentExecutor = createEventStoreExecutor(hrCommentTable, hrCommentEntity, {
342
+ entityName: "hr-comment",
343
+ });
344
+
345
+ const purgeArchivedCommentsPayload = z.object({ commentIds: z.array(z.uuid()) });
346
+
303
347
  const hrWrite = { access: { roles: ["Admin"] } } as const;
304
348
  const hrRead = { access: { roles: ["Admin"] } } as const;
305
349
 
@@ -315,5 +359,23 @@ export const hrFeature = defineFeature("hr", (r) => {
315
359
  read: hrRead,
316
360
  verbs: { update: false, delete: false, restore: false, list: false },
317
361
  });
362
+
363
+ // A job runs without a write-handler entry, so the irreversible-operation gate refuses
364
+ // `forget` here unless the job declares why it may. Remove the declaration and the run fails.
365
+ r.job(
366
+ "purge-archived-comments",
367
+ {
368
+ trigger: { maintenance: true },
369
+ runIn: "worker",
370
+ irreversibleWithoutEntryHandler: "high-risk-or-cron-pipeline",
371
+ },
372
+ async (payload, ctx) => {
373
+ const { commentIds } = purgeArchivedCommentsPayload.parse(payload);
374
+ for (const id of commentIds) {
375
+ const result = await hrCommentExecutor.forget({ id }, ctx.systemUser, ctx.db);
376
+ if (!result.isSuccess) throw new Error(`purge of hr-comment ${id} failed`);
377
+ }
378
+ },
379
+ );
318
380
  });
319
381
  ```
@@ -1018,6 +1018,7 @@ import { z } from "zod";
1018
1018
  import { createOrderDeskFeature } from "../feature";
1019
1019
  import {
1020
1020
  answerBriefing,
1021
+ answerNextReminder,
1021
1022
  answerOrderDetail,
1022
1023
  answerOrderList,
1023
1024
  answerOrderSummary,
@@ -1135,6 +1136,7 @@ describe("record-detail-layout showcase — work queue", () => {
1135
1136
  display: "select",
1136
1137
  showCounts: true,
1137
1138
  label: "order-desk.orders.todo",
1139
+ narrowPlacement: "behind-filter",
1138
1140
  });
1139
1141
  const buttons = (screen.rowActions ?? []).filter((action) => action.display === "button");
1140
1142
  expect(buttons.map((action) => [action.id, action.visible])).toEqual([
@@ -1279,6 +1281,34 @@ describe("record-detail-layout showcase — phone variants", () => {
1279
1281
  });
1280
1282
  });
1281
1283
 
1284
+ describe("record-detail-layout showcase — board gaps round 8", () => {
1285
+ test("two narrow-only value columns stand side by side on the phone card", () => {
1286
+ const screen = registry.getScreen("order-desk:screen:orders");
1287
+ if (screen?.type !== "projectionList") throw new Error("expected projectionList");
1288
+ const inline = screen.columns
1289
+ .map((column) => normalizeListColumn(column))
1290
+ .filter((column) => column.narrowInline === true);
1291
+ expect(inline.map((column) => [column.field, column.showOnNarrowOnly])).toEqual([
1292
+ ["narrowOpen", true],
1293
+ ["narrowStatus", true],
1294
+ ]);
1295
+ const first = answerOrderList(orderListSchema.parse({}));
1296
+ expect("rows" in first && first.rows[0]?.narrowOpen).toBe("€ 312.00 open");
1297
+ });
1298
+
1299
+ test("the reminder-due empty state takes its description params from a registered query", () => {
1300
+ const screen = registry.getScreen("order-desk:screen:orders");
1301
+ if (screen?.type !== "projectionList") throw new Error("expected projectionList");
1302
+ const reminder = screen.namedFilters?.find((filter) => filter.id === "reminder-due");
1303
+ expect(reminder?.emptyState).toEqual({
1304
+ title: "order-desk.orders.all-done",
1305
+ description: "order-desk.orders.next-reminder",
1306
+ paramsQuery: "order-desk:query:order:next-reminder",
1307
+ });
1308
+ expect(answerNextReminder()).toEqual({ customer: "Aiko Tanaka", due: "by Friday" });
1309
+ });
1310
+ });
1311
+
1282
1312
  describe("record-detail-layout showcase — empty states", () => {
1283
1313
  test("the payments tab declares a record-dependent empty text ahead of its default", () => {
1284
1314
  const screen = registry.getScreen("order-desk:screen:order-detail");
@@ -1355,6 +1385,43 @@ describe("record-detail-layout showcase — boot-validator catches author mistak
1355
1385
  });
1356
1386
  ```
1357
1387
 
1388
+ ### src/__tests__/next-reminder.integration.test.ts
1389
+
1390
+ ```ts
1391
+ import { afterAll, beforeAll, describe, expect, test } from "bun:test";
1392
+ import { createTestUser, testTenantId } from "@cosmicdrift/kumiko-framework/seeding";
1393
+ import { setupTestStack, type TestStack } from "@cosmicdrift/kumiko-testing/stack";
1394
+ import { createOrderDeskFeature } from "../feature";
1395
+
1396
+ let stack: TestStack;
1397
+ const support = createTestUser({ roles: ["Support"], tenantId: testTenantId(1) });
1398
+
1399
+ beforeAll(async () => {
1400
+ stack = await setupTestStack({ features: [createOrderDeskFeature()], systemHooks: [] });
1401
+ });
1402
+
1403
+ afterAll(async () => {
1404
+ await stack.cleanup();
1405
+ });
1406
+
1407
+ describe("emptyState.paramsQuery over HTTP", () => {
1408
+ test("the query the reminder-due empty state names answers the params of its description", async () => {
1409
+ const params = await stack.http.queryOk<{ customer: string; due: string }>(
1410
+ "order-desk:query:order:next-reminder",
1411
+ {},
1412
+ support,
1413
+ );
1414
+ expect(params).toEqual({ customer: "Aiko Tanaka", due: "by Friday" });
1415
+ });
1416
+
1417
+ test("a caller without the list's roles cannot read the params", async () => {
1418
+ const outsider = createTestUser({ roles: ["User"], tenantId: testTenantId(1) });
1419
+ const denied = await stack.http.queryErr("order-desk:query:order:next-reminder", {}, outsider);
1420
+ expect(denied.code).toBe("access_denied");
1421
+ });
1422
+ });
1423
+ ```
1424
+
1358
1425
  ### src/feature.ts
1359
1426
 
1360
1427
  ```ts
@@ -1387,6 +1454,10 @@ describe("record-detail-layout showcase — boot-validator catches author mistak
1387
1454
  // 10. `focus: true` gives the detail a focused shell; phones get a top bar with the
1388
1455
  // record title, a back arrow to the list and the page-header overflow menu.
1389
1456
  //
1457
+ // 11. Phone card values: two `showOnNarrowOnly` columns with `narrowInline` stand side by side on one line.
1458
+ // The named-filter select sits behind the filter icon on phones (`narrowPlacement: "behind-filter"`),
1459
+ // and the "reminder due" empty state fills its description from a query (`emptyState.paramsQuery`).
1460
+ //
1390
1461
  // projectionDetail binds to an explicit query, not an entity: every field name below
1391
1462
  // (header, metrics, fields) is a column of that query's row.
1392
1463
 
@@ -1397,6 +1468,7 @@ import {
1397
1468
  answerCustomers,
1398
1469
  answerDeadlines,
1399
1470
  answerMoney,
1471
+ answerNextReminder,
1400
1472
  answerNowList,
1401
1473
  answerOrderDetail,
1402
1474
  answerOrderList,
@@ -1436,6 +1508,13 @@ export function createOrderDeskFeature(): FeatureDefinition {
1436
1508
  access: accessRoles,
1437
1509
  });
1438
1510
 
1511
+ r.queryHandler({
1512
+ name: "order:next-reminder",
1513
+ schema: noPayloadSchema,
1514
+ handler: async () => answerNextReminder(),
1515
+ access: accessRoles,
1516
+ });
1517
+
1439
1518
  r.queryHandler({
1440
1519
  name: "order:briefing",
1441
1520
  schema: noPayloadSchema,
@@ -1523,6 +1602,7 @@ export function createOrderDeskFeature(): FeatureDefinition {
1523
1602
  "order-desk.orders.nothing-open": { en: "Nothing to do" },
1524
1603
  "order-desk.orders.all-done": { en: "All done" },
1525
1604
  "order-desk.orders.all-done-hint": { en: "No order needs you right now." },
1605
+ "order-desk.orders.next-reminder": { en: "Next reminder: {customer}, due {due}." },
1526
1606
  "order-desk.filter.action-needed": { en: "Needs action" },
1527
1607
  "order-desk.filter.reminder-due": { en: "Reminder due" },
1528
1608
  "order-desk.filter.ending-soon": { en: "Ending soon" },
@@ -1548,7 +1628,8 @@ export function createOrderDeskFeature(): FeatureDefinition {
1548
1628
  "order-desk.today.inbox-link": { en: "All orders" },
1549
1629
  "order-desk.today.deadlines": { en: "Deadlines" },
1550
1630
  "order-desk.today.deadlines-all": { en: "All deadlines" },
1551
- "order-desk.col.narrow-meta": { en: "Details" },
1631
+ "order-desk.col.narrow-open": { en: "Open amount" },
1632
+ "order-desk.col.narrow-status": { en: "Status" },
1552
1633
  "order-desk.today.customers": { en: "Customers" },
1553
1634
  "order-desk.today.money": { en: "Money" },
1554
1635
  "order-desk.today.money-sub": { en: "Across all open orders" },
@@ -1592,7 +1673,7 @@ export function createOrderDeskFeature(): FeatureDefinition {
1592
1673
  rowToneField: "tone",
1593
1674
  columns: [
1594
1675
  { field: "orderNumber", label: "order-desk.col.order" },
1595
- { field: "customerName", label: "order-desk.col.customer" },
1676
+ { field: "customerName", label: "order-desk.col.customer", hideOnNarrow: true },
1596
1677
  {
1597
1678
  field: "urgencyLabel",
1598
1679
  label: "order-desk.col.urgency",
@@ -1614,7 +1695,18 @@ export function createOrderDeskFeature(): FeatureDefinition {
1614
1695
  minWidth: 240,
1615
1696
  },
1616
1697
  { field: "openAmount", label: "order-desk.col.open-amount", hideOnNarrow: true },
1617
- { field: "narrowMeta", label: "order-desk.col.narrow-meta", showOnNarrowOnly: true },
1698
+ {
1699
+ field: "narrowOpen",
1700
+ label: "order-desk.col.narrow-open",
1701
+ showOnNarrowOnly: true,
1702
+ narrowInline: true,
1703
+ },
1704
+ {
1705
+ field: "narrowStatus",
1706
+ label: "order-desk.col.narrow-status",
1707
+ showOnNarrowOnly: true,
1708
+ narrowInline: true,
1709
+ },
1618
1710
  ],
1619
1711
  defaultSort: { field: "urgency", dir: "desc" },
1620
1712
  sortOptions: [
@@ -1636,12 +1728,18 @@ export function createOrderDeskFeature(): FeatureDefinition {
1636
1728
  label: "order-desk.filter.reminder-due",
1637
1729
  emptyState: {
1638
1730
  title: "order-desk.orders.all-done",
1639
- description: "order-desk.orders.all-done-hint",
1731
+ description: "order-desk.orders.next-reminder",
1732
+ paramsQuery: "order-desk:query:order:next-reminder",
1640
1733
  },
1641
1734
  },
1642
1735
  { id: "ending-soon", label: "order-desk.filter.ending-soon" },
1643
1736
  ],
1644
- namedFilterFacet: { display: "select", showCounts: true, label: "order-desk.orders.todo" },
1737
+ namedFilterFacet: {
1738
+ display: "select",
1739
+ showCounts: true,
1740
+ label: "order-desk.orders.todo",
1741
+ narrowPlacement: "behind-filter",
1742
+ },
1645
1743
  narrowFacets: "pills",
1646
1744
  table: {
1647
1745
  frame: "card",
@@ -2288,7 +2386,8 @@ export type OrderListAnswer =
2288
2386
  }
2289
2387
  | {
2290
2388
  readonly rows: readonly (OrderRow & {
2291
- readonly narrowMeta: string;
2389
+ readonly narrowOpen: string;
2390
+ readonly narrowStatus: string;
2292
2391
  readonly actionScreen?: string;
2293
2392
  readonly actionParams?: { readonly entityId: string };
2294
2393
  })[];
@@ -2316,7 +2415,8 @@ export function answerOrderList(payload: OrderListPayload): OrderListAnswer {
2316
2415
  const offset = payload.offset ?? 0;
2317
2416
  const rows = ordered.slice(offset, offset + (payload.limit ?? DEFAULT_PAGE_SIZE)).map((row) => ({
2318
2417
  ...row,
2319
- narrowMeta: `${euro(row.openAmount)} open · ${row.status}`,
2418
+ narrowOpen: `${euro(row.openAmount)} open`,
2419
+ narrowStatus: row.status,
2320
2420
  nextStepShort: row.nextStepDue === "" ? "" : `${row.nextStepDue} · ${euro(row.openAmount)}`,
2321
2421
  ...(row.nextStep !== "" && {
2322
2422
  actionScreen: ORDER_DETAIL_SCREEN_QN,
@@ -2371,6 +2471,12 @@ export function answerNowList() {
2371
2471
  };
2372
2472
  }
2373
2473
 
2474
+ // The params of the "reminder due" empty state; null while no order is waiting for a reminder.
2475
+ export function answerNextReminder(): { readonly customer: string; readonly due: string } | null {
2476
+ const next = ORDER_ROWS.find((row) => row.canRemind);
2477
+ return next === undefined ? null : { customer: next.customerName, due: next.nextStepDue };
2478
+ }
2479
+
2374
2480
  export function answerBriefing() {
2375
2481
  const open = actionNeededRows(ORDER_ROWS.length);
2376
2482
  const [first] = open;
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,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;