@hotmeshio/hotmesh 0.26.3 → 0.27.1

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.3",
3
+ "version": "0.27.1",
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({
@@ -101,6 +101,16 @@ declare class ExporterService {
101
101
  * ```
102
102
  */
103
103
  export(jobId: string, options?: ExportOptions): Promise<DurableJobExport>;
104
+ /**
105
+ * Read the workflow input arguments without a full export. Resolves the
106
+ * `trigger/output/data/arguments` symbol and reads that single field from
107
+ * the job hash, so the cost is one symbol lookup (cached) plus a one-field
108
+ * `hmget` rather than a whole-hash read.
109
+ *
110
+ * @param jobId - the workflow ID
111
+ * @returns the input arguments array, or undefined if unavailable
112
+ */
113
+ getInput(jobId: string): Promise<any>;
104
114
  /**
105
115
  * Export a workflow execution as a structured event history ({@link WorkflowExecution}).
106
116
  *
@@ -220,6 +220,26 @@ class ExporterService {
220
220
  const jobExport = this.inflate(jobData, options);
221
221
  return jobExport;
222
222
  }
223
+ /**
224
+ * Read the workflow input arguments without a full export. Resolves the
225
+ * `trigger/output/data/arguments` symbol and reads that single field from
226
+ * the job hash, so the cost is one symbol lookup (cached) plus a one-field
227
+ * `hmget` rather than a whole-hash read.
228
+ *
229
+ * @param jobId - the workflow ID
230
+ * @returns the input arguments array, or undefined if unavailable
231
+ */
232
+ async getInput(jobId) {
233
+ if (!this.store.getJobArguments) {
234
+ return undefined;
235
+ }
236
+ const symbolSets = await this.store.getSymbolKeys(['trigger']);
237
+ const field = this.resolveSymbolField(symbolSets, 'trigger', 'trigger/output/data/arguments');
238
+ if (!field) {
239
+ return undefined;
240
+ }
241
+ return this.store.getJobArguments(jobId, field);
242
+ }
223
243
  /**
224
244
  * Export a workflow execution as a structured event history ({@link WorkflowExecution}).
225
245
  *
@@ -119,6 +119,36 @@ export declare class WorkflowHandleService {
119
119
  * @param fields - The field names to retrieve.
120
120
  */
121
121
  queryState(fields: string[]): Promise<Record<string, any>>;
122
+ /**
123
+ * Returns the input arguments the workflow was started with, exactly as
124
+ * passed to `client.workflow.start({ args })`. Reads a single field from
125
+ * the job hash (no full export), so it stays cheap on large jobs and is
126
+ * available for the life of the job — while running or after completion.
127
+ *
128
+ * @template T - The tuple type of the workflow's arguments.
129
+ *
130
+ * @example
131
+ * ```typescript
132
+ * const [orderId, region] = await handle.input<[string, string]>();
133
+ * ```
134
+ */
135
+ input<T = any[]>(): Promise<T>;
136
+ /**
137
+ * Returns the workflow's response if it has completed, or `undefined`
138
+ * while it is still running. Unlike {@link result}, this never blocks —
139
+ * it reads the current state and returns immediately.
140
+ *
141
+ * @template T - The workflow's return type.
142
+ *
143
+ * @example
144
+ * ```typescript
145
+ * const value = await handle.output<{ ok: boolean }>();
146
+ * if (value === undefined) {
147
+ * // still running
148
+ * }
149
+ * ```
150
+ */
151
+ output<T = any>(): Promise<T | undefined>;
122
152
  /**
123
153
  * Returns the workflow's numeric status code: `0` = completed,
124
154
  * positive = still running, negative = interrupted/errored.
@@ -147,6 +147,44 @@ class WorkflowHandleService {
147
147
  async queryState(fields) {
148
148
  return await this.hotMesh.getQueryState(this.workflowId, fields);
149
149
  }
150
+ /**
151
+ * Returns the input arguments the workflow was started with, exactly as
152
+ * passed to `client.workflow.start({ args })`. Reads a single field from
153
+ * the job hash (no full export), so it stays cheap on large jobs and is
154
+ * available for the life of the job — while running or after completion.
155
+ *
156
+ * @template T - The tuple type of the workflow's arguments.
157
+ *
158
+ * @example
159
+ * ```typescript
160
+ * const [orderId, region] = await handle.input<[string, string]>();
161
+ * ```
162
+ */
163
+ async input() {
164
+ return (await this.exporter.getInput(this.workflowId));
165
+ }
166
+ /**
167
+ * Returns the workflow's response if it has completed, or `undefined`
168
+ * while it is still running. Unlike {@link result}, this never blocks —
169
+ * it reads the current state and returns immediately.
170
+ *
171
+ * @template T - The workflow's return type.
172
+ *
173
+ * @example
174
+ * ```typescript
175
+ * const value = await handle.output<{ ok: boolean }>();
176
+ * if (value === undefined) {
177
+ * // still running
178
+ * }
179
+ * ```
180
+ */
181
+ async output() {
182
+ const state = await this.hotMesh.getState(`${this.hotMesh.appId}.execute`, this.workflowId);
183
+ if (!state.data && state.metadata?.err) {
184
+ throw new Error(JSON.parse(state.metadata.err));
185
+ }
186
+ return state.data?.response;
187
+ }
150
188
  /**
151
189
  * Returns the workflow's numeric status code: `0` = completed,
152
190
  * positive = still running, negative = interrupted/errored.
@@ -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.
@@ -66,7 +66,7 @@ class EscalationClientService {
66
66
  * Detached (not awaited); a publish error never fails the caller.
67
67
  * @private
68
68
  */
69
- _emit(verb, entry) {
69
+ _emit(verb, entry, assignedAtCreation) {
70
70
  if (!this._events?.publish)
71
71
  return;
72
72
  const ts = new Date().toISOString();
@@ -85,6 +85,7 @@ class EscalationClientService {
85
85
  parent_id: entry.parent_id ?? undefined,
86
86
  trace_id: entry.trace_id ?? undefined,
87
87
  span_id: entry.span_id ?? undefined,
88
+ ...(assignedAtCreation !== undefined ? { assigned_at_creation: assignedAtCreation } : {}),
88
89
  data: entry,
89
90
  };
90
91
  void Promise.resolve(this._events.publish(event)).catch(() => { });
@@ -93,9 +94,9 @@ class EscalationClientService {
93
94
  * Fires per-row events for bulk operations. Skipped rows are not emitted.
94
95
  * @private
95
96
  */
96
- _emitMany(verb, entries) {
97
+ _emitMany(verb, entries, assignedAtCreation) {
97
98
  for (const entry of entries)
98
- this._emit(verb, entry);
99
+ this._emit(verb, entry, assignedAtCreation);
99
100
  }
100
101
  _makeEngineFactory(connection) {
101
102
  return async (topic, namespace) => {
@@ -261,8 +262,13 @@ class EscalationClientService {
261
262
  async create(params) {
262
263
  const hm = await this._engine(null, params.namespace);
263
264
  const entry = await hm.engine.store.createEscalation(params);
264
- if (entry)
265
+ if (entry) {
265
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
+ }
266
272
  return entry;
267
273
  }
268
274
  /**
@@ -287,7 +293,7 @@ class EscalationClientService {
287
293
  const hm = await this._engine(null, params.namespace);
288
294
  const result = await hm.engine.store.claimEscalation(params);
289
295
  if (result.ok === true)
290
- this._emit('claimed', result.entry);
296
+ this._emit('claimed', result.entry, false);
291
297
  return result;
292
298
  }
293
299
  /**
@@ -300,7 +306,7 @@ class EscalationClientService {
300
306
  const hm = await this._engine(null, params.namespace);
301
307
  const result = await hm.engine.store.claimEscalationByMetadata(params);
302
308
  if (result.ok === true)
303
- this._emit('claimed', result.entry);
309
+ this._emit('claimed', result.entry, false);
304
310
  return result;
305
311
  }
306
312
  /** Releases a claimed escalation, returning it to available status. */
@@ -474,7 +480,7 @@ class EscalationClientService {
474
480
  async claimMany(params) {
475
481
  const hm = await this._engine(null, params.namespace);
476
482
  const { entries, skipped } = await hm.engine.store.claimManyEscalations(params);
477
- this._emitMany('claimed', entries);
483
+ this._emitMany('claimed', entries, false);
478
484
  return { claimed: entries.length, skipped };
479
485
  }
480
486
  /**
@@ -488,7 +494,7 @@ class EscalationClientService {
488
494
  async claimManyByQuery(params) {
489
495
  const hm = await this._engine(null, params.namespace);
490
496
  const entries = await hm.engine.store.claimManyEscalationsByQuery(params);
491
- this._emitMany('claimed', entries);
497
+ this._emitMany('claimed', entries, false);
492
498
  return { claimed: entries.length, entries };
493
499
  }
494
500
  /**
@@ -135,6 +135,16 @@ declare abstract class StoreService<Provider extends ProviderClient, Transaction
135
135
  * @returns Map of child_workflow_id -> parsed input arguments
136
136
  */
137
137
  getChildWorkflowInputs?(childJobKeys: string[], symbolField: string): Promise<Map<string, any>>;
138
+ /**
139
+ * Fetch and decode a single compressed-symbol field from a job's HASH.
140
+ * Reads one field with `hmget` rather than the whole hash, so it is the
141
+ * cheap path for narrow getters like the workflow input arguments.
142
+ *
143
+ * @param jobId - The job ID
144
+ * @param symbolField - The compressed symbol field (symbol + dimension)
145
+ * @returns The decoded value, or undefined if the field is absent
146
+ */
147
+ getJobArguments?(jobId: string, symbolField: string): Promise<any>;
138
148
  /**
139
149
  * Fetch stream message history for a job from worker_streams.
140
150
  * Returns raw activity input/output data from soft-deleted messages.
@@ -202,6 +202,13 @@ declare class PostgresStoreService extends StoreService<ProviderClient, Provider
202
202
  * Deploy time-aware notification triggers and functions
203
203
  */
204
204
  private deployTimeNotificationTriggers;
205
+ /**
206
+ * Fetch and decode a single compressed-symbol field from a job's HASH.
207
+ * Reads one field with `hmget` (no full-hash scan), then decodes it with
208
+ * the same rules the serializer uses on write. Powers narrow getters such
209
+ * as the workflow input arguments without a full export.
210
+ */
211
+ getJobArguments(jobId: string, symbolField: string): Promise<any>;
205
212
  /**
206
213
  * Fetch activity inputs for a workflow. Used by the exporter to enrich
207
214
  * timeline events with activity arguments.
@@ -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
@@ -1302,6 +1314,20 @@ class PostgresStoreService extends __1.StoreService {
1302
1314
  }
1303
1315
  }
1304
1316
  // ── Exporter queries ───────────────────────────────────────────────────────
1317
+ /**
1318
+ * Fetch and decode a single compressed-symbol field from a job's HASH.
1319
+ * Reads one field with `hmget` (no full-hash scan), then decodes it with
1320
+ * the same rules the serializer uses on write. Powers narrow getters such
1321
+ * as the workflow input arguments without a full export.
1322
+ */
1323
+ async getJobArguments(jobId, symbolField) {
1324
+ const key = this.mintKey(key_1.KeyType.JOB_STATE, { appId: this.appId, jobId });
1325
+ const [raw] = await this.kvsql().hmget(key, [symbolField]);
1326
+ if (raw === undefined || raw === null) {
1327
+ return undefined;
1328
+ }
1329
+ return this.parseHmshValue(raw);
1330
+ }
1305
1331
  /**
1306
1332
  * Fetch activity inputs for a workflow. Used by the exporter to enrich
1307
1333
  * timeline events with activity arguments.
@@ -1498,7 +1524,7 @@ class PostgresStoreService extends __1.StoreService {
1498
1524
  }
1499
1525
  }
1500
1526
  _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;
1527
+ 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
1528
  return [
1503
1529
  namespace ?? 'hmsh',
1504
1530
  appId ?? 'hmsh',
@@ -1524,6 +1550,8 @@ class PostgresStoreService extends __1.StoreService {
1524
1550
  metadata ? JSON.stringify(metadata) : null,
1525
1551
  envelope ? JSON.stringify(envelope) : null,
1526
1552
  expiresAt ?? null,
1553
+ assignee ?? null,
1554
+ durationMinutes ?? null,
1527
1555
  ];
1528
1556
  }
1529
1557
  async createEscalation(params) {
@@ -1635,7 +1663,7 @@ class PostgresStoreService extends __1.StoreService {
1635
1663
  return result.rows[0] ?? null;
1636
1664
  }
1637
1665
  _escalationFilterConditions(params, startIdx = 1) {
1638
- const { namespace, role, roles, type, subtype, entity, status, assignedTo, workflowId, originId, available, priority, metadata, ids, taskId } = params;
1666
+ const { namespace, role, roles, type, subtype, entity, status, assignedTo, workflowId, originId, parentId, available, priority, metadata, ids, taskId } = params;
1639
1667
  const conditions = [];
1640
1668
  const values = [];
1641
1669
  let idx = startIdx;
@@ -1679,6 +1707,10 @@ class PostgresStoreService extends __1.StoreService {
1679
1707
  conditions.push(`origin_id = $${idx++}`);
1680
1708
  values.push(originId);
1681
1709
  }
1710
+ if (parentId) {
1711
+ conditions.push(`parent_id = $${idx++}`);
1712
+ values.push(parentId);
1713
+ }
1682
1714
  if (priority !== undefined) {
1683
1715
  conditions.push(`priority = $${idx++}`);
1684
1716
  values.push(priority);
@@ -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
@@ -203,6 +219,12 @@ export interface ListEscalationsParams {
203
219
  assignedTo?: string;
204
220
  workflowId?: string;
205
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;
206
228
  /** When true, returns only rows without an active claim. When false, returns only actively claimed rows. */
207
229
  available?: boolean;
208
230
  /** Exact priority match. */
@@ -275,6 +297,14 @@ export interface CreateEscalationParams {
275
297
  metadata?: Record<string, unknown>;
276
298
  envelope?: Record<string, unknown>;
277
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;
278
308
  }
279
309
  /**
280
310
  * Fields that can be patched on an existing escalation. All fields are
@@ -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.3",
3
+ "version": "0.27.1",
4
4
  "description": "Durable Workflow",
5
5
  "main": "./build/index.js",
6
6
  "types": "./build/index.d.ts",