assignment-user-matcher 1.2.0 → 1.2.2
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.
- package/README.md +523 -2
- package/dist/index.d.ts +3 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +8 -1
- package/dist/learning/features.d.ts +19 -0
- package/dist/learning/features.d.ts.map +1 -0
- package/dist/learning/features.js +55 -0
- package/dist/managers/LearningManager.d.ts +94 -0
- package/dist/managers/LearningManager.d.ts.map +1 -0
- package/dist/managers/LearningManager.js +194 -0
- package/dist/managers/WorkflowManager.d.ts +10 -6
- package/dist/managers/WorkflowManager.d.ts.map +1 -1
- package/dist/managers/WorkflowManager.js +115 -23
- package/dist/matcher.class.d.ts +79 -8
- package/dist/matcher.class.d.ts.map +1 -1
- package/dist/matcher.class.js +352 -22
- package/dist/scoring/match-score.d.ts +11 -1
- package/dist/scoring/match-score.d.ts.map +1 -1
- package/dist/scoring/match-score.js +49 -2
- package/dist/types/matcher.d.ts +133 -5
- package/dist/types/matcher.d.ts.map +1 -1
- package/dist/utils/keys.d.ts +5 -0
- package/dist/utils/keys.d.ts.map +1 -1
- package/dist/utils/keys.js +6 -0
- package/dist/workflow-builder.d.ts +15 -4
- package/dist/workflow-builder.d.ts.map +1 -1
- package/dist/workflow-builder.js +25 -42
- package/dist/workflow-validation.d.ts +4 -0
- package/dist/workflow-validation.d.ts.map +1 -0
- package/dist/workflow-validation.js +85 -0
- package/package.json +4 -2
package/dist/matcher.class.js
CHANGED
|
@@ -7,6 +7,8 @@ const cidr_1 = require("./utils/cidr");
|
|
|
7
7
|
const keys_1 = require("./utils/keys");
|
|
8
8
|
const pagination_1 = require("./queries/pagination");
|
|
9
9
|
const match_score_1 = require("./scoring/match-score");
|
|
10
|
+
const features_1 = require("./learning/features");
|
|
11
|
+
const LearningManager_1 = require("./managers/LearningManager");
|
|
10
12
|
const ReliabilityManager_1 = require("./managers/ReliabilityManager");
|
|
11
13
|
const TelemetryManager_1 = require("./managers/TelemetryManager");
|
|
12
14
|
const WorkflowManager_1 = require("./managers/WorkflowManager");
|
|
@@ -32,6 +34,7 @@ class AssignmentMatcher {
|
|
|
32
34
|
this.redisClient = redisClient;
|
|
33
35
|
this.luaScriptSha = null;
|
|
34
36
|
this.autoReleaseInterval = null;
|
|
37
|
+
this.idleUserInterval = null;
|
|
35
38
|
this.relevantBatchSize = options?.relevantBatchSize ?? 50;
|
|
36
39
|
this.enableDefaultMatching = options?.enableDefaultMatching ?? true;
|
|
37
40
|
this.redisPrefix = options?.redisPrefix ?? '';
|
|
@@ -42,6 +45,7 @@ class AssignmentMatcher {
|
|
|
42
45
|
this.assignmentsRefKey = this.keys.assignmentsRef();
|
|
43
46
|
this.maxUserBacklogSize = options?.maxUserBacklogSize ?? 9;
|
|
44
47
|
this.matchExpirationMs = options?.matchExpirationMs ?? 60000;
|
|
48
|
+
this.idleUserTimeoutMs = options?.idleUserTimeoutMs ?? null;
|
|
45
49
|
this.pendingAssignmentsKey = this.keys.pendingAssignmentsData();
|
|
46
50
|
this.pendingAssignmentsExpiryKey = this.keys.pendingAssignmentsExpiry();
|
|
47
51
|
this.assignmentOwnerKey = this.keys.assignmentOwner();
|
|
@@ -49,6 +53,7 @@ class AssignmentMatcher {
|
|
|
49
53
|
this.acceptedAssignmentsKey = this.keys.acceptedAssignments();
|
|
50
54
|
this.completedAssignmentsKey = this.keys.completedAssignments();
|
|
51
55
|
this.calculatePriority = options?.prioritizationFunction ?? this.calculatePriority;
|
|
56
|
+
this.usingDefaultMatchScore = !options?.matchingFunction;
|
|
52
57
|
this.matchScore = options?.matchingFunction ?? this.defaultMatchScore.bind(this);
|
|
53
58
|
// Workflow options
|
|
54
59
|
this.enableWorkflows = options?.enableWorkflows ?? false;
|
|
@@ -65,13 +70,27 @@ class AssignmentMatcher {
|
|
|
65
70
|
streamConsumerName: this.streamConsumerName,
|
|
66
71
|
});
|
|
67
72
|
this.telemetry = new TelemetryManager_1.TelemetryManager(options?.enableOpenTelemetry ?? false);
|
|
73
|
+
// Learning layer (opt-in contextual bandit re-ranking)
|
|
74
|
+
this.enableLearning = options?.enableLearning ?? false;
|
|
75
|
+
this.learningFeatureExtractor = options?.learningFeatureExtractor ?? features_1.extractMatchFeatures;
|
|
76
|
+
this.learning = new LearningManager_1.LearningManager(this.redisClient, this.keys, {
|
|
77
|
+
learningRate: options?.learningRate,
|
|
78
|
+
explorationRate: options?.learningExplorationRate,
|
|
79
|
+
shadowMode: options?.learningShadowMode,
|
|
80
|
+
boostFactor: options?.learningBoostFactor,
|
|
81
|
+
rewards: options?.learningRewards,
|
|
82
|
+
decisionTtlMs: options?.learningDecisionTtlMs,
|
|
83
|
+
signalWeights: options?.learningSignalWeights,
|
|
84
|
+
feedbackTtlMs: options?.learningFeedbackTtlMs,
|
|
85
|
+
});
|
|
68
86
|
this.workflow = new WorkflowManager_1.WorkflowManager(this.redisClient, this.keys, this.reliability, this.telemetry, this, {
|
|
69
87
|
enableWorkflows: this.enableWorkflows,
|
|
70
88
|
streamConsumerGroup: this.streamConsumerGroup,
|
|
71
89
|
streamConsumerName: this.streamConsumerName,
|
|
72
|
-
reclaimIntervalMs: options?.
|
|
90
|
+
reclaimIntervalMs: options?.workflowReclaimPollIntervalMs ?? 5000,
|
|
91
|
+
reclaimMinIdleMs: options?.workflowOrphanReclaimMs ?? 60000,
|
|
73
92
|
});
|
|
74
|
-
this.initRedis();
|
|
93
|
+
this.readyPromise = this.initRedis();
|
|
75
94
|
}
|
|
76
95
|
/** Keys for the three assignment stores (used by pagination queries) */
|
|
77
96
|
get assignmentStoreKeys() {
|
|
@@ -95,6 +114,12 @@ class AssignmentMatcher {
|
|
|
95
114
|
}
|
|
96
115
|
return this;
|
|
97
116
|
}
|
|
117
|
+
/**
|
|
118
|
+
* Wait until the matcher has connected and initialized workflow internals.
|
|
119
|
+
*/
|
|
120
|
+
async waitUntilReady() {
|
|
121
|
+
return this.readyPromise;
|
|
122
|
+
}
|
|
98
123
|
/**
|
|
99
124
|
* Load Lua scripts into Redis for atomic operations.
|
|
100
125
|
*/
|
|
@@ -110,27 +135,32 @@ class AssignmentMatcher {
|
|
|
110
135
|
}
|
|
111
136
|
}
|
|
112
137
|
async atomicWorkflowTransition(instanceId, expectedVersion, newStatus, newStepId, updatedContext, historyEntry) {
|
|
138
|
+
await this.readyPromise;
|
|
113
139
|
return this.workflow.atomicWorkflowTransition(instanceId, expectedVersion, newStatus, newStepId, updatedContext, historyEntry);
|
|
114
140
|
}
|
|
115
141
|
async reclaimOrphanedMessages() {
|
|
142
|
+
await this.readyPromise;
|
|
116
143
|
return this.workflow.reclaimOrphanedMessages();
|
|
117
144
|
}
|
|
118
145
|
/**
|
|
119
146
|
* Get events from the Dead Letter Queue.
|
|
120
147
|
*/
|
|
121
148
|
async getDeadLetterEvents(limit = 100, offset = 0) {
|
|
149
|
+
await this.readyPromise;
|
|
122
150
|
return this.reliability.getDeadLetterEvents(limit, offset);
|
|
123
151
|
}
|
|
124
152
|
/**
|
|
125
153
|
* Get Dead Letter Queue size.
|
|
126
154
|
*/
|
|
127
155
|
async getDeadLetterQueueSize() {
|
|
156
|
+
await this.readyPromise;
|
|
128
157
|
return this.reliability.getDeadLetterQueueSize();
|
|
129
158
|
}
|
|
130
159
|
/**
|
|
131
160
|
* Replay a Dead Letter Queue event.
|
|
132
161
|
*/
|
|
133
162
|
async replayDeadLetterEvent(eventJson) {
|
|
163
|
+
await this.readyPromise;
|
|
134
164
|
const entry = JSON.parse(eventJson);
|
|
135
165
|
// Reset retry count
|
|
136
166
|
await this.redisClient.del(this.keys.eventRetryCount(entry.event.eventId));
|
|
@@ -144,15 +174,70 @@ class AssignmentMatcher {
|
|
|
144
174
|
* Clear all events from the Dead Letter Queue.
|
|
145
175
|
*/
|
|
146
176
|
async clearDeadLetterQueue() {
|
|
177
|
+
await this.readyPromise;
|
|
147
178
|
return this.reliability.clearDeadLetterQueue();
|
|
148
179
|
}
|
|
149
180
|
/**
|
|
150
181
|
* Get audit events from the audit stream.
|
|
151
182
|
*/
|
|
152
183
|
async getAuditEvents(count = 100) {
|
|
184
|
+
await this.readyPromise;
|
|
153
185
|
return this.reliability.getAuditEvents(count);
|
|
154
186
|
}
|
|
155
187
|
// ============================================================================
|
|
188
|
+
// Learning (Contextual Bandit) Methods
|
|
189
|
+
// ============================================================================
|
|
190
|
+
/**
|
|
191
|
+
* Get the learned model weights (feature -> weight).
|
|
192
|
+
*/
|
|
193
|
+
async getLearningModel() {
|
|
194
|
+
await this.readyPromise;
|
|
195
|
+
return this.learning.getModel();
|
|
196
|
+
}
|
|
197
|
+
/**
|
|
198
|
+
* Get aggregate learning statistics (decisions, rewards, average reward).
|
|
199
|
+
*/
|
|
200
|
+
async getLearningStats() {
|
|
201
|
+
await this.readyPromise;
|
|
202
|
+
return this.learning.getStats();
|
|
203
|
+
}
|
|
204
|
+
/**
|
|
205
|
+
* Apply a manual reward to a matched assignment's decision context.
|
|
206
|
+
* Enables custom reward shaping beyond the built-in lifecycle outcomes.
|
|
207
|
+
* Returns false when no decision context exists for the assignment.
|
|
208
|
+
*/
|
|
209
|
+
async recordLearningReward(assignmentId, reward) {
|
|
210
|
+
await this.readyPromise;
|
|
211
|
+
return this.learning.recordReward(assignmentId, reward);
|
|
212
|
+
}
|
|
213
|
+
/**
|
|
214
|
+
* Feed external post-processing signals into the model for an assignment
|
|
215
|
+
* (e.g. { accuracy: 0.95, csat: 0.8 }). Works for live decisions and for
|
|
216
|
+
* archived episodes of already-completed assignments (within the feedback TTL).
|
|
217
|
+
* Signal values are weighted via the `learningSignalWeights` option (default 1).
|
|
218
|
+
* Returns false when no learning context exists for the assignment.
|
|
219
|
+
*/
|
|
220
|
+
async recordLearningFeedback(assignmentId, signals) {
|
|
221
|
+
await this.readyPromise;
|
|
222
|
+
return this.learning.recordFeedback(assignmentId, signals);
|
|
223
|
+
}
|
|
224
|
+
/**
|
|
225
|
+
* Train the model directly with raw (features, reward) samples from an
|
|
226
|
+
* external pipeline (offline evaluation jobs, historical data imports).
|
|
227
|
+
* Returns the number of samples applied.
|
|
228
|
+
*/
|
|
229
|
+
async trainLearningSamples(samples) {
|
|
230
|
+
await this.readyPromise;
|
|
231
|
+
return this.learning.trainSamples(samples);
|
|
232
|
+
}
|
|
233
|
+
/**
|
|
234
|
+
* Reset the learned model weights and statistics.
|
|
235
|
+
*/
|
|
236
|
+
async resetLearningModel() {
|
|
237
|
+
await this.readyPromise;
|
|
238
|
+
return this.learning.resetModel();
|
|
239
|
+
}
|
|
240
|
+
// ============================================================================
|
|
156
241
|
// OpenTelemetry Tracing Hooks
|
|
157
242
|
// ============================================================================
|
|
158
243
|
/**
|
|
@@ -181,13 +266,16 @@ class AssignmentMatcher {
|
|
|
181
266
|
}
|
|
182
267
|
}
|
|
183
268
|
async addUser(user) {
|
|
269
|
+
await this.readyPromise;
|
|
184
270
|
await this.redisClient.hSet(this.usersKey, user.id, JSON.stringify({
|
|
185
271
|
...user,
|
|
186
272
|
tags: [...user.tags, ...(this.enableDefaultMatching ? ['default'] : [])],
|
|
187
273
|
}));
|
|
274
|
+
await this.touchUser(user.id);
|
|
188
275
|
return user;
|
|
189
276
|
}
|
|
190
277
|
async addAssignment(assignment) {
|
|
278
|
+
await this.readyPromise;
|
|
191
279
|
let { id, tags, priority, latitude, longitude } = assignment;
|
|
192
280
|
if (!priority)
|
|
193
281
|
priority = await this.calculatePriority(assignment);
|
|
@@ -225,6 +313,7 @@ class AssignmentMatcher {
|
|
|
225
313
|
return assignment;
|
|
226
314
|
}
|
|
227
315
|
async removeAssignment(id) {
|
|
316
|
+
await this.readyPromise;
|
|
228
317
|
const assignmentPriorityKey = this.keys.assignmentPriority(id);
|
|
229
318
|
const assignmentTagsKey = this.keys.assignmentTags(id);
|
|
230
319
|
const assignmentGeoKey = this.keys.assignmentsGeo();
|
|
@@ -260,10 +349,12 @@ class AssignmentMatcher {
|
|
|
260
349
|
return id;
|
|
261
350
|
}
|
|
262
351
|
async removeUser(userId) {
|
|
352
|
+
await this.readyPromise;
|
|
263
353
|
const multi = this.redisClient
|
|
264
354
|
.multi()
|
|
265
355
|
.del(this.keys.userAssignments(userId))
|
|
266
356
|
.del(this.keys.userRejected(userId))
|
|
357
|
+
.zRem(this.keys.userActivity(), userId)
|
|
267
358
|
.hDel(this.usersKey, userId);
|
|
268
359
|
await multi.exec();
|
|
269
360
|
return userId;
|
|
@@ -273,6 +364,7 @@ class AssignmentMatcher {
|
|
|
273
364
|
* For large datasets, prefer using getAssignmentsPaginated() instead.
|
|
274
365
|
*/
|
|
275
366
|
async getAllAssignments() {
|
|
367
|
+
await this.readyPromise;
|
|
276
368
|
return (0, pagination_1.getAllAssignmentsFromStores)(this.redisClient, this.assignmentStoreKeys);
|
|
277
369
|
}
|
|
278
370
|
/**
|
|
@@ -285,6 +377,7 @@ class AssignmentMatcher {
|
|
|
285
377
|
* @param options.includeTotal - Whether to include total count (slower for large datasets)
|
|
286
378
|
*/
|
|
287
379
|
async getAssignmentsPaginated(options) {
|
|
380
|
+
await this.readyPromise;
|
|
288
381
|
return (0, pagination_1.getAssignmentsPaginatedFromStores)(this.redisClient, this.assignmentStoreKeys, options);
|
|
289
382
|
}
|
|
290
383
|
/**
|
|
@@ -292,23 +385,69 @@ class AssignmentMatcher {
|
|
|
292
385
|
* Efficient for dashboards and monitoring.
|
|
293
386
|
*/
|
|
294
387
|
async getAssignmentCounts() {
|
|
388
|
+
await this.readyPromise;
|
|
295
389
|
return (0, pagination_1.getAssignmentCountsFromStores)(this.redisClient, this.assignmentStoreKeys);
|
|
296
390
|
}
|
|
297
391
|
/**
|
|
298
392
|
* Get a single assignment by ID from any status.
|
|
299
393
|
*/
|
|
300
394
|
async getAssignment(id) {
|
|
395
|
+
await this.readyPromise;
|
|
301
396
|
return (0, pagination_1.getAssignmentById)(this.redisClient, this.assignmentStoreKeys, id);
|
|
302
397
|
}
|
|
303
398
|
/**
|
|
304
399
|
* Get multiple assignments by IDs efficiently.
|
|
305
400
|
*/
|
|
306
401
|
async getAssignmentsByIds(ids) {
|
|
402
|
+
await this.readyPromise;
|
|
307
403
|
return (0, pagination_1.getAssignmentsByIdsBatch)(this.redisClient, this.assignmentStoreKeys, ids);
|
|
308
404
|
}
|
|
405
|
+
/**
|
|
406
|
+
* Get all pending assignments with owner and pending duration metadata.
|
|
407
|
+
*/
|
|
408
|
+
async getPendingAssignmentsWithAge() {
|
|
409
|
+
await this.readyPromise;
|
|
410
|
+
const now = Date.now();
|
|
411
|
+
const pendingEntries = await this.redisClient.hGetAll(this.pendingAssignmentsKey);
|
|
412
|
+
const assignmentIds = Object.keys(pendingEntries);
|
|
413
|
+
if (assignmentIds.length === 0) {
|
|
414
|
+
return [];
|
|
415
|
+
}
|
|
416
|
+
const [owners, expiryScores] = await Promise.all([
|
|
417
|
+
this.redisClient.hmGet(this.assignmentOwnerKey, assignmentIds),
|
|
418
|
+
Promise.all(assignmentIds.map((id) => this.redisClient.zScore(this.pendingAssignmentsExpiryKey, id))),
|
|
419
|
+
]);
|
|
420
|
+
const results = [];
|
|
421
|
+
for (let i = 0; i < assignmentIds.length; i++) {
|
|
422
|
+
const id = assignmentIds[i];
|
|
423
|
+
const json = pendingEntries[id];
|
|
424
|
+
if (!json)
|
|
425
|
+
continue;
|
|
426
|
+
let assignment;
|
|
427
|
+
try {
|
|
428
|
+
assignment = JSON.parse(json);
|
|
429
|
+
}
|
|
430
|
+
catch {
|
|
431
|
+
continue;
|
|
432
|
+
}
|
|
433
|
+
const score = expiryScores[i];
|
|
434
|
+
const expiresAt = score === null ? null : Number(score);
|
|
435
|
+
const pendingSince = expiresAt === null ? null : expiresAt - this.matchExpirationMs;
|
|
436
|
+
const pendingForMs = pendingSince === null ? null : Math.max(0, now - pendingSince);
|
|
437
|
+
results.push({
|
|
438
|
+
assignment,
|
|
439
|
+
ownerId: owners[i] ?? null,
|
|
440
|
+
pendingForMs,
|
|
441
|
+
pendingSince,
|
|
442
|
+
expiresAt,
|
|
443
|
+
});
|
|
444
|
+
}
|
|
445
|
+
results.sort((a, b) => (b.pendingForMs ?? -1) - (a.pendingForMs ?? -1));
|
|
446
|
+
return results;
|
|
447
|
+
}
|
|
309
448
|
/** 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));
|
|
449
|
+
defaultMatchScore(user, assignmentTags, assignmentPriority, _assignmentId, skillThresholds) {
|
|
450
|
+
return Promise.resolve((0, match_score_1.calculateMatchScore)(user, assignmentTags, assignmentPriority, this.enableDefaultMatching, skillThresholds));
|
|
312
451
|
}
|
|
313
452
|
async calculatePriority(...args) {
|
|
314
453
|
const [assignment] = args;
|
|
@@ -389,6 +528,8 @@ class AssignmentMatcher {
|
|
|
389
528
|
}
|
|
390
529
|
async getUserRelatedAssignments(user) {
|
|
391
530
|
const userAssignments = [];
|
|
531
|
+
const routingWeights = user.routingWeights;
|
|
532
|
+
const hasRoutingWeights = Boolean(routingWeights && Object.keys(routingWeights).length > 0);
|
|
392
533
|
// Priority 1: Check for workflow-targeted assignments (deterministic matching)
|
|
393
534
|
if (this.enableWorkflows) {
|
|
394
535
|
const workflowAssignments = await this.getWorkflowTargetedAssignments(user.id);
|
|
@@ -403,8 +544,8 @@ class AssignmentMatcher {
|
|
|
403
544
|
// Priority 2: Build candidate assignments using per-tag zset union with user weights for scalability.
|
|
404
545
|
const positiveWeights = [];
|
|
405
546
|
const zeroWeightTags = [];
|
|
406
|
-
if (
|
|
407
|
-
for (const [tag, w] of Object.entries(
|
|
547
|
+
if (hasRoutingWeights) {
|
|
548
|
+
for (const [tag, w] of Object.entries(routingWeights)) {
|
|
408
549
|
if (typeof w === 'number' && w > 0)
|
|
409
550
|
positiveWeights.push({ tag, weight: w });
|
|
410
551
|
else if (w === 0)
|
|
@@ -417,18 +558,26 @@ class AssignmentMatcher {
|
|
|
417
558
|
positiveWeights.push({ tag, weight: 1 });
|
|
418
559
|
}
|
|
419
560
|
}
|
|
420
|
-
// Ensure default tag is included
|
|
421
|
-
|
|
561
|
+
// Ensure default tag is included for unweighted users.
|
|
562
|
+
// In weighted + default scoring path, only explicit positive weights may match.
|
|
563
|
+
if (this.enableDefaultMatching && !hasRoutingWeights) {
|
|
422
564
|
const defaultInPos = positiveWeights.find((t) => t.tag === 'default');
|
|
423
|
-
const defaultZero = zeroWeightTags.
|
|
565
|
+
const defaultZero = zeroWeightTags.some((tag) => tag === 'default' || (tag.endsWith('*') && 'default'.startsWith(tag.slice(0, -1))));
|
|
424
566
|
if (!defaultInPos && !defaultZero)
|
|
425
567
|
positiveWeights.push({ tag: 'default', weight: 1 });
|
|
426
568
|
}
|
|
569
|
+
// In weighted default matching, users must define at least one positive weight.
|
|
570
|
+
// If they don't, nothing should be assigned and queue remains intact.
|
|
571
|
+
if (hasRoutingWeights && this.usingDefaultMatchScore && positiveWeights.length === 0) {
|
|
572
|
+
return userAssignments;
|
|
573
|
+
}
|
|
427
574
|
if (positiveWeights.length === 0)
|
|
428
575
|
return userAssignments;
|
|
429
576
|
// Expand wildcards
|
|
430
577
|
const expandedPositive = await this.expandTagWildcards(positiveWeights);
|
|
431
|
-
const expandedZero =
|
|
578
|
+
const expandedZero = this.usingDefaultMatchScore
|
|
579
|
+
? await this.expandTagWildcards(zeroWeightTags.map((t) => ({ tag: t, weight: 0 })))
|
|
580
|
+
: [];
|
|
432
581
|
const finalZeroTags = expandedZero.map((t) => t.tag);
|
|
433
582
|
if (expandedPositive.length === 0)
|
|
434
583
|
return userAssignments;
|
|
@@ -482,32 +631,75 @@ class AssignmentMatcher {
|
|
|
482
631
|
const tags = String(flat[i * 3 + 1] || '');
|
|
483
632
|
const assignmentJson = flat[i * 3 + 2];
|
|
484
633
|
let allowedCidrs;
|
|
634
|
+
let skillThresholds;
|
|
635
|
+
let raw;
|
|
485
636
|
if (assignmentJson) {
|
|
486
637
|
try {
|
|
487
638
|
const parsed = JSON.parse(assignmentJson);
|
|
488
639
|
allowedCidrs = parsed.allowedCidrs;
|
|
640
|
+
skillThresholds = parsed.skillThresholds;
|
|
641
|
+
raw = parsed;
|
|
489
642
|
}
|
|
490
643
|
catch {
|
|
491
644
|
// Ignore JSON parse errors
|
|
492
645
|
}
|
|
493
646
|
}
|
|
494
|
-
details.push({ id: assignmentId, basePriority: priority, tags, allowedCidrs });
|
|
647
|
+
details.push({ id: assignmentId, basePriority: priority, tags, allowedCidrs, skillThresholds, raw });
|
|
495
648
|
}
|
|
496
649
|
// Prefer higher base priority first to satisfy tests and practical expectations
|
|
497
650
|
details.sort((a, b) => b.basePriority - a.basePriority);
|
|
498
651
|
const selected = [];
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
652
|
+
if (this.enableLearning) {
|
|
653
|
+
// Learning path: evaluate all eligible candidates, then re-rank by
|
|
654
|
+
// base priority + predicted reward (hard filters still apply first).
|
|
655
|
+
const modelWeights = await this.learning.getModel();
|
|
656
|
+
const eligible = [];
|
|
657
|
+
for (const d of details) {
|
|
658
|
+
if (!(0, cidr_1.checkCidrMatch)(user.ip, d.allowedCidrs))
|
|
659
|
+
continue;
|
|
660
|
+
const [score, combinedPriority] = await this.matchScore(user, d.tags, d.basePriority, d.id, d.skillThresholds);
|
|
661
|
+
if (!score || !combinedPriority)
|
|
662
|
+
continue;
|
|
663
|
+
const context = {
|
|
664
|
+
...(d.raw ?? {}),
|
|
665
|
+
id: d.id,
|
|
666
|
+
tags: d.tags ? d.tags.split(',').filter(Boolean) : [],
|
|
667
|
+
};
|
|
668
|
+
const features = this.learningFeatureExtractor(user, context);
|
|
669
|
+
const predicted = this.learning.predict(features, modelWeights);
|
|
670
|
+
// Shadow mode observes without influencing ranking.
|
|
671
|
+
// Epsilon-greedy exploration adds random jitter to gather data on under-served candidates.
|
|
672
|
+
const exploration = !this.learning.shadowMode && this.learning.shouldExplore()
|
|
673
|
+
? Math.random() * this.learning.boostFactor
|
|
674
|
+
: 0;
|
|
675
|
+
const effectivePriority = this.learning.shadowMode
|
|
676
|
+
? combinedPriority
|
|
677
|
+
: combinedPriority + this.learning.boostFactor * predicted + exploration;
|
|
678
|
+
eligible.push({ detail: d, combinedPriority, features, predicted, effectivePriority });
|
|
505
679
|
}
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
680
|
+
eligible.sort((a, b) => b.effectivePriority - a.effectivePriority);
|
|
681
|
+
for (const c of eligible) {
|
|
682
|
+
if (userAssignments.length >= this.maxUserBacklogSize)
|
|
683
|
+
break;
|
|
684
|
+
userAssignments.push({ id: c.detail.id, priority: c.effectivePriority });
|
|
685
|
+
selected.push({ id: c.detail.id, tags: c.detail.tags });
|
|
686
|
+
await this.learning.recordDecision(user.id, c.detail.id, c.features, c.predicted);
|
|
687
|
+
}
|
|
688
|
+
}
|
|
689
|
+
else {
|
|
690
|
+
for (const d of details) {
|
|
691
|
+
if (userAssignments.length >= this.maxUserBacklogSize)
|
|
692
|
+
break;
|
|
693
|
+
// Check CIDR restrictions: if assignment has allowedCidrs, user must have matching IP
|
|
694
|
+
if (!(0, cidr_1.checkCidrMatch)(user.ip, d.allowedCidrs)) {
|
|
695
|
+
continue; // Skip this assignment - user IP doesn't match allowed CIDRs
|
|
696
|
+
}
|
|
697
|
+
// Use custom matchScore (supports weights and thresholds) for a final check and tie-break
|
|
698
|
+
const [score, combinedPriority] = await this.matchScore(user, d.tags, d.basePriority, d.id, d.skillThresholds);
|
|
699
|
+
if (score && combinedPriority) {
|
|
700
|
+
userAssignments.push({ id: d.id, priority: combinedPriority });
|
|
701
|
+
selected.push({ id: d.id, tags: d.tags });
|
|
702
|
+
}
|
|
511
703
|
}
|
|
512
704
|
}
|
|
513
705
|
// Batch-remove all selected assignments from indexes and references to reduce round trips
|
|
@@ -543,6 +735,7 @@ class AssignmentMatcher {
|
|
|
543
735
|
return userAssignments;
|
|
544
736
|
}
|
|
545
737
|
async matchUsersAssignments(userId) {
|
|
738
|
+
await this.readyPromise;
|
|
546
739
|
// If a specific userId is provided, process only that user for precise per-user matching.
|
|
547
740
|
if (userId) {
|
|
548
741
|
const userJson = await this.redisClient.hGet(this.usersKey, userId);
|
|
@@ -586,10 +779,12 @@ class AssignmentMatcher {
|
|
|
586
779
|
}));
|
|
587
780
|
}
|
|
588
781
|
async getCurrentAssignmentsForUser(userId) {
|
|
782
|
+
await this.readyPromise;
|
|
589
783
|
const userAssignments = await this.redisClient.sMembers(this.keys.userAssignments(userId));
|
|
590
784
|
return userAssignments.map((el) => el.split(':')[1]);
|
|
591
785
|
}
|
|
592
786
|
async acceptAssignment(userId, assignmentId) {
|
|
787
|
+
await this.readyPromise;
|
|
593
788
|
const isAssigned = await this.redisClient.sIsMember(this.keys.userAssignments(userId), `assignment:${assignmentId}`);
|
|
594
789
|
if (!isAssigned)
|
|
595
790
|
throw new Error('Assignment not found for user');
|
|
@@ -605,9 +800,14 @@ class AssignmentMatcher {
|
|
|
605
800
|
multi.hSet(this.acceptedAssignmentsKey, assignmentId, json);
|
|
606
801
|
}
|
|
607
802
|
await multi.exec();
|
|
803
|
+
if (this.enableLearning) {
|
|
804
|
+
await this.learning.applyOutcome(assignmentId, 'accept');
|
|
805
|
+
}
|
|
806
|
+
await this.touchUser(userId);
|
|
608
807
|
return true;
|
|
609
808
|
}
|
|
610
809
|
async rejectAssignment(userId, assignmentId) {
|
|
810
|
+
await this.readyPromise;
|
|
611
811
|
const isAssigned = await this.redisClient.sIsMember(this.keys.userAssignments(userId), `assignment:${assignmentId}`);
|
|
612
812
|
if (!isAssigned)
|
|
613
813
|
throw new Error('Assignment not found for user');
|
|
@@ -620,6 +820,10 @@ class AssignmentMatcher {
|
|
|
620
820
|
// Add to rejected list to prevent immediate re-assignment
|
|
621
821
|
multi.sAdd(this.keys.userRejected(userId), assignmentId);
|
|
622
822
|
await multi.exec();
|
|
823
|
+
if (this.enableLearning) {
|
|
824
|
+
await this.learning.applyOutcome(assignmentId, 'reject');
|
|
825
|
+
}
|
|
826
|
+
await this.touchUser(userId);
|
|
623
827
|
if (json) {
|
|
624
828
|
await this.addAssignment(JSON.parse(json));
|
|
625
829
|
}
|
|
@@ -635,6 +839,7 @@ class AssignmentMatcher {
|
|
|
635
839
|
* @param result - Optional result payload for routing decisions
|
|
636
840
|
*/
|
|
637
841
|
async completeAssignment(userId, assignmentId, result) {
|
|
842
|
+
await this.readyPromise;
|
|
638
843
|
// Verify assignment is in accepted state
|
|
639
844
|
const json = await this.redisClient.hGet(this.acceptedAssignmentsKey, assignmentId);
|
|
640
845
|
if (!json) {
|
|
@@ -654,6 +859,9 @@ class AssignmentMatcher {
|
|
|
654
859
|
};
|
|
655
860
|
multi.hSet(this.completedAssignmentsKey, assignmentId, JSON.stringify(completedData));
|
|
656
861
|
await multi.exec();
|
|
862
|
+
if (this.enableLearning) {
|
|
863
|
+
await this.learning.applyOutcome(assignmentId, 'complete');
|
|
864
|
+
}
|
|
657
865
|
// Publish workflow event if workflows are enabled
|
|
658
866
|
if (this.enableWorkflows) {
|
|
659
867
|
await this.publishWorkflowEvent({
|
|
@@ -675,6 +883,7 @@ class AssignmentMatcher {
|
|
|
675
883
|
* @param reason - Optional reason for failure
|
|
676
884
|
*/
|
|
677
885
|
async failAssignment(userId, assignmentId, reason) {
|
|
886
|
+
await this.readyPromise;
|
|
678
887
|
const json = await this.redisClient.hGet(this.acceptedAssignmentsKey, assignmentId);
|
|
679
888
|
if (!json) {
|
|
680
889
|
throw new Error('Assignment not found in accepted state');
|
|
@@ -692,6 +901,9 @@ class AssignmentMatcher {
|
|
|
692
901
|
};
|
|
693
902
|
multi.hSet(this.completedAssignmentsKey, assignmentId, JSON.stringify(failedData));
|
|
694
903
|
await multi.exec();
|
|
904
|
+
if (this.enableLearning) {
|
|
905
|
+
await this.learning.applyOutcome(assignmentId, 'fail');
|
|
906
|
+
}
|
|
695
907
|
// Publish workflow event if workflows are enabled
|
|
696
908
|
if (this.enableWorkflows) {
|
|
697
909
|
await this.publishWorkflowEvent({
|
|
@@ -717,48 +929,67 @@ class AssignmentMatcher {
|
|
|
717
929
|
* Register a new workflow definition.
|
|
718
930
|
*/
|
|
719
931
|
async registerWorkflow(definition) {
|
|
932
|
+
await this.readyPromise;
|
|
720
933
|
return this.workflow.registerWorkflow(definition);
|
|
721
934
|
}
|
|
722
935
|
/**
|
|
723
936
|
* Get a workflow definition by ID.
|
|
724
937
|
*/
|
|
725
938
|
async getWorkflowDefinition(id) {
|
|
939
|
+
await this.readyPromise;
|
|
726
940
|
return this.workflow.getWorkflowDefinition(id);
|
|
727
941
|
}
|
|
728
942
|
/**
|
|
729
943
|
* List all registered workflow definitions.
|
|
730
944
|
*/
|
|
731
945
|
async listWorkflowDefinitions() {
|
|
946
|
+
await this.readyPromise;
|
|
732
947
|
return this.workflow.listWorkflowDefinitions();
|
|
733
948
|
}
|
|
949
|
+
/**
|
|
950
|
+
* Register and start a workflow in one call, or start an already-registered workflow by ID.
|
|
951
|
+
*/
|
|
952
|
+
async executeWorkflow(workflowOrId, userId, initialContext) {
|
|
953
|
+
await this.readyPromise;
|
|
954
|
+
if (typeof workflowOrId === 'string') {
|
|
955
|
+
return this.workflow.startWorkflow(workflowOrId, userId, initialContext);
|
|
956
|
+
}
|
|
957
|
+
const definition = await this.workflow.registerWorkflow(workflowOrId);
|
|
958
|
+
return this.workflow.startWorkflow(definition.id, userId, initialContext);
|
|
959
|
+
}
|
|
734
960
|
/**
|
|
735
961
|
* Start a new workflow instance for a user.
|
|
736
962
|
*/
|
|
737
963
|
async startWorkflow(workflowDefinitionId, userId, initialContext) {
|
|
964
|
+
await this.readyPromise;
|
|
738
965
|
return this.workflow.startWorkflow(workflowDefinitionId, userId, initialContext);
|
|
739
966
|
}
|
|
740
967
|
/**
|
|
741
968
|
* Get a workflow instance by ID.
|
|
742
969
|
*/
|
|
743
970
|
async getWorkflowInstance(instanceId) {
|
|
971
|
+
await this.readyPromise;
|
|
744
972
|
return this.workflow.getWorkflowInstance(instanceId);
|
|
745
973
|
}
|
|
746
974
|
/**
|
|
747
975
|
* Get a workflow instance with its snapshot definition.
|
|
748
976
|
*/
|
|
749
977
|
async getWorkflowInstanceWithSnapshot(instanceId) {
|
|
978
|
+
await this.readyPromise;
|
|
750
979
|
return this.workflow.getWorkflowInstanceWithSnapshot(instanceId);
|
|
751
980
|
}
|
|
752
981
|
/**
|
|
753
982
|
* Get all active workflow instances for a user.
|
|
754
983
|
*/
|
|
755
984
|
async getActiveWorkflowsForUser(userId) {
|
|
985
|
+
await this.readyPromise;
|
|
756
986
|
return this.workflow.getActiveWorkflowsForUser(userId);
|
|
757
987
|
}
|
|
758
988
|
/**
|
|
759
989
|
* Cancel a workflow instance.
|
|
760
990
|
*/
|
|
761
991
|
async cancelWorkflow(instanceId) {
|
|
992
|
+
await this.readyPromise;
|
|
762
993
|
return this.workflow.cancelWorkflow(instanceId);
|
|
763
994
|
}
|
|
764
995
|
/**
|
|
@@ -766,12 +997,14 @@ class AssignmentMatcher {
|
|
|
766
997
|
* Should be called periodically.
|
|
767
998
|
*/
|
|
768
999
|
async processExpiredWorkflowSteps() {
|
|
1000
|
+
await this.readyPromise;
|
|
769
1001
|
return this.workflow.processExpiredWorkflowSteps();
|
|
770
1002
|
}
|
|
771
1003
|
/**
|
|
772
1004
|
* Publish a workflow event to the Redis Stream.
|
|
773
1005
|
*/
|
|
774
1006
|
async publishWorkflowEvent(event) {
|
|
1007
|
+
await this.readyPromise;
|
|
775
1008
|
return this.workflow.publishWorkflowEvent(event);
|
|
776
1009
|
}
|
|
777
1010
|
/**
|
|
@@ -779,15 +1012,18 @@ class AssignmentMatcher {
|
|
|
779
1012
|
* This listens to the event stream and processes workflow transitions.
|
|
780
1013
|
*/
|
|
781
1014
|
async startOrchestrator() {
|
|
1015
|
+
await this.readyPromise;
|
|
782
1016
|
return this.workflow.startOrchestrator();
|
|
783
1017
|
}
|
|
784
1018
|
/**
|
|
785
1019
|
* Stop the workflow orchestrator.
|
|
786
1020
|
*/
|
|
787
1021
|
async stopOrchestrator() {
|
|
1022
|
+
await this.readyPromise;
|
|
788
1023
|
return this.workflow.stopOrchestrator();
|
|
789
1024
|
}
|
|
790
1025
|
async processExpiredMatches() {
|
|
1026
|
+
await this.readyPromise;
|
|
791
1027
|
const now = Date.now();
|
|
792
1028
|
const expiredIds = await this.redisClient.zRangeByScore(this.pendingAssignmentsExpiryKey, '-inf', now);
|
|
793
1029
|
for (const id of expiredIds) {
|
|
@@ -801,6 +1037,9 @@ class AssignmentMatcher {
|
|
|
801
1037
|
multi.zRem(this.pendingAssignmentsExpiryKey, id);
|
|
802
1038
|
multi.hDel(this.assignmentOwnerKey, id);
|
|
803
1039
|
await multi.exec();
|
|
1040
|
+
if (this.enableLearning) {
|
|
1041
|
+
await this.learning.applyOutcome(id, 'expire');
|
|
1042
|
+
}
|
|
804
1043
|
// Publish workflow expired event if workflows are enabled
|
|
805
1044
|
if (this.enableWorkflows && owner) {
|
|
806
1045
|
await this.workflow.publishWorkflowEvent({
|
|
@@ -830,6 +1069,97 @@ class AssignmentMatcher {
|
|
|
830
1069
|
this.autoReleaseInterval = null;
|
|
831
1070
|
}
|
|
832
1071
|
}
|
|
1072
|
+
// ============================================================================
|
|
1073
|
+
// Idle User Auto-Rejection (opt-in via idleUserTimeoutMs)
|
|
1074
|
+
// ============================================================================
|
|
1075
|
+
/**
|
|
1076
|
+
* Record activity for a user (heartbeat). Resets the idle clock used by
|
|
1077
|
+
* processIdleUsers(). Called automatically on addUser, acceptAssignment,
|
|
1078
|
+
* and rejectAssignment; consumers can also call it directly as a heartbeat.
|
|
1079
|
+
*/
|
|
1080
|
+
async touchUser(userId) {
|
|
1081
|
+
await this.readyPromise;
|
|
1082
|
+
await this.redisClient.zAdd(this.keys.userActivity(), { score: Date.now(), value: userId });
|
|
1083
|
+
}
|
|
1084
|
+
/**
|
|
1085
|
+
* Detect users that have been idle longer than idleUserTimeoutMs while
|
|
1086
|
+
* holding pending (unactioned) assignments. Idle users are removed from
|
|
1087
|
+
* the matching pool and their pending assignments are requeued for
|
|
1088
|
+
* distribution to other users.
|
|
1089
|
+
*
|
|
1090
|
+
* No-op (returns []) when idleUserTimeoutMs is not configured.
|
|
1091
|
+
*
|
|
1092
|
+
* @returns IDs of users that were removed
|
|
1093
|
+
*/
|
|
1094
|
+
async processIdleUsers() {
|
|
1095
|
+
await this.readyPromise;
|
|
1096
|
+
if (this.idleUserTimeoutMs === null)
|
|
1097
|
+
return [];
|
|
1098
|
+
const cutoff = Date.now() - this.idleUserTimeoutMs;
|
|
1099
|
+
const idleCandidates = await this.redisClient.zRangeByScore(this.keys.userActivity(), '-inf', cutoff);
|
|
1100
|
+
const removed = [];
|
|
1101
|
+
for (const userId of idleCandidates) {
|
|
1102
|
+
// Skip users no longer in the pool (clean up stale activity entry)
|
|
1103
|
+
const exists = await this.redisClient.hExists(this.usersKey, userId);
|
|
1104
|
+
if (!exists) {
|
|
1105
|
+
await this.redisClient.zRem(this.keys.userActivity(), userId);
|
|
1106
|
+
continue;
|
|
1107
|
+
}
|
|
1108
|
+
// Only consider a user idle if they are sitting on unactioned assignments
|
|
1109
|
+
const pendingCount = await this.redisClient.sCard(this.keys.userAssignments(userId));
|
|
1110
|
+
if (pendingCount === 0)
|
|
1111
|
+
continue;
|
|
1112
|
+
await this.releaseUserPendingAssignments(userId);
|
|
1113
|
+
await this.removeUser(userId);
|
|
1114
|
+
removed.push(userId);
|
|
1115
|
+
}
|
|
1116
|
+
return removed;
|
|
1117
|
+
}
|
|
1118
|
+
/**
|
|
1119
|
+
* Requeue all pending assignments currently held by a user.
|
|
1120
|
+
*/
|
|
1121
|
+
async releaseUserPendingAssignments(userId) {
|
|
1122
|
+
const members = await this.redisClient.sMembers(this.keys.userAssignments(userId));
|
|
1123
|
+
const now = Date.now();
|
|
1124
|
+
for (const member of members) {
|
|
1125
|
+
const id = member.split(':')[1];
|
|
1126
|
+
const json = await this.redisClient.hGet(this.pendingAssignmentsKey, id);
|
|
1127
|
+
const multi = this.redisClient.multi();
|
|
1128
|
+
multi.sRem(this.keys.userAssignments(userId), member);
|
|
1129
|
+
multi.hDel(this.pendingAssignmentsKey, id);
|
|
1130
|
+
multi.zRem(this.pendingAssignmentsExpiryKey, id);
|
|
1131
|
+
multi.hDel(this.assignmentOwnerKey, id);
|
|
1132
|
+
await multi.exec();
|
|
1133
|
+
if (this.enableLearning) {
|
|
1134
|
+
await this.learning.applyOutcome(id, 'expire');
|
|
1135
|
+
}
|
|
1136
|
+
if (this.enableWorkflows) {
|
|
1137
|
+
await this.workflow.publishWorkflowEvent({
|
|
1138
|
+
eventId: (0, crypto_1.randomUUID)(),
|
|
1139
|
+
type: 'EXPIRED',
|
|
1140
|
+
userId,
|
|
1141
|
+
assignmentId: id,
|
|
1142
|
+
timestamp: now,
|
|
1143
|
+
});
|
|
1144
|
+
}
|
|
1145
|
+
if (json) {
|
|
1146
|
+
await this.addAssignment(JSON.parse(json));
|
|
1147
|
+
}
|
|
1148
|
+
}
|
|
1149
|
+
}
|
|
1150
|
+
startIdleUserInterval(intervalMs = 10000) {
|
|
1151
|
+
if (this.idleUserInterval)
|
|
1152
|
+
return;
|
|
1153
|
+
this.idleUserInterval = setInterval(() => {
|
|
1154
|
+
this.processIdleUsers().catch(console.error);
|
|
1155
|
+
}, intervalMs);
|
|
1156
|
+
}
|
|
1157
|
+
stopIdleUserInterval() {
|
|
1158
|
+
if (this.idleUserInterval) {
|
|
1159
|
+
clearInterval(this.idleUserInterval);
|
|
1160
|
+
this.idleUserInterval = null;
|
|
1161
|
+
}
|
|
1162
|
+
}
|
|
833
1163
|
/**
|
|
834
1164
|
* Get assignments specifically targeted at a user through active workflows.
|
|
835
1165
|
* These take priority over general pool assignments for deterministic matching.
|