@hotmeshio/hotmesh 0.27.0 → 0.28.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.27.0",
3
+ "version": "0.28.0",
4
4
  "description": "Durable Workflow",
5
5
  "main": "./build/index.js",
6
6
  "types": "./build/index.d.ts",
@@ -51,6 +51,7 @@
51
51
  "test:durable:readonly": "docker compose --profile readonly up -d --build && docker compose exec hotmesh-readonly npx vitest run --config tests/durable/readonly/vitest.config.mts",
52
52
  "test:durable:unknown": "vitest run tests/durable/unknown/postgres.test.ts",
53
53
  "test:durable:escalations": "HMSH_LOGLEVEL=info vitest run tests/durable/escalations",
54
+ "test:durable:escalations-batch": "HMSH_LOGLEVEL=info vitest run tests/durable/escalations-batch",
54
55
  "test:durable:exporter": "HMSH_LOGLEVEL=info vitest run tests/durable/exporter",
55
56
  "test:durable:exporter:debug": "EXPORT_DEBUG=1 HMSH_LOGLEVEL=error vitest run tests/durable/basic/postgres.test.ts",
56
57
  "test:durable:codec": "vitest run tests/durable/codec/postgres.test.ts",
@@ -88,6 +89,7 @@
88
89
  "test:unit": "vitest run tests/unit",
89
90
  "prove": "docker compose exec hotmesh npx vitest run tests/durable 2>&1 | tee /tmp/hmsh-durable.txt && grep -E 'FAIL|Tests |Files ' /tmp/hmsh-durable.txt | tail -5",
90
91
  "prove:escalations": "docker compose exec hotmesh npx vitest run tests/durable/escalations/postgres.test.ts 2>&1 | tee /tmp/hmsh-escalations.txt && grep -E 'FAIL|Tests |Files ' /tmp/hmsh-escalations.txt | tail -5",
92
+ "prove:escalations-batch": "docker compose exec hotmesh npx vitest run tests/durable/escalations-batch 2>&1 | tee /tmp/hmsh-escalations-batch.txt && grep -E 'FAIL|Tests |Files ' /tmp/hmsh-escalations-batch.txt | tail -5",
91
93
  "prove:migrations": "docker compose exec hotmesh npx vitest run tests/durable/migrations/postgres.test.ts 2>&1 | tee /tmp/hmsh-migrations.txt && grep -E 'FAIL|Tests |Files ' /tmp/hmsh-migrations.txt | tail -5",
92
94
  "prove:events": "docker compose exec hotmesh npx vitest run tests/durable/events/postgres.test.ts 2>&1 | tee /tmp/hmsh-events.txt && grep -E 'FAIL|Tests |Files ' /tmp/hmsh-events.txt | tail -5",
93
95
  "prove:functional": "docker compose exec hotmesh npx vitest run tests/functional 2>&1 | tee /tmp/hmsh-functional.txt && grep -E 'FAIL|Tests |Files ' /tmp/hmsh-functional.txt | tail -5",
@@ -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.
@@ -83,6 +83,34 @@ import { ConditionQueueConfig } from '../../../types/hmsh_escalations';
83
83
  * them immediately. Add `durationMinutes` to arm the claim TTL window at
84
84
  * creation, locking the row to the assignee exactly as `claim()` would.
85
85
  *
86
+ * ## Batch accumulation: one wait, N contributions
87
+ *
88
+ * Set `batch` in the config to declare the wait as an accumulator. Each
89
+ * declared item key is filled exactly once via
90
+ * `client.escalations.resolveBatchItem()`; interim fills are cheap row
91
+ * updates (`accepted`, row stays pending), and the LAST fill resolves the
92
+ * row and resumes the wait with the full collection — one atomic statement.
93
+ * Type the generic as the collection:
94
+ *
95
+ * ```typescript
96
+ * const parts = await Durable.workflow.condition<
97
+ * Record<'cut' | 'weld' | 'paint', StationResult>
98
+ * >(signalId, {
99
+ * role: 'assembly',
100
+ * batch: ['cut', 'weld', 'paint'],
101
+ * metadata: { orderId },
102
+ * timeout: '24h',
103
+ * });
104
+ * if (parts === false) return 'sla-expired'; // partial items audit on the expired row
105
+ * if (parts === null) return 'cancelled';
106
+ * parts.weld; // typed item payload
107
+ * ```
108
+ *
109
+ * The row's `metadata.batch_pending` / `batch_count` facets track progress
110
+ * (`@>`-queryable); payloads accumulate in `envelope.batch_items`. A plain
111
+ * `resolve()` on a batch row remains an admin override that resolves the
112
+ * whole row with the payload given.
113
+ *
86
114
  * ## Placement: call escalation-bearing waits from main workflow code
87
115
  *
88
116
  * The resolve/signal delivery pipeline routes to the main flow's waiter.
@@ -4,6 +4,7 @@ exports.condition = void 0;
4
4
  const common_1 = require("./common");
5
5
  const cancellationScope_1 = require("./cancellationScope");
6
6
  const didRun_1 = require("./didRun");
7
+ const batch_1 = require("../../escalations/batch");
7
8
  /**
8
9
  * Pauses the workflow until a signal with the given `signalId` is received.
9
10
  * The workflow suspends durably — it survives process restarts and will
@@ -88,6 +89,34 @@ const didRun_1 = require("./didRun");
88
89
  * them immediately. Add `durationMinutes` to arm the claim TTL window at
89
90
  * creation, locking the row to the assignee exactly as `claim()` would.
90
91
  *
92
+ * ## Batch accumulation: one wait, N contributions
93
+ *
94
+ * Set `batch` in the config to declare the wait as an accumulator. Each
95
+ * declared item key is filled exactly once via
96
+ * `client.escalations.resolveBatchItem()`; interim fills are cheap row
97
+ * updates (`accepted`, row stays pending), and the LAST fill resolves the
98
+ * row and resumes the wait with the full collection — one atomic statement.
99
+ * Type the generic as the collection:
100
+ *
101
+ * ```typescript
102
+ * const parts = await Durable.workflow.condition<
103
+ * Record<'cut' | 'weld' | 'paint', StationResult>
104
+ * >(signalId, {
105
+ * role: 'assembly',
106
+ * batch: ['cut', 'weld', 'paint'],
107
+ * metadata: { orderId },
108
+ * timeout: '24h',
109
+ * });
110
+ * if (parts === false) return 'sla-expired'; // partial items audit on the expired row
111
+ * if (parts === null) return 'cancelled';
112
+ * parts.weld; // typed item payload
113
+ * ```
114
+ *
115
+ * The row's `metadata.batch_pending` / `batch_count` facets track progress
116
+ * (`@>`-queryable); payloads accumulate in `envelope.batch_items`. A plain
117
+ * `resolve()` on a batch row remains an admin override that resolves the
118
+ * whole row with the payload given.
119
+ *
91
120
  * ## Placement: call escalation-bearing waits from main workflow code
92
121
  *
93
122
  * The resolve/signal delivery pipeline routes to the main flow's waiter.
@@ -149,7 +178,11 @@ async function condition(signalId, timeoutOrConfig) {
149
178
  // A string arg is a bare timeout; a config object may carry its own
150
179
  // `timeout` field — the engine's waiter block accepts duration and
151
180
  // queueConfig together (one wait: escalation row + resume timer).
152
- const queueConfig = timeoutOrConfig && typeof timeoutOrConfig === 'object' ? timeoutOrConfig : undefined;
181
+ // A `batch` declaration folds into metadata/envelope here, before the
182
+ // interruption message is built, so the accumulator shape rides the
183
+ // same Leg1-atomic INSERT as every other config field.
184
+ const rawConfig = timeoutOrConfig && typeof timeoutOrConfig === 'object' ? timeoutOrConfig : undefined;
185
+ const queueConfig = rawConfig?.batch ? (0, batch_1.foldBatchConfig)(rawConfig) : rawConfig;
153
186
  const timeout = typeof timeoutOrConfig === 'string' ? timeoutOrConfig : queueConfig?.timeout;
154
187
  const [didRunAlready, execIndex, result] = await (0, didRun_1.didRun)('wait');
155
188
  (0, cancellationScope_1.checkCancellation)();
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Folds a `batch` declaration into the escalation's storage shape:
3
+ * queryable facets in `metadata` (`batch_pending`, `batch_count`,
4
+ * `batch_keys`) and the payload accumulator in `envelope`
5
+ * (`batch_items: {}`). Pure and deterministic — safe on the replayed
6
+ * `condition()` path. Throws synchronously on an invalid declaration so
7
+ * a bad batch never reaches a durable write.
8
+ */
9
+ export declare function foldBatchConfig<T extends {
10
+ batch?: string[];
11
+ metadata?: Record<string, unknown>;
12
+ envelope?: Record<string, unknown>;
13
+ }>(config: T): Omit<T, 'batch'>;
@@ -0,0 +1,57 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.foldBatchConfig = void 0;
4
+ const hmsh_escalations_1 = require("../../types/hmsh_escalations");
5
+ const RESERVED_METADATA_KEYS = new Set([
6
+ hmsh_escalations_1.ESCALATION_BATCH_PENDING_KEY,
7
+ hmsh_escalations_1.ESCALATION_BATCH_COUNT_KEY,
8
+ hmsh_escalations_1.ESCALATION_BATCH_KEYS_KEY,
9
+ ]);
10
+ /**
11
+ * Folds a `batch` declaration into the escalation's storage shape:
12
+ * queryable facets in `metadata` (`batch_pending`, `batch_count`,
13
+ * `batch_keys`) and the payload accumulator in `envelope`
14
+ * (`batch_items: {}`). Pure and deterministic — safe on the replayed
15
+ * `condition()` path. Throws synchronously on an invalid declaration so
16
+ * a bad batch never reaches a durable write.
17
+ */
18
+ function foldBatchConfig(config) {
19
+ const { batch, ...rest } = config;
20
+ if (!batch)
21
+ return rest;
22
+ if (!Array.isArray(batch) || batch.length === 0) {
23
+ throw new Error('batch must be a non-empty array of item keys');
24
+ }
25
+ const seen = new Set();
26
+ for (const key of batch) {
27
+ if (typeof key !== 'string' || key.length === 0) {
28
+ throw new Error('batch item keys must be non-empty strings');
29
+ }
30
+ if (seen.has(key)) {
31
+ throw new Error(`batch item keys must be unique: '${key}'`);
32
+ }
33
+ seen.add(key);
34
+ }
35
+ for (const reserved of RESERVED_METADATA_KEYS) {
36
+ if (rest.metadata && reserved in rest.metadata) {
37
+ throw new Error(`metadata key '${reserved}' is reserved for batch state`);
38
+ }
39
+ }
40
+ if (rest.envelope && hmsh_escalations_1.ESCALATION_BATCH_ITEMS_KEY in rest.envelope) {
41
+ throw new Error(`envelope key '${hmsh_escalations_1.ESCALATION_BATCH_ITEMS_KEY}' is reserved for batch state`);
42
+ }
43
+ return {
44
+ ...rest,
45
+ metadata: {
46
+ ...(rest.metadata ?? {}),
47
+ [hmsh_escalations_1.ESCALATION_BATCH_PENDING_KEY]: [...batch],
48
+ [hmsh_escalations_1.ESCALATION_BATCH_COUNT_KEY]: batch.length,
49
+ [hmsh_escalations_1.ESCALATION_BATCH_KEYS_KEY]: [...batch],
50
+ },
51
+ envelope: {
52
+ ...(rest.envelope ?? {}),
53
+ [hmsh_escalations_1.ESCALATION_BATCH_ITEMS_KEY]: {},
54
+ },
55
+ };
56
+ }
57
+ exports.foldBatchConfig = foldBatchConfig;
@@ -1,7 +1,7 @@
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, ClaimManyByQueryParams } 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, ResolveBatchItemParams, ResolveBatchItemByMetadataParams, ResolveBatchItemResult } from '../../types/hmsh_escalations';
5
5
  /**
6
6
  * Reserved signal-payload key carrying resolution provenance
7
7
  * (`EscalationResolution`) to the waiting workflow. The `$` prefix marks the
@@ -205,6 +205,49 @@ export declare class EscalationClientService {
205
205
  * GIN-indexed `metadata` in the same atomic UPDATE. See {@link resolve}.
206
206
  */
207
207
  resolveByMetadata(params: ResolveByMetadataParams, namespace?: string): Promise<ResolveEscalationResult>;
208
+ /**
209
+ * Pre-serializes the `$resolution` control object merged into a completing
210
+ * batch item's delivered collection. Rides the signal only — the stored
211
+ * `resolver_payload` receives the bare collection.
212
+ */
213
+ private _batchResolutionJson;
214
+ /**
215
+ * Shared post-statement handling for both batch-item forms: post-commit
216
+ * wake fallback (the committed `resolver_payload` — the full assembled
217
+ * collection — is the recovery record) and lifecycle events
218
+ * (`batch-item` on interim fills, `resolved` on completion).
219
+ */
220
+ private _settleBatchItemResult;
221
+ /**
222
+ * Fills ONE declared item of a batch escalation (a wait created with
223
+ * `condition(signalId, { batch: [...] })` or a standalone `create()` with
224
+ * `batch`). One atomic statement: the payload lands in
225
+ * `envelope.batch_items[itemKey]` only while `itemKey` is still pending,
226
+ * the `batch_pending`/`batch_count` facets recompute, and — on the LAST
227
+ * item — the row resolves with the assembled collection as its
228
+ * `resolver_payload` and the waiting workflow's wake commits WITH the
229
+ * fill (same durability contract as `resolve()`). The caller that lands
230
+ * the last item learns it from `outcome: 'completed'`.
231
+ *
232
+ * Fills are claim-agnostic by default — a batch accumulates contributions
233
+ * from multiple principals. Pass `assertClaim` to opt into the same
234
+ * claim-lock assertion as `resolve()`. Pass `metadata` to merge an outcome
235
+ * patch into the row's GIN-indexed metadata in the same UPDATE (reserved
236
+ * batch keys cannot be overridden). Pass `resolvedBy` on submissions to
237
+ * deliver `$resolution` provenance with the completing item's signal.
238
+ *
239
+ * A duplicate submission of an already-filled key returns
240
+ * `outcome: 'duplicate-item'` without touching the row — safe under
241
+ * webhook retries.
242
+ */
243
+ resolveBatchItem(params: ResolveBatchItemParams, namespace?: string): Promise<ResolveBatchItemResult>;
244
+ /**
245
+ * Batch-item fill selecting the row by metadata facet — the highest
246
+ * priority pending row whose `metadata` contains the key/value, mirroring
247
+ * `resolveByMetadata()`'s selector semantics. See {@link resolveBatchItem}
248
+ * for the fill contract.
249
+ */
250
+ resolveBatchItemByMetadata(params: ResolveBatchItemByMetadataParams, namespace?: string): Promise<ResolveBatchItemResult>;
208
251
  /**
209
252
  * Full-fidelity migration: inserts an escalation row preserving the original
210
253
  * UUID and lifecycle state. Returns `null` on duplicate (idempotent).
@@ -454,6 +454,110 @@ class EscalationClientService {
454
454
  this._emit('resolved', dbResult.entry);
455
455
  return { ok: true, entry: dbResult.entry };
456
456
  }
457
+ /**
458
+ * Pre-serializes the `$resolution` control object merged into a completing
459
+ * batch item's delivered collection. Rides the signal only — the stored
460
+ * `resolver_payload` receives the bare collection.
461
+ */
462
+ _batchResolutionJson(escalationId, resolvedBy) {
463
+ if (!resolvedBy)
464
+ return null;
465
+ return JSON.stringify({
466
+ [exports.ESCALATION_RESOLUTION_KEY]: {
467
+ escalationId,
468
+ resolvedBy: resolvedBy.id,
469
+ ...(resolvedBy.email ? { resolvedByEmail: resolvedBy.email } : {}),
470
+ },
471
+ });
472
+ }
473
+ /**
474
+ * Shared post-statement handling for both batch-item forms: post-commit
475
+ * wake fallback (the committed `resolver_payload` — the full assembled
476
+ * collection — is the recovery record) and lifecycle events
477
+ * (`batch-item` on interim fills, `resolved` on completion).
478
+ */
479
+ async _settleBatchItemResult(ns, dbResult, resolvedBy) {
480
+ if (!dbResult.ok)
481
+ return dbResult;
482
+ if (dbResult.outcome === 'completed') {
483
+ if (dbResult.signalKey && !dbResult.wakeEnqueued) {
484
+ await this._deliverEscalationSignal(ns, dbResult.topic, {
485
+ id: dbResult.signalKey,
486
+ data: this._signalData(dbResult.entry.resolver_payload ?? {}, dbResult.entry.id, resolvedBy),
487
+ });
488
+ }
489
+ this._emit('resolved', dbResult.entry);
490
+ }
491
+ else {
492
+ this._emit('batch-item', dbResult.entry);
493
+ }
494
+ return { ok: true, outcome: dbResult.outcome, remaining: dbResult.remaining, entry: dbResult.entry };
495
+ }
496
+ /**
497
+ * Fills ONE declared item of a batch escalation (a wait created with
498
+ * `condition(signalId, { batch: [...] })` or a standalone `create()` with
499
+ * `batch`). One atomic statement: the payload lands in
500
+ * `envelope.batch_items[itemKey]` only while `itemKey` is still pending,
501
+ * the `batch_pending`/`batch_count` facets recompute, and — on the LAST
502
+ * item — the row resolves with the assembled collection as its
503
+ * `resolver_payload` and the waiting workflow's wake commits WITH the
504
+ * fill (same durability contract as `resolve()`). The caller that lands
505
+ * the last item learns it from `outcome: 'completed'`.
506
+ *
507
+ * Fills are claim-agnostic by default — a batch accumulates contributions
508
+ * from multiple principals. Pass `assertClaim` to opt into the same
509
+ * claim-lock assertion as `resolve()`. Pass `metadata` to merge an outcome
510
+ * patch into the row's GIN-indexed metadata in the same UPDATE (reserved
511
+ * batch keys cannot be overridden). Pass `resolvedBy` on submissions to
512
+ * deliver `$resolution` provenance with the completing item's signal.
513
+ *
514
+ * A duplicate submission of an already-filled key returns
515
+ * `outcome: 'duplicate-item'` without touching the row — safe under
516
+ * webhook retries.
517
+ */
518
+ async resolveBatchItem(params, namespace) {
519
+ const ns = (params.namespace ?? namespace) ?? factory_1.APP_ID;
520
+ const hm = await this._engine(null, ns);
521
+ const store = hm.engine.store;
522
+ //pre-build the wake with a placeholder payload — the store overwrites
523
+ //the {data,data} slot with the assembled collection inside the fill
524
+ //statement, so the wake commits WITH the completing fill
525
+ let wakeCommand = null;
526
+ const preview = params.id
527
+ ? await store.getEscalation(params.id, params.namespace)
528
+ : await store.getEscalationBySignalKey(params.signalKey, params.namespace);
529
+ if (preview?.signal_key) {
530
+ wakeCommand = await this._buildWakeCommand(ns, preview.topic, preview.signal_key, {});
531
+ }
532
+ const dbResult = await store.resolveEscalationBatchItem(params, wakeCommand ?? undefined, preview ? this._batchResolutionJson(preview.id, params.resolvedBy) : null);
533
+ return this._settleBatchItemResult(ns, dbResult, params.resolvedBy);
534
+ }
535
+ /**
536
+ * Batch-item fill selecting the row by metadata facet — the highest
537
+ * priority pending row whose `metadata` contains the key/value, mirroring
538
+ * `resolveByMetadata()`'s selector semantics. See {@link resolveBatchItem}
539
+ * for the fill contract.
540
+ */
541
+ async resolveBatchItemByMetadata(params, namespace) {
542
+ const ns = (params.namespace ?? namespace) ?? factory_1.APP_ID;
543
+ const hm = await this._engine(null, ns);
544
+ const store = hm.engine.store;
545
+ //peek the row the fill is expected to lock; forSignalKey pins the wake
546
+ //to that row, so a different row winning the race falls through to
547
+ //post-commit delivery using the winner's own committed collection
548
+ let wakeCommand = null;
549
+ const preview = await store.peekEscalationByMetadata({
550
+ key: params.key,
551
+ value: params.value,
552
+ roles: params.roles,
553
+ namespace: params.namespace,
554
+ });
555
+ if (preview?.signalKey) {
556
+ wakeCommand = await this._buildWakeCommand(ns, preview.topic, preview.signalKey, {});
557
+ }
558
+ const dbResult = await store.resolveEscalationBatchItemByMetadata(params, wakeCommand ?? undefined, preview ? this._batchResolutionJson(preview.id, params.resolvedBy) : null);
559
+ return this._settleBatchItemResult(ns, dbResult, params.resolvedBy);
560
+ }
457
561
  /**
458
562
  * Full-fidelity migration: inserts an escalation row preserving the original
459
563
  * UUID and lifecycle state. Returns `null` on duplicate (idempotent).
@@ -65,3 +65,5 @@ declare class EscalationsClass {
65
65
  export { EscalationsClass as Escalations };
66
66
  export { EscalationClientService };
67
67
  export { ESCALATION_RESOLUTION_KEY } from './client';
68
+ export { foldBatchConfig } from './batch';
69
+ export { ESCALATION_BATCH_PENDING_KEY, ESCALATION_BATCH_COUNT_KEY, ESCALATION_BATCH_KEYS_KEY, ESCALATION_BATCH_ITEMS_KEY, } from '../../types/hmsh_escalations';
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ESCALATION_RESOLUTION_KEY = exports.EscalationClientService = exports.Escalations = void 0;
3
+ exports.ESCALATION_BATCH_ITEMS_KEY = exports.ESCALATION_BATCH_KEYS_KEY = exports.ESCALATION_BATCH_COUNT_KEY = exports.ESCALATION_BATCH_PENDING_KEY = exports.foldBatchConfig = 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; } });
@@ -71,3 +71,10 @@ EscalationsClass.guid = utils_1.guid;
71
71
  EscalationsClass.uuid = utils_1.uuid;
72
72
  var client_2 = require("./client");
73
73
  Object.defineProperty(exports, "ESCALATION_RESOLUTION_KEY", { enumerable: true, get: function () { return client_2.ESCALATION_RESOLUTION_KEY; } });
74
+ var batch_1 = require("./batch");
75
+ Object.defineProperty(exports, "foldBatchConfig", { enumerable: true, get: function () { return batch_1.foldBatchConfig; } });
76
+ var hmsh_escalations_1 = require("../../types/hmsh_escalations");
77
+ Object.defineProperty(exports, "ESCALATION_BATCH_PENDING_KEY", { enumerable: true, get: function () { return hmsh_escalations_1.ESCALATION_BATCH_PENDING_KEY; } });
78
+ Object.defineProperty(exports, "ESCALATION_BATCH_COUNT_KEY", { enumerable: true, get: function () { return hmsh_escalations_1.ESCALATION_BATCH_COUNT_KEY; } });
79
+ Object.defineProperty(exports, "ESCALATION_BATCH_KEYS_KEY", { enumerable: true, get: function () { return hmsh_escalations_1.ESCALATION_BATCH_KEYS_KEY; } });
80
+ Object.defineProperty(exports, "ESCALATION_BATCH_ITEMS_KEY", { enumerable: true, get: function () { return hmsh_escalations_1.ESCALATION_BATCH_ITEMS_KEY; } });
@@ -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.
@@ -315,6 +322,51 @@ declare class PostgresStoreService extends StoreService<ProviderClient, Provider
315
322
  topic?: string | null;
316
323
  wakeEnqueued?: boolean;
317
324
  }>;
325
+ /**
326
+ * Composes the batch-completion wake CTE. Unlike
327
+ * `composeEscalationWakeCTE`, the signal payload is only knowable inside
328
+ * the statement (the assembled item collection), so the pre-built message
329
+ * carries a placeholder that `jsonb_set` overwrites at `{data,data}` —
330
+ * the exact slot `condition()` unwraps. The jsonb round-trip may reorder
331
+ * keys; the engine parses the message by key, so this is safe. The INSERT
332
+ * fires only when the fill CTE resolved the row (last item) and its
333
+ * signal_key matches the wake.
334
+ */
335
+ private composeBatchWakeCTE;
336
+ /**
337
+ * The shared body of both batch-item store ops: guarded fill of one item
338
+ * into `envelope.batch_items`, `batch_pending`/`batch_count` recompute,
339
+ * resolve-on-last-item with the assembled collection as
340
+ * `resolver_payload`, wake enqueue, and outcome classification — one
341
+ * atomic statement. `targetCTE` supplies the row selector; it must expose
342
+ * id, signal_key, topic, status, assigned_to, assigned_until, batch_keys,
343
+ * batch_pending.
344
+ */
345
+ private _batchItemStatement;
346
+ private _mapBatchItemRow;
347
+ /**
348
+ * Fills one declared item of a batch escalation — see
349
+ * `_batchItemStatement` for the atomicity contract. Selects the row by
350
+ * `id` or `signalKey` (exactly one required). `resolutionJson` is the
351
+ * pre-serialized `$resolution` object merged into the delivered
352
+ * collection ONLY (never into the stored `resolver_payload`).
353
+ */
354
+ resolveEscalationBatchItem(params: import('../../../../types/hmsh_escalations').ResolveBatchItemParams, wakeCommand?: import('../../../../types/hmsh_escalations').EscalationWakeCommand, resolutionJson?: string | null): Promise<import('../../../../types/hmsh_escalations').ResolveBatchItemResult & {
355
+ signalKey?: string | null;
356
+ topic?: string | null;
357
+ wakeEnqueued?: boolean;
358
+ }>;
359
+ /**
360
+ * Batch-item fill selecting the row by metadata facet — the highest
361
+ * priority pending row whose `metadata` contains the key/value, mirroring
362
+ * `resolveEscalationByMetadata`'s selector. No claim assertion on this
363
+ * variant, matching the by-metadata precedent.
364
+ */
365
+ resolveEscalationBatchItemByMetadata(params: import('../../../../types/hmsh_escalations').ResolveBatchItemByMetadataParams, wakeCommand?: import('../../../../types/hmsh_escalations').EscalationWakeCommand, resolutionJson?: string | null): Promise<import('../../../../types/hmsh_escalations').ResolveBatchItemResult & {
366
+ signalKey?: string | null;
367
+ topic?: string | null;
368
+ wakeEnqueued?: boolean;
369
+ }>;
318
370
  cancelEscalation(id: string, namespace?: string, wakeCommand?: import('../../../../types/hmsh_escalations').EscalationWakeCommand): Promise<import('../../../../types/hmsh_escalations').CancelEscalationResult & {
319
371
  wakeEnqueued?: boolean;
320
372
  }>;
@@ -33,6 +33,7 @@ const utils_3 = require("./kvtypes/hash/utils");
33
33
  const enums_1 = require("../../../../modules/enums");
34
34
  const cache_1 = require("../../cache");
35
35
  const __1 = require("../..");
36
+ const batch_1 = require("../../../escalations/batch");
36
37
  const kvsql_1 = require("./kvsql");
37
38
  const kvtables_1 = require("./kvtables");
38
39
  const time_notify_1 = require("./time-notify");
@@ -1314,6 +1315,20 @@ class PostgresStoreService extends __1.StoreService {
1314
1315
  }
1315
1316
  }
1316
1317
  // ── Exporter queries ───────────────────────────────────────────────────────
1318
+ /**
1319
+ * Fetch and decode a single compressed-symbol field from a job's HASH.
1320
+ * Reads one field with `hmget` (no full-hash scan), then decodes it with
1321
+ * the same rules the serializer uses on write. Powers narrow getters such
1322
+ * as the workflow input arguments without a full export.
1323
+ */
1324
+ async getJobArguments(jobId, symbolField) {
1325
+ const key = this.mintKey(key_1.KeyType.JOB_STATE, { appId: this.appId, jobId });
1326
+ const [raw] = await this.kvsql().hmget(key, [symbolField]);
1327
+ if (raw === undefined || raw === null) {
1328
+ return undefined;
1329
+ }
1330
+ return this.parseHmshValue(raw);
1331
+ }
1317
1332
  /**
1318
1333
  * Fetch activity inputs for a workflow. Used by the exporter to enrich
1319
1334
  * timeline events with activity arguments.
@@ -1510,7 +1525,10 @@ class PostgresStoreService extends __1.StoreService {
1510
1525
  }
1511
1526
  }
1512
1527
  _escalationInsertParams(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;
1528
+ // A `batch` declaration folds into metadata/envelope so the accumulator
1529
+ // shape is present from the row's first visible moment.
1530
+ const folded = params.batch ? (0, batch_1.foldBatchConfig)(params) : params;
1531
+ 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, } = folded;
1514
1532
  return [
1515
1533
  namespace ?? 'hmsh',
1516
1534
  appId ?? 'hmsh',
@@ -2074,6 +2092,205 @@ class PostgresStoreService extends __1.StoreService {
2074
2092
  wakeEnqueued: row.wake_count > 0,
2075
2093
  };
2076
2094
  }
2095
+ /**
2096
+ * Composes the batch-completion wake CTE. Unlike
2097
+ * `composeEscalationWakeCTE`, the signal payload is only knowable inside
2098
+ * the statement (the assembled item collection), so the pre-built message
2099
+ * carries a placeholder that `jsonb_set` overwrites at `{data,data}` —
2100
+ * the exact slot `condition()` unwraps. The jsonb round-trip may reorder
2101
+ * keys; the engine parses the message by key, so this is safe. The INSERT
2102
+ * fires only when the fill CTE resolved the row (last item) and its
2103
+ * signal_key matches the wake.
2104
+ */
2105
+ composeBatchWakeCTE(wakeCommand, resolutionJson, params, fromCTE) {
2106
+ if (!wakeCommand) {
2107
+ return { wakeCTE: '', wakeCount: '0::int AS wake_count' };
2108
+ }
2109
+ const schemaName = this.kvsql().safeName(this.appId);
2110
+ const base = params.length;
2111
+ params.push(this.appId, wakeCommand.message, wakeCommand.forSignalKey, resolutionJson);
2112
+ return {
2113
+ wakeCTE: `,
2114
+ wake AS (
2115
+ INSERT INTO ${schemaName}.engine_streams (stream_name, message, priority)
2116
+ SELECT $${base + 1},
2117
+ jsonb_set($${base + 2}::jsonb, '{data,data}',
2118
+ ${fromCTE}.resolver_payload::jsonb || COALESCE($${base + 4}::jsonb, '{}'::jsonb))::text,
2119
+ 5
2120
+ FROM ${fromCTE}
2121
+ WHERE ${fromCTE}.status = 'resolved' AND ${fromCTE}.signal_key = $${base + 3}
2122
+ RETURNING id
2123
+ )`,
2124
+ wakeCount: '(SELECT COUNT(*) FROM wake)::int AS wake_count',
2125
+ };
2126
+ }
2127
+ /**
2128
+ * The shared body of both batch-item store ops: guarded fill of one item
2129
+ * into `envelope.batch_items`, `batch_pending`/`batch_count` recompute,
2130
+ * resolve-on-last-item with the assembled collection as
2131
+ * `resolver_payload`, wake enqueue, and outcome classification — one
2132
+ * atomic statement. `targetCTE` supplies the row selector; it must expose
2133
+ * id, signal_key, topic, status, assigned_to, assigned_until, batch_keys,
2134
+ * batch_pending.
2135
+ */
2136
+ _batchItemStatement(targetCTE, itemKeyIdx, payloadIdx, metaIdx, claimIdx, wakeCTE, wakeCount) {
2137
+ const remaining = `jsonb_array_length((e.metadata->'batch_pending') - $${itemKeyIdx}::text)`;
2138
+ return `
2139
+ WITH target AS MATERIALIZED (${targetCTE}),
2140
+ filled AS (
2141
+ UPDATE public.hmsh_escalations e
2142
+ SET envelope = COALESCE(e.envelope, '{}'::jsonb)
2143
+ || jsonb_build_object('batch_items',
2144
+ COALESCE(e.envelope->'batch_items', '{}'::jsonb)
2145
+ || jsonb_build_object($${itemKeyIdx}::text, $${payloadIdx}::jsonb)),
2146
+ metadata = COALESCE(e.metadata, '{}'::jsonb)
2147
+ || COALESCE($${metaIdx}::jsonb, '{}'::jsonb)
2148
+ || jsonb_build_object(
2149
+ 'batch_pending', (e.metadata->'batch_pending') - $${itemKeyIdx}::text,
2150
+ 'batch_count', ${remaining}),
2151
+ status = CASE WHEN ${remaining} = 0 THEN 'resolved' ELSE e.status END,
2152
+ resolved_at = CASE WHEN ${remaining} = 0 THEN NOW() ELSE e.resolved_at END,
2153
+ resolver_payload = CASE WHEN ${remaining} = 0
2154
+ THEN COALESCE(e.envelope->'batch_items', '{}'::jsonb)
2155
+ || jsonb_build_object($${itemKeyIdx}::text, $${payloadIdx}::jsonb)
2156
+ ELSE e.resolver_payload END,
2157
+ updated_at = NOW()
2158
+ FROM target
2159
+ WHERE e.id = target.id
2160
+ AND target.status = 'pending'
2161
+ AND jsonb_typeof(target.batch_pending) = 'array'
2162
+ AND target.batch_pending ? $${itemKeyIdx}::text
2163
+ AND ($${claimIdx}::text IS NULL
2164
+ OR target.assigned_to IS NULL
2165
+ OR target.assigned_until IS NULL
2166
+ OR (target.assigned_to = $${claimIdx}::text AND target.assigned_until > NOW())
2167
+ OR (target.assigned_to <> $${claimIdx}::text AND target.assigned_until <= NOW()))
2168
+ RETURNING e.*
2169
+ )${wakeCTE}
2170
+ SELECT t.id, t.status AS prior_status, t.signal_key, t.topic, t.assigned_to,
2171
+ CASE
2172
+ WHEN f.id IS NOT NULL AND f.status = 'resolved' THEN 'completed'
2173
+ WHEN f.id IS NOT NULL THEN 'accepted'
2174
+ WHEN t.id IS NULL THEN 'not-found'
2175
+ WHEN t.status <> 'pending' THEN 'blocked'
2176
+ WHEN NOT ($${claimIdx}::text IS NULL
2177
+ OR t.assigned_to IS NULL
2178
+ OR t.assigned_until IS NULL
2179
+ OR (t.assigned_to = $${claimIdx}::text AND t.assigned_until > NOW())
2180
+ OR (t.assigned_to <> $${claimIdx}::text AND t.assigned_until <= NOW()))
2181
+ THEN 'claim-blocked'
2182
+ WHEN jsonb_typeof(t.batch_pending) IS DISTINCT FROM 'array' THEN 'not-batch'
2183
+ WHEN NOT (t.batch_keys ? $${itemKeyIdx}::text) THEN 'unknown-item'
2184
+ ELSE 'duplicate-item'
2185
+ END AS outcome,
2186
+ jsonb_array_length(f.metadata->'batch_pending')::int AS remaining,
2187
+ row_to_json(f.*) AS entry_json,
2188
+ ${wakeCount}
2189
+ FROM (SELECT * FROM target) t
2190
+ FULL OUTER JOIN (SELECT * FROM filled) f ON f.id = t.id
2191
+ `;
2192
+ }
2193
+ _mapBatchItemRow(row, assertClaim) {
2194
+ if (!row || row.outcome === 'not-found')
2195
+ return { ok: false, outcome: 'not-found' };
2196
+ if (row.outcome === 'completed' || row.outcome === 'accepted') {
2197
+ return {
2198
+ ok: true,
2199
+ outcome: row.outcome,
2200
+ remaining: row.remaining ?? 0,
2201
+ entry: row.entry_json,
2202
+ signalKey: row.signal_key,
2203
+ topic: row.topic,
2204
+ wakeEnqueued: row.wake_count > 0,
2205
+ };
2206
+ }
2207
+ if (row.outcome === 'blocked') {
2208
+ if (row.prior_status === 'cancelled')
2209
+ return { ok: false, outcome: 'already-cancelled' };
2210
+ if (row.prior_status === 'expired')
2211
+ return { ok: false, outcome: 'already-expired' };
2212
+ return { ok: false, outcome: 'already-resolved' };
2213
+ }
2214
+ if (row.outcome === 'claim-blocked') {
2215
+ return {
2216
+ ok: false,
2217
+ outcome: row.assigned_to === assertClaim ? 'claim-expired' : 'claimed-by-other',
2218
+ };
2219
+ }
2220
+ return { ok: false, outcome: row.outcome };
2221
+ }
2222
+ /**
2223
+ * Fills one declared item of a batch escalation — see
2224
+ * `_batchItemStatement` for the atomicity contract. Selects the row by
2225
+ * `id` or `signalKey` (exactly one required). `resolutionJson` is the
2226
+ * pre-serialized `$resolution` object merged into the delivered
2227
+ * collection ONLY (never into the stored `resolver_payload`).
2228
+ */
2229
+ async resolveEscalationBatchItem(params, wakeCommand, resolutionJson) {
2230
+ const { id, signalKey, namespace, itemKey, payload, metadata, assertClaim } = params;
2231
+ if ((id ? 1 : 0) + (signalKey ? 1 : 0) !== 1) {
2232
+ throw new Error('resolveBatchItem requires exactly one of `id` or `signalKey`');
2233
+ }
2234
+ const sqlParams = [
2235
+ id ?? signalKey,
2236
+ itemKey,
2237
+ JSON.stringify(payload ?? {}),
2238
+ metadata ? JSON.stringify(metadata) : null,
2239
+ assertClaim ?? null,
2240
+ ];
2241
+ let nsClause = '';
2242
+ if (namespace) {
2243
+ sqlParams.push(namespace);
2244
+ nsClause = ` AND namespace = $${sqlParams.length}`;
2245
+ }
2246
+ const { wakeCTE, wakeCount } = this.composeBatchWakeCTE(wakeCommand, resolutionJson ?? null, sqlParams, 'filled');
2247
+ const targetCTE = `
2248
+ SELECT id, signal_key, topic, status, assigned_to, assigned_until,
2249
+ metadata->'batch_keys' AS batch_keys,
2250
+ metadata->'batch_pending' AS batch_pending
2251
+ FROM public.hmsh_escalations
2252
+ WHERE ${id ? 'id' : 'signal_key'} = $1${nsClause}
2253
+ LIMIT 1 FOR UPDATE`;
2254
+ const result = await this.pgClient.query(this._batchItemStatement(targetCTE, 2, 3, 4, 5, wakeCTE, wakeCount), sqlParams);
2255
+ return this._mapBatchItemRow(result.rows[0], assertClaim ?? undefined);
2256
+ }
2257
+ /**
2258
+ * Batch-item fill selecting the row by metadata facet — the highest
2259
+ * priority pending row whose `metadata` contains the key/value, mirroring
2260
+ * `resolveEscalationByMetadata`'s selector. No claim assertion on this
2261
+ * variant, matching the by-metadata precedent.
2262
+ */
2263
+ async resolveEscalationBatchItemByMetadata(params, wakeCommand, resolutionJson) {
2264
+ const { key, value, roles, namespace, itemKey, payload, metadata } = params;
2265
+ const filter = JSON.stringify({ [key]: value });
2266
+ const sqlParams = [
2267
+ filter,
2268
+ itemKey,
2269
+ JSON.stringify(payload ?? {}),
2270
+ metadata ? JSON.stringify(metadata) : null,
2271
+ null,
2272
+ roles ?? null,
2273
+ ];
2274
+ let nsClause = '';
2275
+ if (namespace) {
2276
+ sqlParams.push(namespace);
2277
+ nsClause = `namespace = $${sqlParams.length} AND`;
2278
+ }
2279
+ const { wakeCTE, wakeCount } = this.composeBatchWakeCTE(wakeCommand, resolutionJson ?? null, sqlParams, 'filled');
2280
+ const targetCTE = `
2281
+ SELECT id, signal_key, topic, status, assigned_to, assigned_until,
2282
+ metadata->'batch_keys' AS batch_keys,
2283
+ metadata->'batch_pending' AS batch_pending
2284
+ FROM public.hmsh_escalations
2285
+ WHERE ${nsClause}
2286
+ metadata @> $1::jsonb
2287
+ AND ($6::text[] IS NULL OR role = ANY($6::text[]))
2288
+ AND status IN ('pending', 'cancelled')
2289
+ ORDER BY priority ASC, created_at ASC
2290
+ LIMIT 1 FOR UPDATE`;
2291
+ const result = await this.pgClient.query(this._batchItemStatement(targetCTE, 2, 3, 4, 5, wakeCTE, wakeCount), sqlParams);
2292
+ return this._mapBatchItemRow(result.rows[0]);
2293
+ }
2077
2294
  async cancelEscalation(id, namespace, wakeCommand) {
2078
2295
  //single statement: the cancellation wake is a data-modifying CTE
2079
2296
  //that fires iff the cancel lands AND the row's signal_key matches
@@ -17,6 +17,19 @@ export interface ConditionQueueConfig {
17
17
  /** Unindexed display/form context for resolver UIs */
18
18
  envelope?: Record<string, unknown>;
19
19
  expiresAt?: Date;
20
+ /**
21
+ * Declares the wait as a batch accumulator: the escalation only resolves
22
+ * once every named item has been submitted via `resolveBatchItem()`. Each
23
+ * entry is an item key a contributor fills exactly once; the wait's signal
24
+ * fires with the full collection (`Record<itemKey, payload>`) when the LAST
25
+ * item lands. Folded at creation into the row's queryable facets
26
+ * (`metadata.batch_pending` / `batch_count` / `batch_keys`) and payload
27
+ * accumulator (`envelope.batch_items`) — one atomic INSERT with the
28
+ * workflow checkpoint. `timeout` and `cancel()` semantics are unchanged:
29
+ * `false` / `null`, with any partially filled items preserved on the
30
+ * terminal row for audit.
31
+ */
32
+ batch?: string[];
20
33
  /**
21
34
  * Born-assigned: writes `assigned_to` in the same atomic INSERT that
22
35
  * creates the row — on the `condition()` path, one commit with the
@@ -305,6 +318,12 @@ export interface CreateEscalationParams {
305
318
  assignee?: string;
306
319
  /** With `assignee`, arms the claim TTL window at creation. See {@link ConditionQueueConfig.durationMinutes}. */
307
320
  durationMinutes?: number;
321
+ /**
322
+ * Declares the row as a batch accumulator. See
323
+ * {@link ConditionQueueConfig.batch}. Standalone batch rows (no
324
+ * `signalKey`) accumulate and complete identically; the wake is a no-op.
325
+ */
326
+ batch?: string[];
308
327
  }
309
328
  /**
310
329
  * Fields that can be patched on an existing escalation. All fields are
@@ -413,6 +432,77 @@ export interface EscalateToRoleParams {
413
432
  targetRole: string;
414
433
  namespace?: string;
415
434
  }
435
+ /** Metadata facet: item keys still awaiting submission (jsonb string array).
436
+ * `metadata @> '{"batch_pending":["x"]}'` finds rows still missing item `x`. */
437
+ export declare const ESCALATION_BATCH_PENDING_KEY = "batch_pending";
438
+ /** Metadata facet: count of items still awaiting submission. Recomputed from
439
+ * `batch_pending` in every fill statement — the two can never drift. */
440
+ export declare const ESCALATION_BATCH_COUNT_KEY = "batch_count";
441
+ /** Metadata facet: the full declared item-key list, immutable after creation. */
442
+ export declare const ESCALATION_BATCH_KEYS_KEY = "batch_keys";
443
+ /** Envelope key: the payload accumulator (`Record<itemKey, payload>`).
444
+ * Payloads are plumbing, not facets — they live in the unindexed envelope. */
445
+ export declare const ESCALATION_BATCH_ITEMS_KEY = "batch_items";
446
+ /**
447
+ * Outcome of a `resolveBatchItem()` call.
448
+ * - `completed` — this was the LAST item: the row resolved and the waiting
449
+ * workflow was woken with the full collection, in the same statement.
450
+ * - `accepted` — interim fill: the item landed, the row stays `pending`.
451
+ * - `duplicate-item` — the key was declared but already filled.
452
+ * - `unknown-item` — the key was never declared in `batch_keys`.
453
+ * - `not-batch` — the row carries no batch declaration.
454
+ * - Remaining values match {@link ResolveEscalationResult} semantics.
455
+ */
456
+ export type BatchItemOutcome = 'completed' | 'accepted' | 'duplicate-item' | 'unknown-item' | 'not-batch' | 'not-found' | 'already-resolved' | 'already-cancelled' | 'already-expired' | 'claim-expired' | 'claimed-by-other';
457
+ export interface ResolveBatchItemParams {
458
+ /** Row selector — exactly one of `id` | `signalKey`. */
459
+ id?: string;
460
+ /** Row selector — the value passed to `condition()`. */
461
+ signalKey?: string;
462
+ namespace?: string;
463
+ /** The declared batch key this submission fills. */
464
+ itemKey: string;
465
+ /** The item's payload — stored under `envelope.batch_items[itemKey]` and,
466
+ * on completion, delivered as `collection[itemKey]` to the waiter. */
467
+ payload: Record<string, unknown>;
468
+ /** Merge patch applied to the row's GIN-indexed `metadata` in the same
469
+ * atomic UPDATE. See {@link ResolveEscalationParams.metadata}. */
470
+ metadata?: Record<string, unknown>;
471
+ /** Claim-lock assertion inside the same guarded UPDATE. Batch fills are
472
+ * claim-agnostic without it (multiple contributors are the norm). See
473
+ * {@link ResolveEscalationParams.assertClaim}. */
474
+ assertClaim?: string;
475
+ /** Resolver identity. Delivered under `$resolution` ONLY on the completing
476
+ * item's signal. See {@link ResolveEscalationParams.resolvedBy}. */
477
+ resolvedBy?: ResolvedByIdentity;
478
+ }
479
+ export interface ResolveBatchItemByMetadataParams {
480
+ /** Facet selector — mirrors {@link ResolveByMetadataParams}. */
481
+ key: string;
482
+ value: unknown;
483
+ roles?: string[];
484
+ namespace?: string;
485
+ itemKey: string;
486
+ payload: Record<string, unknown>;
487
+ /** Merge patch for the matched row's `metadata` — distinct from the
488
+ * `key`/`value` selector. */
489
+ metadata?: Record<string, unknown>;
490
+ resolvedBy?: ResolvedByIdentity;
491
+ }
492
+ /**
493
+ * Result of `resolveBatchItem()` / `resolveBatchItemByMetadata()`. On
494
+ * `ok: true`, `remaining` is the count of items still unfilled (0 exactly
495
+ * when `outcome` is `completed`) and `entry` is the post-fill row.
496
+ */
497
+ export type ResolveBatchItemResult = {
498
+ ok: true;
499
+ outcome: 'completed' | 'accepted';
500
+ remaining: number;
501
+ entry: EscalationEntry;
502
+ } | {
503
+ ok: false;
504
+ outcome: Exclude<BatchItemOutcome, 'completed' | 'accepted'>;
505
+ };
416
506
  /**
417
507
  * Query selector for `claimManyByQuery()` — the filterable subset of
418
508
  * `ListEscalationsParams` that describes a claimable population. `status` is
@@ -1,2 +1,15 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ESCALATION_BATCH_ITEMS_KEY = exports.ESCALATION_BATCH_KEYS_KEY = exports.ESCALATION_BATCH_COUNT_KEY = exports.ESCALATION_BATCH_PENDING_KEY = void 0;
4
+ // ─── Batch accumulation ───────────────────────────────────────────────────────
5
+ /** Metadata facet: item keys still awaiting submission (jsonb string array).
6
+ * `metadata @> '{"batch_pending":["x"]}'` finds rows still missing item `x`. */
7
+ exports.ESCALATION_BATCH_PENDING_KEY = 'batch_pending';
8
+ /** Metadata facet: count of items still awaiting submission. Recomputed from
9
+ * `batch_pending` in every fill statement — the two can never drift. */
10
+ exports.ESCALATION_BATCH_COUNT_KEY = 'batch_count';
11
+ /** Metadata facet: the full declared item-key list, immutable after creation. */
12
+ exports.ESCALATION_BATCH_KEYS_KEY = 'batch_keys';
13
+ /** Envelope key: the payload accumulator (`Record<itemKey, payload>`).
14
+ * Payloads are plumbing, not facets — they live in the unindexed envelope. */
15
+ exports.ESCALATION_BATCH_ITEMS_KEY = 'batch_items';
@@ -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, EscalationResolution, ResolvedByIdentity, ClaimManyQuerySelector, ClaimManyByQueryParams, } 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, BatchItemOutcome, ResolveBatchItemParams, ResolveBatchItemByMetadataParams, ResolveBatchItemResult, ESCALATION_BATCH_PENDING_KEY, ESCALATION_BATCH_COUNT_KEY, ESCALATION_BATCH_KEYS_KEY, ESCALATION_BATCH_ITEMS_KEY, } from './hmsh_escalations';
29
29
  export { EscalationVerb, EngineVerb, WorkerVerb, SystemEvent, EventsConfig } from './system_events';
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ValueType = exports.trace = exports.SpanKind = exports.SpanStatusCode = exports.propagation = exports.metrics = exports.context = exports.StreamStatus = exports.StreamRole = exports.StreamDataType = exports.KeyType = exports.HookGate = exports.CollationFaultType = void 0;
3
+ exports.ESCALATION_BATCH_ITEMS_KEY = exports.ESCALATION_BATCH_KEYS_KEY = exports.ESCALATION_BATCH_COUNT_KEY = exports.ESCALATION_BATCH_PENDING_KEY = exports.ValueType = exports.trace = exports.SpanKind = exports.SpanStatusCode = exports.propagation = exports.metrics = exports.context = exports.StreamStatus = exports.StreamRole = exports.StreamDataType = exports.KeyType = exports.HookGate = exports.CollationFaultType = void 0;
4
4
  var collator_1 = require("./collator");
5
5
  Object.defineProperty(exports, "CollationFaultType", { enumerable: true, get: function () { return collator_1.CollationFaultType; } });
6
6
  var hook_1 = require("./hook");
@@ -19,3 +19,8 @@ Object.defineProperty(exports, "SpanStatusCode", { enumerable: true, get: functi
19
19
  Object.defineProperty(exports, "SpanKind", { enumerable: true, get: function () { return telemetry_1.SpanKind; } });
20
20
  Object.defineProperty(exports, "trace", { enumerable: true, get: function () { return telemetry_1.trace; } });
21
21
  Object.defineProperty(exports, "ValueType", { enumerable: true, get: function () { return telemetry_1.ValueType; } });
22
+ var hmsh_escalations_1 = require("./hmsh_escalations");
23
+ Object.defineProperty(exports, "ESCALATION_BATCH_PENDING_KEY", { enumerable: true, get: function () { return hmsh_escalations_1.ESCALATION_BATCH_PENDING_KEY; } });
24
+ Object.defineProperty(exports, "ESCALATION_BATCH_COUNT_KEY", { enumerable: true, get: function () { return hmsh_escalations_1.ESCALATION_BATCH_COUNT_KEY; } });
25
+ Object.defineProperty(exports, "ESCALATION_BATCH_KEYS_KEY", { enumerable: true, get: function () { return hmsh_escalations_1.ESCALATION_BATCH_KEYS_KEY; } });
26
+ Object.defineProperty(exports, "ESCALATION_BATCH_ITEMS_KEY", { enumerable: true, get: function () { return hmsh_escalations_1.ESCALATION_BATCH_ITEMS_KEY; } });
@@ -115,7 +115,7 @@
115
115
  * ```
116
116
  */
117
117
  /** Verbs for escalation lifecycle transitions. */
118
- export type EscalationVerb = 'created' | 'claimed' | 'released' | 'reassigned' | 'resolved' | 'cancelled';
118
+ export type EscalationVerb = 'created' | 'claimed' | 'released' | 'reassigned' | 'resolved' | 'cancelled' | 'batch-item';
119
119
  /** Verbs for engine lifecycle transitions. */
120
120
  export type EngineVerb = 'started' | 'stopped' | 'deployed';
121
121
  /** Verbs for worker lifecycle transitions. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hotmeshio/hotmesh",
3
- "version": "0.27.0",
3
+ "version": "0.28.0",
4
4
  "description": "Durable Workflow",
5
5
  "main": "./build/index.js",
6
6
  "types": "./build/index.d.ts",
@@ -51,6 +51,7 @@
51
51
  "test:durable:readonly": "docker compose --profile readonly up -d --build && docker compose exec hotmesh-readonly npx vitest run --config tests/durable/readonly/vitest.config.mts",
52
52
  "test:durable:unknown": "vitest run tests/durable/unknown/postgres.test.ts",
53
53
  "test:durable:escalations": "HMSH_LOGLEVEL=info vitest run tests/durable/escalations",
54
+ "test:durable:escalations-batch": "HMSH_LOGLEVEL=info vitest run tests/durable/escalations-batch",
54
55
  "test:durable:exporter": "HMSH_LOGLEVEL=info vitest run tests/durable/exporter",
55
56
  "test:durable:exporter:debug": "EXPORT_DEBUG=1 HMSH_LOGLEVEL=error vitest run tests/durable/basic/postgres.test.ts",
56
57
  "test:durable:codec": "vitest run tests/durable/codec/postgres.test.ts",
@@ -88,6 +89,7 @@
88
89
  "test:unit": "vitest run tests/unit",
89
90
  "prove": "docker compose exec hotmesh npx vitest run tests/durable 2>&1 | tee /tmp/hmsh-durable.txt && grep -E 'FAIL|Tests |Files ' /tmp/hmsh-durable.txt | tail -5",
90
91
  "prove:escalations": "docker compose exec hotmesh npx vitest run tests/durable/escalations/postgres.test.ts 2>&1 | tee /tmp/hmsh-escalations.txt && grep -E 'FAIL|Tests |Files ' /tmp/hmsh-escalations.txt | tail -5",
92
+ "prove:escalations-batch": "docker compose exec hotmesh npx vitest run tests/durable/escalations-batch 2>&1 | tee /tmp/hmsh-escalations-batch.txt && grep -E 'FAIL|Tests |Files ' /tmp/hmsh-escalations-batch.txt | tail -5",
91
93
  "prove:migrations": "docker compose exec hotmesh npx vitest run tests/durable/migrations/postgres.test.ts 2>&1 | tee /tmp/hmsh-migrations.txt && grep -E 'FAIL|Tests |Files ' /tmp/hmsh-migrations.txt | tail -5",
92
94
  "prove:events": "docker compose exec hotmesh npx vitest run tests/durable/events/postgres.test.ts 2>&1 | tee /tmp/hmsh-events.txt && grep -E 'FAIL|Tests |Files ' /tmp/hmsh-events.txt | tail -5",
93
95
  "prove:functional": "docker compose exec hotmesh npx vitest run tests/functional 2>&1 | tee /tmp/hmsh-functional.txt && grep -E 'FAIL|Tests |Files ' /tmp/hmsh-functional.txt | tail -5",