assignment-user-matcher 1.1.2 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/dist/index.d.ts +4 -0
  2. package/dist/index.d.ts.map +1 -1
  3. package/dist/index.js +26 -1
  4. package/dist/managers/ReliabilityManager.d.ts +42 -0
  5. package/dist/managers/ReliabilityManager.d.ts.map +1 -0
  6. package/dist/managers/ReliabilityManager.js +115 -0
  7. package/dist/managers/TelemetryManager.d.ts +13 -0
  8. package/dist/managers/TelemetryManager.d.ts.map +1 -0
  9. package/dist/managers/TelemetryManager.js +52 -0
  10. package/dist/managers/WorkflowManager.d.ts +62 -0
  11. package/dist/managers/WorkflowManager.d.ts.map +1 -0
  12. package/dist/managers/WorkflowManager.js +654 -0
  13. package/dist/matcher.class.d.ts +161 -51
  14. package/dist/matcher.class.d.ts.map +1 -1
  15. package/dist/matcher.class.js +472 -254
  16. package/dist/queries/index.d.ts +5 -0
  17. package/dist/queries/index.d.ts.map +1 -0
  18. package/dist/queries/index.js +20 -0
  19. package/dist/queries/pagination.d.ts +51 -0
  20. package/dist/queries/pagination.d.ts.map +1 -0
  21. package/dist/queries/pagination.js +200 -0
  22. package/dist/scoring/index.d.ts +5 -0
  23. package/dist/scoring/index.d.ts.map +1 -0
  24. package/dist/scoring/index.js +20 -0
  25. package/dist/scoring/match-score.d.ts +19 -0
  26. package/dist/scoring/match-score.d.ts.map +1 -0
  27. package/dist/scoring/match-score.js +84 -0
  28. package/dist/types/matcher.d.ts +261 -0
  29. package/dist/types/matcher.d.ts.map +1 -0
  30. package/dist/types/matcher.js +2 -0
  31. package/dist/utils/cidr.d.ts +40 -0
  32. package/dist/utils/cidr.d.ts.map +1 -0
  33. package/dist/utils/cidr.js +150 -0
  34. package/dist/utils/index.d.ts +6 -0
  35. package/dist/utils/index.d.ts.map +1 -0
  36. package/dist/utils/index.js +21 -0
  37. package/dist/utils/keys.d.ts +45 -0
  38. package/dist/utils/keys.d.ts.map +1 -0
  39. package/dist/utils/keys.js +57 -0
  40. package/dist/workflow-builder.d.ts +182 -0
  41. package/dist/workflow-builder.d.ts.map +1 -0
  42. package/dist/workflow-builder.js +341 -0
  43. package/package.json +6 -2
@@ -1,32 +1,185 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ const crypto_1 = require("crypto");
4
+ const fs_1 = require("fs");
5
+ const path_1 = require("path");
6
+ const cidr_1 = require("./utils/cidr");
7
+ const keys_1 = require("./utils/keys");
8
+ const pagination_1 = require("./queries/pagination");
9
+ const match_score_1 = require("./scoring/match-score");
10
+ const ReliabilityManager_1 = require("./managers/ReliabilityManager");
11
+ const TelemetryManager_1 = require("./managers/TelemetryManager");
12
+ const WorkflowManager_1 = require("./managers/WorkflowManager");
13
+ // Load Lua scripts from files
14
+ const LUA_SCRIPTS_DIR = (0, path_1.join)(__dirname, 'lua');
15
+ /**
16
+ * Load a Lua script from the lua directory.
17
+ * Falls back to empty string if file not found.
18
+ */
19
+ function loadLuaScript(filename) {
20
+ try {
21
+ return (0, fs_1.readFileSync)((0, path_1.join)(LUA_SCRIPTS_DIR, filename), 'utf-8');
22
+ }
23
+ catch {
24
+ console.warn(`Lua script not found: ${filename}`);
25
+ return '';
26
+ }
27
+ }
28
+ // Lua script for atomic workflow transitions
29
+ const WORKFLOW_TRANSITION_LUA = loadLuaScript('workflow-transition.lua');
3
30
  class AssignmentMatcher {
4
31
  constructor(redisClient, options) {
5
32
  this.redisClient = redisClient;
33
+ this.luaScriptSha = null;
6
34
  this.autoReleaseInterval = null;
7
35
  this.relevantBatchSize = options?.relevantBatchSize ?? 50;
8
36
  this.enableDefaultMatching = options?.enableDefaultMatching ?? true;
9
37
  this.redisPrefix = options?.redisPrefix ?? '';
10
- this.usersKey = this.redisPrefix + 'users';
11
- this.assignmentsKey = this.redisPrefix + 'assignments';
12
- this.assignmentsRefKey = this.redisPrefix + 'assignments:ref';
38
+ // Initialize key builders
39
+ this.keys = (0, keys_1.createKeyBuilders)({ prefix: this.redisPrefix });
40
+ this.usersKey = this.keys.users();
41
+ this.assignmentsKey = this.keys.assignments();
42
+ this.assignmentsRefKey = this.keys.assignmentsRef();
13
43
  this.maxUserBacklogSize = options?.maxUserBacklogSize ?? 9;
14
44
  this.matchExpirationMs = options?.matchExpirationMs ?? 60000;
15
- this.pendingAssignmentsKey = this.redisPrefix + 'assignments:pending:data';
16
- this.pendingAssignmentsExpiryKey = this.redisPrefix + 'assignments:pending:expiry';
17
- this.assignmentOwnerKey = this.redisPrefix + 'assignments:pending:owner';
18
- this.allTagsKey = this.redisPrefix + 'all:tags';
45
+ this.pendingAssignmentsKey = this.keys.pendingAssignmentsData();
46
+ this.pendingAssignmentsExpiryKey = this.keys.pendingAssignmentsExpiry();
47
+ this.assignmentOwnerKey = this.keys.assignmentOwner();
48
+ this.allTagsKey = this.keys.allTags();
49
+ this.acceptedAssignmentsKey = this.keys.acceptedAssignments();
50
+ this.completedAssignmentsKey = this.keys.completedAssignments();
19
51
  this.calculatePriority = options?.prioritizationFunction ?? this.calculatePriority;
20
- this.matchScore = options?.matchingFunction ?? this.matchScore;
52
+ this.matchScore = options?.matchingFunction ?? this.defaultMatchScore.bind(this);
53
+ // Workflow options
54
+ this.enableWorkflows = options?.enableWorkflows ?? false;
55
+ this.streamConsumerGroup = options?.streamConsumerGroup ?? 'orchestrator';
56
+ this.streamConsumerName = options?.streamConsumerName ?? (0, crypto_1.randomUUID)();
57
+ // Initialize managers
58
+ this.reliability = new ReliabilityManager_1.ReliabilityManager(this.redisClient, this.keys, {
59
+ workflowMaxRetries: options?.workflowMaxRetries ?? 3,
60
+ workflowIdempotencyTtlMs: options?.workflowIdempotencyTtlMs ?? 86400000,
61
+ workflowCircuitBreakerThreshold: options?.workflowCircuitBreakerThreshold ?? 5,
62
+ workflowCircuitBreakerResetMs: options?.workflowCircuitBreakerResetMs ?? 30000,
63
+ workflowAuditEnabled: options?.workflowAuditEnabled ?? false,
64
+ workflowSnapshotDefinitions: options?.workflowSnapshotDefinitions ?? true,
65
+ streamConsumerName: this.streamConsumerName,
66
+ });
67
+ this.telemetry = new TelemetryManager_1.TelemetryManager(options?.enableOpenTelemetry ?? false);
68
+ this.workflow = new WorkflowManager_1.WorkflowManager(this.redisClient, this.keys, this.reliability, this.telemetry, this, {
69
+ enableWorkflows: this.enableWorkflows,
70
+ streamConsumerGroup: this.streamConsumerGroup,
71
+ streamConsumerName: this.streamConsumerName,
72
+ reclaimIntervalMs: options?.workflowOrphanReclaimMs ?? 60000,
73
+ });
21
74
  this.initRedis();
22
75
  }
76
+ /** Keys for the three assignment stores (used by pagination queries) */
77
+ get assignmentStoreKeys() {
78
+ return {
79
+ queued: this.assignmentsRefKey,
80
+ pending: this.pendingAssignmentsKey,
81
+ accepted: this.acceptedAssignmentsKey,
82
+ completed: this.completedAssignmentsKey,
83
+ };
84
+ }
23
85
  async initRedis() {
24
86
  // Only attempt to connect if the client isn't already connected
25
87
  if (!this.redisClient.isOpen) {
26
88
  await this.redisClient.connect();
27
89
  }
90
+ // Initialize workflow stream consumer group if workflows are enabled
91
+ if (this.enableWorkflows) {
92
+ await this.workflow.init();
93
+ // Load Lua script for atomic transitions
94
+ await this.loadLuaScripts();
95
+ }
28
96
  return this;
29
97
  }
98
+ /**
99
+ * Load Lua scripts into Redis for atomic operations.
100
+ */
101
+ async loadLuaScripts() {
102
+ try {
103
+ this.luaScriptSha = await this.redisClient.scriptLoad(WORKFLOW_TRANSITION_LUA);
104
+ this.workflow.setLuaScriptSha(this.luaScriptSha);
105
+ }
106
+ catch (err) {
107
+ console.error('Failed to load Lua scripts:', err);
108
+ // Fallback to non-atomic mode
109
+ this.luaScriptSha = null;
110
+ }
111
+ }
112
+ async atomicWorkflowTransition(instanceId, expectedVersion, newStatus, newStepId, updatedContext, historyEntry) {
113
+ return this.workflow.atomicWorkflowTransition(instanceId, expectedVersion, newStatus, newStepId, updatedContext, historyEntry);
114
+ }
115
+ async reclaimOrphanedMessages() {
116
+ return this.workflow.reclaimOrphanedMessages();
117
+ }
118
+ /**
119
+ * Get events from the Dead Letter Queue.
120
+ */
121
+ async getDeadLetterEvents(limit = 100, offset = 0) {
122
+ return this.reliability.getDeadLetterEvents(limit, offset);
123
+ }
124
+ /**
125
+ * Get Dead Letter Queue size.
126
+ */
127
+ async getDeadLetterQueueSize() {
128
+ return this.reliability.getDeadLetterQueueSize();
129
+ }
130
+ /**
131
+ * Replay a Dead Letter Queue event.
132
+ */
133
+ async replayDeadLetterEvent(eventJson) {
134
+ const entry = JSON.parse(eventJson);
135
+ // Reset retry count
136
+ await this.redisClient.del(this.keys.eventRetryCount(entry.event.eventId));
137
+ // Re-publish the event
138
+ await this.publishWorkflowEvent(entry.event);
139
+ // Remove from DLQ
140
+ await this.redisClient.zRem(this.keys.deadLetterQueue(), eventJson);
141
+ return true;
142
+ }
143
+ /**
144
+ * Clear all events from the Dead Letter Queue.
145
+ */
146
+ async clearDeadLetterQueue() {
147
+ return this.reliability.clearDeadLetterQueue();
148
+ }
149
+ /**
150
+ * Get audit events from the audit stream.
151
+ */
152
+ async getAuditEvents(count = 100) {
153
+ return this.reliability.getAuditEvents(count);
154
+ }
155
+ // ============================================================================
156
+ // OpenTelemetry Tracing Hooks
157
+ // ============================================================================
158
+ /**
159
+ * Set the OpenTelemetry tracer instance.
160
+ */
161
+ setTracer(tracer) {
162
+ this.telemetry.setTracer(tracer);
163
+ }
164
+ /**
165
+ * Initialize the Redis Stream consumer group for workflow events.
166
+ * Creates the stream and consumer group if they don't exist.
167
+ */
168
+ async initStreamConsumerGroup() {
169
+ const streamKey = this.keys.eventStream();
170
+ try {
171
+ // Try to create the consumer group (and stream if needed)
172
+ await this.redisClient.xGroupCreate(streamKey, this.streamConsumerGroup, '0', {
173
+ MKSTREAM: true,
174
+ });
175
+ }
176
+ catch (err) {
177
+ // Ignore "BUSYGROUP" error - group already exists
178
+ if (!err.message?.includes('BUSYGROUP')) {
179
+ throw err;
180
+ }
181
+ }
182
+ }
30
183
  async addUser(user) {
31
184
  await this.redisClient.hSet(this.usersKey, user.id, JSON.stringify({
32
185
  ...user,
@@ -38,9 +191,9 @@ class AssignmentMatcher {
38
191
  let { id, tags, priority, latitude, longitude } = assignment;
39
192
  if (!priority)
40
193
  priority = await this.calculatePriority(assignment);
41
- const assignmentPriorityKey = this.redisPrefix + `assignment:${id}:priority`;
42
- const assignmentTagsKey = this.redisPrefix + `assignment:${id}:tags`;
43
- const assignmentGeoKey = this.redisPrefix + `assignments:geo`;
194
+ const assignmentPriorityKey = this.keys.assignmentPriority(id);
195
+ const assignmentTagsKey = this.keys.assignmentTags(id);
196
+ const assignmentGeoKey = this.keys.assignmentsGeo();
44
197
  const multi = this.redisClient
45
198
  .multi()
46
199
  .hSet(this.assignmentsRefKey, id, JSON.stringify(assignment))
@@ -62,7 +215,7 @@ class AssignmentMatcher {
62
215
  // This enables efficient weighted matching via ZUNIONSTORE.
63
216
  const indexTags = [...tags, ...(this.enableDefaultMatching ? ['default'] : [])];
64
217
  for (const tag of indexTags) {
65
- multi.zAdd(this.redisPrefix + `tag:${tag}:assignments`, {
218
+ multi.zAdd(this.keys.tagAssignments(tag), {
66
219
  score: Number(priority),
67
220
  value: id,
68
221
  });
@@ -72,245 +225,94 @@ class AssignmentMatcher {
72
225
  return assignment;
73
226
  }
74
227
  async removeAssignment(id) {
75
- const assignmentPriorityKey = this.redisPrefix + `assignment:${id}:priority`;
76
- const assignmentTagsKey = this.redisPrefix + `assignment:${id}:tags`;
77
- // Fetch tags to remove from per-tag indices
78
- const [tagsCsv] = await this.redisClient.multi().hGet(assignmentTagsKey, 'tags').exec();
228
+ const assignmentPriorityKey = this.keys.assignmentPriority(id);
229
+ const assignmentTagsKey = this.keys.assignmentTags(id);
230
+ const assignmentGeoKey = this.keys.assignmentsGeo();
231
+ // Fetch tags and owner in case it's pending
232
+ const [tagsCsv, owner] = await Promise.all([
233
+ this.redisClient.hGet(assignmentTagsKey, 'tags'),
234
+ this.redisClient.hGet(this.assignmentOwnerKey, id)
235
+ ]);
79
236
  let tags = [];
80
- if (typeof tagsCsv === 'string' && tagsCsv.length > 0) {
237
+ if (tagsCsv && tagsCsv.length > 0) {
81
238
  tags = tagsCsv.split(',');
82
239
  }
83
240
  const multi = this.redisClient.multi();
84
- // Remove from reference and per-assignment hashes
241
+ // 1. Remove from Queued state
85
242
  multi.hDel(this.assignmentsRefKey, id);
86
243
  multi.del(assignmentPriorityKey);
87
244
  multi.del(assignmentTagsKey);
88
- // Remove from global zset
89
245
  multi.zRem(this.assignmentsKey, id.toString());
90
- // Remove from per-tag zsets
91
246
  for (const tag of tags) {
92
- multi.zRem(this.redisPrefix + `tag:${tag}:assignments`, id.toString());
247
+ multi.zRem(this.keys.tagAssignments(tag), id.toString());
93
248
  }
249
+ multi.zRem(assignmentGeoKey, id.toString());
250
+ // 2. Remove from Pending state
251
+ multi.hDel(this.pendingAssignmentsKey, id);
252
+ multi.zRem(this.pendingAssignmentsExpiryKey, id);
253
+ multi.hDel(this.assignmentOwnerKey, id);
254
+ if (owner) {
255
+ multi.sRem(this.keys.userAssignments(owner), `assignment:${id}`);
256
+ }
257
+ // 3. Remove from Accepted state
258
+ multi.hDel(this.acceptedAssignmentsKey, id);
94
259
  await multi.exec();
95
260
  return id;
96
261
  }
97
262
  async removeUser(userId) {
98
263
  const multi = this.redisClient
99
264
  .multi()
100
- .del(this.redisPrefix + `user:${userId}:assignments`)
101
- .del(this.redisPrefix + `user:${userId}:rejected`)
265
+ .del(this.keys.userAssignments(userId))
266
+ .del(this.keys.userRejected(userId))
102
267
  .hDel(this.usersKey, userId);
103
268
  await multi.exec();
104
269
  return userId;
105
270
  }
106
- async getAllAssignments() {
107
- const assignments = await this.redisClient.hGetAll(this.assignmentsRefKey);
108
- return Object.values(assignments).map((assignment) => JSON.parse(assignment));
109
- }
110
- // ==================== CIDR/IP Matching Utilities ====================
111
271
  /**
112
- * Parse an IPv4 address into a BigInt representation
272
+ * Get all assignments (queued, pending, and accepted).
273
+ * For large datasets, prefer using getAssignmentsPaginated() instead.
113
274
  */
114
- parseIPv4(ip) {
115
- const parts = ip.split('.');
116
- if (parts.length !== 4)
117
- return null;
118
- let result = 0n;
119
- for (const part of parts) {
120
- const num = parseInt(part, 10);
121
- if (isNaN(num) || num < 0 || num > 255)
122
- return null;
123
- result = (result << 8n) | BigInt(num);
124
- }
125
- return result;
275
+ async getAllAssignments() {
276
+ return (0, pagination_1.getAllAssignmentsFromStores)(this.redisClient, this.assignmentStoreKeys);
126
277
  }
127
278
  /**
128
- * Parse an IPv6 address into a BigInt representation
129
- * Handles full, compressed (::), and IPv4-mapped formats
279
+ * Get assignments with pagination support for efficient querying of large datasets.
280
+ * Uses cursor-based pagination across statuses.
281
+ *
282
+ * @param options.cursor - Cursor for pagination (null/undefined for first page)
283
+ * @param options.limit - Maximum number of assignments to return per page (default: 100)
284
+ * @param options.status - Filter by status: 'queued' | 'pending' | 'accepted' | 'all' (default: 'all')
285
+ * @param options.includeTotal - Whether to include total count (slower for large datasets)
130
286
  */
131
- parseIPv6(ip) {
132
- // Handle IPv4-mapped IPv6 (::ffff:192.168.1.1)
133
- const ipv4MappedMatch = ip.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/i);
134
- if (ipv4MappedMatch) {
135
- const ipv4 = this.parseIPv4(ipv4MappedMatch[1]);
136
- if (ipv4 === null)
137
- return null;
138
- return 0xffff00000000n | ipv4;
139
- }
140
- // Handle :: expansion
141
- let fullIp = ip.toLowerCase();
142
- if (fullIp.includes('::')) {
143
- const parts = fullIp.split('::');
144
- if (parts.length > 2)
145
- return null; // Invalid: more than one ::
146
- const leftParts = parts[0] ? parts[0].split(':') : [];
147
- const rightParts = parts[1] ? parts[1].split(':') : [];
148
- const missingGroups = 8 - leftParts.length - rightParts.length;
149
- if (missingGroups < 0)
150
- return null;
151
- const allParts = [...leftParts, ...Array(missingGroups).fill('0'), ...rightParts];
152
- fullIp = allParts.join(':');
153
- }
154
- const groups = fullIp.split(':');
155
- if (groups.length !== 8)
156
- return null;
157
- let result = 0n;
158
- for (const group of groups) {
159
- if (group.length === 0 || group.length > 4)
160
- return null;
161
- const num = parseInt(group, 16);
162
- if (isNaN(num) || num < 0 || num > 0xffff)
163
- return null;
164
- result = (result << 16n) | BigInt(num);
165
- }
166
- return result;
287
+ async getAssignmentsPaginated(options) {
288
+ return (0, pagination_1.getAssignmentsPaginatedFromStores)(this.redisClient, this.assignmentStoreKeys, options);
167
289
  }
168
290
  /**
169
- * Parse an IP address (auto-detect IPv4 or IPv6)
170
- * Returns { value: BigInt, isIPv6: boolean } or null if invalid
291
+ * Get assignment counts by status without fetching the data.
292
+ * Efficient for dashboards and monitoring.
171
293
  */
172
- parseIP(ip) {
173
- if (!ip || typeof ip !== 'string')
174
- return null;
175
- const trimmed = ip.trim();
176
- // Try IPv4 first (contains dots, no colons)
177
- if (trimmed.includes('.') && !trimmed.includes(':')) {
178
- const value = this.parseIPv4(trimmed);
179
- if (value !== null)
180
- return { value, isIPv6: false };
181
- }
182
- // Try IPv6 (contains colons)
183
- if (trimmed.includes(':')) {
184
- const value = this.parseIPv6(trimmed);
185
- if (value !== null)
186
- return { value, isIPv6: true };
187
- }
188
- return null;
294
+ async getAssignmentCounts() {
295
+ return (0, pagination_1.getAssignmentCountsFromStores)(this.redisClient, this.assignmentStoreKeys);
189
296
  }
190
297
  /**
191
- * Parse a CIDR notation string (e.g., '192.168.1.0/24' or '2001:db8::/32')
192
- * Returns { network: BigInt, prefixLength: number, isIPv6: boolean } or null
298
+ * Get a single assignment by ID from any status.
193
299
  */
194
- parseCIDR(cidr) {
195
- if (!cidr || typeof cidr !== 'string')
196
- return null;
197
- const parts = cidr.trim().split('/');
198
- if (parts.length !== 2)
199
- return null;
200
- const ip = this.parseIP(parts[0]);
201
- if (!ip)
202
- return null;
203
- const prefixLength = parseInt(parts[1], 10);
204
- const maxPrefix = ip.isIPv6 ? 128 : 32;
205
- if (isNaN(prefixLength) || prefixLength < 0 || prefixLength > maxPrefix)
206
- return null;
207
- // Calculate network address by masking
208
- const totalBits = ip.isIPv6 ? 128 : 32;
209
- const hostBits = totalBits - prefixLength;
210
- const mask = hostBits === totalBits ? 0n : ((1n << BigInt(totalBits)) - 1n) ^ ((1n << BigInt(hostBits)) - 1n);
211
- const network = ip.value & mask;
212
- return { network, prefixLength, isIPv6: ip.isIPv6 };
300
+ async getAssignment(id) {
301
+ return (0, pagination_1.getAssignmentById)(this.redisClient, this.assignmentStoreKeys, id);
213
302
  }
214
303
  /**
215
- * Check if an IP address is within a CIDR range
304
+ * Get multiple assignments by IDs efficiently.
216
305
  */
217
- isIpInCidr(ip, cidr) {
218
- const parsedIp = this.parseIP(ip);
219
- const parsedCidr = this.parseCIDR(cidr);
220
- if (!parsedIp || !parsedCidr)
221
- return false;
222
- // IP version must match CIDR version
223
- if (parsedIp.isIPv6 !== parsedCidr.isIPv6)
224
- return false;
225
- const totalBits = parsedIp.isIPv6 ? 128 : 32;
226
- const hostBits = totalBits - parsedCidr.prefixLength;
227
- const mask = hostBits === totalBits ? 0n : ((1n << BigInt(totalBits)) - 1n) ^ ((1n << BigInt(hostBits)) - 1n);
228
- return (parsedIp.value & mask) === parsedCidr.network;
306
+ async getAssignmentsByIds(ids) {
307
+ return (0, pagination_1.getAssignmentsByIdsBatch)(this.redisClient, this.assignmentStoreKeys, ids);
229
308
  }
230
- /**
231
- * Check if a user's IP matches any of the allowed CIDRs
232
- * Returns true if no CIDRs are specified (open assignment) or if IP matches any CIDR
233
- */
234
- checkCidrMatch(userIp, allowedCidrs) {
235
- // If no CIDR restrictions, assignment is open to all
236
- if (!allowedCidrs || allowedCidrs.length === 0)
237
- return true;
238
- // If CIDRs are specified but user has no IP, deny match
239
- if (!userIp)
240
- return false;
241
- // Check if user IP matches any allowed CIDR
242
- for (const cidr of allowedCidrs) {
243
- if (this.isIpInCidr(userIp, cidr))
244
- return true;
245
- }
246
- return false;
247
- }
248
- // ==================== End CIDR/IP Matching Utilities ====================
249
- async matchScore(user, assignmentTags, assignmentPriority, assignmentId) {
250
- const aTags = assignmentTags ? assignmentTags.split(',') : [];
251
- const matchesPattern = (pattern, tag) => {
252
- if (pattern === tag)
253
- return true;
254
- if (pattern.endsWith('*')) {
255
- const prefix = pattern.slice(0, -1);
256
- return tag.startsWith(prefix);
257
- }
258
- return false;
259
- };
260
- // If weighted skills are present, use them for scoring
261
- if (user.routingWeights && Object.keys(user.routingWeights).length > 0) {
262
- // Check for exclusions (weight 0)
263
- for (const [pattern, weight] of Object.entries(user.routingWeights)) {
264
- if (weight === 0) {
265
- for (const t of aTags) {
266
- if (matchesPattern(pattern, t)) {
267
- return [0, Number(assignmentPriority) || 0];
268
- }
269
- }
270
- }
271
- }
272
- let weightSum = 0;
273
- for (const t of aTags) {
274
- let matchedByRouting = false;
275
- for (const [pattern, weight] of Object.entries(user.routingWeights)) {
276
- if (typeof weight === 'number' && weight > 0) {
277
- if (matchesPattern(pattern, t)) {
278
- weightSum += weight;
279
- matchedByRouting = true;
280
- }
281
- }
282
- }
283
- // If enableDefaultMatching is true, and the tag is 'default', and it wasn't matched by any routing weight,
284
- // we give it default weight 1.
285
- if (this.enableDefaultMatching && t === 'default' && !matchedByRouting) {
286
- weightSum += 1;
287
- }
288
- }
289
- const base = Number(assignmentPriority) || 0;
290
- return [weightSum, base + weightSum];
291
- }
292
- // Fallback to default tag-intersection scoring
293
- const userTagSet = new Set(user.tags);
294
- const assignmentTagSet = new Set(aTags);
295
- let intersectionSize = 0;
296
- for (const userTag of userTagSet) {
297
- let matched = false;
298
- for (const assignmentTag of assignmentTagSet) {
299
- if (matchesPattern(userTag, assignmentTag)) {
300
- matched = true;
301
- break;
302
- }
303
- }
304
- if (matched)
305
- intersectionSize++;
306
- }
307
- const score = userTagSet.size > 0 ? intersectionSize / userTagSet.size : 0;
308
- const base = Number(assignmentPriority) || 0;
309
- return [score || 0, base + (score || 0)];
309
+ /** Default match score implementation using extracted scoring module */
310
+ defaultMatchScore(user, assignmentTags, assignmentPriority, _assignmentId) {
311
+ return Promise.resolve((0, match_score_1.calculateMatchScore)(user, assignmentTags, assignmentPriority, this.enableDefaultMatching));
310
312
  }
311
313
  async calculatePriority(...args) {
312
314
  const [assignment] = args;
313
- return new Date().getTime() - assignment?.createdAt || 0;
315
+ return (0, match_score_1.calculateDefaultPriority)(assignment?.createdAt);
314
316
  }
315
317
  get stats() {
316
318
  return (async () => {
@@ -338,22 +340,22 @@ class AssignmentMatcher {
338
340
  })();
339
341
  }
340
342
  async setAssignmentPriority(id, priority) {
341
- const assignmentPriorityKey = this.redisPrefix + `assignment:${id}:priority`;
343
+ const assignmentPriorityKey = this.keys.assignmentPriority(id);
342
344
  // Fetch tags to update per-tag indices
343
- const assignmentTagsKey = this.redisPrefix + `assignment:${id}:tags`;
345
+ const assignmentTagsKey = this.keys.assignmentTags(id);
344
346
  const [existsRef, tagsCsv] = await this.redisClient
345
347
  .multi()
346
348
  .hExists(this.assignmentsRefKey, id)
347
349
  .hGet(assignmentTagsKey, 'tags')
348
350
  .exec();
349
- const tags = (typeof tagsCsv === 'string' && tagsCsv.length > 0 ? tagsCsv.split(',') : []);
351
+ const tags = (tagsCsv && tagsCsv.length > 0 ? tagsCsv.split(',') : []);
350
352
  const multi = this.redisClient.multi();
351
353
  multi.hSet(assignmentPriorityKey, 'priority', priority);
352
354
  if (existsRef) {
353
355
  // Update global zset score and per-tag zset scores only if assignment still exists
354
356
  multi.zAdd(this.assignmentsKey, { score: Number(priority), value: id });
355
357
  for (const tag of tags) {
356
- multi.zAdd(this.redisPrefix + `tag:${tag}:assignments`, { score: Number(priority), value: id });
358
+ multi.zAdd(this.keys.tagAssignments(tag), { score: Number(priority), value: id });
357
359
  }
358
360
  }
359
361
  await multi.exec();
@@ -370,7 +372,7 @@ class AssignmentMatcher {
370
372
  const multi = this.redisClient.multi();
371
373
  for (const assignment of relevantAssignments) {
372
374
  const id = assignment.id;
373
- const assignmentPriorityKey = this.redisPrefix + `assignment:${id}:priority`;
375
+ const assignmentPriorityKey = this.keys.assignmentPriority(id);
374
376
  // Update the stored priority
375
377
  multi.hSet(assignmentPriorityKey, 'priority', priority);
376
378
  // Update global zset score
@@ -378,7 +380,7 @@ class AssignmentMatcher {
378
380
  // Update per-tag zset scores
379
381
  const idxTags = [...assignment.tags, ...(this.enableDefaultMatching ? ['default'] : [])];
380
382
  for (const tag of idxTags) {
381
- multi.zAdd(this.redisPrefix + `tag:${tag}:assignments`, { score: Number(priority), value: id });
383
+ multi.zAdd(this.keys.tagAssignments(tag), { score: Number(priority), value: id });
382
384
  }
383
385
  }
384
386
  await multi.exec();
@@ -386,7 +388,19 @@ class AssignmentMatcher {
386
388
  return relevantAssignments.map((assignment) => ({ id: assignment.id, priority }));
387
389
  }
388
390
  async getUserRelatedAssignments(user) {
389
- // Build candidate assignments using per-tag zset union with user weights for scalability.
391
+ const userAssignments = [];
392
+ // Priority 1: Check for workflow-targeted assignments (deterministic matching)
393
+ if (this.enableWorkflows) {
394
+ const workflowAssignments = await this.getWorkflowTargetedAssignments(user.id);
395
+ if (workflowAssignments.length > 0) {
396
+ // Workflow assignments take precedence - add them first with highest priority
397
+ userAssignments.push(...workflowAssignments);
398
+ if (userAssignments.length >= this.maxUserBacklogSize) {
399
+ return userAssignments;
400
+ }
401
+ }
402
+ }
403
+ // Priority 2: Build candidate assignments using per-tag zset union with user weights for scalability.
390
404
  const positiveWeights = [];
391
405
  const zeroWeightTags = [];
392
406
  if (user.routingWeights && Object.keys(user.routingWeights).length > 0) {
@@ -410,7 +424,6 @@ class AssignmentMatcher {
410
424
  if (!defaultInPos && !defaultZero)
411
425
  positiveWeights.push({ tag: 'default', weight: 1 });
412
426
  }
413
- const userAssignments = [];
414
427
  if (positiveWeights.length === 0)
415
428
  return userAssignments;
416
429
  // Expand wildcards
@@ -419,19 +432,23 @@ class AssignmentMatcher {
419
432
  const finalZeroTags = expandedZero.map((t) => t.tag);
420
433
  if (expandedPositive.length === 0)
421
434
  return userAssignments;
422
- const tempKey = this.redisPrefix + `tmp:user:${user.id}:candidates`;
423
- const tempZeroKey = this.redisPrefix + `tmp:user:${user.id}:exclude`;
424
- const tempFinalKey = this.redisPrefix + `tmp:user:${user.id}:final`;
425
- const rejectedKey = this.redisPrefix + `user:${user.id}:rejected`;
426
- const unionKeys = expandedPositive.map((pw) => this.redisPrefix + `tag:${pw.tag}:assignments`);
427
- const unionWeights = expandedPositive.map((pw) => pw.weight);
435
+ const tempKey = this.keys.tempUserCandidates(user.id);
436
+ const tempZeroKey = this.keys.tempUserExclude(user.id);
437
+ const tempFinalKey = this.keys.tempUserFinal(user.id);
438
+ const rejectedKey = this.keys.userRejected(user.id);
439
+ const unionKeysWithWeights = expandedPositive.map((pw) => ({
440
+ key: this.keys.tagAssignments(pw.tag),
441
+ weight: pw.weight
442
+ }));
428
443
  const multi = this.redisClient.multi();
429
444
  // Weighted union of positive tag assignment zsets
430
- multi.zUnionStore(tempKey, unionKeys, { WEIGHTS: unionWeights });
445
+ if (unionKeysWithWeights.length > 0) {
446
+ multi.zUnionStore(tempKey, unionKeysWithWeights);
447
+ }
431
448
  const excludeKeys = [];
432
449
  // Optional exclude set for zero-weight tags
433
450
  if (finalZeroTags.length > 0) {
434
- const zeroKeys = finalZeroTags.map((t) => this.redisPrefix + `tag:${t}:assignments`);
451
+ const zeroKeys = finalZeroTags.map((t) => this.keys.tagAssignments(t));
435
452
  multi.zUnionStore(tempZeroKey, zeroKeys);
436
453
  multi.expire(tempZeroKey, 5);
437
454
  excludeKeys.push(tempZeroKey);
@@ -452,10 +469,8 @@ class AssignmentMatcher {
452
469
  const batched = this.redisClient.multi();
453
470
  for (const entry of top) {
454
471
  const assignmentId = entry.value;
455
- const assignmentPriorityKey = this.redisPrefix + `assignment:${assignmentId}:priority`;
456
- const assignmentTagsKey = this.redisPrefix + `assignment:${assignmentId}:tags`;
457
- batched.hGet(assignmentPriorityKey, 'priority');
458
- batched.hGet(assignmentTagsKey, 'tags');
472
+ batched.hGet(this.keys.assignmentPriority(assignmentId), 'priority');
473
+ batched.hGet(this.keys.assignmentTags(assignmentId), 'tags');
459
474
  // Also fetch assignment JSON to access allowedCidrs for network matching
460
475
  batched.hGet(this.assignmentsRefKey, assignmentId);
461
476
  }
@@ -485,7 +500,7 @@ class AssignmentMatcher {
485
500
  if (userAssignments.length >= this.maxUserBacklogSize)
486
501
  break;
487
502
  // Check CIDR restrictions: if assignment has allowedCidrs, user must have matching IP
488
- if (!this.checkCidrMatch(user.ip, d.allowedCidrs)) {
503
+ if (!(0, cidr_1.checkCidrMatch)(user.ip, d.allowedCidrs)) {
489
504
  continue; // Skip this assignment - user IP doesn't match allowed CIDRs
490
505
  }
491
506
  // Use custom matchScore (supports weights) for a final check and tie-break
@@ -505,18 +520,16 @@ class AssignmentMatcher {
505
520
  for (let i = 0; i < selected.length; i++) {
506
521
  const s = selected[i];
507
522
  const json = jsons[i];
508
- const assignmentPriorityKey = this.redisPrefix + `assignment:${s.id}:priority`;
509
- const assignmentTagsKey = this.redisPrefix + `assignment:${s.id}:tags`;
510
523
  // Remove from reference and per-assignment hashes
511
524
  rm.hDel(this.assignmentsRefKey, s.id);
512
- rm.del(assignmentPriorityKey);
513
- rm.del(assignmentTagsKey);
525
+ rm.del(this.keys.assignmentPriority(s.id));
526
+ rm.del(this.keys.assignmentTags(s.id));
514
527
  // Remove from global zset
515
528
  rm.zRem(this.assignmentsKey, s.id);
516
529
  // Remove from per-tag zsets
517
530
  const tags = (s.tags ? s.tags.split(',').filter(Boolean) : []);
518
531
  for (const tag of tags) {
519
- rm.zRem(this.redisPrefix + `tag:${tag}:assignments`, s.id);
532
+ rm.zRem(this.keys.tagAssignments(tag), s.id);
520
533
  }
521
534
  // Add to pending structures
522
535
  if (json) {
@@ -536,7 +549,7 @@ class AssignmentMatcher {
536
549
  if (!userJson)
537
550
  return;
538
551
  const user = JSON.parse(userJson);
539
- const userMatchesCount = await this.redisClient.sCard(this.redisPrefix + `user:${user.id}:assignments`);
552
+ const userMatchesCount = await this.redisClient.sCard(this.keys.userAssignments(user.id));
540
553
  if (userMatchesCount >= this.maxUserBacklogSize)
541
554
  return;
542
555
  const relevantAssignments = await this.getUserRelatedAssignments(user);
@@ -544,22 +557,22 @@ class AssignmentMatcher {
544
557
  .sort((a, b) => b.priority - a.priority)
545
558
  .map((a) => `assignment:${a.id}`);
546
559
  if (relevantAssignmentKeys.length > 0) {
547
- await this.redisClient.sAdd(this.redisPrefix + `user:${user.id}:assignments`, relevantAssignmentKeys);
560
+ await this.redisClient.sAdd(this.keys.userAssignments(user.id), relevantAssignmentKeys);
548
561
  }
549
562
  return;
550
563
  }
551
564
  // Otherwise, process all users in parallel as before.
552
565
  let users = [];
553
- let cursor = 0;
566
+ let cursor = '0';
554
567
  // Fetch all users in a single loop
555
568
  do {
556
- const { cursor: nextCursor, tuples } = await this.redisClient.hScan(this.usersKey, cursor);
557
- users.push(...tuples.map((t) => JSON.parse(t.value)));
569
+ const { cursor: nextCursor, entries } = await this.redisClient.hScan(this.usersKey, cursor);
570
+ users.push(...entries.map((t) => JSON.parse(t.value)));
558
571
  cursor = nextCursor;
559
- } while (cursor !== 0);
572
+ } while (cursor !== '0');
560
573
  // Process users in parallel
561
574
  await Promise.all(users.map(async (user) => {
562
- const userMatchesCount = await this.redisClient.sCard(this.redisPrefix + `user:${user.id}:assignments`);
575
+ const userMatchesCount = await this.redisClient.sCard(this.keys.userAssignments(user.id));
563
576
  if (userMatchesCount >= this.maxUserBacklogSize) {
564
577
  return;
565
578
  }
@@ -568,44 +581,212 @@ class AssignmentMatcher {
568
581
  .sort((a, b) => b.priority - a.priority)
569
582
  .map((a) => `assignment:${a.id}`);
570
583
  if (relevantAssignmentKeys.length > 0) {
571
- await this.redisClient.sAdd(this.redisPrefix + `user:${user.id}:assignments`, relevantAssignmentKeys);
584
+ await this.redisClient.sAdd(this.keys.userAssignments(user.id), relevantAssignmentKeys);
572
585
  }
573
586
  }));
574
587
  }
575
588
  async getCurrentAssignmentsForUser(userId) {
576
- const userAssignments = await this.redisClient.sMembers(this.redisPrefix + `user:${userId}:assignments`);
589
+ const userAssignments = await this.redisClient.sMembers(this.keys.userAssignments(userId));
577
590
  return userAssignments.map((el) => el.split(':')[1]);
578
591
  }
579
592
  async acceptAssignment(userId, assignmentId) {
580
- const isAssigned = await this.redisClient.sIsMember(this.redisPrefix + `user:${userId}:assignments`, `assignment:${assignmentId}`);
593
+ const isAssigned = await this.redisClient.sIsMember(this.keys.userAssignments(userId), `assignment:${assignmentId}`);
581
594
  if (!isAssigned)
582
595
  throw new Error('Assignment not found for user');
596
+ // Get the assignment JSON before removing from pending
597
+ const json = await this.redisClient.hGet(this.pendingAssignmentsKey, assignmentId);
583
598
  const multi = this.redisClient.multi();
584
- multi.sRem(this.redisPrefix + `user:${userId}:assignments`, `assignment:${assignmentId}`);
599
+ multi.sRem(this.keys.userAssignments(userId), `assignment:${assignmentId}`);
585
600
  multi.hDel(this.pendingAssignmentsKey, assignmentId);
586
601
  multi.zRem(this.pendingAssignmentsExpiryKey, assignmentId);
587
602
  multi.hDel(this.assignmentOwnerKey, assignmentId);
603
+ // Store in accepted assignments
604
+ if (json) {
605
+ multi.hSet(this.acceptedAssignmentsKey, assignmentId, json);
606
+ }
588
607
  await multi.exec();
589
608
  return true;
590
609
  }
591
610
  async rejectAssignment(userId, assignmentId) {
592
- const isAssigned = await this.redisClient.sIsMember(this.redisPrefix + `user:${userId}:assignments`, `assignment:${assignmentId}`);
611
+ const isAssigned = await this.redisClient.sIsMember(this.keys.userAssignments(userId), `assignment:${assignmentId}`);
593
612
  if (!isAssigned)
594
613
  throw new Error('Assignment not found for user');
595
614
  const json = await this.redisClient.hGet(this.pendingAssignmentsKey, assignmentId);
596
615
  const multi = this.redisClient.multi();
597
- multi.sRem(this.redisPrefix + `user:${userId}:assignments`, `assignment:${assignmentId}`);
616
+ multi.sRem(this.keys.userAssignments(userId), `assignment:${assignmentId}`);
598
617
  multi.hDel(this.pendingAssignmentsKey, assignmentId);
599
618
  multi.zRem(this.pendingAssignmentsExpiryKey, assignmentId);
600
619
  multi.hDel(this.assignmentOwnerKey, assignmentId);
601
620
  // Add to rejected list to prevent immediate re-assignment
602
- multi.sAdd(this.redisPrefix + `user:${userId}:rejected`, assignmentId);
621
+ multi.sAdd(this.keys.userRejected(userId), assignmentId);
603
622
  await multi.exec();
604
623
  if (json) {
605
624
  await this.addAssignment(JSON.parse(json));
606
625
  }
607
626
  return true;
608
627
  }
628
+ /**
629
+ * Complete an assignment with a result payload.
630
+ * Moves the assignment from 'accepted' to 'completed' state and publishes an event
631
+ * for workflow orchestration.
632
+ *
633
+ * @param userId - The user completing the assignment
634
+ * @param assignmentId - The assignment being completed
635
+ * @param result - Optional result payload for routing decisions
636
+ */
637
+ async completeAssignment(userId, assignmentId, result) {
638
+ // Verify assignment is in accepted state
639
+ const json = await this.redisClient.hGet(this.acceptedAssignmentsKey, assignmentId);
640
+ if (!json) {
641
+ throw new Error('Assignment not found in accepted state');
642
+ }
643
+ const assignment = JSON.parse(json);
644
+ const now = Date.now();
645
+ // Move from accepted to completed
646
+ const multi = this.redisClient.multi();
647
+ multi.hDel(this.acceptedAssignmentsKey, assignmentId);
648
+ // Store in completed with result metadata
649
+ const completedData = {
650
+ ...assignment,
651
+ _completedBy: userId,
652
+ _completedAt: now,
653
+ _result: result,
654
+ };
655
+ multi.hSet(this.completedAssignmentsKey, assignmentId, JSON.stringify(completedData));
656
+ await multi.exec();
657
+ // Publish workflow event if workflows are enabled
658
+ if (this.enableWorkflows) {
659
+ await this.publishWorkflowEvent({
660
+ eventId: (0, crypto_1.randomUUID)(),
661
+ type: 'COMPLETED',
662
+ userId,
663
+ assignmentId,
664
+ timestamp: now,
665
+ payload: result?.data,
666
+ });
667
+ }
668
+ return true;
669
+ }
670
+ /**
671
+ * Fail an assignment explicitly (e.g., user reports inability to complete).
672
+ *
673
+ * @param userId - The user failing the assignment
674
+ * @param assignmentId - The assignment being failed
675
+ * @param reason - Optional reason for failure
676
+ */
677
+ async failAssignment(userId, assignmentId, reason) {
678
+ const json = await this.redisClient.hGet(this.acceptedAssignmentsKey, assignmentId);
679
+ if (!json) {
680
+ throw new Error('Assignment not found in accepted state');
681
+ }
682
+ const assignment = JSON.parse(json);
683
+ const now = Date.now();
684
+ // Move from accepted to completed (with failed status)
685
+ const multi = this.redisClient.multi();
686
+ multi.hDel(this.acceptedAssignmentsKey, assignmentId);
687
+ const failedData = {
688
+ ...assignment,
689
+ _failedBy: userId,
690
+ _failedAt: now,
691
+ _failureReason: reason,
692
+ };
693
+ multi.hSet(this.completedAssignmentsKey, assignmentId, JSON.stringify(failedData));
694
+ await multi.exec();
695
+ // Publish workflow event if workflows are enabled
696
+ if (this.enableWorkflows) {
697
+ await this.publishWorkflowEvent({
698
+ eventId: (0, crypto_1.randomUUID)(),
699
+ type: 'FAILED',
700
+ userId,
701
+ assignmentId,
702
+ timestamp: now,
703
+ payload: { reason },
704
+ });
705
+ }
706
+ return true;
707
+ }
708
+ // ============================================================================
709
+ // Workflow Management Methods
710
+ // ============================================================================
711
+ /**
712
+ * Register a workflow definition.
713
+ *
714
+ * @param definition - The workflow definition to register
715
+ */
716
+ /**
717
+ * Register a new workflow definition.
718
+ */
719
+ async registerWorkflow(definition) {
720
+ return this.workflow.registerWorkflow(definition);
721
+ }
722
+ /**
723
+ * Get a workflow definition by ID.
724
+ */
725
+ async getWorkflowDefinition(id) {
726
+ return this.workflow.getWorkflowDefinition(id);
727
+ }
728
+ /**
729
+ * List all registered workflow definitions.
730
+ */
731
+ async listWorkflowDefinitions() {
732
+ return this.workflow.listWorkflowDefinitions();
733
+ }
734
+ /**
735
+ * Start a new workflow instance for a user.
736
+ */
737
+ async startWorkflow(workflowDefinitionId, userId, initialContext) {
738
+ return this.workflow.startWorkflow(workflowDefinitionId, userId, initialContext);
739
+ }
740
+ /**
741
+ * Get a workflow instance by ID.
742
+ */
743
+ async getWorkflowInstance(instanceId) {
744
+ return this.workflow.getWorkflowInstance(instanceId);
745
+ }
746
+ /**
747
+ * Get a workflow instance with its snapshot definition.
748
+ */
749
+ async getWorkflowInstanceWithSnapshot(instanceId) {
750
+ return this.workflow.getWorkflowInstanceWithSnapshot(instanceId);
751
+ }
752
+ /**
753
+ * Get all active workflow instances for a user.
754
+ */
755
+ async getActiveWorkflowsForUser(userId) {
756
+ return this.workflow.getActiveWorkflowsForUser(userId);
757
+ }
758
+ /**
759
+ * Cancel a workflow instance.
760
+ */
761
+ async cancelWorkflow(instanceId) {
762
+ return this.workflow.cancelWorkflow(instanceId);
763
+ }
764
+ /**
765
+ * Check and process expired workflow steps.
766
+ * Should be called periodically.
767
+ */
768
+ async processExpiredWorkflowSteps() {
769
+ return this.workflow.processExpiredWorkflowSteps();
770
+ }
771
+ /**
772
+ * Publish a workflow event to the Redis Stream.
773
+ */
774
+ async publishWorkflowEvent(event) {
775
+ return this.workflow.publishWorkflowEvent(event);
776
+ }
777
+ /**
778
+ * Start the workflow orchestrator.
779
+ * This listens to the event stream and processes workflow transitions.
780
+ */
781
+ async startOrchestrator() {
782
+ return this.workflow.startOrchestrator();
783
+ }
784
+ /**
785
+ * Stop the workflow orchestrator.
786
+ */
787
+ async stopOrchestrator() {
788
+ return this.workflow.stopOrchestrator();
789
+ }
609
790
  async processExpiredMatches() {
610
791
  const now = Date.now();
611
792
  const expiredIds = await this.redisClient.zRangeByScore(this.pendingAssignmentsExpiryKey, '-inf', now);
@@ -614,12 +795,22 @@ class AssignmentMatcher {
614
795
  const json = await this.redisClient.hGet(this.pendingAssignmentsKey, id);
615
796
  const multi = this.redisClient.multi();
616
797
  if (owner) {
617
- multi.sRem(this.redisPrefix + `user:${owner}:assignments`, `assignment:${id}`);
798
+ multi.sRem(this.keys.userAssignments(owner), `assignment:${id}`);
618
799
  }
619
800
  multi.hDel(this.pendingAssignmentsKey, id);
620
801
  multi.zRem(this.pendingAssignmentsExpiryKey, id);
621
802
  multi.hDel(this.assignmentOwnerKey, id);
622
803
  await multi.exec();
804
+ // Publish workflow expired event if workflows are enabled
805
+ if (this.enableWorkflows && owner) {
806
+ await this.workflow.publishWorkflowEvent({
807
+ eventId: (0, crypto_1.randomUUID)(),
808
+ type: 'EXPIRED',
809
+ userId: owner,
810
+ assignmentId: id,
811
+ timestamp: now,
812
+ });
813
+ }
623
814
  if (json) {
624
815
  await this.addAssignment(JSON.parse(json));
625
816
  }
@@ -639,6 +830,33 @@ class AssignmentMatcher {
639
830
  this.autoReleaseInterval = null;
640
831
  }
641
832
  }
833
+ /**
834
+ * Get assignments specifically targeted at a user through active workflows.
835
+ * These take priority over general pool assignments for deterministic matching.
836
+ */
837
+ async getWorkflowTargetedAssignments(userId) {
838
+ const targeted = [];
839
+ // Scan queued assignments for those with _targetUserId matching this user
840
+ const queuedAssignments = await this.redisClient.hGetAll(this.assignmentsRefKey);
841
+ for (const [assignmentId, json] of Object.entries(queuedAssignments)) {
842
+ try {
843
+ const assignment = JSON.parse(json);
844
+ if (assignment._targetUserId === userId && assignment._workflowInstanceId) {
845
+ // This is a workflow assignment targeted at this user
846
+ targeted.push({
847
+ id: assignmentId,
848
+ priority: assignment.priority ?? 1000,
849
+ });
850
+ }
851
+ }
852
+ catch {
853
+ // Ignore parse errors
854
+ }
855
+ }
856
+ // Sort by priority (higher first)
857
+ targeted.sort((a, b) => b.priority - a.priority);
858
+ return targeted;
859
+ }
642
860
  async expandTagWildcards(tags) {
643
861
  const expanded = [];
644
862
  const wildcards = tags.filter((t) => t.tag.endsWith('*'));