@hotmeshio/hotmesh 0.31.2 → 0.32.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.31.2",
3
+ "version": "0.32.0",
4
4
  "description": "Durable Workflow",
5
5
  "main": "./build/index.js",
6
6
  "types": "./build/index.d.ts",
@@ -125,6 +125,26 @@ import { ConditionQueueConfig } from '../../../types/hmsh_escalations';
125
125
  * });
126
126
  * ```
127
127
  *
128
+ * `wakeOnFill` resumes the wait on a fill, so the workflow acts on each
129
+ * item as it lands: `true` for every key, or a list of keys. The fill
130
+ * resolves the row and the wait returns the items so far with
131
+ * `$filled: [itemKey]`, `$filledAt`, `$filledBy`, and `$trigger: 'fill'`.
132
+ * The next round parks with every fill carried forward; the last key
133
+ * completes as on any batch.
134
+ *
135
+ * ```typescript
136
+ * let filled;
137
+ * for (;;) {
138
+ * const out = await Durable.workflow.condition(`receive-${Durable.guid()}`, {
139
+ * role: 'receiving', batch: boxes, wakeOnFill: true, ...(filled ? { filled } : {}),
140
+ * });
141
+ * if (!out || out.$trigger !== 'fill') return out; // complete, expired, or cancelled
142
+ * await recordReceipt(out.$filled[0]); // a proxied activity
143
+ * filled = Object.fromEntries(Object.keys(out.$filledAt).map((key) =>
144
+ * [key, { payload: out[key], at: out.$filledAt[key], actor: out.$filledBy?.[key] }]));
145
+ * }
146
+ * ```
147
+ *
128
148
  * ## Placement: call escalation-bearing waits from main workflow code
129
149
  *
130
150
  * The resolve/signal delivery pipeline routes to the main flow's waiter.
@@ -131,6 +131,26 @@ const didRun_1 = require("./didRun");
131
131
  * });
132
132
  * ```
133
133
  *
134
+ * `wakeOnFill` resumes the wait on a fill, so the workflow acts on each
135
+ * item as it lands: `true` for every key, or a list of keys. The fill
136
+ * resolves the row and the wait returns the items so far with
137
+ * `$filled: [itemKey]`, `$filledAt`, `$filledBy`, and `$trigger: 'fill'`.
138
+ * The next round parks with every fill carried forward; the last key
139
+ * completes as on any batch.
140
+ *
141
+ * ```typescript
142
+ * let filled;
143
+ * for (;;) {
144
+ * const out = await Durable.workflow.condition(`receive-${Durable.guid()}`, {
145
+ * role: 'receiving', batch: boxes, wakeOnFill: true, ...(filled ? { filled } : {}),
146
+ * });
147
+ * if (!out || out.$trigger !== 'fill') return out; // complete, expired, or cancelled
148
+ * await recordReceipt(out.$filled[0]); // a proxied activity
149
+ * filled = Object.fromEntries(Object.keys(out.$filledAt).map((key) =>
150
+ * [key, { payload: out[key], at: out.$filledAt[key], actor: out.$filledBy?.[key] }]));
151
+ * }
152
+ * ```
153
+ *
134
154
  * ## Placement: call escalation-bearing waits from main workflow code
135
155
  *
136
156
  * The resolve/signal delivery pipeline routes to the main flow's waiter.
@@ -1,10 +1,12 @@
1
- import { AccumulateConfig, BatchFilledEntry } from '../../types/hmsh_escalations';
1
+ import { AccumulateConfig, BatchFilledEntry, FlagBatchItemParams } from '../../types/hmsh_escalations';
2
2
  /**
3
3
  * Folds a `batch` declaration into the escalation's storage shape:
4
4
  * queryable facets in `metadata` (`batch_pending`, `batch_count`,
5
5
  * `batch_keys`) and the payload accumulator in `envelope`
6
6
  * (`batch_items: {}`). `partialOnTimeout` is stored beside the items so
7
- * the expiry statement delivers the filled items instead of `false`.
7
+ * the expiry statement delivers the filled items instead of `false`;
8
+ * `wakeOnFlag` is stored the same way so a flag ends the wait, and
9
+ * `wakeOnFill` (`true` or its list of keys) so a fill ends it.
8
10
  * `filled` entries start satisfied: they are left out of `batch_pending`
9
11
  * and written into `batch_items`, `batch_filled_at`, and (when an entry
10
12
  * names an actor) `batch_filled_by`. Pure
@@ -15,8 +17,17 @@ import { AccumulateConfig, BatchFilledEntry } from '../../types/hmsh_escalations
15
17
  export declare function foldBatchConfig<T extends {
16
18
  batch?: string[];
17
19
  partialOnTimeout?: boolean;
20
+ wakeOnFlag?: boolean;
21
+ wakeOnFill?: boolean | string[];
18
22
  filled?: Record<string, BatchFilledEntry>;
19
23
  accumulate?: AccumulateConfig;
20
24
  metadata?: Record<string, unknown>;
21
25
  envelope?: Record<string, unknown>;
22
- }>(config: T): Omit<T, 'batch' | 'partialOnTimeout' | 'filled'>;
26
+ }>(config: T): Omit<T, 'batch' | 'partialOnTimeout' | 'wakeOnFlag' | 'wakeOnFill' | 'filled'>;
27
+ /**
28
+ * Validates a `flagBatchItem()` request before any read or write: exactly
29
+ * one row selector, a non-empty key and label within their limits, object
30
+ * `payload` and `metadata`, a non-empty `actor`, and no reserved batch key
31
+ * in the metadata patch. Throws on the first violation.
32
+ */
33
+ export declare function assertBatchFlagParams(params: FlagBatchItemParams): void;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.foldBatchConfig = void 0;
3
+ exports.assertBatchFlagParams = exports.foldBatchConfig = void 0;
4
4
  const hmsh_escalations_1 = require("../../types/hmsh_escalations");
5
5
  const RESERVED_METADATA_KEYS = new Set([
6
6
  hmsh_escalations_1.ESCALATION_BATCH_PENDING_KEY,
@@ -12,7 +12,31 @@ const RESERVED_ENVELOPE_KEYS = new Set([
12
12
  hmsh_escalations_1.ESCALATION_BATCH_FILLED_AT_KEY,
13
13
  hmsh_escalations_1.ESCALATION_BATCH_FILLED_BY_KEY,
14
14
  hmsh_escalations_1.ESCALATION_BATCH_PARTIAL_ON_TIMEOUT_KEY,
15
+ hmsh_escalations_1.ESCALATION_BATCH_FLAGS_KEY,
16
+ hmsh_escalations_1.ESCALATION_BATCH_WAKE_ON_FLAG_KEY,
17
+ hmsh_escalations_1.ESCALATION_BATCH_WAKE_ON_FILL_KEY,
15
18
  ]);
19
+ /**
20
+ * Validates `wakeOnFill` against the declared keys and returns its stored
21
+ * form: `true`, the de-duplicated key list, or `null` when the opt-in is
22
+ * absent, `false`, or an empty list.
23
+ */
24
+ function foldWakeOnFill(batch, wakeOnFill) {
25
+ if (wakeOnFill === undefined || wakeOnFill === false)
26
+ return null;
27
+ if (wakeOnFill === true)
28
+ return true;
29
+ if (!Array.isArray(wakeOnFill)) {
30
+ throw new Error('wakeOnFill must be a boolean or a list of batch keys');
31
+ }
32
+ for (const key of wakeOnFill) {
33
+ if (typeof key !== 'string' || !batch.includes(key)) {
34
+ throw new Error(`wakeOnFill key '${String(key)}' is not declared in batch`);
35
+ }
36
+ }
37
+ const keys = [...new Set(wakeOnFill)];
38
+ return keys.length ? keys : null;
39
+ }
16
40
  /**
17
41
  * Validates `filled` against the declared keys and splits it into the
18
42
  * envelope maps. Pure: `at` is normalized from the caller's value, never
@@ -65,7 +89,9 @@ function foldFilledEntries(batch, filled) {
65
89
  * queryable facets in `metadata` (`batch_pending`, `batch_count`,
66
90
  * `batch_keys`) and the payload accumulator in `envelope`
67
91
  * (`batch_items: {}`). `partialOnTimeout` is stored beside the items so
68
- * the expiry statement delivers the filled items instead of `false`.
92
+ * the expiry statement delivers the filled items instead of `false`;
93
+ * `wakeOnFlag` is stored the same way so a flag ends the wait, and
94
+ * `wakeOnFill` (`true` or its list of keys) so a fill ends it.
69
95
  * `filled` entries start satisfied: they are left out of `batch_pending`
70
96
  * and written into `batch_items`, `batch_filled_at`, and (when an entry
71
97
  * names an actor) `batch_filled_by`. Pure
@@ -74,11 +100,17 @@ function foldFilledEntries(batch, filled) {
74
100
  * durable write.
75
101
  */
76
102
  function foldBatchConfig(config) {
77
- const { batch, partialOnTimeout, filled, ...rest } = config;
103
+ const { batch, partialOnTimeout, wakeOnFlag, wakeOnFill, filled, ...rest } = config;
78
104
  if (!batch) {
79
105
  if (partialOnTimeout !== undefined) {
80
106
  throw new Error('partialOnTimeout requires a batch declaration');
81
107
  }
108
+ if (wakeOnFlag !== undefined) {
109
+ throw new Error('wakeOnFlag requires a batch declaration');
110
+ }
111
+ if (wakeOnFill !== undefined) {
112
+ throw new Error('wakeOnFill requires a batch declaration');
113
+ }
82
114
  if (filled !== undefined) {
83
115
  throw new Error('filled requires a batch declaration');
84
116
  }
@@ -90,6 +122,9 @@ function foldBatchConfig(config) {
90
122
  if (partialOnTimeout !== undefined && typeof partialOnTimeout !== 'boolean') {
91
123
  throw new Error('partialOnTimeout must be a boolean');
92
124
  }
125
+ if (wakeOnFlag !== undefined && typeof wakeOnFlag !== 'boolean') {
126
+ throw new Error('wakeOnFlag must be a boolean');
127
+ }
93
128
  if (!Array.isArray(batch) || batch.length === 0) {
94
129
  throw new Error('batch must be a non-empty array of item keys');
95
130
  }
@@ -116,6 +151,7 @@ function foldBatchConfig(config) {
116
151
  throw new Error(`envelope key '${reserved}' is reserved for batch state`);
117
152
  }
118
153
  }
154
+ const wakeKeys = foldWakeOnFill(batch, wakeOnFill);
119
155
  const fills = foldFilledEntries(batch, filled);
120
156
  return {
121
157
  ...rest,
@@ -135,7 +171,55 @@ function foldBatchConfig(config) {
135
171
  ...(partialOnTimeout
136
172
  ? { [hmsh_escalations_1.ESCALATION_BATCH_PARTIAL_ON_TIMEOUT_KEY]: true }
137
173
  : {}),
174
+ ...(wakeOnFlag ? { [hmsh_escalations_1.ESCALATION_BATCH_WAKE_ON_FLAG_KEY]: true } : {}),
175
+ ...(wakeKeys !== null
176
+ ? { [hmsh_escalations_1.ESCALATION_BATCH_WAKE_ON_FILL_KEY]: wakeKeys }
177
+ : {}),
138
178
  },
139
179
  };
140
180
  }
141
181
  exports.foldBatchConfig = foldBatchConfig;
182
+ /**
183
+ * Validates a `flagBatchItem()` request before any read or write: exactly
184
+ * one row selector, a non-empty key and label within their limits, object
185
+ * `payload` and `metadata`, a non-empty `actor`, and no reserved batch key
186
+ * in the metadata patch. Throws on the first violation.
187
+ */
188
+ function assertBatchFlagParams(params) {
189
+ const { id, signalKey, itemKey, label, payload, actor, metadata } = params;
190
+ if ((id ? 1 : 0) + (signalKey ? 1 : 0) !== 1) {
191
+ throw new Error('flagBatchItem requires exactly one of `id` or `signalKey`');
192
+ }
193
+ if (typeof itemKey !== 'string' || itemKey.length === 0) {
194
+ throw new Error('itemKey must be a non-empty string');
195
+ }
196
+ if (itemKey.length > hmsh_escalations_1.ESCALATION_BATCH_ITEM_KEY_MAX_LENGTH) {
197
+ throw new Error(`itemKey must be at most ${hmsh_escalations_1.ESCALATION_BATCH_ITEM_KEY_MAX_LENGTH} characters`);
198
+ }
199
+ if (typeof label !== 'string' || label.length === 0) {
200
+ throw new Error('label must be a non-empty string');
201
+ }
202
+ if (label.length > hmsh_escalations_1.ESCALATION_BATCH_FLAG_LABEL_MAX_LENGTH) {
203
+ throw new Error(`label must be at most ${hmsh_escalations_1.ESCALATION_BATCH_FLAG_LABEL_MAX_LENGTH} characters`);
204
+ }
205
+ if (payload !== undefined && !isPlainObject(payload)) {
206
+ throw new Error('payload must be an object');
207
+ }
208
+ if (actor !== undefined &&
209
+ (typeof actor !== 'string' || actor.length === 0)) {
210
+ throw new Error('actor must be a non-empty string');
211
+ }
212
+ if (metadata !== undefined) {
213
+ if (!isPlainObject(metadata))
214
+ throw new Error('metadata must be an object');
215
+ for (const reserved of RESERVED_METADATA_KEYS) {
216
+ if (reserved in metadata) {
217
+ throw new Error(`metadata key '${reserved}' is reserved for batch state`);
218
+ }
219
+ }
220
+ }
221
+ }
222
+ exports.assertBatchFlagParams = assertBatchFlagParams;
223
+ function isPlainObject(value) {
224
+ return !!value && typeof value === 'object' && !Array.isArray(value);
225
+ }
@@ -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, ResolveBatchItemParams, ResolveBatchItemByMetadataParams, ResolveBatchItemResult, AccumulateItemParams, AccumulateItemByMetadataParams, AccumulateItemResult, RemoveAccumulatedItemParams, RemoveAccumulatedItemByMetadataParams, RemoveAccumulatedItemResult } 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, AccumulateItemParams, AccumulateItemByMetadataParams, AccumulateItemResult, RemoveAccumulatedItemParams, RemoveAccumulatedItemByMetadataParams, RemoveAccumulatedItemResult, FlagBatchItemParams, FlagBatchItemResult, UnflagBatchItemParams, UnflagBatchItemResult } 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
@@ -215,7 +215,8 @@ export declare class EscalationClientService {
215
215
  * Shared post-statement handling for both batch-item forms: post-commit
216
216
  * wake fallback (the committed `resolver_payload` — the full assembled
217
217
  * collection — is the recovery record) and lifecycle events
218
- * (`batch-item` on interim fills, `resolved` on completion).
218
+ * (`batch-item` on interim fills, `resolved` on completion and on a
219
+ * `wakeOnFill` wake).
219
220
  */
220
221
  private _settleBatchItemResult;
221
222
  /**
@@ -227,7 +228,11 @@ export declare class EscalationClientService {
227
228
  * item — the row resolves with the assembled collection as its
228
229
  * `resolver_payload` and the waiting workflow's wake commits WITH the
229
230
  * fill (same durability contract as `resolve()`). The caller that lands
230
- * the last item learns it from `outcome: 'completed'`.
231
+ * the last item learns it from `outcome: 'completed'`. On a row whose wait
232
+ * declared `wakeOnFill` for this key, the same statement resolves the row
233
+ * early and the waiter wakes with the items filled so far, `$filled`,
234
+ * `$filledAt`, `$filledBy`, and `$trigger: 'fill'` (outcome `woke`,
235
+ * `remaining` > 0).
231
236
  *
232
237
  * Fills are claim-agnostic by default — a batch accumulates contributions
233
238
  * from multiple principals. Pass `assertClaim` to opt into the same
@@ -250,6 +255,26 @@ export declare class EscalationClientService {
250
255
  * for the fill contract.
251
256
  */
252
257
  resolveBatchItemByMetadata(params: ResolveBatchItemByMetadataParams, namespace?: string): Promise<ResolveBatchItemResult>;
258
+ /**
259
+ * Flags ONE pending key of a batch escalation (for example, `Missing`).
260
+ * One atomic statement writes `envelope.batch_flags[itemKey]` with the
261
+ * label, optional payload and actor, and the database clock, only while
262
+ * the row and the key are pending. The key stays pending: a later fill
263
+ * still lands and still counts toward completion.
264
+ *
265
+ * On a row whose wait declared `wakeOnFlag`, the same statement resolves
266
+ * the row and the waiter wakes with the items filled so far, `$flags`,
267
+ * and `$trigger: 'flag'` (outcome `completed`); the wake commits with the
268
+ * resolve, as on a completing fill. Otherwise the outcome is `flagged`
269
+ * and the wait continues. Flagging a flagged key replaces its flag.
270
+ */
271
+ flagBatchItem(params: FlagBatchItemParams, namespace?: string): Promise<FlagBatchItemResult>;
272
+ /**
273
+ * Clears ONE key's flag while the row is pending ("found it"). Only that
274
+ * key's entry is removed; items, pending keys and status are untouched.
275
+ * A key without a flag answers `not-flagged`.
276
+ */
277
+ unflagBatchItem(params: UnflagBatchItemParams, namespace?: string): Promise<UnflagBatchItemResult>;
253
278
  private _previewAccumulateRow;
254
279
  /**
255
280
  * Pre-builds one side's wake with a placeholder payload; the store
@@ -6,8 +6,10 @@ 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
+ const hmsh_escalations_1 = require("../../types/hmsh_escalations");
9
10
  const factory_1 = require("../durable/schemas/factory");
10
11
  const accumulate_1 = require("./accumulate");
12
+ const batch_1 = require("./batch");
11
13
  /**
12
14
  * Reserved signal-payload key carrying resolution provenance
13
15
  * (`EscalationResolution`) to the waiting workflow. The `$` prefix marks the
@@ -491,12 +493,13 @@ class EscalationClientService {
491
493
  * Shared post-statement handling for both batch-item forms: post-commit
492
494
  * wake fallback (the committed `resolver_payload` — the full assembled
493
495
  * collection — is the recovery record) and lifecycle events
494
- * (`batch-item` on interim fills, `resolved` on completion).
496
+ * (`batch-item` on interim fills, `resolved` on completion and on a
497
+ * `wakeOnFill` wake).
495
498
  */
496
499
  async _settleBatchItemResult(ns, dbResult, resolvedBy) {
497
500
  if (!dbResult.ok)
498
501
  return dbResult;
499
- if (dbResult.outcome === 'completed') {
502
+ if (dbResult.outcome === 'completed' || dbResult.outcome === 'woke') {
500
503
  if (dbResult.signalKey && !dbResult.wakeEnqueued) {
501
504
  await this._deliverEscalationSignal(ns, dbResult.topic, {
502
505
  id: dbResult.signalKey,
@@ -524,7 +527,11 @@ class EscalationClientService {
524
527
  * item — the row resolves with the assembled collection as its
525
528
  * `resolver_payload` and the waiting workflow's wake commits WITH the
526
529
  * fill (same durability contract as `resolve()`). The caller that lands
527
- * the last item learns it from `outcome: 'completed'`.
530
+ * the last item learns it from `outcome: 'completed'`. On a row whose wait
531
+ * declared `wakeOnFill` for this key, the same statement resolves the row
532
+ * early and the waiter wakes with the items filled so far, `$filled`,
533
+ * `$filledAt`, `$filledBy`, and `$trigger: 'fill'` (outcome `woke`,
534
+ * `remaining` > 0).
528
535
  *
529
536
  * Fills are claim-agnostic by default — a batch accumulates contributions
530
537
  * from multiple principals. Pass `assertClaim` to opt into the same
@@ -582,6 +589,67 @@ class EscalationClientService {
582
589
  const dbResult = await store.resolveEscalationBatchItemByMetadata(params, wakeCommand ?? undefined, preview ? this._batchResolutionJson(preview.id, params.resolvedBy) : null);
583
590
  return this._settleBatchItemResult(ns, dbResult, params.resolvedBy);
584
591
  }
592
+ /**
593
+ * Flags ONE pending key of a batch escalation (for example, `Missing`).
594
+ * One atomic statement writes `envelope.batch_flags[itemKey]` with the
595
+ * label, optional payload and actor, and the database clock, only while
596
+ * the row and the key are pending. The key stays pending: a later fill
597
+ * still lands and still counts toward completion.
598
+ *
599
+ * On a row whose wait declared `wakeOnFlag`, the same statement resolves
600
+ * the row and the waiter wakes with the items filled so far, `$flags`,
601
+ * and `$trigger: 'flag'` (outcome `completed`); the wake commits with the
602
+ * resolve, as on a completing fill. Otherwise the outcome is `flagged`
603
+ * and the wait continues. Flagging a flagged key replaces its flag.
604
+ */
605
+ async flagBatchItem(params, namespace) {
606
+ (0, batch_1.assertBatchFlagParams)(params);
607
+ const ns = params.namespace ?? namespace ?? factory_1.APP_ID;
608
+ const hm = await this._engine(null, ns);
609
+ const store = hm.engine.store;
610
+ //the wake is built only for a row that declared wakeOnFlag at creation;
611
+ //the declaration never changes, so the preview decides it safely
612
+ const preview = params.id
613
+ ? await store.getEscalation(params.id, params.namespace)
614
+ : await store.getEscalationBySignalKey(params.signalKey, params.namespace);
615
+ let wakeCommand = null;
616
+ if (preview?.signal_key &&
617
+ preview.envelope?.[hmsh_escalations_1.ESCALATION_BATCH_WAKE_ON_FLAG_KEY] === true) {
618
+ wakeCommand = await this._buildWakeCommand(ns, preview.topic, preview.signal_key, {});
619
+ }
620
+ const dbResult = await store.flagEscalationBatchItem(params, wakeCommand ?? undefined, preview ? this._batchResolutionJson(preview.id, params.resolvedBy) : null);
621
+ if (!dbResult.ok)
622
+ return dbResult;
623
+ if (dbResult.outcome === 'completed') {
624
+ if (dbResult.signalKey && !dbResult.wakeEnqueued) {
625
+ await this._deliverEscalationSignal(ns, dbResult.topic, {
626
+ id: dbResult.signalKey,
627
+ data: this._signalData(dbResult.entry.resolver_payload ?? {}, dbResult.entry.id, params.resolvedBy),
628
+ });
629
+ }
630
+ this._emit('resolved', dbResult.entry);
631
+ }
632
+ else {
633
+ this._emit('flagged', dbResult.entry);
634
+ }
635
+ return { ok: true, outcome: dbResult.outcome, entry: dbResult.entry };
636
+ }
637
+ /**
638
+ * Clears ONE key's flag while the row is pending ("found it"). Only that
639
+ * key's entry is removed; items, pending keys and status are untouched.
640
+ * A key without a flag answers `not-flagged`.
641
+ */
642
+ async unflagBatchItem(params, namespace) {
643
+ if (typeof params.itemKey !== 'string' || params.itemKey.length === 0) {
644
+ throw new Error('itemKey must be a non-empty string');
645
+ }
646
+ const ns = params.namespace ?? namespace ?? factory_1.APP_ID;
647
+ const hm = await this._engine(null, ns);
648
+ const result = await hm.engine.store.unflagEscalationBatchItem(params);
649
+ if (result.ok)
650
+ this._emit('unflagged', result.entry);
651
+ return result;
652
+ }
585
653
  // ─── Open accumulation ──────────────────────────────────────────────────────
586
654
  async _previewAccumulateRow(store, selector, namespace) {
587
655
  if (selector.id) {
@@ -2,6 +2,8 @@ import { AccumulateConfig, BatchFilledEntry } from '../../types/hmsh_escalations
2
2
  type Foldable = {
3
3
  batch?: string[];
4
4
  partialOnTimeout?: boolean;
5
+ wakeOnFlag?: boolean;
6
+ wakeOnFill?: boolean | string[];
5
7
  filled?: Record<string, BatchFilledEntry>;
6
8
  accumulate?: AccumulateConfig;
7
9
  metadata?: Record<string, unknown>;
@@ -13,5 +15,5 @@ type Foldable = {
13
15
  * config through untouched. The single entry point for both the
14
16
  * `condition()` path and standalone `create()`.
15
17
  */
16
- export declare function foldEscalationConfig<T extends Foldable>(config: T): Omit<T, 'batch' | 'partialOnTimeout' | 'filled' | 'accumulate'>;
18
+ export declare function foldEscalationConfig<T extends Foldable>(config: T): Omit<T, 'batch' | 'partialOnTimeout' | 'wakeOnFlag' | 'wakeOnFill' | 'filled' | 'accumulate'>;
17
19
  export {};
@@ -10,7 +10,7 @@ const batch_1 = require("./batch");
10
10
  * `condition()` path and standalone `create()`.
11
11
  */
12
12
  function foldEscalationConfig(config) {
13
- const { batch, partialOnTimeout, filled, accumulate, ...rest } = config;
13
+ const { batch, partialOnTimeout, wakeOnFlag, wakeOnFill, filled, accumulate, ...rest } = config;
14
14
  if (batch) {
15
15
  if (accumulate) {
16
16
  throw new Error('accumulate and batch are mutually exclusive');
@@ -19,6 +19,8 @@ function foldEscalationConfig(config) {
19
19
  ...rest,
20
20
  batch,
21
21
  partialOnTimeout,
22
+ wakeOnFlag,
23
+ wakeOnFill,
22
24
  filled,
23
25
  });
24
26
  }
@@ -26,6 +28,12 @@ function foldEscalationConfig(config) {
26
28
  if (filled !== undefined) {
27
29
  throw new Error('filled applies to batch only');
28
30
  }
31
+ if (wakeOnFlag !== undefined) {
32
+ throw new Error('wakeOnFlag applies to batch only');
33
+ }
34
+ if (wakeOnFill !== undefined) {
35
+ throw new Error('wakeOnFill applies to batch only');
36
+ }
29
37
  return (0, accumulate_1.foldAccumulateConfig)({ ...rest, accumulate });
30
38
  }
31
39
  if (partialOnTimeout !== undefined) {
@@ -34,6 +42,12 @@ function foldEscalationConfig(config) {
34
42
  if (filled !== undefined) {
35
43
  throw new Error('filled requires a batch declaration');
36
44
  }
45
+ if (wakeOnFlag !== undefined) {
46
+ throw new Error('wakeOnFlag requires a batch declaration');
47
+ }
48
+ if (wakeOnFill !== undefined) {
49
+ throw new Error('wakeOnFill requires a batch declaration');
50
+ }
37
51
  return rest;
38
52
  }
39
53
  exports.foldEscalationConfig = foldEscalationConfig;
@@ -68,4 +68,4 @@ export { ESCALATION_RESOLUTION_KEY } from './client';
68
68
  export { foldBatchConfig } from './batch';
69
69
  export { foldAccumulateConfig, assertAccumulateItemKey } from './accumulate';
70
70
  export { foldEscalationConfig } from './fold';
71
- export { ESCALATION_BATCH_PENDING_KEY, ESCALATION_BATCH_COUNT_KEY, ESCALATION_BATCH_KEYS_KEY, ESCALATION_BATCH_ITEMS_KEY, ESCALATION_BATCH_FILLED_AT_KEY, ESCALATION_BATCH_FILLED_BY_KEY, ESCALATION_BATCH_PARTIAL_ON_TIMEOUT_KEY, ESCALATION_BATCH_ITEM_KEY_MAX_LENGTH, ESCALATION_ACCUMULATE_COUNT_KEY, ESCALATION_ACCUMULATE_MAX_KEY, ESCALATION_ACCUMULATE_KEYS_KEY, ESCALATION_ACCUMULATE_ITEMS_KEY, ESCALATION_ACCUMULATE_CONFIG_KEY, ESCALATION_ACCUMULATED_KEY, ESCALATION_TRIGGER_KEY, } from '../../types/hmsh_escalations';
71
+ export { ESCALATION_BATCH_PENDING_KEY, ESCALATION_BATCH_COUNT_KEY, ESCALATION_BATCH_KEYS_KEY, ESCALATION_BATCH_ITEMS_KEY, ESCALATION_BATCH_FILLED_AT_KEY, ESCALATION_BATCH_FILLED_BY_KEY, ESCALATION_BATCH_PARTIAL_ON_TIMEOUT_KEY, ESCALATION_BATCH_ITEM_KEY_MAX_LENGTH, ESCALATION_BATCH_FLAGS_KEY, ESCALATION_BATCH_WAKE_ON_FLAG_KEY, ESCALATION_BATCH_FLAG_LABEL_MAX_LENGTH, ESCALATION_FLAGS_KEY, ESCALATION_BATCH_WAKE_ON_FILL_KEY, ESCALATION_FILLED_KEY, ESCALATION_FILLED_AT_KEY, ESCALATION_FILLED_BY_KEY, ESCALATION_ACCUMULATE_COUNT_KEY, ESCALATION_ACCUMULATE_MAX_KEY, ESCALATION_ACCUMULATE_KEYS_KEY, ESCALATION_ACCUMULATE_ITEMS_KEY, ESCALATION_ACCUMULATE_CONFIG_KEY, ESCALATION_ACCUMULATED_KEY, ESCALATION_TRIGGER_KEY, } from '../../types/hmsh_escalations';
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ESCALATION_TRIGGER_KEY = exports.ESCALATION_ACCUMULATED_KEY = exports.ESCALATION_ACCUMULATE_CONFIG_KEY = exports.ESCALATION_ACCUMULATE_ITEMS_KEY = exports.ESCALATION_ACCUMULATE_KEYS_KEY = exports.ESCALATION_ACCUMULATE_MAX_KEY = exports.ESCALATION_ACCUMULATE_COUNT_KEY = exports.ESCALATION_BATCH_ITEM_KEY_MAX_LENGTH = exports.ESCALATION_BATCH_PARTIAL_ON_TIMEOUT_KEY = exports.ESCALATION_BATCH_FILLED_BY_KEY = exports.ESCALATION_BATCH_FILLED_AT_KEY = exports.ESCALATION_BATCH_ITEMS_KEY = exports.ESCALATION_BATCH_KEYS_KEY = exports.ESCALATION_BATCH_COUNT_KEY = exports.ESCALATION_BATCH_PENDING_KEY = exports.foldEscalationConfig = exports.assertAccumulateItemKey = exports.foldAccumulateConfig = exports.foldBatchConfig = exports.ESCALATION_RESOLUTION_KEY = exports.EscalationClientService = exports.Escalations = void 0;
3
+ exports.ESCALATION_TRIGGER_KEY = exports.ESCALATION_ACCUMULATED_KEY = exports.ESCALATION_ACCUMULATE_CONFIG_KEY = exports.ESCALATION_ACCUMULATE_ITEMS_KEY = exports.ESCALATION_ACCUMULATE_KEYS_KEY = exports.ESCALATION_ACCUMULATE_MAX_KEY = exports.ESCALATION_ACCUMULATE_COUNT_KEY = exports.ESCALATION_FILLED_BY_KEY = exports.ESCALATION_FILLED_AT_KEY = exports.ESCALATION_FILLED_KEY = exports.ESCALATION_BATCH_WAKE_ON_FILL_KEY = exports.ESCALATION_FLAGS_KEY = exports.ESCALATION_BATCH_FLAG_LABEL_MAX_LENGTH = exports.ESCALATION_BATCH_WAKE_ON_FLAG_KEY = exports.ESCALATION_BATCH_FLAGS_KEY = exports.ESCALATION_BATCH_ITEM_KEY_MAX_LENGTH = exports.ESCALATION_BATCH_PARTIAL_ON_TIMEOUT_KEY = exports.ESCALATION_BATCH_FILLED_BY_KEY = exports.ESCALATION_BATCH_FILLED_AT_KEY = exports.ESCALATION_BATCH_ITEMS_KEY = exports.ESCALATION_BATCH_KEYS_KEY = exports.ESCALATION_BATCH_COUNT_KEY = exports.ESCALATION_BATCH_PENDING_KEY = exports.foldEscalationConfig = exports.assertAccumulateItemKey = exports.foldAccumulateConfig = 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; } });
@@ -87,6 +87,14 @@ Object.defineProperty(exports, "ESCALATION_BATCH_FILLED_AT_KEY", { enumerable: t
87
87
  Object.defineProperty(exports, "ESCALATION_BATCH_FILLED_BY_KEY", { enumerable: true, get: function () { return hmsh_escalations_1.ESCALATION_BATCH_FILLED_BY_KEY; } });
88
88
  Object.defineProperty(exports, "ESCALATION_BATCH_PARTIAL_ON_TIMEOUT_KEY", { enumerable: true, get: function () { return hmsh_escalations_1.ESCALATION_BATCH_PARTIAL_ON_TIMEOUT_KEY; } });
89
89
  Object.defineProperty(exports, "ESCALATION_BATCH_ITEM_KEY_MAX_LENGTH", { enumerable: true, get: function () { return hmsh_escalations_1.ESCALATION_BATCH_ITEM_KEY_MAX_LENGTH; } });
90
+ Object.defineProperty(exports, "ESCALATION_BATCH_FLAGS_KEY", { enumerable: true, get: function () { return hmsh_escalations_1.ESCALATION_BATCH_FLAGS_KEY; } });
91
+ Object.defineProperty(exports, "ESCALATION_BATCH_WAKE_ON_FLAG_KEY", { enumerable: true, get: function () { return hmsh_escalations_1.ESCALATION_BATCH_WAKE_ON_FLAG_KEY; } });
92
+ Object.defineProperty(exports, "ESCALATION_BATCH_FLAG_LABEL_MAX_LENGTH", { enumerable: true, get: function () { return hmsh_escalations_1.ESCALATION_BATCH_FLAG_LABEL_MAX_LENGTH; } });
93
+ Object.defineProperty(exports, "ESCALATION_FLAGS_KEY", { enumerable: true, get: function () { return hmsh_escalations_1.ESCALATION_FLAGS_KEY; } });
94
+ Object.defineProperty(exports, "ESCALATION_BATCH_WAKE_ON_FILL_KEY", { enumerable: true, get: function () { return hmsh_escalations_1.ESCALATION_BATCH_WAKE_ON_FILL_KEY; } });
95
+ Object.defineProperty(exports, "ESCALATION_FILLED_KEY", { enumerable: true, get: function () { return hmsh_escalations_1.ESCALATION_FILLED_KEY; } });
96
+ Object.defineProperty(exports, "ESCALATION_FILLED_AT_KEY", { enumerable: true, get: function () { return hmsh_escalations_1.ESCALATION_FILLED_AT_KEY; } });
97
+ Object.defineProperty(exports, "ESCALATION_FILLED_BY_KEY", { enumerable: true, get: function () { return hmsh_escalations_1.ESCALATION_FILLED_BY_KEY; } });
90
98
  Object.defineProperty(exports, "ESCALATION_ACCUMULATE_COUNT_KEY", { enumerable: true, get: function () { return hmsh_escalations_1.ESCALATION_ACCUMULATE_COUNT_KEY; } });
91
99
  Object.defineProperty(exports, "ESCALATION_ACCUMULATE_MAX_KEY", { enumerable: true, get: function () { return hmsh_escalations_1.ESCALATION_ACCUMULATE_MAX_KEY; } });
92
100
  Object.defineProperty(exports, "ESCALATION_ACCUMULATE_KEYS_KEY", { enumerable: true, get: function () { return hmsh_escalations_1.ESCALATION_ACCUMULATE_KEYS_KEY; } });
@@ -0,0 +1,66 @@
1
+ import { FlagBatchItemResult, UnflagBatchItemResult } from '../../../../types/hmsh_escalations';
2
+ import { AccumulateWake } from './escalation-accumulate';
3
+ /**
4
+ * SQL builders for the batch flag store operations. Each builder is a pure
5
+ * function of its input; the provider owns the connection. One statement
6
+ * locks the row, writes only while the row and the key are pending, and
7
+ * classifies the outcome. A flag never changes `batch_pending`, so every
8
+ * fill and completion path reads the row as before.
9
+ */
10
+ export type BatchRowSelector = {
11
+ kind: 'id';
12
+ id: string;
13
+ } | {
14
+ kind: 'signalKey';
15
+ signalKey: string;
16
+ };
17
+ /** The flag value as the caller supplies it; the statement stamps `at`. */
18
+ export interface BatchFlagValue {
19
+ label: string;
20
+ payload?: Record<string, unknown>;
21
+ actor?: string;
22
+ }
23
+ export interface FlagStatementInput {
24
+ selector: BatchRowSelector;
25
+ namespace?: string;
26
+ itemKey: string;
27
+ flag: BatchFlagValue;
28
+ metadata: Record<string, unknown> | null;
29
+ /** Present when the row declared `wakeOnFlag`; fires only if the row resolves. */
30
+ wake: AccumulateWake | null;
31
+ appId: string;
32
+ schemaName: string;
33
+ }
34
+ export interface UnflagStatementInput {
35
+ selector: BatchRowSelector;
36
+ namespace?: string;
37
+ itemKey: string;
38
+ }
39
+ /** A provider result: the public result plus what the client needs to settle a wake. */
40
+ export type FlagRowResult = FlagBatchItemResult & {
41
+ signalKey?: string | null;
42
+ topic?: string | null;
43
+ wakeEnqueued?: boolean;
44
+ };
45
+ /**
46
+ * Flag one pending batch key. The flag lands in `envelope.batch_flags`
47
+ * beside the items, stamped with the database clock. On a row that
48
+ * declared `wakeOnFlag` the same UPDATE resolves the row with the items
49
+ * filled so far, `$flags`, and `$trigger: 'flag'`, and the wake commits
50
+ * with it. A key already filled, a row no longer pending, or a race lost to
51
+ * the completing fill writes nothing.
52
+ */
53
+ export declare function buildFlagStatement(input: FlagStatementInput): {
54
+ sql: string;
55
+ values: unknown[];
56
+ };
57
+ /**
58
+ * Clear one key's flag while the row is pending. Removes only that key's
59
+ * entry; the row's status, items and pending keys are untouched.
60
+ */
61
+ export declare function buildUnflagStatement(input: UnflagStatementInput): {
62
+ sql: string;
63
+ values: unknown[];
64
+ };
65
+ export declare function mapFlagRow(row: any): FlagRowResult;
66
+ export declare function mapUnflagRow(row: any): UnflagBatchItemResult;
@@ -0,0 +1,184 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.mapUnflagRow = exports.mapFlagRow = exports.buildUnflagStatement = exports.buildFlagStatement = void 0;
4
+ const hmsh_escalations_1 = require("../../../../types/hmsh_escalations");
5
+ const escalation_accumulate_1 = require("./escalation-accumulate");
6
+ const FLAGS = hmsh_escalations_1.ESCALATION_BATCH_FLAGS_KEY;
7
+ const ITEMS = hmsh_escalations_1.ESCALATION_BATCH_ITEMS_KEY;
8
+ const PENDING = hmsh_escalations_1.ESCALATION_BATCH_PENDING_KEY;
9
+ const KEYS = hmsh_escalations_1.ESCALATION_BATCH_KEYS_KEY;
10
+ const COUNT = hmsh_escalations_1.ESCALATION_BATCH_COUNT_KEY;
11
+ const WAKE_ON_FLAG = hmsh_escalations_1.ESCALATION_BATCH_WAKE_ON_FLAG_KEY;
12
+ function targetCte(selector, namespace, p) {
13
+ const column = selector.kind === 'id' ? 'id' : 'signal_key';
14
+ const value = p.add(selector.kind === 'id' ? selector.id : selector.signalKey);
15
+ const ns = namespace ? ` AND namespace = ${p.add(namespace)}` : '';
16
+ return `target AS MATERIALIZED (
17
+ SELECT id, signal_key, topic, status,
18
+ metadata->'${KEYS}' AS batch_keys,
19
+ metadata->'${PENDING}' AS batch_pending,
20
+ envelope->'${FLAGS}' AS batch_flags,
21
+ COALESCE((envelope->>'${WAKE_ON_FLAG}')::boolean, false) AS wake_on_flag
22
+ FROM public.hmsh_escalations
23
+ WHERE ${column} = ${value}${ns}
24
+ LIMIT 1 FOR UPDATE
25
+ )`;
26
+ }
27
+ /** Outcome cases shared by both statements, after the success case. */
28
+ function refusalCases(key, fallback) {
29
+ return `WHEN t.id IS NULL THEN 'not-found'
30
+ WHEN t.status <> 'pending' THEN 'blocked'
31
+ WHEN jsonb_typeof(t.batch_pending) IS DISTINCT FROM 'array' THEN 'not-batch'
32
+ WHEN NOT COALESCE(t.batch_keys ? ${key}::text, false) THEN 'unknown-item'
33
+ ELSE '${fallback}'`;
34
+ }
35
+ /**
36
+ * Flag one pending batch key. The flag lands in `envelope.batch_flags`
37
+ * beside the items, stamped with the database clock. On a row that
38
+ * declared `wakeOnFlag` the same UPDATE resolves the row with the items
39
+ * filled so far, `$flags`, and `$trigger: 'flag'`, and the wake commits
40
+ * with it. A key already filled, a row no longer pending, or a race lost to
41
+ * the completing fill writes nothing.
42
+ */
43
+ function buildFlagStatement(input) {
44
+ const p = new escalation_accumulate_1.SqlParams();
45
+ const target = targetCte(input.selector, input.namespace, p);
46
+ const key = p.add(input.itemKey);
47
+ const flag = p.add(JSON.stringify(input.flag));
48
+ const meta = p.add(input.metadata ? JSON.stringify(input.metadata) : null);
49
+ const flags = `(COALESCE(e.envelope->'${FLAGS}', '{}'::jsonb)
50
+ || jsonb_build_object(${key}::text,
51
+ ${flag}::jsonb || jsonb_build_object('at', to_jsonb(NOW()))))`;
52
+ const wake = wakeCte(input.wake, input.appId, input.schemaName, p);
53
+ const sql = `
54
+ WITH ${target},
55
+ written AS (
56
+ UPDATE public.hmsh_escalations e
57
+ SET envelope = COALESCE(e.envelope, '{}'::jsonb)
58
+ || jsonb_build_object('${FLAGS}', ${flags}),
59
+ metadata = COALESCE(e.metadata, '{}'::jsonb)
60
+ || COALESCE(${meta}::jsonb, '{}'::jsonb)
61
+ || jsonb_build_object(
62
+ '${PENDING}', e.metadata->'${PENDING}',
63
+ '${COUNT}', e.metadata->'${COUNT}',
64
+ '${KEYS}', e.metadata->'${KEYS}'),
65
+ status = CASE WHEN t.wake_on_flag THEN 'resolved' ELSE e.status END,
66
+ resolved_at = CASE WHEN t.wake_on_flag THEN NOW() ELSE e.resolved_at END,
67
+ resolver_payload = CASE WHEN t.wake_on_flag
68
+ THEN COALESCE(e.envelope->'${ITEMS}', '{}'::jsonb)
69
+ || jsonb_build_object('${hmsh_escalations_1.ESCALATION_FLAGS_KEY}', ${flags},
70
+ '${hmsh_escalations_1.ESCALATION_TRIGGER_KEY}', 'flag')
71
+ ELSE e.resolver_payload END,
72
+ updated_at = NOW()
73
+ FROM target t
74
+ WHERE e.id = t.id
75
+ AND t.status = 'pending'
76
+ AND jsonb_typeof(t.batch_pending) = 'array'
77
+ AND t.batch_pending ? ${key}::text
78
+ RETURNING e.*
79
+ )${wake.cte}
80
+ SELECT t.id, t.status AS prior_status, t.signal_key, t.topic,
81
+ CASE
82
+ WHEN w.id IS NOT NULL AND w.status = 'resolved' THEN 'completed'
83
+ WHEN w.id IS NOT NULL THEN 'flagged'
84
+ ${refusalCases(key, 'already-filled')}
85
+ END AS outcome,
86
+ row_to_json(w.*) AS entry_json,
87
+ ${wake.count}
88
+ FROM (SELECT * FROM target) t
89
+ FULL OUTER JOIN (SELECT * FROM written) w ON w.id = t.id`;
90
+ return { sql, values: p.values };
91
+ }
92
+ exports.buildFlagStatement = buildFlagStatement;
93
+ /**
94
+ * Clear one key's flag while the row is pending. Removes only that key's
95
+ * entry; the row's status, items and pending keys are untouched.
96
+ */
97
+ function buildUnflagStatement(input) {
98
+ const p = new escalation_accumulate_1.SqlParams();
99
+ const target = targetCte(input.selector, input.namespace, p);
100
+ const key = p.add(input.itemKey);
101
+ const sql = `
102
+ WITH ${target},
103
+ written AS (
104
+ UPDATE public.hmsh_escalations e
105
+ SET envelope = e.envelope
106
+ || jsonb_build_object('${FLAGS}', (e.envelope->'${FLAGS}') - ${key}::text),
107
+ updated_at = NOW()
108
+ FROM target t
109
+ WHERE e.id = t.id
110
+ AND t.status = 'pending'
111
+ AND jsonb_typeof(t.batch_pending) = 'array'
112
+ AND jsonb_typeof(t.batch_flags) = 'object'
113
+ AND t.batch_flags ? ${key}::text
114
+ RETURNING e.*
115
+ )
116
+ SELECT t.id, t.status AS prior_status,
117
+ CASE
118
+ WHEN w.id IS NOT NULL THEN 'unflagged'
119
+ ${refusalCases(key, 'not-flagged')}
120
+ END AS outcome,
121
+ row_to_json(w.*) AS entry_json
122
+ FROM (SELECT * FROM target) t
123
+ FULL OUTER JOIN (SELECT * FROM written) w ON w.id = t.id`;
124
+ return { sql, values: p.values };
125
+ }
126
+ exports.buildUnflagStatement = buildUnflagStatement;
127
+ function wakeCte(wake, appId, schemaName, p) {
128
+ if (!wake)
129
+ return { cte: '', count: '0::int AS wake_count' };
130
+ const app = p.add(appId);
131
+ const msg = p.add(wake.command.message);
132
+ const sk = p.add(wake.command.forSignalKey);
133
+ const res = p.add(wake.resolutionJson);
134
+ return {
135
+ cte: `,
136
+ wake AS (
137
+ INSERT INTO ${schemaName}.engine_streams (stream_name, message, priority)
138
+ SELECT ${app},
139
+ jsonb_set(${msg}::jsonb, '{data,data}',
140
+ w.resolver_payload::jsonb || COALESCE(${res}::jsonb, '{}'::jsonb))::text,
141
+ 5
142
+ FROM written w
143
+ WHERE w.status = 'resolved' AND w.signal_key = ${sk}
144
+ RETURNING id
145
+ )`,
146
+ count: '(SELECT COUNT(*) FROM wake)::int AS wake_count',
147
+ };
148
+ }
149
+ /** `blocked` names the row's prior terminal status. */
150
+ function blockedOutcome(priorStatus) {
151
+ if (priorStatus === 'cancelled')
152
+ return 'already-cancelled';
153
+ if (priorStatus === 'expired')
154
+ return 'already-expired';
155
+ return 'already-resolved';
156
+ }
157
+ function mapFlagRow(row) {
158
+ if (!row || row.outcome === 'not-found')
159
+ return { ok: false, outcome: 'not-found' };
160
+ if (row.outcome === 'flagged' || row.outcome === 'completed') {
161
+ return {
162
+ ok: true,
163
+ outcome: row.outcome,
164
+ entry: row.entry_json,
165
+ signalKey: row.signal_key,
166
+ topic: row.topic,
167
+ wakeEnqueued: row.wake_count > 0,
168
+ };
169
+ }
170
+ if (row.outcome === 'blocked')
171
+ return { ok: false, outcome: blockedOutcome(row.prior_status) };
172
+ return { ok: false, outcome: row.outcome };
173
+ }
174
+ exports.mapFlagRow = mapFlagRow;
175
+ function mapUnflagRow(row) {
176
+ if (!row || row.outcome === 'not-found')
177
+ return { ok: false, outcome: 'not-found' };
178
+ if (row.outcome === 'unflagged')
179
+ return { ok: true, outcome: 'unflagged', entry: row.entry_json };
180
+ if (row.outcome === 'blocked')
181
+ return { ok: false, outcome: blockedOutcome(row.prior_status) };
182
+ return { ok: false, outcome: row.outcome };
183
+ }
184
+ exports.mapUnflagRow = mapUnflagRow;
@@ -13,6 +13,7 @@ import { WorkListTaskType } from '../../../../types/task';
13
13
  import { ThrottleOptions } from '../../../../types/quorum';
14
14
  import { StoreService } from '../..';
15
15
  import { AccumulateWake } from './escalation-accumulate';
16
+ import { FlagRowResult } from './escalation-batch-flag';
16
17
  import { PostgresClientType } from '../../../../types';
17
18
  import { KVSQL } from './kvsql';
18
19
  import { KVTables } from './kvtables';
@@ -374,6 +375,15 @@ declare class PostgresStoreService extends StoreService<ProviderClient, Provider
374
375
  topic?: string | null;
375
376
  wakeEnqueued?: boolean;
376
377
  }>;
378
+ /**
379
+ * Flags one pending batch key in one statement. See `buildFlagStatement`.
380
+ * `wakeCommand` is passed only for a row that declared `wakeOnFlag`; the
381
+ * wake commits with the resolve. `resolutionJson` rides the wake only.
382
+ */
383
+ flagEscalationBatchItem(params: import('../../../../types/hmsh_escalations').FlagBatchItemParams, wakeCommand?: import('../../../../types/hmsh_escalations').EscalationWakeCommand, resolutionJson?: string | null): Promise<FlagRowResult>;
384
+ /** Clears one key's flag while the row is pending. See `buildUnflagStatement`. */
385
+ unflagEscalationBatchItem(params: import('../../../../types/hmsh_escalations').UnflagBatchItemParams): Promise<import('../../../../types/hmsh_escalations').UnflagBatchItemResult>;
386
+ private _batchSelector;
377
387
  private _accumulateSelector;
378
388
  private _mapAccumulateRows;
379
389
  /**
@@ -35,6 +35,7 @@ const cache_1 = require("../../cache");
35
35
  const __1 = require("../..");
36
36
  const fold_1 = require("../../../escalations/fold");
37
37
  const escalation_accumulate_1 = require("./escalation-accumulate");
38
+ const escalation_batch_flag_1 = require("./escalation-batch-flag");
38
39
  const kvsql_1 = require("./kvsql");
39
40
  const kvtables_1 = require("./kvtables");
40
41
  const time_notify_1 = require("./time-notify");
@@ -2169,6 +2170,13 @@ class PostgresStoreService extends __1.StoreService {
2169
2170
  */
2170
2171
  _batchItemStatement(targetCTE, itemKeyIdx, payloadIdx, metaIdx, claimIdx, actorIdx, wakeCTE, wakeCount) {
2171
2172
  const remaining = `jsonb_array_length((e.metadata->'batch_pending') - $${itemKeyIdx}::text)`;
2173
+ // a wakeOnFill row resolves on this fill: every key (true) or a listed key
2174
+ const wakes = `(target.wake_on_fill = 'true'::jsonb
2175
+ OR (jsonb_typeof(target.wake_on_fill) = 'array'
2176
+ AND target.wake_on_fill ? $${itemKeyIdx}::text))`;
2177
+ const resolves = `(${remaining} = 0 OR ${wakes})`;
2178
+ const collected = `COALESCE(e.envelope->'batch_items', '{}'::jsonb)
2179
+ || jsonb_build_object($${itemKeyIdx}::text, $${payloadIdx}::jsonb)`;
2172
2180
  return `
2173
2181
  WITH target AS MATERIALIZED (${targetCTE}),
2174
2182
  filled AS (
@@ -2192,11 +2200,28 @@ class PostgresStoreService extends __1.StoreService {
2192
2200
  || jsonb_build_object(
2193
2201
  'batch_pending', (e.metadata->'batch_pending') - $${itemKeyIdx}::text,
2194
2202
  'batch_count', ${remaining}),
2195
- status = CASE WHEN ${remaining} = 0 THEN 'resolved' ELSE e.status END,
2196
- resolved_at = CASE WHEN ${remaining} = 0 THEN NOW() ELSE e.resolved_at END,
2203
+ status = CASE WHEN ${resolves} THEN 'resolved' ELSE e.status END,
2204
+ resolved_at = CASE WHEN ${resolves} THEN NOW() ELSE e.resolved_at END,
2197
2205
  resolver_payload = CASE WHEN ${remaining} = 0
2198
- THEN COALESCE(e.envelope->'batch_items', '{}'::jsonb)
2199
- || jsonb_build_object($${itemKeyIdx}::text, $${payloadIdx}::jsonb)
2206
+ THEN ${collected}
2207
+ WHEN ${wakes}
2208
+ THEN ${collected}
2209
+ || jsonb_build_object(
2210
+ '$filled', jsonb_build_array($${itemKeyIdx}::text),
2211
+ '$trigger', 'fill',
2212
+ '$filledAt',
2213
+ COALESCE(e.envelope->'batch_filled_at', '{}'::jsonb)
2214
+ || jsonb_build_object($${itemKeyIdx}::text, to_jsonb(NOW())))
2215
+ || CASE WHEN $${actorIdx}::text IS NULL
2216
+ AND e.envelope->'batch_filled_by' IS NULL
2217
+ THEN '{}'::jsonb
2218
+ ELSE jsonb_build_object(
2219
+ '$filledBy',
2220
+ COALESCE(e.envelope->'batch_filled_by', '{}'::jsonb)
2221
+ || CASE WHEN $${actorIdx}::text IS NULL THEN '{}'::jsonb
2222
+ ELSE jsonb_build_object($${itemKeyIdx}::text, $${actorIdx}::text)
2223
+ END)
2224
+ END
2200
2225
  ELSE e.resolver_payload END,
2201
2226
  updated_at = NOW()
2202
2227
  FROM target
@@ -2213,6 +2238,8 @@ class PostgresStoreService extends __1.StoreService {
2213
2238
  )${wakeCTE}
2214
2239
  SELECT t.id, t.status AS prior_status, t.signal_key, t.topic, t.assigned_to,
2215
2240
  CASE
2241
+ WHEN f.id IS NOT NULL AND f.status = 'resolved'
2242
+ AND jsonb_array_length(f.metadata->'batch_pending') > 0 THEN 'woke'
2216
2243
  WHEN f.id IS NOT NULL AND f.status = 'resolved' THEN 'completed'
2217
2244
  WHEN f.id IS NOT NULL THEN 'accepted'
2218
2245
  WHEN t.id IS NULL THEN 'not-found'
@@ -2237,7 +2264,9 @@ class PostgresStoreService extends __1.StoreService {
2237
2264
  _mapBatchItemRow(row, assertClaim) {
2238
2265
  if (!row || row.outcome === 'not-found')
2239
2266
  return { ok: false, outcome: 'not-found' };
2240
- if (row.outcome === 'completed' || row.outcome === 'accepted') {
2267
+ if (row.outcome === 'completed' ||
2268
+ row.outcome === 'accepted' ||
2269
+ row.outcome === 'woke') {
2241
2270
  return {
2242
2271
  ok: true,
2243
2272
  outcome: row.outcome,
@@ -2292,7 +2321,8 @@ class PostgresStoreService extends __1.StoreService {
2292
2321
  const targetCTE = `
2293
2322
  SELECT id, signal_key, topic, status, assigned_to, assigned_until,
2294
2323
  metadata->'batch_keys' AS batch_keys,
2295
- metadata->'batch_pending' AS batch_pending
2324
+ metadata->'batch_pending' AS batch_pending,
2325
+ envelope->'batch_wake_on_fill' AS wake_on_fill
2296
2326
  FROM public.hmsh_escalations
2297
2327
  WHERE ${id ? 'id' : 'signal_key'} = $1${nsClause}
2298
2328
  LIMIT 1 FOR UPDATE`;
@@ -2326,7 +2356,8 @@ class PostgresStoreService extends __1.StoreService {
2326
2356
  const targetCTE = `
2327
2357
  SELECT id, signal_key, topic, status, assigned_to, assigned_until,
2328
2358
  metadata->'batch_keys' AS batch_keys,
2329
- metadata->'batch_pending' AS batch_pending
2359
+ metadata->'batch_pending' AS batch_pending,
2360
+ envelope->'batch_wake_on_fill' AS wake_on_fill
2330
2361
  FROM public.hmsh_escalations
2331
2362
  WHERE ${nsClause}
2332
2363
  metadata @> $1::jsonb
@@ -2337,6 +2368,49 @@ class PostgresStoreService extends __1.StoreService {
2337
2368
  const result = await this.pgClient.query(this._batchItemStatement(targetCTE, 2, 3, 4, 5, 7, wakeCTE, wakeCount), sqlParams);
2338
2369
  return this._mapBatchItemRow(result.rows[0]);
2339
2370
  }
2371
+ /**
2372
+ * Flags one pending batch key in one statement. See `buildFlagStatement`.
2373
+ * `wakeCommand` is passed only for a row that declared `wakeOnFlag`; the
2374
+ * wake commits with the resolve. `resolutionJson` rides the wake only.
2375
+ */
2376
+ async flagEscalationBatchItem(params, wakeCommand, resolutionJson) {
2377
+ const { sql, values } = (0, escalation_batch_flag_1.buildFlagStatement)({
2378
+ selector: this._batchSelector(params, 'flagBatchItem'),
2379
+ namespace: params.namespace,
2380
+ itemKey: params.itemKey,
2381
+ flag: {
2382
+ label: params.label,
2383
+ ...(params.payload ? { payload: params.payload } : {}),
2384
+ ...(params.actor ? { actor: params.actor } : {}),
2385
+ },
2386
+ metadata: params.metadata ?? null,
2387
+ wake: wakeCommand
2388
+ ? { command: wakeCommand, resolutionJson: resolutionJson ?? null }
2389
+ : null,
2390
+ appId: this.appId,
2391
+ schemaName: this.kvsql().safeName(this.appId),
2392
+ });
2393
+ const result = await this.pgClient.query(sql, values);
2394
+ return (0, escalation_batch_flag_1.mapFlagRow)(result.rows[0]);
2395
+ }
2396
+ /** Clears one key's flag while the row is pending. See `buildUnflagStatement`. */
2397
+ async unflagEscalationBatchItem(params) {
2398
+ const { sql, values } = (0, escalation_batch_flag_1.buildUnflagStatement)({
2399
+ selector: this._batchSelector(params, 'unflagBatchItem'),
2400
+ namespace: params.namespace,
2401
+ itemKey: params.itemKey,
2402
+ });
2403
+ const result = await this.pgClient.query(sql, values);
2404
+ return (0, escalation_batch_flag_1.mapUnflagRow)(result.rows[0]);
2405
+ }
2406
+ _batchSelector(sel, label) {
2407
+ if ((sel.id ? 1 : 0) + (sel.signalKey ? 1 : 0) !== 1) {
2408
+ throw new Error(`${label} requires exactly one of \`id\` or \`signalKey\``);
2409
+ }
2410
+ return sel.id
2411
+ ? { kind: 'id', id: sel.id }
2412
+ : { kind: 'signalKey', signalKey: sel.signalKey };
2413
+ }
2340
2414
  _accumulateSelector(sel, label) {
2341
2415
  const forms = (sel.id ? 1 : 0) + (sel.signalKey ? 1 : 0) + (sel.key !== undefined ? 1 : 0);
2342
2416
  if (forms !== 1) {
@@ -36,6 +36,26 @@ export interface ConditionQueueConfig {
36
36
  * existing batch waiters are unchanged.
37
37
  */
38
38
  partialOnTimeout?: boolean;
39
+ /**
40
+ * With `batch`, a `flagBatchItem()` call ends the wait: the row resolves
41
+ * and the wait resumes with the items filled so far, the flags
42
+ * (`$flags`), and `$trigger: 'flag'`. Off by default: a flag is then
43
+ * recorded on the row and the wait continues.
44
+ */
45
+ wakeOnFlag?: boolean;
46
+ /**
47
+ * With `batch`, a `resolveBatchItem()` fill ends the wait: the row
48
+ * resolves and the wait resumes with the items filled so far, the key
49
+ * that woke it (`$filled: [itemKey]`), `$trigger: 'fill'`, each filled
50
+ * key's fill time (`$filledAt`) and recorded actor (`$filledBy`). `true`
51
+ * wakes on every fill; a list of declared keys wakes only when one of
52
+ * those keys fills. The last fill completes the wait as on any batch.
53
+ * Pair with `filled` to park the next round with the items carried
54
+ * forward: `$filledAt` and `$filledBy` supply each entry's `at` and
55
+ * `actor`. Off by default: a fill is then recorded on the row and the
56
+ * wait continues until the last key.
57
+ */
58
+ wakeOnFill?: boolean | string[];
39
59
  /**
40
60
  * With `batch`, entries already satisfied when the row is created (for
41
61
  * example, received before the wait began). Each key must be declared in
@@ -356,6 +376,10 @@ export interface CreateEscalationParams {
356
376
  batch?: string[];
357
377
  /** See {@link ConditionQueueConfig.partialOnTimeout}. */
358
378
  partialOnTimeout?: boolean;
379
+ /** See {@link ConditionQueueConfig.wakeOnFlag}. */
380
+ wakeOnFlag?: boolean;
381
+ /** See {@link ConditionQueueConfig.wakeOnFill}. */
382
+ wakeOnFill?: boolean | string[];
359
383
  /** See {@link ConditionQueueConfig.filled}. */
360
384
  filled?: Record<string, BatchFilledEntry>;
361
385
  /**
@@ -509,6 +533,34 @@ export declare const ESCALATION_BATCH_ITEM_KEY_MAX_LENGTH = 128;
509
533
  /** Envelope key: set by `partialOnTimeout` on a batch row so the expiry
510
534
  * statement knows to deliver the filled items with `$trigger: 'timeout'`. */
511
535
  export declare const ESCALATION_BATCH_PARTIAL_ON_TIMEOUT_KEY = "batch_partial_on_timeout";
536
+ /** Envelope key: per-item flags (`Record<itemKey, BatchItemFlag>`), written
537
+ * by `flagBatchItem()` while the key is pending and cleared by
538
+ * `unflagBatchItem()`. A flagged key stays pending and can still be filled. */
539
+ export declare const ESCALATION_BATCH_FLAGS_KEY = "batch_flags";
540
+ /** Envelope key: set by `wakeOnFlag` on a batch row so the flag statement
541
+ * resolves the row and wakes the waiter. */
542
+ export declare const ESCALATION_BATCH_WAKE_ON_FLAG_KEY = "batch_wake_on_flag";
543
+ /** Reserved signal-payload key: the flags delivered when a flag ends the
544
+ * wait (`wakeOnFlag`). */
545
+ export declare const ESCALATION_FLAGS_KEY = "$flags";
546
+ /** Envelope key: set by `wakeOnFill` on a batch row (`true`, or the list of
547
+ * keys that wake) so the fill statement resolves the row and wakes the
548
+ * waiter. */
549
+ export declare const ESCALATION_BATCH_WAKE_ON_FILL_KEY = "batch_wake_on_fill";
550
+ /** Reserved signal-payload key: the item key whose fill ended the wait
551
+ * (`wakeOnFill`), as a one-element array. */
552
+ export declare const ESCALATION_FILLED_KEY = "$filled";
553
+ /** Reserved signal-payload key: when a fill ends the wait (`wakeOnFill`),
554
+ * the database-clock fill time of every filled key
555
+ * (`Record<itemKey, ISO-8601>`), the source of record for `filled[key].at`
556
+ * when the workflow parks its next round. */
557
+ export declare const ESCALATION_FILLED_AT_KEY = "$filledAt";
558
+ /** Reserved signal-payload key: when a fill ends the wait (`wakeOnFill`),
559
+ * the recorded actor of every filled key that has one
560
+ * (`Record<itemKey, actor>`). Present when at least one fill named an actor. */
561
+ export declare const ESCALATION_FILLED_BY_KEY = "$filledBy";
562
+ /** Flag labels are non-empty strings up to this length. */
563
+ export declare const ESCALATION_BATCH_FLAG_LABEL_MAX_LENGTH = 128;
512
564
  /** Metadata facet: number of items currently held. Recomputed from
513
565
  * `accumulate_keys` in every add/remove statement so the two never drift. */
514
566
  export declare const ESCALATION_ACCUMULATE_COUNT_KEY = "accumulate_count";
@@ -529,7 +581,8 @@ export declare const ESCALATION_ACCUMULATE_CONFIG_KEY = "accumulate_config";
529
581
  * waiter of an accumulator row. */
530
582
  export declare const ESCALATION_ACCUMULATED_KEY = "$accumulated";
531
583
  /** Reserved signal-payload key: which terminal path delivered the
532
- * collection (`count` | `timeout` | `resolve`). */
584
+ * collection (`count` | `timeout` | `resolve`; `flag` or `fill` on a batch
585
+ * row). */
533
586
  export declare const ESCALATION_TRIGGER_KEY = "$trigger";
534
587
  export interface AccumulateConfig {
535
588
  /** Count trigger. Absent means unbounded: only `timeout` or a manual
@@ -716,12 +769,15 @@ export interface ExpireEscalationResult {
716
769
  * - `completed` — this was the LAST item: the row resolved and the waiting
717
770
  * workflow was woken with the full collection, in the same statement.
718
771
  * - `accepted` — interim fill: the item landed, the row stays `pending`.
772
+ * - `woke` — the item landed and the row resolved before every key was
773
+ * filled, because its wait declared `wakeOnFill` for this key: the waiter
774
+ * woke with the items filled so far, `$filled`, and `$trigger: 'fill'`.
719
775
  * - `duplicate-item` — the key was declared but already filled.
720
776
  * - `unknown-item` — the key was never declared in `batch_keys`.
721
777
  * - `not-batch` — the row carries no batch declaration.
722
778
  * - Remaining values match {@link ResolveEscalationResult} semantics.
723
779
  */
724
- export type BatchItemOutcome = 'completed' | 'accepted' | 'duplicate-item' | 'unknown-item' | 'not-batch' | 'not-found' | 'already-resolved' | 'already-cancelled' | 'already-expired' | 'claim-expired' | 'claimed-by-other';
780
+ export type BatchItemOutcome = 'completed' | 'accepted' | 'woke' | 'duplicate-item' | 'unknown-item' | 'not-batch' | 'not-found' | 'already-resolved' | 'already-cancelled' | 'already-expired' | 'claim-expired' | 'claimed-by-other';
725
781
  export interface ResolveBatchItemParams {
726
782
  /** Row selector — exactly one of `id` | `signalKey`. */
727
783
  id?: string;
@@ -743,8 +799,9 @@ export interface ResolveBatchItemParams {
743
799
  /** Recorded under `envelope.batch_filled_by[itemKey]` in the same
744
800
  * statement as the fill. */
745
801
  actor?: string;
746
- /** Resolver identity. Delivered under `$resolution` ONLY on the completing
747
- * item's signal. See {@link ResolveEscalationParams.resolvedBy}. */
802
+ /** Resolver identity. Delivered under `$resolution` on the signal that
803
+ * ends the wait: the completing item's, or a `wakeOnFill` fill's. See
804
+ * {@link ResolveEscalationParams.resolvedBy}. */
748
805
  resolvedBy?: ResolvedByIdentity;
749
806
  }
750
807
  export interface ResolveBatchItemByMetadataParams {
@@ -769,12 +826,69 @@ export interface ResolveBatchItemByMetadataParams {
769
826
  */
770
827
  export type ResolveBatchItemResult = {
771
828
  ok: true;
772
- outcome: 'completed' | 'accepted';
829
+ outcome: 'completed' | 'accepted' | 'woke';
773
830
  remaining: number;
774
831
  entry: EscalationEntry;
775
832
  } | {
776
833
  ok: false;
777
- outcome: Exclude<BatchItemOutcome, 'completed' | 'accepted'>;
834
+ outcome: Exclude<BatchItemOutcome, 'completed' | 'accepted' | 'woke'>;
835
+ };
836
+ /** One flag on a batch item, stored under `envelope.batch_flags[itemKey]`. */
837
+ export interface BatchItemFlag {
838
+ label: string;
839
+ payload?: Record<string, unknown>;
840
+ actor?: string;
841
+ /** Database clock, stamped by the flag statement. */
842
+ at: string;
843
+ }
844
+ export interface FlagBatchItemParams {
845
+ /** Row selector — exactly one of `id` | `signalKey`. */
846
+ id?: string;
847
+ signalKey?: string;
848
+ namespace?: string;
849
+ /** A declared batch key that is still pending. */
850
+ itemKey: string;
851
+ /** What the flag says, e.g. `Missing`. */
852
+ label: string;
853
+ /** Detail stored with the flag and delivered with `$flags`. */
854
+ payload?: Record<string, unknown>;
855
+ /** Recorded on the flag. */
856
+ actor?: string;
857
+ /** Merge patch for the row's `metadata`, in the same UPDATE. Reserved
858
+ * batch keys are rejected. */
859
+ metadata?: Record<string, unknown>;
860
+ /** Delivered under `$resolution` when the flag ends the wait. */
861
+ resolvedBy?: ResolvedByIdentity;
862
+ }
863
+ export interface UnflagBatchItemParams {
864
+ /** Row selector — exactly one of `id` | `signalKey`. */
865
+ id?: string;
866
+ signalKey?: string;
867
+ namespace?: string;
868
+ itemKey: string;
869
+ }
870
+ /**
871
+ * `flagged`: the flag is stored and the row stays pending. `completed`: the
872
+ * row declared `wakeOnFlag`, so it resolved and the waiter woke.
873
+ * `already-filled`: the key is declared but no longer pending.
874
+ */
875
+ export type FlagBatchItemOutcome = 'flagged' | 'completed' | 'already-filled' | 'unknown-item' | 'not-batch' | 'not-found' | 'already-resolved' | 'already-cancelled' | 'already-expired';
876
+ export type FlagBatchItemResult = {
877
+ ok: true;
878
+ outcome: 'flagged' | 'completed';
879
+ entry: EscalationEntry;
880
+ } | {
881
+ ok: false;
882
+ outcome: Exclude<FlagBatchItemOutcome, 'flagged' | 'completed'>;
883
+ };
884
+ export type UnflagBatchItemOutcome = 'unflagged' | 'not-flagged' | 'unknown-item' | 'not-batch' | 'not-found' | 'already-resolved' | 'already-cancelled' | 'already-expired';
885
+ export type UnflagBatchItemResult = {
886
+ ok: true;
887
+ outcome: 'unflagged';
888
+ entry: EscalationEntry;
889
+ } | {
890
+ ok: false;
891
+ outcome: Exclude<UnflagBatchItemOutcome, 'unflagged'>;
778
892
  };
779
893
  /**
780
894
  * Query selector for `claimManyByQuery()` — the filterable subset of
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ESCALATION_TRIGGER_KEY = exports.ESCALATION_ACCUMULATED_KEY = exports.ESCALATION_ACCUMULATE_CONFIG_KEY = exports.ESCALATION_ACCUMULATE_ITEMS_KEY = exports.ESCALATION_ACCUMULATE_KEYS_KEY = exports.ESCALATION_ACCUMULATE_MAX_KEY = exports.ESCALATION_ACCUMULATE_COUNT_KEY = exports.ESCALATION_BATCH_PARTIAL_ON_TIMEOUT_KEY = exports.ESCALATION_BATCH_ITEM_KEY_MAX_LENGTH = exports.ESCALATION_BATCH_FILLED_BY_KEY = exports.ESCALATION_BATCH_FILLED_AT_KEY = exports.ESCALATION_BATCH_ITEMS_KEY = exports.ESCALATION_BATCH_KEYS_KEY = exports.ESCALATION_BATCH_COUNT_KEY = exports.ESCALATION_BATCH_PENDING_KEY = void 0;
3
+ exports.ESCALATION_TRIGGER_KEY = exports.ESCALATION_ACCUMULATED_KEY = exports.ESCALATION_ACCUMULATE_CONFIG_KEY = exports.ESCALATION_ACCUMULATE_ITEMS_KEY = exports.ESCALATION_ACCUMULATE_KEYS_KEY = exports.ESCALATION_ACCUMULATE_MAX_KEY = exports.ESCALATION_ACCUMULATE_COUNT_KEY = exports.ESCALATION_BATCH_FLAG_LABEL_MAX_LENGTH = exports.ESCALATION_FILLED_BY_KEY = exports.ESCALATION_FILLED_AT_KEY = exports.ESCALATION_FILLED_KEY = exports.ESCALATION_BATCH_WAKE_ON_FILL_KEY = exports.ESCALATION_FLAGS_KEY = exports.ESCALATION_BATCH_WAKE_ON_FLAG_KEY = exports.ESCALATION_BATCH_FLAGS_KEY = exports.ESCALATION_BATCH_PARTIAL_ON_TIMEOUT_KEY = exports.ESCALATION_BATCH_ITEM_KEY_MAX_LENGTH = exports.ESCALATION_BATCH_FILLED_BY_KEY = exports.ESCALATION_BATCH_FILLED_AT_KEY = exports.ESCALATION_BATCH_ITEMS_KEY = exports.ESCALATION_BATCH_KEYS_KEY = exports.ESCALATION_BATCH_COUNT_KEY = exports.ESCALATION_BATCH_PENDING_KEY = void 0;
4
4
  // ─── Batch accumulation ───────────────────────────────────────────────────────
5
5
  /** Metadata facet: item keys still awaiting submission (jsonb string array).
6
6
  * `metadata @> '{"batch_pending":["x"]}'` finds rows still missing item `x`. */
@@ -30,6 +30,34 @@ exports.ESCALATION_BATCH_ITEM_KEY_MAX_LENGTH = 128;
30
30
  /** Envelope key: set by `partialOnTimeout` on a batch row so the expiry
31
31
  * statement knows to deliver the filled items with `$trigger: 'timeout'`. */
32
32
  exports.ESCALATION_BATCH_PARTIAL_ON_TIMEOUT_KEY = 'batch_partial_on_timeout';
33
+ /** Envelope key: per-item flags (`Record<itemKey, BatchItemFlag>`), written
34
+ * by `flagBatchItem()` while the key is pending and cleared by
35
+ * `unflagBatchItem()`. A flagged key stays pending and can still be filled. */
36
+ exports.ESCALATION_BATCH_FLAGS_KEY = 'batch_flags';
37
+ /** Envelope key: set by `wakeOnFlag` on a batch row so the flag statement
38
+ * resolves the row and wakes the waiter. */
39
+ exports.ESCALATION_BATCH_WAKE_ON_FLAG_KEY = 'batch_wake_on_flag';
40
+ /** Reserved signal-payload key: the flags delivered when a flag ends the
41
+ * wait (`wakeOnFlag`). */
42
+ exports.ESCALATION_FLAGS_KEY = '$flags';
43
+ /** Envelope key: set by `wakeOnFill` on a batch row (`true`, or the list of
44
+ * keys that wake) so the fill statement resolves the row and wakes the
45
+ * waiter. */
46
+ exports.ESCALATION_BATCH_WAKE_ON_FILL_KEY = 'batch_wake_on_fill';
47
+ /** Reserved signal-payload key: the item key whose fill ended the wait
48
+ * (`wakeOnFill`), as a one-element array. */
49
+ exports.ESCALATION_FILLED_KEY = '$filled';
50
+ /** Reserved signal-payload key: when a fill ends the wait (`wakeOnFill`),
51
+ * the database-clock fill time of every filled key
52
+ * (`Record<itemKey, ISO-8601>`), the source of record for `filled[key].at`
53
+ * when the workflow parks its next round. */
54
+ exports.ESCALATION_FILLED_AT_KEY = '$filledAt';
55
+ /** Reserved signal-payload key: when a fill ends the wait (`wakeOnFill`),
56
+ * the recorded actor of every filled key that has one
57
+ * (`Record<itemKey, actor>`). Present when at least one fill named an actor. */
58
+ exports.ESCALATION_FILLED_BY_KEY = '$filledBy';
59
+ /** Flag labels are non-empty strings up to this length. */
60
+ exports.ESCALATION_BATCH_FLAG_LABEL_MAX_LENGTH = 128;
33
61
  // ─── Open accumulation ────────────────────────────────────────────────────────
34
62
  /** Metadata facet: number of items currently held. Recomputed from
35
63
  * `accumulate_keys` in every add/remove statement so the two never drift. */
@@ -51,5 +79,6 @@ exports.ESCALATION_ACCUMULATE_CONFIG_KEY = 'accumulate_config';
51
79
  * waiter of an accumulator row. */
52
80
  exports.ESCALATION_ACCUMULATED_KEY = '$accumulated';
53
81
  /** Reserved signal-payload key: which terminal path delivered the
54
- * collection (`count` | `timeout` | `resolve`). */
82
+ * collection (`count` | `timeout` | `resolve`; `flag` or `fill` on a batch
83
+ * row). */
55
84
  exports.ESCALATION_TRIGGER_KEY = '$trigger';
@@ -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, BatchItemOutcome, ResolveBatchItemParams, ResolveBatchItemByMetadataParams, ResolveBatchItemResult, ESCALATION_BATCH_PENDING_KEY, ESCALATION_BATCH_COUNT_KEY, ESCALATION_BATCH_KEYS_KEY, ESCALATION_BATCH_ITEMS_KEY, ESCALATION_BATCH_FILLED_AT_KEY, ESCALATION_BATCH_FILLED_BY_KEY, ESCALATION_BATCH_PARTIAL_ON_TIMEOUT_KEY, ESCALATION_BATCH_ITEM_KEY_MAX_LENGTH, BatchFilledEntry, AccumulateConfig, AccumulatedEntry, AccumulatedItem, AccumulatorTrigger, AccumulatorResult, AccumulateReciprocalSelector, AccumulateItemOutcome, AccumulateItemParams, AccumulateItemByMetadataParams, AccumulateReciprocalResult, AccumulateItemResult, RemoveAccumulatedItemOutcome, RemoveAccumulatedItemParams, RemoveAccumulatedItemByMetadataParams, RemoveAccumulatedItemResult, ExpireEscalationResult, ESCALATION_ACCUMULATE_COUNT_KEY, ESCALATION_ACCUMULATE_MAX_KEY, ESCALATION_ACCUMULATE_KEYS_KEY, ESCALATION_ACCUMULATE_ITEMS_KEY, ESCALATION_ACCUMULATE_CONFIG_KEY, ESCALATION_ACCUMULATED_KEY, ESCALATION_TRIGGER_KEY, } 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, ESCALATION_BATCH_FILLED_AT_KEY, ESCALATION_BATCH_FILLED_BY_KEY, ESCALATION_BATCH_PARTIAL_ON_TIMEOUT_KEY, ESCALATION_BATCH_ITEM_KEY_MAX_LENGTH, ESCALATION_BATCH_FLAGS_KEY, ESCALATION_BATCH_WAKE_ON_FLAG_KEY, ESCALATION_BATCH_FLAG_LABEL_MAX_LENGTH, ESCALATION_FLAGS_KEY, ESCALATION_BATCH_WAKE_ON_FILL_KEY, ESCALATION_FILLED_KEY, ESCALATION_FILLED_AT_KEY, ESCALATION_FILLED_BY_KEY, BatchItemFlag, FlagBatchItemParams, FlagBatchItemOutcome, FlagBatchItemResult, UnflagBatchItemParams, UnflagBatchItemOutcome, UnflagBatchItemResult, BatchFilledEntry, AccumulateConfig, AccumulatedEntry, AccumulatedItem, AccumulatorTrigger, AccumulatorResult, AccumulateReciprocalSelector, AccumulateItemOutcome, AccumulateItemParams, AccumulateItemByMetadataParams, AccumulateReciprocalResult, AccumulateItemResult, RemoveAccumulatedItemOutcome, RemoveAccumulatedItemParams, RemoveAccumulatedItemByMetadataParams, RemoveAccumulatedItemResult, ExpireEscalationResult, ESCALATION_ACCUMULATE_COUNT_KEY, ESCALATION_ACCUMULATE_MAX_KEY, ESCALATION_ACCUMULATE_KEYS_KEY, ESCALATION_ACCUMULATE_ITEMS_KEY, ESCALATION_ACCUMULATE_CONFIG_KEY, ESCALATION_ACCUMULATED_KEY, ESCALATION_TRIGGER_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.ESCALATION_TRIGGER_KEY = exports.ESCALATION_ACCUMULATED_KEY = exports.ESCALATION_ACCUMULATE_CONFIG_KEY = exports.ESCALATION_ACCUMULATE_ITEMS_KEY = exports.ESCALATION_ACCUMULATE_KEYS_KEY = exports.ESCALATION_ACCUMULATE_MAX_KEY = exports.ESCALATION_ACCUMULATE_COUNT_KEY = exports.ESCALATION_BATCH_ITEM_KEY_MAX_LENGTH = exports.ESCALATION_BATCH_PARTIAL_ON_TIMEOUT_KEY = exports.ESCALATION_BATCH_FILLED_BY_KEY = exports.ESCALATION_BATCH_FILLED_AT_KEY = 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;
3
+ exports.ESCALATION_TRIGGER_KEY = exports.ESCALATION_ACCUMULATED_KEY = exports.ESCALATION_ACCUMULATE_CONFIG_KEY = exports.ESCALATION_ACCUMULATE_ITEMS_KEY = exports.ESCALATION_ACCUMULATE_KEYS_KEY = exports.ESCALATION_ACCUMULATE_MAX_KEY = exports.ESCALATION_ACCUMULATE_COUNT_KEY = exports.ESCALATION_FILLED_BY_KEY = exports.ESCALATION_FILLED_AT_KEY = exports.ESCALATION_FILLED_KEY = exports.ESCALATION_BATCH_WAKE_ON_FILL_KEY = exports.ESCALATION_FLAGS_KEY = exports.ESCALATION_BATCH_FLAG_LABEL_MAX_LENGTH = exports.ESCALATION_BATCH_WAKE_ON_FLAG_KEY = exports.ESCALATION_BATCH_FLAGS_KEY = exports.ESCALATION_BATCH_ITEM_KEY_MAX_LENGTH = exports.ESCALATION_BATCH_PARTIAL_ON_TIMEOUT_KEY = exports.ESCALATION_BATCH_FILLED_BY_KEY = exports.ESCALATION_BATCH_FILLED_AT_KEY = 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");
@@ -28,6 +28,14 @@ Object.defineProperty(exports, "ESCALATION_BATCH_FILLED_AT_KEY", { enumerable: t
28
28
  Object.defineProperty(exports, "ESCALATION_BATCH_FILLED_BY_KEY", { enumerable: true, get: function () { return hmsh_escalations_1.ESCALATION_BATCH_FILLED_BY_KEY; } });
29
29
  Object.defineProperty(exports, "ESCALATION_BATCH_PARTIAL_ON_TIMEOUT_KEY", { enumerable: true, get: function () { return hmsh_escalations_1.ESCALATION_BATCH_PARTIAL_ON_TIMEOUT_KEY; } });
30
30
  Object.defineProperty(exports, "ESCALATION_BATCH_ITEM_KEY_MAX_LENGTH", { enumerable: true, get: function () { return hmsh_escalations_1.ESCALATION_BATCH_ITEM_KEY_MAX_LENGTH; } });
31
+ Object.defineProperty(exports, "ESCALATION_BATCH_FLAGS_KEY", { enumerable: true, get: function () { return hmsh_escalations_1.ESCALATION_BATCH_FLAGS_KEY; } });
32
+ Object.defineProperty(exports, "ESCALATION_BATCH_WAKE_ON_FLAG_KEY", { enumerable: true, get: function () { return hmsh_escalations_1.ESCALATION_BATCH_WAKE_ON_FLAG_KEY; } });
33
+ Object.defineProperty(exports, "ESCALATION_BATCH_FLAG_LABEL_MAX_LENGTH", { enumerable: true, get: function () { return hmsh_escalations_1.ESCALATION_BATCH_FLAG_LABEL_MAX_LENGTH; } });
34
+ Object.defineProperty(exports, "ESCALATION_FLAGS_KEY", { enumerable: true, get: function () { return hmsh_escalations_1.ESCALATION_FLAGS_KEY; } });
35
+ Object.defineProperty(exports, "ESCALATION_BATCH_WAKE_ON_FILL_KEY", { enumerable: true, get: function () { return hmsh_escalations_1.ESCALATION_BATCH_WAKE_ON_FILL_KEY; } });
36
+ Object.defineProperty(exports, "ESCALATION_FILLED_KEY", { enumerable: true, get: function () { return hmsh_escalations_1.ESCALATION_FILLED_KEY; } });
37
+ Object.defineProperty(exports, "ESCALATION_FILLED_AT_KEY", { enumerable: true, get: function () { return hmsh_escalations_1.ESCALATION_FILLED_AT_KEY; } });
38
+ Object.defineProperty(exports, "ESCALATION_FILLED_BY_KEY", { enumerable: true, get: function () { return hmsh_escalations_1.ESCALATION_FILLED_BY_KEY; } });
31
39
  Object.defineProperty(exports, "ESCALATION_ACCUMULATE_COUNT_KEY", { enumerable: true, get: function () { return hmsh_escalations_1.ESCALATION_ACCUMULATE_COUNT_KEY; } });
32
40
  Object.defineProperty(exports, "ESCALATION_ACCUMULATE_MAX_KEY", { enumerable: true, get: function () { return hmsh_escalations_1.ESCALATION_ACCUMULATE_MAX_KEY; } });
33
41
  Object.defineProperty(exports, "ESCALATION_ACCUMULATE_KEYS_KEY", { enumerable: true, get: function () { return hmsh_escalations_1.ESCALATION_ACCUMULATE_KEYS_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' | 'expired' | 'batch-item' | 'accumulated' | 'removed';
118
+ export type EscalationVerb = 'created' | 'claimed' | 'released' | 'reassigned' | 'resolved' | 'cancelled' | 'expired' | 'batch-item' | 'flagged' | 'unflagged' | 'accumulated' | 'removed';
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.31.2",
3
+ "version": "0.32.0",
4
4
  "description": "Durable Workflow",
5
5
  "main": "./build/index.js",
6
6
  "types": "./build/index.d.ts",