@hotmeshio/hotmesh 0.26.2 → 0.27.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.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hotmeshio/hotmesh",
3
- "version": "0.26.2",
3
+ "version": "0.27.0",
4
4
  "description": "Durable Workflow",
5
5
  "main": "./build/index.js",
6
6
  "types": "./build/index.d.ts",
@@ -362,8 +362,8 @@ class Hook extends activity_1.Activity {
362
362
  if (pending) {
363
363
  await this.redeliverPendingSignal(pending);
364
364
  }
365
- // Post-commit: fire the escalation.created event using the row returned
366
- // directly from the RETURNING * clause — no extra SELECT.
365
+ // Post-commit: fire the escalation lifecycle events using the row
366
+ // returned directly from the RETURNING * clause — no extra SELECT.
367
367
  if (escalationSignalKey) {
368
368
  const store = this.store;
369
369
  if (store.eventsPublish) {
@@ -371,9 +371,9 @@ class Hook extends activity_1.Activity {
371
371
  if (row?.id) {
372
372
  const ts = new Date().toISOString();
373
373
  const updatedAt = row.updated_at ? new Date(row.updated_at).toISOString() : ts;
374
- void Promise.resolve(store.eventsPublish({
375
- event_id: `${row.id}:created:${updatedAt}`,
376
- type: `system.escalation.${row.id}.created`,
374
+ const publish = (verb, extras) => void Promise.resolve(store.eventsPublish({
375
+ event_id: `${row.id}:${verb}:${updatedAt}`,
376
+ type: `system.escalation.${row.id}.${verb}`,
377
377
  ts,
378
378
  namespace: row.namespace ?? this.engine.namespace ?? this.engine.appId,
379
379
  app_id: row.app_id ?? this.engine.appId,
@@ -383,8 +383,16 @@ class Hook extends activity_1.Activity {
383
383
  parent_id: row.parent_id ?? undefined,
384
384
  trace_id: row.trace_id ?? undefined,
385
385
  span_id: row.span_id ?? undefined,
386
+ ...extras,
386
387
  data: row,
387
388
  })).catch(() => { });
389
+ publish('created');
390
+ // A born-assigned row is created AND claimed in the same Leg1
391
+ // commit — state both, in that order, so hand-off consumers act
392
+ // on the canonical claimed event instead of inferring from timing.
393
+ if (row.assigned_to != null) {
394
+ publish('claimed', { assigned_at_creation: true });
395
+ }
388
396
  }
389
397
  }
390
398
  }
@@ -429,13 +437,16 @@ class Hook extends activity_1.Activity {
429
437
  metadata: resolveObj(escalationConfig.metadata),
430
438
  envelope: resolveObj(escalationConfig.envelope),
431
439
  expiresAt: resolveField(escalationConfig.expiresAt),
440
+ assignee: resolveField(escalationConfig.assignee),
441
+ durationMinutes: resolveField(escalationConfig.durationMinutes),
432
442
  taskQueue: resolveField(escalationConfig.taskQueue),
433
443
  workflowType: resolveField(escalationConfig.workflowType),
434
444
  };
435
445
  // Skip the INSERT when no escalation fields resolved — this happens when
436
446
  // the factory waiter runs for a condition() call that had no queueConfig.
437
447
  if (params.role == null && params.type == null &&
438
- params.priority == null && params.metadata == null)
448
+ params.priority == null && params.metadata == null &&
449
+ params.assignee == null)
439
450
  return null;
440
451
  const signalKey = await this.deriveEscalationSignalKey();
441
452
  store.addEscalationToTransaction({
@@ -1,4 +1,4 @@
1
- declare const APP_VERSION = "17";
1
+ declare const APP_VERSION = "18";
2
2
  declare const APP_ID = "durable";
3
3
  /**
4
4
  * returns a new durable workflow schema
@@ -6,9 +6,10 @@ exports.APP_ID = exports.APP_VERSION = exports.getWorkflowYAML = void 0;
6
6
  // schema upgrade and hot-swap to it (see WorkerService.activateWorkflow and
7
7
  // ClientService.deployAndActivate). Changing the YAML without a bump leaves
8
8
  // every already-deployed database on the old schema forever. Numeric string —
9
- // compared with `Number()` for ordering. (v17: collator_waiter escalation block —
10
- // escalation-bearing condition() inside Promise.all writes its hmsh_escalations row.)
11
- const APP_VERSION = '17';
9
+ // compared with `Number()` for ordering. (v18: assign-at-creation — the
10
+ // escalation blocks forward queueConfig.assignee/durationMinutes so a
11
+ // condition() row is born assigned in the Leg1 commit.)
12
+ const APP_VERSION = '18';
12
13
  exports.APP_VERSION = APP_VERSION;
13
14
  const APP_ID = 'durable';
14
15
  exports.APP_ID = APP_ID;
@@ -395,6 +396,8 @@ const getWorkflowYAML = (app, version) => {
395
396
  traceId: '{worker.output.data.queueConfig.traceId}'
396
397
  spanId: '{worker.output.data.queueConfig.spanId}'
397
398
  expiresAt: '{worker.output.data.queueConfig.expiresAt}'
399
+ assignee: '{worker.output.data.queueConfig.assignee}'
400
+ durationMinutes: '{worker.output.data.queueConfig.durationMinutes}'
398
401
  taskQueue: '{trigger.output.data.taskQueue}'
399
402
  workflowType: '{trigger.output.data.workflowName}'
400
403
  sleep: '{worker.output.data.duration}'
@@ -1210,6 +1213,8 @@ const getWorkflowYAML = (app, version) => {
1210
1213
  traceId: '{signaler_worker.output.data.queueConfig.traceId}'
1211
1214
  spanId: '{signaler_worker.output.data.queueConfig.spanId}'
1212
1215
  expiresAt: '{signaler_worker.output.data.queueConfig.expiresAt}'
1216
+ assignee: '{signaler_worker.output.data.queueConfig.assignee}'
1217
+ durationMinutes: '{signaler_worker.output.data.queueConfig.durationMinutes}'
1213
1218
  taskQueue: '{trigger.output.data.taskQueue}'
1214
1219
  workflowType: '{trigger.output.data.workflowName}'
1215
1220
  sleep: '{signaler_worker.output.data.duration}'
@@ -1986,6 +1991,8 @@ const getWorkflowYAML = (app, version) => {
1986
1991
  traceId: '{$self.output.data.queueConfig.traceId}'
1987
1992
  spanId: '{$self.output.data.queueConfig.spanId}'
1988
1993
  expiresAt: '{$self.output.data.queueConfig.expiresAt}'
1994
+ assignee: '{$self.output.data.queueConfig.assignee}'
1995
+ durationMinutes: '{$self.output.data.queueConfig.durationMinutes}'
1989
1996
  taskQueue: '{$self.output.data.taskQueue}'
1990
1997
  workflowType: '{$self.output.data.workflowName}'
1991
1998
  hook:
@@ -75,6 +75,14 @@ import { ConditionQueueConfig } from '../../../types/hmsh_escalations';
75
75
  * await client.escalations.resolve({ id: item.id, resolverPayload: { approved: true } });
76
76
  * ```
77
77
  *
78
+ * ## Assign at creation
79
+ *
80
+ * Set `assignee` in the config to write `assigned_to` in the same atomic
81
+ * commit — the row is born routed to that user (e.g. hand the follow-on step
82
+ * to `$resolution.resolvedBy` of a prior escalation) and is resolvable by
83
+ * them immediately. Add `durationMinutes` to arm the claim TTL window at
84
+ * creation, locking the row to the assignee exactly as `claim()` would.
85
+ *
78
86
  * ## Placement: call escalation-bearing waits from main workflow code
79
87
  *
80
88
  * The resolve/signal delivery pipeline routes to the main flow's waiter.
@@ -80,6 +80,14 @@ const didRun_1 = require("./didRun");
80
80
  * await client.escalations.resolve({ id: item.id, resolverPayload: { approved: true } });
81
81
  * ```
82
82
  *
83
+ * ## Assign at creation
84
+ *
85
+ * Set `assignee` in the config to write `assigned_to` in the same atomic
86
+ * commit — the row is born routed to that user (e.g. hand the follow-on step
87
+ * to `$resolution.resolvedBy` of a prior escalation) and is resolvable by
88
+ * them immediately. Add `durationMinutes` to arm the claim TTL window at
89
+ * creation, locking the row to the assignee exactly as `claim()` would.
90
+ *
83
91
  * ## Placement: call escalation-bearing waits from main workflow code
84
92
  *
85
93
  * The resolve/signal delivery pipeline routes to the main flow's waiter.
@@ -1,7 +1,13 @@
1
1
  import { HotMesh } from '../hotmesh';
2
2
  import { EventsConfig } from '../../types/system_events';
3
3
  import { Connection } from '../../types/durable';
4
- import { EscalationEntry, ClaimEscalationResult, ClaimByMetadataResult, ReleaseEscalationResult, ResolveEscalationResult, CancelEscalationResult, ListEscalationsParams, StatsEscalationsParams, EscalationStats, CreateEscalationParams, UpdateEscalationParams, AppendMilestonesParams, ClaimEscalationParams, ClaimByMetadataParams, ReleaseEscalationParams, ResolveEscalationParams, ResolveByMetadataParams, EscalateToRoleParams, MigrateEscalationParams, ClaimManyParams, EscalateManyToRoleParams, UpdateManyPriorityParams, ResolveManyParams, ResolveAllOrNoneParams, ResolveAllOrNoneResult, PruneEscalationsParams, PruneEscalationsResult } from '../../types/hmsh_escalations';
4
+ import { EscalationEntry, ClaimEscalationResult, ClaimByMetadataResult, ReleaseEscalationResult, ResolveEscalationResult, CancelEscalationResult, ListEscalationsParams, StatsEscalationsParams, EscalationStats, CreateEscalationParams, UpdateEscalationParams, AppendMilestonesParams, ClaimEscalationParams, ClaimByMetadataParams, ReleaseEscalationParams, ResolveEscalationParams, ResolveByMetadataParams, EscalateToRoleParams, MigrateEscalationParams, ClaimManyParams, EscalateManyToRoleParams, UpdateManyPriorityParams, ResolveManyParams, ResolveAllOrNoneParams, ResolveAllOrNoneResult, PruneEscalationsParams, PruneEscalationsResult, ClaimManyByQueryParams } from '../../types/hmsh_escalations';
5
+ /**
6
+ * Reserved signal-payload key carrying resolution provenance
7
+ * (`EscalationResolution`) to the waiting workflow. The `$` prefix marks the
8
+ * control-key namespace — consumer payload fields never collide with it.
9
+ */
10
+ export declare const ESCALATION_RESOLUTION_KEY = "$resolution";
5
11
  export type GetHotMeshFn = (topic: string | null, namespace?: string) => Promise<HotMesh>;
6
12
  export interface EscalationClientConfig {
7
13
  /** Postgres connection options — used when creating a standalone EscalationClient. */
@@ -71,6 +77,17 @@ export declare class EscalationClientService {
71
77
  private _emitMany;
72
78
  private _makeEngineFactory;
73
79
  private _hashConnection;
80
+ /**
81
+ * Composes the signal `data` delivered to the waiting workflow. When the
82
+ * resolving caller supplies `resolvedBy`, resolution provenance (escalation
83
+ * id + resolver identity) rides under the reserved `$resolution` key —
84
+ * making the waiter's payload contract deterministic per call site. Without
85
+ * `resolvedBy` the payload passes through byte-identical, so callers that
86
+ * exact-match on payloads are unaffected. The enrichment rides the SIGNAL
87
+ * only — the stored `resolver_payload` column receives the caller's payload
88
+ * untouched.
89
+ */
90
+ private _signalData;
74
91
  private _deliverEscalationSignal;
75
92
  /**
76
93
  * Builds the wake as a webhook message so the store can commit it
@@ -207,6 +224,18 @@ export declare class EscalationClientService {
207
224
  claimed: number;
208
225
  skipped: number;
209
226
  }>;
227
+ /**
228
+ * Atomic query-form bulk claim: one UPDATE selects and claims every pending,
229
+ * claimable row matching the selector (role/type/priority equality, metadata
230
+ * `@>` containment). Prefer this over `list()` + `claimMany({ids})` when the
231
+ * population is describable by filter — a row that re-parks between a search
232
+ * and an ids-claim is invisible to the ids form but claimed by this one.
233
+ * Returns the claimed rows.
234
+ */
235
+ claimManyByQuery(params: ClaimManyByQueryParams): Promise<{
236
+ claimed: number;
237
+ entries: EscalationEntry[];
238
+ }>;
210
239
  /**
211
240
  * Bulk-reassigns pending escalations to a new role, clearing any current claim.
212
241
  * Returns the count of rows updated.
@@ -1,12 +1,18 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.EscalationClientService = void 0;
3
+ exports.EscalationClientService = exports.ESCALATION_RESOLUTION_KEY = void 0;
4
4
  const enums_1 = require("../../modules/enums");
5
5
  const utils_1 = require("../../modules/utils");
6
6
  const hotmesh_1 = require("../hotmesh");
7
7
  const types_1 = require("../../types");
8
8
  const stream_1 = require("../../types/stream");
9
9
  const factory_1 = require("../durable/schemas/factory");
10
+ /**
11
+ * Reserved signal-payload key carrying resolution provenance
12
+ * (`EscalationResolution`) to the waiting workflow. The `$` prefix marks the
13
+ * control-key namespace — consumer payload fields never collide with it.
14
+ */
15
+ exports.ESCALATION_RESOLUTION_KEY = '$resolution';
10
16
  /**
11
17
  * Standalone client for the `public.hmsh_escalations` signal-pause surface.
12
18
  *
@@ -60,7 +66,7 @@ class EscalationClientService {
60
66
  * Detached (not awaited); a publish error never fails the caller.
61
67
  * @private
62
68
  */
63
- _emit(verb, entry) {
69
+ _emit(verb, entry, assignedAtCreation) {
64
70
  if (!this._events?.publish)
65
71
  return;
66
72
  const ts = new Date().toISOString();
@@ -79,6 +85,7 @@ class EscalationClientService {
79
85
  parent_id: entry.parent_id ?? undefined,
80
86
  trace_id: entry.trace_id ?? undefined,
81
87
  span_id: entry.span_id ?? undefined,
88
+ ...(assignedAtCreation !== undefined ? { assigned_at_creation: assignedAtCreation } : {}),
82
89
  data: entry,
83
90
  };
84
91
  void Promise.resolve(this._events.publish(event)).catch(() => { });
@@ -87,9 +94,9 @@ class EscalationClientService {
87
94
  * Fires per-row events for bulk operations. Skipped rows are not emitted.
88
95
  * @private
89
96
  */
90
- _emitMany(verb, entries) {
97
+ _emitMany(verb, entries, assignedAtCreation) {
91
98
  for (const entry of entries)
92
- this._emit(verb, entry);
99
+ this._emit(verb, entry, assignedAtCreation);
93
100
  }
94
101
  _makeEngineFactory(connection) {
95
102
  return async (topic, namespace) => {
@@ -122,6 +129,28 @@ class EscalationClientService {
122
129
  return parts.join('');
123
130
  }
124
131
  // ─── Signal delivery ───────────────────────────────────────────────────────
132
+ /**
133
+ * Composes the signal `data` delivered to the waiting workflow. When the
134
+ * resolving caller supplies `resolvedBy`, resolution provenance (escalation
135
+ * id + resolver identity) rides under the reserved `$resolution` key —
136
+ * making the waiter's payload contract deterministic per call site. Without
137
+ * `resolvedBy` the payload passes through byte-identical, so callers that
138
+ * exact-match on payloads are unaffected. The enrichment rides the SIGNAL
139
+ * only — the stored `resolver_payload` column receives the caller's payload
140
+ * untouched.
141
+ */
142
+ _signalData(payload, escalationId, resolvedBy) {
143
+ if (!resolvedBy)
144
+ return payload ?? {};
145
+ return {
146
+ ...(payload ?? {}),
147
+ [exports.ESCALATION_RESOLUTION_KEY]: {
148
+ escalationId,
149
+ resolvedBy: resolvedBy.id,
150
+ ...(resolvedBy.email ? { resolvedByEmail: resolvedBy.email } : {}),
151
+ },
152
+ };
153
+ }
125
154
  async _deliverEscalationSignal(ns, topic, signalPayload) {
126
155
  if (topic) {
127
156
  try {
@@ -233,8 +262,13 @@ class EscalationClientService {
233
262
  async create(params) {
234
263
  const hm = await this._engine(null, params.namespace);
235
264
  const entry = await hm.engine.store.createEscalation(params);
236
- if (entry)
265
+ if (entry) {
237
266
  this._emit('created', entry);
267
+ // A born-assigned row is created AND claimed in one commit — state
268
+ // both, in that order, so hand-off consumers act without inferring.
269
+ if (entry.assigned_to != null)
270
+ this._emit('claimed', entry, true);
271
+ }
238
272
  return entry;
239
273
  }
240
274
  /**
@@ -259,7 +293,7 @@ class EscalationClientService {
259
293
  const hm = await this._engine(null, params.namespace);
260
294
  const result = await hm.engine.store.claimEscalation(params);
261
295
  if (result.ok === true)
262
- this._emit('claimed', result.entry);
296
+ this._emit('claimed', result.entry, false);
263
297
  return result;
264
298
  }
265
299
  /**
@@ -272,7 +306,7 @@ class EscalationClientService {
272
306
  const hm = await this._engine(null, params.namespace);
273
307
  const result = await hm.engine.store.claimEscalationByMetadata(params);
274
308
  if (result.ok === true)
275
- this._emit('claimed', result.entry);
309
+ this._emit('claimed', result.entry, false);
276
310
  return result;
277
311
  }
278
312
  /** Releases a claimed escalation, returning it to available status. */
@@ -365,7 +399,7 @@ class EscalationClientService {
365
399
  let wakeCommand = null;
366
400
  const preview = await store.getEscalation(params.id, params.namespace);
367
401
  if (preview?.signal_key) {
368
- wakeCommand = await this._buildWakeCommand(ns, preview.topic, preview.signal_key, params.resolverPayload ?? {});
402
+ wakeCommand = await this._buildWakeCommand(ns, preview.topic, preview.signal_key, this._signalData(params.resolverPayload, params.id, params.resolvedBy));
369
403
  }
370
404
  const dbResult = await store.resolveEscalation({ id: params.id, resolverPayload: params.resolverPayload, metadata: params.metadata, assertClaim: params.assertClaim }, wakeCommand ?? undefined);
371
405
  if (!dbResult.ok)
@@ -375,7 +409,7 @@ class EscalationClientService {
375
409
  //enqueue was rolled back to its savepoint) — deliver post-commit
376
410
  await this._deliverEscalationSignal(ns, dbResult.topic, {
377
411
  id: dbResult.signalKey,
378
- data: params.resolverPayload ?? {},
412
+ data: this._signalData(params.resolverPayload, params.id, params.resolvedBy),
379
413
  });
380
414
  }
381
415
  this._emit('resolved', dbResult.entry);
@@ -403,7 +437,10 @@ class EscalationClientService {
403
437
  namespace: params.namespace,
404
438
  });
405
439
  if (preview?.signalKey) {
406
- wakeCommand = await this._buildWakeCommand(ns, preview.topic, preview.signalKey, params.resolverPayload ?? {});
440
+ //the wake embeds the previewed row's id; forSignalKey pins it to that
441
+ //row, so a different row winning the race falls through to post-commit
442
+ //delivery where the winner's own id is used
443
+ wakeCommand = await this._buildWakeCommand(ns, preview.topic, preview.signalKey, this._signalData(params.resolverPayload, preview.id, params.resolvedBy));
407
444
  }
408
445
  const dbResult = await store.resolveEscalationByMetadata({ key: params.key, value: params.value, resolverPayload: params.resolverPayload, roles: params.roles, metadata: params.metadata }, wakeCommand ?? undefined);
409
446
  if (!dbResult.ok)
@@ -411,7 +448,7 @@ class EscalationClientService {
411
448
  if (dbResult.signalKey && !dbResult.wakeEnqueued) {
412
449
  await this._deliverEscalationSignal(ns, dbResult.topic, {
413
450
  id: dbResult.signalKey,
414
- data: params.resolverPayload ?? {},
451
+ data: this._signalData(params.resolverPayload, dbResult.entry.id, params.resolvedBy),
415
452
  });
416
453
  }
417
454
  this._emit('resolved', dbResult.entry);
@@ -443,9 +480,23 @@ class EscalationClientService {
443
480
  async claimMany(params) {
444
481
  const hm = await this._engine(null, params.namespace);
445
482
  const { entries, skipped } = await hm.engine.store.claimManyEscalations(params);
446
- this._emitMany('claimed', entries);
483
+ this._emitMany('claimed', entries, false);
447
484
  return { claimed: entries.length, skipped };
448
485
  }
486
+ /**
487
+ * Atomic query-form bulk claim: one UPDATE selects and claims every pending,
488
+ * claimable row matching the selector (role/type/priority equality, metadata
489
+ * `@>` containment). Prefer this over `list()` + `claimMany({ids})` when the
490
+ * population is describable by filter — a row that re-parks between a search
491
+ * and an ids-claim is invisible to the ids form but claimed by this one.
492
+ * Returns the claimed rows.
493
+ */
494
+ async claimManyByQuery(params) {
495
+ const hm = await this._engine(null, params.namespace);
496
+ const entries = await hm.engine.store.claimManyEscalationsByQuery(params);
497
+ this._emitMany('claimed', entries, false);
498
+ return { claimed: entries.length, entries };
499
+ }
449
500
  /**
450
501
  * Bulk-reassigns pending escalations to a new role, clearing any current claim.
451
502
  * Returns the count of rows updated.
@@ -524,7 +575,7 @@ class EscalationClientService {
524
575
  for (const row of previews) {
525
576
  if (!row.signal_key)
526
577
  continue;
527
- const cmd = await this._buildWakeCommand(ns, row.topic, row.signal_key, payloadById.get(row.id) ?? {});
578
+ const cmd = await this._buildWakeCommand(ns, row.topic, row.signal_key, this._signalData(payloadById.get(row.id), row.id, params.resolvedBy));
528
579
  if (cmd)
529
580
  wakeCommands.push(cmd);
530
581
  }
@@ -543,7 +594,7 @@ class EscalationClientService {
543
594
  if (entry.signal_key && !enqueuedKeys.has(entry.signal_key)) {
544
595
  await this._deliverEscalationSignal(ns, entry.topic, {
545
596
  id: entry.signal_key,
546
- data: payloadById.get(entry.id) ?? {},
597
+ data: this._signalData(payloadById.get(entry.id), entry.id, params.resolvedBy),
547
598
  });
548
599
  }
549
600
  }
@@ -64,3 +64,4 @@ declare class EscalationsClass {
64
64
  }
65
65
  export { EscalationsClass as Escalations };
66
66
  export { EscalationClientService };
67
+ export { ESCALATION_RESOLUTION_KEY } from './client';
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.EscalationClientService = exports.Escalations = void 0;
3
+ exports.ESCALATION_RESOLUTION_KEY = exports.EscalationClientService = exports.Escalations = void 0;
4
4
  const utils_1 = require("../../modules/utils");
5
5
  const client_1 = require("./client");
6
6
  Object.defineProperty(exports, "EscalationClientService", { enumerable: true, get: function () { return client_1.EscalationClientService; } });
@@ -69,3 +69,5 @@ EscalationsClass.guid = utils_1.guid;
69
69
  * when calling `client.migrate()` or any direct UUID column insert.
70
70
  */
71
71
  EscalationsClass.uuid = utils_1.uuid;
72
+ var client_2 = require("./client");
73
+ Object.defineProperty(exports, "ESCALATION_RESOLUTION_KEY", { enumerable: true, get: function () { return client_2.ESCALATION_RESOLUTION_KEY; } });
@@ -325,6 +325,13 @@ declare class PostgresStoreService extends StoreService<ProviderClient, Provider
325
325
  entries: import('../../../../types/hmsh_escalations').EscalationEntry[];
326
326
  skipped: number;
327
327
  }>;
328
+ /**
329
+ * Atomic query-form bulk claim: the selector composes into the UPDATE's own
330
+ * WHERE via `_escalationFilterConditions`, so selection and claim are one
331
+ * statement — no SELECT-then-claim window. `status='pending'` and the
332
+ * claimability guard are forced regardless of the selector.
333
+ */
334
+ claimManyEscalationsByQuery(params: import('../../../../types/hmsh_escalations').ClaimManyByQueryParams): Promise<import('../../../../types/hmsh_escalations').EscalationEntry[]>;
328
335
  escalateManyEscalationsToRole(params: import('../../../../types/hmsh_escalations').EscalateManyToRoleParams): Promise<number>;
329
336
  updateManyEscalationsPriority(params: import('../../../../types/hmsh_escalations').UpdateManyPriorityParams): Promise<number>;
330
337
  resolveManyEscalations(params: import('../../../../types/hmsh_escalations').ResolveManyParams): Promise<import('../../../../types/hmsh_escalations').EscalationEntry[]>;
@@ -44,17 +44,29 @@ class PostgresStoreService extends __1.StoreService {
44
44
  super(storeClient);
45
45
  this.isScout = false;
46
46
  // ─── hmsh_escalations ────────────────────────────────────────────────────────
47
+ // Born-assigned rows ($25 assignee, $26 durationMinutes): assignee alone is
48
+ // a durable pre-assignment (assigned_to, no window — a routing hint);
49
+ // with durationMinutes the TTL window is armed in the same INSERT, exactly
50
+ // as claimEscalation writes it (assigned_until = claim_expires_at). Both
51
+ // NULL → every claim column NULL, byte-identical to the pre-feature row.
47
52
  this._escalationInsertSql = `
48
53
  INSERT INTO public.hmsh_escalations
49
54
  (namespace, app_id, signal_key, topic, workflow_id, task_queue, workflow_type,
50
55
  type, subtype, entity, description, role, priority,
51
56
  origin_id, parent_id, initiated_by, created_by, trace_id, span_id,
52
- task_id, escalation_payload, metadata, envelope, expires_at)
57
+ task_id, escalation_payload, metadata, envelope, expires_at,
58
+ assigned_to, assigned_until, claimed_at, claim_expires_at)
53
59
  VALUES
54
60
  ($1, $2, $3, $4, $5, $6, $7,
55
61
  $8, $9, $10, $11, $12, $13,
56
62
  $14, $15, $16, $17, $18, $19,
57
- $20, $21, $22, $23, $24)
63
+ $20, $21, $22, $23, $24,
64
+ $25,
65
+ CASE WHEN $25::text IS NOT NULL AND $26::numeric IS NOT NULL
66
+ THEN NOW() + ($26::numeric * INTERVAL '1 minute') END,
67
+ CASE WHEN $25::text IS NOT NULL THEN NOW() END,
68
+ CASE WHEN $25::text IS NOT NULL AND $26::numeric IS NOT NULL
69
+ THEN NOW() + ($26::numeric * INTERVAL '1 minute') END)
58
70
  ON CONFLICT (namespace, app_id, signal_key) WHERE signal_key IS NOT NULL DO NOTHING`;
59
71
  //Instead of directly referencing the 'pg' package and methods like 'query',
60
72
  // the PostgresStore wraps the 'pg' client in a class that implements
@@ -1498,7 +1510,7 @@ class PostgresStoreService extends __1.StoreService {
1498
1510
  }
1499
1511
  }
1500
1512
  _escalationInsertParams(params) {
1501
- const { namespace, appId, signalKey, topic, workflowId, taskQueue, workflowType, type, subtype, entity, description, role, priority, originId, parentId, initiatedBy, createdBy, traceId, spanId, taskId, escalationPayload, metadata, envelope, expiresAt, } = params;
1513
+ const { namespace, appId, signalKey, topic, workflowId, taskQueue, workflowType, type, subtype, entity, description, role, priority, originId, parentId, initiatedBy, createdBy, traceId, spanId, taskId, escalationPayload, metadata, envelope, expiresAt, assignee, durationMinutes, } = params;
1502
1514
  return [
1503
1515
  namespace ?? 'hmsh',
1504
1516
  appId ?? 'hmsh',
@@ -1524,6 +1536,8 @@ class PostgresStoreService extends __1.StoreService {
1524
1536
  metadata ? JSON.stringify(metadata) : null,
1525
1537
  envelope ? JSON.stringify(envelope) : null,
1526
1538
  expiresAt ?? null,
1539
+ assignee ?? null,
1540
+ durationMinutes ?? null,
1527
1541
  ];
1528
1542
  }
1529
1543
  async createEscalation(params) {
@@ -1635,7 +1649,7 @@ class PostgresStoreService extends __1.StoreService {
1635
1649
  return result.rows[0] ?? null;
1636
1650
  }
1637
1651
  _escalationFilterConditions(params, startIdx = 1) {
1638
- const { namespace, role, roles, type, subtype, entity, status, assignedTo, workflowId, originId, available, priority, metadata, ids, taskId } = params;
1652
+ const { namespace, role, roles, type, subtype, entity, status, assignedTo, workflowId, originId, parentId, available, priority, metadata, ids, taskId } = params;
1639
1653
  const conditions = [];
1640
1654
  const values = [];
1641
1655
  let idx = startIdx;
@@ -1679,6 +1693,10 @@ class PostgresStoreService extends __1.StoreService {
1679
1693
  conditions.push(`origin_id = $${idx++}`);
1680
1694
  values.push(originId);
1681
1695
  }
1696
+ if (parentId) {
1697
+ conditions.push(`parent_id = $${idx++}`);
1698
+ values.push(parentId);
1699
+ }
1682
1700
  if (priority !== undefined) {
1683
1701
  conditions.push(`priority = $${idx++}`);
1684
1702
  values.push(priority);
@@ -2203,6 +2221,44 @@ class PostgresStoreService extends __1.StoreService {
2203
2221
  const entries = result.rows;
2204
2222
  return { entries, skipped: ids.length - entries.length };
2205
2223
  }
2224
+ /**
2225
+ * Atomic query-form bulk claim: the selector composes into the UPDATE's own
2226
+ * WHERE via `_escalationFilterConditions`, so selection and claim are one
2227
+ * statement — no SELECT-then-claim window. `status='pending'` and the
2228
+ * claimability guard are forced regardless of the selector.
2229
+ */
2230
+ async claimManyEscalationsByQuery(params) {
2231
+ const { query, namespace, assignee, durationMinutes = 1 } = params;
2232
+ const selectorIsEmpty = !query.role && !query.roles?.length && !query.type && !query.subtype &&
2233
+ !query.entity && query.priority === undefined &&
2234
+ !(query.metadata && Object.keys(query.metadata).length);
2235
+ if (selectorIsEmpty) {
2236
+ throw new Error('claimManyEscalationsByQuery: empty selector — an unbounded bulk claim is not allowed');
2237
+ }
2238
+ const { conditions, values, idx } = this._escalationFilterConditions({
2239
+ namespace,
2240
+ role: query.role,
2241
+ roles: query.roles,
2242
+ type: query.type,
2243
+ subtype: query.subtype,
2244
+ entity: query.entity,
2245
+ priority: query.priority,
2246
+ metadata: query.metadata,
2247
+ }, 1);
2248
+ const assigneeIdx = idx;
2249
+ const durationIdx = idx + 1;
2250
+ const result = await this.pgClient.query(`UPDATE public.hmsh_escalations
2251
+ SET assigned_to = $${assigneeIdx},
2252
+ claimed_at = NOW(),
2253
+ claim_expires_at = NOW() + ($${durationIdx} * INTERVAL '1 minute'),
2254
+ assigned_until = NOW() + ($${durationIdx} * INTERVAL '1 minute'),
2255
+ updated_at = NOW()
2256
+ WHERE ${conditions.join(' AND ')}
2257
+ AND status = 'pending'
2258
+ AND (assigned_to IS NULL OR assigned_until IS NULL OR assigned_until <= NOW() OR assigned_to = $${assigneeIdx})
2259
+ RETURNING *`, [...values, assignee, durationMinutes]);
2260
+ return result.rows;
2261
+ }
2206
2262
  async escalateManyEscalationsToRole(params) {
2207
2263
  const { ids, namespace, targetRole } = params;
2208
2264
  const result = await this.pgClient.query(`UPDATE public.hmsh_escalations
@@ -17,6 +17,22 @@ export interface ConditionQueueConfig {
17
17
  /** Unindexed display/form context for resolver UIs */
18
18
  envelope?: Record<string, unknown>;
19
19
  expiresAt?: Date;
20
+ /**
21
+ * Born-assigned: writes `assigned_to` in the same atomic INSERT that
22
+ * creates the row — on the `condition()` path, one commit with the
23
+ * workflow's Leg1 checkpoint. Alone it is a durable pre-assignment: the
24
+ * row surfaces in the assignee's `list({ assignedTo })` immediately, is
25
+ * resolvable by the assignee with `assertClaim`, and remains claimable
26
+ * by others (a routing hint). With `durationMinutes` it is a hard claim
27
+ * at creation. The `created` event payload carries the assignment.
28
+ */
29
+ assignee?: string;
30
+ /**
31
+ * With `assignee`, arms the claim TTL window (`assigned_until` /
32
+ * `claim_expires_at`) at creation — the row is born locked to the
33
+ * assignee, exactly as a post-create `claim()` locks it.
34
+ */
35
+ durationMinutes?: number;
20
36
  /**
21
37
  * SLA timer for the wait itself (e.g. `'30m'`, `'24h'`). Arms the same
22
38
  * resume timer as `condition(signalId, '30m')`: when it fires first, the
@@ -117,6 +133,43 @@ export interface EscalationWakeCommand {
117
133
  forSignalKey: string;
118
134
  message: string;
119
135
  }
136
+ /**
137
+ * Resolution provenance delivered to the waiting workflow alongside the
138
+ * resolver payload, under the reserved `$resolution` key. Present exactly when
139
+ * the resolving caller supplied `resolvedBy` — without it the signal payload
140
+ * passes through byte-identical, so existing waiters are unaffected. The
141
+ * `$`-prefixed key namespace is reserved for control data riding the signal
142
+ * (like `$escalation_id` on the legacy routing path); consumer payload fields
143
+ * never collide with it. The stored `resolver_payload` row column stays clean —
144
+ * provenance rides the signal only.
145
+ *
146
+ * A waiting workflow declares the key in its `condition()` payload generic:
147
+ *
148
+ * ```typescript
149
+ * const decision = await Durable.workflow.condition<{
150
+ * approved: boolean;
151
+ * $resolution?: EscalationResolution;
152
+ * }>(signalId, config);
153
+ * decision.$resolution?.resolvedBy; // who resolved it
154
+ * ```
155
+ */
156
+ export interface EscalationResolution {
157
+ /** The id of the escalation row whose resolve delivered this signal. */
158
+ escalationId: string;
159
+ /** Resolver's user id. */
160
+ resolvedBy: string;
161
+ /** Resolver's email — present when supplied alongside the id. */
162
+ resolvedByEmail?: string;
163
+ }
164
+ /**
165
+ * Resolver identity, supplied by the resolving caller (the API layer that
166
+ * authenticated the human or agent). Delivered to the waiting workflow inside
167
+ * `$resolution`; never written to the stored `resolver_payload`.
168
+ */
169
+ export interface ResolvedByIdentity {
170
+ id: string;
171
+ email?: string;
172
+ }
120
173
  export type ReleaseEscalationResult = {
121
174
  ok: true;
122
175
  entry: EscalationEntry;
@@ -166,6 +219,12 @@ export interface ListEscalationsParams {
166
219
  assignedTo?: string;
167
220
  workflowId?: string;
168
221
  originId?: string;
222
+ /**
223
+ * Filter by `parent_id` — the hand-off lineage key. With `assignedTo`
224
+ * this is the precise fallback query for a born-assigned child: "the
225
+ * child of the escalation I just resolved, assigned to me."
226
+ */
227
+ parentId?: string;
169
228
  /** When true, returns only rows without an active claim. When false, returns only actively claimed rows. */
170
229
  available?: boolean;
171
230
  /** Exact priority match. */
@@ -238,6 +297,14 @@ export interface CreateEscalationParams {
238
297
  metadata?: Record<string, unknown>;
239
298
  envelope?: Record<string, unknown>;
240
299
  expiresAt?: Date;
300
+ /**
301
+ * Born-assigned: writes `assigned_to` in the creation INSERT. See
302
+ * {@link ConditionQueueConfig.assignee} for the two modes (durable
303
+ * pre-assignment vs. hard claim with `durationMinutes`).
304
+ */
305
+ assignee?: string;
306
+ /** With `assignee`, arms the claim TTL window at creation. See {@link ConditionQueueConfig.durationMinutes}. */
307
+ durationMinutes?: number;
241
308
  }
242
309
  /**
243
310
  * Fields that can be patched on an existing escalation. All fields are
@@ -319,6 +386,12 @@ export interface ResolveEscalationParams {
319
386
  * claim-race window for interactive claim-then-resolve flows.
320
387
  */
321
388
  assertClaim?: string;
389
+ /**
390
+ * Resolver identity, delivered to the waiting workflow under the reserved
391
+ * `$resolution` signal key (see {@link EscalationResolution}). Never written
392
+ * to the stored `resolver_payload`.
393
+ */
394
+ resolvedBy?: ResolvedByIdentity;
322
395
  }
323
396
  export interface ResolveByMetadataParams {
324
397
  key: string;
@@ -332,12 +405,42 @@ export interface ResolveByMetadataParams {
332
405
  * `key`/`value` selector used to find the row. See {@link ResolveEscalationParams.metadata}.
333
406
  */
334
407
  metadata?: Record<string, unknown>;
408
+ /** Resolver identity delivered under `$resolution`. See {@link ResolveEscalationParams.resolvedBy}. */
409
+ resolvedBy?: ResolvedByIdentity;
335
410
  }
336
411
  export interface EscalateToRoleParams {
337
412
  id: string;
338
413
  targetRole: string;
339
414
  namespace?: string;
340
415
  }
416
+ /**
417
+ * Query selector for `claimManyByQuery()` — the filterable subset of
418
+ * `ListEscalationsParams` that describes a claimable population. `status` is
419
+ * not accepted: the claim targets pending rows by definition, enforced in SQL.
420
+ */
421
+ export interface ClaimManyQuerySelector {
422
+ role?: string;
423
+ roles?: string[];
424
+ type?: string;
425
+ subtype?: string;
426
+ entity?: string;
427
+ priority?: number;
428
+ /** GIN-indexed `@>` containment against row metadata — the facet filter. */
429
+ metadata?: Record<string, unknown>;
430
+ }
431
+ /**
432
+ * Atomic query-form bulk claim: one UPDATE selects and claims every matching
433
+ * pending, claimable row — no SELECT-then-claim window. Prefer this over
434
+ * `list()` + `claimMany({ids})` whenever the population is describable by
435
+ * filter: a row that re-parks between a search and an ids-claim is invisible
436
+ * to the ids form but claimed by this one.
437
+ */
438
+ export interface ClaimManyByQueryParams {
439
+ query: ClaimManyQuerySelector;
440
+ namespace?: string;
441
+ assignee: string;
442
+ durationMinutes?: number;
443
+ }
341
444
  export interface ClaimManyParams {
342
445
  ids: string[];
343
446
  namespace?: string;
@@ -387,6 +490,11 @@ export interface ResolveAllOrNoneParams {
387
490
  * principal between the caller's claim and this resolve blocks the batch.
388
491
  */
389
492
  assertAssignee?: string;
493
+ /**
494
+ * Resolver identity delivered to EVERY item's waiting workflow under
495
+ * `$resolution` (one resolver per batch). See {@link ResolveEscalationParams.resolvedBy}.
496
+ */
497
+ resolvedBy?: ResolvedByIdentity;
390
498
  }
391
499
  /** Why a specific row blocked a `resolveAllOrNone()` batch. */
392
500
  export type ResolveAllOrNoneBlockReason = 'not-found' | 'already-resolved' | 'already-cancelled' | 'already-expired' | 'assignee-mismatch';
@@ -25,5 +25,5 @@ export { ReclaimedMessageType, RetryPolicy, RouterConfig, StreamCode, StreamConf
25
25
  export { context, Context, Counter, Meter, metrics, propagation, SpanContext, Span, SpanStatus, SpanStatusCode, SpanKind, trace, Tracer, ValueType, } from './telemetry';
26
26
  export { WorkListTaskType } from './task';
27
27
  export { TransitionMatch, TransitionRule, Transitions } from './transition';
28
- export { ConditionQueueConfig, EscalationEntry, ClaimEscalationResult, ClaimByMetadataResult, ReleaseEscalationResult, ResolveEscalationResult, CancelEscalationResult, ListEscalationsParams, CreateEscalationParams, UpdateEscalationParams, AppendMilestonesParams, ClaimEscalationParams, ClaimByMetadataParams, ReleaseEscalationParams, ResolveEscalationParams, ResolveByMetadataParams, ResolveAllOrNoneItem, ResolveAllOrNoneParams, ResolveAllOrNoneBlockReason, ResolveAllOrNoneResult, EscalateToRoleParams, MigrateEscalationParams, } from './hmsh_escalations';
28
+ export { ConditionQueueConfig, EscalationEntry, ClaimEscalationResult, ClaimByMetadataResult, ReleaseEscalationResult, ResolveEscalationResult, CancelEscalationResult, ListEscalationsParams, CreateEscalationParams, UpdateEscalationParams, AppendMilestonesParams, ClaimEscalationParams, ClaimByMetadataParams, ReleaseEscalationParams, ResolveEscalationParams, ResolveByMetadataParams, ResolveAllOrNoneItem, ResolveAllOrNoneParams, ResolveAllOrNoneBlockReason, ResolveAllOrNoneResult, EscalateToRoleParams, MigrateEscalationParams, EscalationResolution, ResolvedByIdentity, ClaimManyQuerySelector, ClaimManyByQueryParams, } from './hmsh_escalations';
29
29
  export { EscalationVerb, EngineVerb, WorkerVerb, SystemEvent, EventsConfig } from './system_events';
@@ -15,7 +15,7 @@
15
15
  * | verb | trigger | `data` shape |
16
16
  * |-------------|----------------------------------------------------------|---------------------|
17
17
  * | `created` | `client.create()` or hook Leg1 INSERT | full `EscalationEntry` row |
18
- * | `claimed` | `client.claim()` / `client.claimByMetadata()` | full `EscalationEntry` row |
18
+ * | `claimed` | `client.claim()` / `client.claimByMetadata()` / born-assigned create (`assignee` set) | full `EscalationEntry` row |
19
19
  * | `released` | `client.release()` | full `EscalationEntry` row |
20
20
  * | `reassigned`| `client.escalateToRole()` / role change | full `EscalationEntry` row |
21
21
  * | `resolved` | `client.resolve()` / `client.resolveByMetadata()` | full `EscalationEntry` row |
@@ -74,6 +74,20 @@
74
74
  * produces distinct IDs because `updated_at` changes on each transition.
75
75
  * - Engine / worker: `${app_id_or_queue}:${verb}:${ts}`.
76
76
  *
77
+ * ## Replay / retry semantics (at-most-once)
78
+ *
79
+ * Both escalation-create emitters publish from the INSERT's `RETURNING *`
80
+ * row. An idempotent re-run — a crash-replayed Leg1 checkpoint or a
81
+ * retried `create()` hitting `ON CONFLICT … DO NOTHING` — returns no row,
82
+ * so the no-op emits nothing: `created`/`claimed` fire exactly once per
83
+ * row that actually commits. The remaining gap is a crash landing between
84
+ * the commit and the post-commit fire-and-forget publish, which drops the
85
+ * event; recover a missed born-assigned hand-off with the precise
86
+ * fallback query (`list({ parentId, assignedTo })` — `claimed_at` equals
87
+ * `created_at` on such rows). A hypothetical duplicate would carry the
88
+ * identical `event_id` (the row's `updated_at` is unchanged by a no-op),
89
+ * so consumer-side `event_id` dedup remains a safe belt-and-braces guard.
90
+ *
77
91
  * ## Fire-and-forget contract
78
92
  *
79
93
  * The SDK wraps every `publish` call in
@@ -141,6 +155,17 @@ export interface SystemEvent {
141
155
  parent_id?: string;
142
156
  trace_id?: string;
143
157
  span_id?: string;
158
+ /**
159
+ * Assignment provenance, present on every `claimed` event. `true` when
160
+ * the row was born assigned (a directed, programmatic assignment via
161
+ * `condition({ assignee })` / `create({ assignee })` — the engine emits
162
+ * `created` then `claimed` from the same commit); `false` when a caller
163
+ * claimed it interactively (`claim`, `claimByMetadata`, `claimMany`,
164
+ * `claimManyByQuery`). Lets a consumer distinguish system-directed
165
+ * hand-offs from claims it observes, as a stated fact of the transition —
166
+ * the committed row alone cannot express how its assignment came to be.
167
+ */
168
+ assigned_at_creation?: boolean;
144
169
  /**
145
170
  * Full committed row for escalation events; lifecycle metadata for
146
171
  * engine/worker events. Each dependent cherry-picks fields for its
@@ -16,7 +16,7 @@
16
16
  * | verb | trigger | `data` shape |
17
17
  * |-------------|----------------------------------------------------------|---------------------|
18
18
  * | `created` | `client.create()` or hook Leg1 INSERT | full `EscalationEntry` row |
19
- * | `claimed` | `client.claim()` / `client.claimByMetadata()` | full `EscalationEntry` row |
19
+ * | `claimed` | `client.claim()` / `client.claimByMetadata()` / born-assigned create (`assignee` set) | full `EscalationEntry` row |
20
20
  * | `released` | `client.release()` | full `EscalationEntry` row |
21
21
  * | `reassigned`| `client.escalateToRole()` / role change | full `EscalationEntry` row |
22
22
  * | `resolved` | `client.resolve()` / `client.resolveByMetadata()` | full `EscalationEntry` row |
@@ -75,6 +75,20 @@
75
75
  * produces distinct IDs because `updated_at` changes on each transition.
76
76
  * - Engine / worker: `${app_id_or_queue}:${verb}:${ts}`.
77
77
  *
78
+ * ## Replay / retry semantics (at-most-once)
79
+ *
80
+ * Both escalation-create emitters publish from the INSERT's `RETURNING *`
81
+ * row. An idempotent re-run — a crash-replayed Leg1 checkpoint or a
82
+ * retried `create()` hitting `ON CONFLICT … DO NOTHING` — returns no row,
83
+ * so the no-op emits nothing: `created`/`claimed` fire exactly once per
84
+ * row that actually commits. The remaining gap is a crash landing between
85
+ * the commit and the post-commit fire-and-forget publish, which drops the
86
+ * event; recover a missed born-assigned hand-off with the precise
87
+ * fallback query (`list({ parentId, assignedTo })` — `claimed_at` equals
88
+ * `created_at` on such rows). A hypothetical duplicate would carry the
89
+ * identical `event_id` (the row's `updated_at` is unchanged by a no-op),
90
+ * so consumer-side `event_id` dedup remains a safe belt-and-braces guard.
91
+ *
78
92
  * ## Fire-and-forget contract
79
93
  *
80
94
  * The SDK wraps every `publish` call in
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hotmeshio/hotmesh",
3
- "version": "0.26.2",
3
+ "version": "0.27.0",
4
4
  "description": "Durable Workflow",
5
5
  "main": "./build/index.js",
6
6
  "types": "./build/index.d.ts",