@cosmicdrift/kumiko-samples 0.417.0 → 0.418.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 (38) hide show
  1. package/package.json +1 -1
  2. package/packages/bundled-features/package.json +1 -1
  3. package/packages/bundled-features/src/agent-tools/api-docs/schema-fields.ts +14 -0
  4. package/packages/bundled-features/src/agent-tools/changes.json +6 -0
  5. package/packages/bundled-features/src/auth-email-password/index.ts +1 -1
  6. package/packages/bundled-features/src/auth-email-password/signup-activation.ts +2 -5
  7. package/packages/bundled-features/src/auth-email-password/signup-token-store.ts +0 -6
  8. package/packages/bundled-features/src/cap-counter/changes.json +6 -0
  9. package/packages/bundled-features/src/cap-counter/stock-cap-guard.ts +46 -13
  10. package/packages/bundled-features/src/channel-whatsapp/changes.json +1 -1
  11. package/packages/bundled-features/src/document-ingest-foundation/changes.json +6 -0
  12. package/packages/bundled-features/src/document-ingest-foundation/feature.ts +13 -1
  13. package/packages/bundled-features/src/document-ingest-foundation/report-ingest-progress.ts +23 -6
  14. package/packages/bundled-features/src/signature/README.md +4 -4
  15. package/packages/bundled-features/src/signature/changes.json +18 -0
  16. package/packages/bundled-features/src/signature/entity.ts +3 -1
  17. package/packages/bundled-features/src/signature/feature.ts +16 -3
  18. package/packages/bundled-features/src/signature/handlers/lifecycle.write.ts +33 -1
  19. package/packages/bundled-features/src/signature/i18n.ts +1 -0
  20. package/packages/bundled-features/src/signature/list-cursor-seal.ts +59 -0
  21. package/packages/bundled-features/src/signature/options.ts +2 -2
  22. package/packages/bundled-features/src/signature/payloads.ts +14 -2
  23. package/packages/bundled-features/src/signature/png.ts +25 -4
  24. package/packages/bundled-features/src/signature/subject-queries.ts +47 -7
  25. package/packages/bundled-features/src/signature/sweep.ts +32 -8
  26. package/packages/bundled-features/src/signature/web/constants.ts +12 -0
  27. package/packages/bundled-features/src/subscription-paddle/changes.json +1 -1
  28. package/packages/bundled-features/src/subscription-stripe/changes.json +6 -0
  29. package/packages/bundled-features/src/subscription-stripe/plugin-methods.ts +2 -0
  30. package/packages/bundled-features/src/subscription-stripe/verify-webhook.ts +21 -16
  31. package/packages/bundled-features/src/tenant-inactivity/handlers/keep-account.write.ts +7 -3
  32. package/packages/bundled-features/src/tenant-lifecycle/changes.json +6 -0
  33. package/packages/bundled-features/src/tenant-lifecycle/run-tenant-destroy.ts +90 -42
  34. package/samples/apps/use-all-bundled/feature-manifest.json +2 -1
  35. package/samples/recipes/crypto-shredding-hr/README.md +1 -1
  36. package/samples/recipes/crypto-shredding-hr/src/feature.ts +1 -1
  37. package/samples/recipes/list-table-options/README.md +9 -3
  38. package/samples/recipes/list-table-options/src/feature.ts +123 -3
@@ -122,13 +122,34 @@ function unfilterRows(raw: Uint8Array, header: Header): boolean {
122
122
  }
123
123
 
124
124
  function countInkPixels(raw: Uint8Array, header: Header): number {
125
- const stride = header.width * header.bytesPerPixel + 1;
125
+ const bytesPerPixel = header.bytesPerPixel;
126
+ const stride = header.width * bytesPerPixel + 1;
127
+ const pixelStart = (row: number, column: number): number =>
128
+ row * stride + 1 + column * bytesPerPixel;
129
+ const background = pixelStart(0, 0);
130
+ const alphaOf = (start: number): number => raw[start + bytesPerPixel - 1] ?? 0;
131
+ const colorMatchesBackground = (start: number): boolean => {
132
+ for (let i = 0; i < bytesPerPixel; i++) {
133
+ if (raw[start + i] !== raw[background + i]) return false;
134
+ }
135
+ return true;
136
+ };
137
+ // Only four identical, opaque corners mean a solid background; a single opaque pixel could be a stroke.
138
+ const corners = [
139
+ background,
140
+ pixelStart(0, header.width - 1),
141
+ pixelStart(header.height - 1, 0),
142
+ pixelStart(header.height - 1, header.width - 1),
143
+ ];
144
+ const hasSolidBackground = corners.every(
145
+ (corner) => alphaOf(corner) > 0 && colorMatchesBackground(corner),
146
+ );
126
147
  let ink = 0;
127
148
  for (let row = 0; row < header.height; row++) {
128
149
  for (let column = 0; column < header.width; column++) {
129
- const alphaIndex =
130
- row * stride + 1 + column * header.bytesPerPixel + header.bytesPerPixel - 1;
131
- if ((raw[alphaIndex] ?? 0) > 0) ink++;
150
+ const start = pixelStart(row, column);
151
+ const isInk = alphaOf(start) > 0 && (!hasSolidBackground || !colorMatchesBackground(start));
152
+ if (isInk) ink++;
132
153
  }
133
154
  }
134
155
  return ink;
@@ -2,12 +2,14 @@ import {
2
2
  DEFAULT_LIST_LIMIT,
3
3
  entityListSchema,
4
4
  type HandlerContext,
5
+ isUuid,
5
6
  MAX_LIST_LIMIT,
6
7
  type QueryHandlerDef,
7
8
  type SessionUser,
8
9
  } from "@cosmicdrift/kumiko-framework/engine";
9
10
  import { AccessDeniedError } from "@cosmicdrift/kumiko-framework/errors";
10
11
  import { requestExecutor } from "./entity.ts";
12
+ import { openListCursor, sealListCursor } from "./list-cursor-seal.ts";
11
13
  import type { SubjectScope } from "./subject-scope.ts";
12
14
 
13
15
  type ListPayload = ReturnType<typeof entityListSchema.parse>;
@@ -45,7 +47,44 @@ const MAX_BASE_PAGES_PER_ANSWER = 10;
45
47
  // authorizeSubject usually queries the database; a page of 200 subjects must not take the whole pool.
46
48
  const SUBJECT_CHECKS_IN_PARALLEL = 10;
47
49
 
48
- export function scopeRequestList(base: QueryHandlerDef, scope: SubjectScope): QueryHandlerDef {
50
+ type ListQuery = Parameters<QueryHandlerDef["handler"]>[0];
51
+
52
+ async function openFirstQuery(
53
+ query: ListQuery,
54
+ payload: ListPayload,
55
+ user: SessionUser,
56
+ cursorSecret: string,
57
+ ): Promise<ListQuery> {
58
+ const { cursor: sealedCursor, ...payloadWithoutCursor } = payload;
59
+ if (sealedCursor === undefined) return query;
60
+ const openedCursor = await openListCursor(sealedCursor, user, cursorSecret);
61
+ if (openedCursor === null) throw new AccessDeniedError();
62
+ return { ...query, payload: { ...payloadWithoutCursor, cursor: openedCursor } };
63
+ }
64
+
65
+ async function sealedPage(
66
+ page: RowsPage,
67
+ visibleRows: unknown[],
68
+ nextCursor: unknown,
69
+ user: SessionUser,
70
+ cursorSecret: string,
71
+ ) {
72
+ // `total` would count requests of foreign subjects. The base cursor names the last base row,
73
+ // which may belong to a foreign subject, so the user only gets it sealed.
74
+ const { total: _total, rows: _rows, nextCursor: _baseCursor, ...rest } = page;
75
+ return {
76
+ ...rest,
77
+ rows: visibleRows,
78
+ nextCursor:
79
+ typeof nextCursor === "string" ? await sealListCursor(nextCursor, user, cursorSecret) : null,
80
+ };
81
+ }
82
+
83
+ export function scopeRequestList(
84
+ base: QueryHandlerDef,
85
+ scope: SubjectScope,
86
+ cursorSecret: string,
87
+ ): QueryHandlerDef {
49
88
  return {
50
89
  ...base,
51
90
  handler: async (query, ctx) => {
@@ -53,14 +92,16 @@ export function scopeRequestList(base: QueryHandlerDef, scope: SubjectScope): Qu
53
92
  if (!scope.isScoped(user)) return base.handler(query, ctx);
54
93
  const payload = entityListSchema.parse(query.payload);
55
94
  // Group counts would include requests of foreign subjects, and an offset counts base rows,
56
- // not the rows this user sees; the screen pages by cursor.
57
- if (payload.aggregate !== undefined || (payload.offset ?? 0) > 0) {
95
+ // not the rows this user sees; the screen pages by cursor. limit 0 would hand out a cursor
96
+ // without checking a row.
97
+ if (payload.aggregate !== undefined || (payload.offset ?? 0) > 0 || payload.limit === 0) {
58
98
  throw new AccessDeniedError();
59
99
  }
60
100
  const limit = payload.limit ?? DEFAULT_LIST_LIMIT;
61
101
  const verdicts = new Map<string, boolean>();
62
102
  const visibleRows: unknown[] = [];
63
- let page: unknown = await base.handler(query, ctx);
103
+ const firstQuery = await openFirstQuery(query, payload, user, cursorSecret);
104
+ let page: unknown = await base.handler(firstQuery, ctx);
64
105
  for (let fetched = 1; ; fetched++) {
65
106
  if (!isRowsPage(page)) throw new Error("signature request list did not return a rows page");
66
107
  const unknownSubjects = new Map(
@@ -84,9 +125,7 @@ export function scopeRequestList(base: QueryHandlerDef, scope: SubjectScope): Qu
84
125
  fetched >= MAX_BASE_PAGES_PER_ANSWER ||
85
126
  verdicts.size >= MAX_LIST_LIMIT
86
127
  ) {
87
- // `total` would count requests of foreign subjects; the cursor continues after the last base page.
88
- const { total: _total, rows: _rows, ...rest } = page;
89
- return { ...rest, rows: visibleRows };
128
+ return sealedPage(page, visibleRows, nextCursor, user, cursorSecret);
90
129
  }
91
130
  page = await base.handler(
92
131
  {
@@ -134,6 +173,7 @@ export function scopeSignerList(base: QueryHandlerDef, scope: SubjectScope): Que
134
173
  ) {
135
174
  throw new AccessDeniedError();
136
175
  }
176
+ if (!isUuid(requestFilter.value)) return emptyPage(payload);
137
177
  const request = await requestExecutor.detail({ id: requestFilter.value }, user, ctx.db);
138
178
  if (request === null || !(await scope.allowsRequest(ctx, user, request))) {
139
179
  return emptyPage(payload);
@@ -24,8 +24,10 @@ import {
24
24
  type SignaturePageEntry,
25
25
  } from "./signature-page.ts";
26
26
  import {
27
+ SIGNATURE_FAILURE_REASON,
27
28
  SIGNATURE_METHOD,
28
29
  SIGNATURE_REQUEST_STATUS,
30
+ type SignatureFailureReason,
29
31
  SignatureInternalHandlers,
30
32
  } from "./web/constants.ts";
31
33
 
@@ -85,8 +87,34 @@ async function signaturePageEntries(
85
87
  return entries;
86
88
  }
87
89
 
88
- // Appends the signature page to the unchanged original. A renderer outage throws, the request
89
- // stays all-signed and the next run tries again.
90
+ async function failRequest(
91
+ ctx: JobContext,
92
+ request: RequestRow,
93
+ reason: SignatureFailureReason,
94
+ ): Promise<void> {
95
+ const failed = await ctx.dispatch.write(SignatureInternalHandlers.fail, {
96
+ requestId: request.id,
97
+ reason,
98
+ });
99
+ if (!failed.isSuccess) {
100
+ ctx.obs.log.error("[signature:sweep] marking the request failed was rejected", {
101
+ requestId: request.id,
102
+ reason,
103
+ error: failed.error,
104
+ });
105
+ return;
106
+ }
107
+ if (propertyOf(failed.data, "failed") === true) {
108
+ ctx.obs.log.warn("[signature:sweep] request cannot be completed, marked failed", {
109
+ requestId: request.id,
110
+ reason,
111
+ });
112
+ }
113
+ }
114
+
115
+ // Appends the signature page to the unchanged original. A missing or changed original or a
116
+ // missing signature image can never heal and ends the request as failed. A renderer outage
117
+ // throws, the request stays all-signed and the next run tries again.
90
118
  async function finalizeRequest(
91
119
  ctx: JobContext,
92
120
  opts: SignatureOptions,
@@ -94,9 +122,7 @@ async function finalizeRequest(
94
122
  ): Promise<void> {
95
123
  const original = await readTenantFile(ctx, ctx.systemUser.tenantId, request.documentFileId);
96
124
  if (original === null || sha256Hex(original.content) !== request.documentSha256) {
97
- ctx.obs.log.warn("[signature:sweep] original document missing or changed, not completing", {
98
- requestId: request.id,
99
- });
125
+ await failRequest(ctx, request, SIGNATURE_FAILURE_REASON.DocumentChanged);
100
126
  return;
101
127
  }
102
128
  const entries = await signaturePageEntries(
@@ -104,9 +130,7 @@ async function finalizeRequest(
104
130
  await listSigners(ctx, ctx.systemUser, request.id),
105
131
  );
106
132
  if (entries === null) {
107
- ctx.obs.log.warn("[signature:sweep] signature image missing, not completing", {
108
- requestId: request.id,
109
- });
133
+ await failRequest(ctx, request, SIGNATURE_FAILURE_REASON.SignatureImageMissing);
110
134
  return;
111
135
  }
112
136
  const html = buildSignaturePageHtml({
@@ -16,6 +16,7 @@ export const SIGNATURE_REQUEST_STATUS = {
16
16
  Completed: "completed",
17
17
  Declined: "declined",
18
18
  Expired: "expired",
19
+ Failed: "failed",
19
20
  Cancelled: "cancelled",
20
21
  } as const;
21
22
 
@@ -64,12 +65,22 @@ export const SIGNATURE_EVENT_SHORT = {
64
65
  completed: "completed",
65
66
  declined: "declined",
66
67
  expired: "expired",
68
+ failed: "failed",
67
69
  } as const;
68
70
 
71
+ export const SIGNATURE_FAILURE_REASON = {
72
+ DocumentChanged: "document-changed",
73
+ SignatureImageMissing: "signature-image-missing",
74
+ } as const;
75
+
76
+ export type SignatureFailureReason =
77
+ (typeof SIGNATURE_FAILURE_REASON)[keyof typeof SIGNATURE_FAILURE_REASON];
78
+
69
79
  export const SignatureEvents = {
70
80
  completed: `${SIGNATURE_FEATURE}:event:${SIGNATURE_EVENT_SHORT.completed}`,
71
81
  declined: `${SIGNATURE_FEATURE}:event:${SIGNATURE_EVENT_SHORT.declined}`,
72
82
  expired: `${SIGNATURE_FEATURE}:event:${SIGNATURE_EVENT_SHORT.expired}`,
83
+ failed: `${SIGNATURE_FEATURE}:event:${SIGNATURE_EVENT_SHORT.failed}`,
73
84
  } as const;
74
85
 
75
86
  // Every link rejection (forged, expired, revoked, used up, already signed) carries this reason, so
@@ -88,5 +99,6 @@ export const SignatureInternalHandlers = {
88
99
  linkDecline: `${SIGNATURE_FEATURE}:write:link-decline`,
89
100
  finish: `${SIGNATURE_FEATURE}:write:finish`,
90
101
  expire: `${SIGNATURE_FEATURE}:write:expire`,
102
+ fail: `${SIGNATURE_FEATURE}:write:fail`,
91
103
  reconcile: `${SIGNATURE_FEATURE}:write:reconcile`,
92
104
  } as const;
@@ -3,7 +3,7 @@
3
3
  "version": "0.415.0",
4
4
  "type": "fix",
5
5
  "title": "unreadable ledger backfill marker no longer causes endless 503",
6
- "detail": "shouldRedeliverLegacyCheckout answers 200 and logs when the marker dispatch fails, because custom_data.tenantBinding is client-settable."
6
+ "detail": "shouldRedeliverLegacyCheckout answers 200 and logs only when the marker dispatch fails with a configuration error (access_denied, not_found, feature_disabled), because custom_data.tenantBinding is client-settable; other dispatch failures still answer 503 so Paddle redelivers a bounded number of times."
7
7
  },
8
8
  {
9
9
  "version": "0.414.0",
@@ -1,4 +1,10 @@
1
1
  [
2
+ {
3
+ "version": "0.418.0",
4
+ "type": "fix",
5
+ "title": "One-off checkouts with a 100% promo code are booked",
6
+ "detail": "A Stripe checkout session in payment mode that a 100% promo code makes free is now booked like a paid one: the handler reads the session metadata in payment mode. Sessions created before the upgrade carry no session metadata and are still discarded."
7
+ },
2
8
  {
3
9
  "version": "0.416.0",
4
10
  "type": "improvement",
@@ -160,6 +160,8 @@ export function createStripeCheckoutSession(
160
160
  ...(mode === "subscription"
161
161
  ? { subscription_data: { metadata } }
162
162
  : {
163
+ // Session metadata too: a 100% promotion code completes without a PaymentIntent.
164
+ metadata,
163
165
  payment_intent_data: { metadata },
164
166
  invoice_creation: { enabled: paymentInvoiceCreation },
165
167
  // Without a customer, Stripe's default "if_required" makes a guest
@@ -399,9 +399,13 @@ async function parsePaymentEvent(
399
399
  ): Promise<PaymentEvent | null> {
400
400
  const session = event.data.object as Stripe.Checkout.Session; // @cast-boundary engine-bridge
401
401
  // mode !== "payment" excludes subscription-checkout sessions (same event types);
402
- // payment_status !== "paid" excludes an unpaid/expired session. Null here — not an
403
- // error — maps to foundation's 200 "ignored", same as the subscription-path's filters.
404
- if (session.mode !== "payment" || session.payment_status !== "paid") {
402
+ // any status but paid / no_payment_required (a 100% promotion code) excludes an
403
+ // unpaid/expired session. Null here — not an error — maps to foundation's 200 "ignored",
404
+ // same as the subscription-path's filters.
405
+ if (
406
+ session.mode !== "payment" ||
407
+ (session.payment_status !== "paid" && session.payment_status !== "no_payment_required")
408
+ ) {
405
409
  return null;
406
410
  }
407
411
 
@@ -420,21 +424,22 @@ async function parsePaymentEvent(
420
424
  throw transientProviderRejection(error);
421
425
  }
422
426
 
423
- // Tenant-resolution: mode:"payment" checkout sessions carry tenantId on
424
- // the PaymentIntent's OWN metadata (plugin-methods.ts sets it via
425
- // payment_intent_data.metadata), NOT on session-level metadata —
426
- // session.metadata is unset for this mode. Reading it off the expanded,
427
- // Stripe-verified PaymentIntent (not a freely-choosable payload field) is
428
- // what keeps tenant-attribution trustworthy: the webhook signature proves
429
- // this whole object chain came from Stripe, and the metadata itself was
430
- // set by our own backend at checkout-creation time.
427
+ // Tenant-resolution: plugin-methods.ts sets tenantId on the PaymentIntent metadata and on the
428
+ // session metadata. A 100% promotion code creates no PaymentIntent, so the session metadata
429
+ // is only read then. Both are set by our own backend at checkout-creation time and reach us
430
+ // through the signature-verified webhook chain, not as a freely-choosable payload field.
431
431
  const paymentIntent = expanded.payment_intent;
432
- if (!paymentIntent || typeof paymentIntent === "string") {
433
- // Not expanded (Stripe-API-drift) or absent — no verified tenant-claim
432
+ if (
433
+ typeof paymentIntent === "string" ||
434
+ (paymentIntent === null && session.payment_status === "paid")
435
+ ) {
436
+ // Not expanded (Stripe-API-drift) or absent on a paid session — no verified tenant-claim
434
437
  // to trust.
435
438
  return dropPaidSession(event, session, "payment_intent_not_expanded");
436
439
  }
437
- const tenantId = paymentIntent.metadata?.["tenantId"];
440
+ const tenantId = paymentIntent
441
+ ? paymentIntent.metadata?.["tenantId"]
442
+ : expanded.metadata?.["tenantId"];
438
443
  if (!tenantId || tenantId.length === 0) {
439
444
  return dropPaidSession(event, session, "missing_tenant_id");
440
445
  }
@@ -450,9 +455,9 @@ async function parsePaymentEvent(
450
455
  const sessionCustomer = expanded.customer;
451
456
  const providerCustomerId =
452
457
  (typeof sessionCustomer === "string" ? sessionCustomer : sessionCustomer?.id) ??
453
- (typeof paymentIntent.customer === "string"
458
+ (typeof paymentIntent?.customer === "string"
454
459
  ? paymentIntent.customer
455
- : paymentIntent.customer?.id);
460
+ : paymentIntent?.customer?.id);
456
461
  if (!providerCustomerId) {
457
462
  return dropPaidSession(event, session, "missing_customer");
458
463
  }
@@ -2,11 +2,13 @@ import { fetchOne, updateMany } from "@cosmicdrift/kumiko-framework/db";
2
2
  import { defineWriteHandler } from "@cosmicdrift/kumiko-framework/engine";
3
3
  import { UnprocessableError, writeFailure } from "@cosmicdrift/kumiko-framework/errors";
4
4
  import * as z from "zod";
5
- import { tenantTable } from "../../tenant/index.ts";
5
+ import { type TenantLifecycleStatus, tenantTable } from "../../tenant/index.ts";
6
6
  import { redeemKeepAccountToken } from "../keep-token.ts";
7
7
  import { lockInactivityCycle } from "../state-store.ts";
8
8
  import { tenantInactivityStateTable } from "../state-table.ts";
9
9
 
10
+ const KEEPABLE_TENANT_STATUS: TenantLifecycleStatus = "active";
11
+
10
12
  const KEEP_ACCOUNT_ESCAPE_HATCH_REASON =
11
13
  "the anonymous link holder has no tenant scope; the tenant comes from the signed token and every statement filters by that tenantId";
12
14
 
@@ -41,8 +43,10 @@ export function createKeepAccountHandler(opts: { readonly keepAccountTokenSecret
41
43
  commitKeep: async (tenantId, cycleId) => {
42
44
  await lockInactivityCycle(runner, tenantId);
43
45
  // A destruction request that won the lock owns the tenant now; reporting "kept" would be a lie.
44
- const tenant = await fetchOne<{ status: string }>(runner, tenantTable, { id: tenantId });
45
- if (tenant?.status !== "active") return false;
46
+ const tenant = await fetchOne<{ status: TenantLifecycleStatus }>(runner, tenantTable, {
47
+ id: tenantId,
48
+ });
49
+ if (tenant?.status !== KEEPABLE_TENANT_STATUS) return false;
46
50
  const updated = await updateMany(
47
51
  runner,
48
52
  tenantInactivityStateTable,
@@ -1,4 +1,10 @@
1
1
  [
2
+ {
3
+ "version": "0.418.0",
4
+ "type": "fix",
5
+ "title": "The tenant destruction sweep locks per tenant",
6
+ "detail": "Overlapping sweeps no longer push a tenant into `destroyFailed`. Each sweep takes a session advisory lock per tenant and skips tenants another sweep holds for that tick; failed stage attempts and abandoned stages are now logged with tenant and stage."
7
+ },
2
8
  {
3
9
  "version": "0.415.0",
4
10
  "type": "fix",
@@ -5,6 +5,7 @@ import {
5
5
  createTenantDb,
6
6
  fetchOne,
7
7
  selectMany,
8
+ tryWithSessionAdvisoryLock,
8
9
  WritePurposes,
9
10
  } from "@cosmicdrift/kumiko-framework/db";
10
11
  import {
@@ -54,6 +55,21 @@ const tenantCrud = createEventStoreExecutor(tenantTable, tenantEntity, { entityN
54
55
 
55
56
  const FEATURE_PREFIX = "tenant-lifecycle:event:";
56
57
 
58
+ const TENANT_DESTRUCTION_LOCK_NAMESPACE = 0x74_64_65_73; // 'tdes'
59
+ const FNV32_OFFSET = 0x81_1c_9d_c5;
60
+ const FNV32_PRIME = 0x01_00_01_93;
61
+
62
+ // Cron ticks of the destruction job overlap (concurrency:"skip" does not hold across ticks),
63
+ // and two sweeps on one tenant make the loser's version conflict count as a failed stage
64
+ // attempt. A hash collision between tenants only skips one tick for the other tenant.
65
+ function tenantDestructionLockKey(tenantId: TenantId): number {
66
+ let hash = FNV32_OFFSET;
67
+ for (let i = 0; i < tenantId.length; i++) {
68
+ hash = Math.imul(hash ^ tenantId.charCodeAt(i), FNV32_PRIME);
69
+ }
70
+ return (hash ^ TENANT_DESTRUCTION_LOCK_NAMESPACE) | 0;
71
+ }
72
+
57
73
  type StageEventName =
58
74
  | typeof TENANT_DESTRUCTION_STARTED_EVENT_SHORT
59
75
  | typeof TENANT_DESTRUCTION_STAGE_STARTED_EVENT_SHORT
@@ -277,7 +293,11 @@ async function haltPipelineOnAbandon(args: {
277
293
  readonly stage: string;
278
294
  readonly attempts: number;
279
295
  readonly error: string;
296
+ readonly log?: (message: string) => void;
280
297
  }): Promise<void> {
298
+ args.log?.(
299
+ `[tenant-lifecycle] destruction halted: tenant ${args.tenantId} stage "${args.stage}" abandoned after ${args.attempts} attempt(s): ${args.error}`,
300
+ );
281
301
  const T = getTemporal();
282
302
  const failedAt = T.Now.instant();
283
303
  // Reload fresh instead of trusting a caller-supplied version: the failed
@@ -346,7 +366,11 @@ async function recordFailedStageAttempt(args: {
346
366
  readonly attempt: number;
347
367
  readonly error: string;
348
368
  readonly version: number;
369
+ readonly log?: (message: string) => void;
349
370
  }): Promise<StageTickResult> {
371
+ args.log?.(
372
+ `[tenant-lifecycle] stage attempt failed: tenant ${args.tenantId} stage "${args.stage.name}" attempt ${args.attempt}/${args.stage.maxAttempts}: ${args.error}`,
373
+ );
350
374
  if (args.attempt >= args.stage.maxAttempts) {
351
375
  await haltPipelineOnAbandon({
352
376
  db: args.db,
@@ -354,6 +378,7 @@ async function recordFailedStageAttempt(args: {
354
378
  stage: args.stage.name,
355
379
  attempts: args.attempt,
356
380
  error: args.error,
381
+ log: args.log,
357
382
  });
358
383
  return { done: false, error: args.error, halted: true };
359
384
  }
@@ -379,6 +404,7 @@ async function recordIdleStageTick(args: {
379
404
  readonly pending: boolean;
380
405
  readonly events: readonly StoredEvent[];
381
406
  readonly now: Temporal.Instant;
407
+ readonly log?: (message: string) => void;
382
408
  }): Promise<StageTickResult> {
383
409
  if (args.pending && isPendingWindowOpen(args.events, args.stage.name, args.now)) {
384
410
  await appendTenantStageEvent(
@@ -405,6 +431,7 @@ async function recordIdleStageTick(args: {
405
431
  ? `stage "${args.stage.name}" still pending after ${DESTRUCTION_STAGE_MAX_PENDING_MS / 60_000} min`
406
432
  : `stage "${args.stage.name}" made no progress`,
407
433
  version: lastEventVersion(args.events),
434
+ log: args.log,
408
435
  });
409
436
  }
410
437
 
@@ -493,6 +520,7 @@ export async function runNextDestructionStage(args: {
493
520
  pending: outcome.pending === true,
494
521
  events: eventsAfterRun,
495
522
  now,
523
+ log: args.log,
496
524
  });
497
525
  }
498
526
  if (!outcome.done) {
@@ -529,6 +557,7 @@ export async function runNextDestructionStage(args: {
529
557
  attempt,
530
558
  error: err instanceof Error ? err.message : String(err),
531
559
  version,
560
+ log: args.log,
532
561
  });
533
562
  }
534
563
  }
@@ -591,36 +620,46 @@ export async function runTenantDestructionSweep(args: {
591
620
  let triggered = 0;
592
621
  for (const row of due) {
593
622
  const tenantId = row.id;
594
- const events = await loadAggregate(args.db, tenantId, SYSTEM_TENANT_ID);
595
- const version = lastEventVersion(events);
596
- const user = createSystemUser(tenantId);
597
- const scopedDb = createTenantDb({
598
- db: args.db,
599
- tenantId,
600
- mode: "system",
601
- reason: "tenant destruction updates the tenant being destroyed, outside its request scope",
602
- });
603
- // Version-guarded (no skipOptimisticLock): a concurrent cancel-destruction
604
- // between the `due` select above and this write also appends to the same
605
- // tenant stream, so an unguarded overwrite here would silently revert the
606
- // cancellation. A version conflict means we lost that race — skip, the
607
- // tenant is no longer due and the next tick re-evaluates it.
608
- const result = await tenantCrud.update(
609
- { id: tenantId, version, changes: { status: "destroying", destroyStartedAt: now } },
610
- user,
611
- scopedDb,
612
- { writePurpose: WritePurposes.erasure },
613
- );
614
- if (!result.isSuccess) continue;
615
- invalidateTenantLifecycleGate(tenantId);
616
- await appendTenantStageEvent(
623
+ const locked = await tryWithSessionAdvisoryLock(
617
624
  args.db,
618
- tenantId,
619
- qualified(TENANT_DESTRUCTION_STARTED_EVENT_SHORT),
620
- { startedAt: now.toString() },
621
- version + 1,
625
+ tenantDestructionLockKey(tenantId),
626
+ async () => {
627
+ // A peer sweep may have started this tenant after our `due` select.
628
+ if ((await tenantStatusOf(args.db, tenantId)) !== "destroyRequested") return false;
629
+ const events = await loadAggregate(args.db, tenantId, SYSTEM_TENANT_ID);
630
+ const version = lastEventVersion(events);
631
+ const user = createSystemUser(tenantId);
632
+ const scopedDb = createTenantDb({
633
+ db: args.db,
634
+ tenantId,
635
+ mode: "system",
636
+ reason:
637
+ "tenant destruction updates the tenant being destroyed, outside its request scope",
638
+ });
639
+ // Version-guarded (no skipOptimisticLock): a concurrent cancel-destruction
640
+ // between the `due` select above and this write also appends to the same
641
+ // tenant stream, so an unguarded overwrite here would silently revert the
642
+ // cancellation. A version conflict means we lost that race — skip, the
643
+ // tenant is no longer due and the next tick re-evaluates it.
644
+ const result = await tenantCrud.update(
645
+ { id: tenantId, version, changes: { status: "destroying", destroyStartedAt: now } },
646
+ user,
647
+ scopedDb,
648
+ { writePurpose: WritePurposes.erasure },
649
+ );
650
+ if (!result.isSuccess) return false;
651
+ invalidateTenantLifecycleGate(tenantId);
652
+ await appendTenantStageEvent(
653
+ args.db,
654
+ tenantId,
655
+ qualified(TENANT_DESTRUCTION_STARTED_EVENT_SHORT),
656
+ { startedAt: now.toString() },
657
+ version + 1,
658
+ );
659
+ return true;
660
+ },
622
661
  );
623
- triggered++;
662
+ if (locked.acquired && locked.value) triggered++;
624
663
  }
625
664
 
626
665
  let advanced = 0;
@@ -636,20 +675,29 @@ export async function runTenantDestructionSweep(args: {
636
675
  for (const row of destroying) {
637
676
  const tenantDeadlineAt = Date.now() + sliceMs;
638
677
  try {
639
- const result = await runNextDestructionStage({
640
- deadlineAt: tenantDeadlineAt,
641
- now,
642
- db: args.db,
643
- registry: args.registry,
644
- tenantId: row.id,
645
- log: args.log,
646
- fileProviderResolver: args.fileProviderResolver,
647
- searchAdapter: args.searchAdapter,
648
- escapeHatchAuditSink: args.escapeHatchAuditSink,
649
- escapeHatchAuditLog: args.escapeHatchAuditLog,
650
- actor: args.actor,
651
- });
652
- if (!result.error && !result.halted && !result.held) advanced++;
678
+ const locked = await tryWithSessionAdvisoryLock(
679
+ args.db,
680
+ tenantDestructionLockKey(row.id),
681
+ async () => {
682
+ // A peer sweep may have finished or halted this tenant after our `destroying` select.
683
+ if ((await tenantStatusOf(args.db, row.id)) !== "destroying") return undefined;
684
+ return await runNextDestructionStage({
685
+ deadlineAt: tenantDeadlineAt,
686
+ now,
687
+ db: args.db,
688
+ registry: args.registry,
689
+ tenantId: row.id,
690
+ log: args.log,
691
+ fileProviderResolver: args.fileProviderResolver,
692
+ searchAdapter: args.searchAdapter,
693
+ escapeHatchAuditSink: args.escapeHatchAuditSink,
694
+ escapeHatchAuditLog: args.escapeHatchAuditLog,
695
+ actor: args.actor,
696
+ });
697
+ },
698
+ );
699
+ const result = locked.acquired ? locked.value : undefined;
700
+ if (result && !result.error && !result.halted && !result.held) advanced++;
653
701
  } catch (err) {
654
702
  // Isolate the failure to this tenant — an uncaught throw here must not
655
703
  // abort the whole sweep tick and starve every other "destroying" tenant
@@ -2679,7 +2679,7 @@
2679
2679
  },
2680
2680
  {
2681
2681
  "name": "signature",
2682
- "description": "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.",
2682
+ "description": "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, expired and failed report the outcome; signer name, email, image, IP and user agent are personal data.",
2683
2683
  "toggleableDefault": null,
2684
2684
  "adoptsBundledLists": true,
2685
2685
  "requires": [
@@ -2702,6 +2702,7 @@
2702
2702
  "signature:write:cancel",
2703
2703
  "signature:write:decline-by-link",
2704
2704
  "signature:write:expire",
2705
+ "signature:write:fail",
2705
2706
  "signature:write:finish",
2706
2707
  "signature:write:issue-link",
2707
2708
  "signature:write:link-decline",
@@ -80,6 +80,6 @@ handler marked `agent: { risk: "high" }`. A job or an event consumer has no hand
80
80
  `irreversibleWithoutEntryHandler` on `r.job` or `r.multiStreamProjection`, or the gate refuses with
81
81
  `irreversible_operation_without_entry_handler`. The value names why no entry handler exists:
82
82
  `rebuildable-derived-data` (the data is derived and a rebuild recreates it), `high-risk-or-cron-pipeline`
83
- (a maintenance pipeline that is high-risk by design, like `purge-archived-comments`) or
83
+ (a manually started or cron pipeline that is high-risk by design, like `purge-archived-comments`) or
84
84
  `per-dispatch-record-key` (the key belongs to one dispatch record). Hooks and routes never inherit the
85
85
  declaration; they dispatch a `risk: "high"` handler instead.
@@ -50,7 +50,7 @@ export const hrFeature = defineFeature("hr", (r) => {
50
50
  r.job(
51
51
  "purge-archived-comments",
52
52
  {
53
- trigger: { maintenance: true },
53
+ trigger: { manual: true },
54
54
  runIn: "worker",
55
55
  irreversibleWithoutEntryHandler: "high-risk-or-cron-pipeline",
56
56
  },
@@ -21,7 +21,13 @@ the `table` block renders and behaves as before.
21
21
  file; `maxRows` lowers the default limit of 10000 rows.
22
22
  Reference columns export their label and timestamps use the browser time zone.
23
23
  - `bulkActions`: row checkboxes and a selection bar. "Delete" runs the delete
24
- row action once per selected row; done tasks are skipped.
24
+ row action once per selected row (done tasks are skipped); "Set status" opens
25
+ an actionForm once for the whole selection. Its `taskIds` field is a
26
+ `multiSelect` with `display: "count"`, and the `task:set-status` handler
27
+ updates every id in one write, bounded by `.max(MAX_BULK_SELECTION)` and
28
+ reading each id through the tenant-scoped executor. The form has a `preview`:
29
+ the `task:set-status-preview` query returns the affected tasks with old and
30
+ new status from the same plan function the handler applies.
25
31
  - `table.grouping`: the server groups the list by status; each header shows the
26
32
  group's count and estimate sum, "done" starts collapsed and the view menu
27
33
  offers grouping by priority or none.
@@ -54,6 +60,6 @@ bun test
54
60
  The test boots the feature through the boot validator and checks that a
55
61
  misspelled key, a hidden column without the picker, an unknown density, a pinned column
56
62
  without `pinning`, a width without `resizing` and a bulk action on a navigate
57
- row action are rejected.
63
+ row action, a form bulk action whose `idsField` is no count list and a preview over an unknown query or field are rejected.
58
64
  `workload.integration.test.ts` runs the hand-written query over HTTP and checks
59
- the grouped sums and the filtered total.
65
+ the grouped sums and the filtered total, the preview query, and the handler's unknown-id and over-cap rejections.