assignment-user-matcher 1.2.2 → 1.2.3

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 (35) hide show
  1. package/README.md +188 -89
  2. package/dist/index.d.ts +5 -3
  3. package/dist/index.d.ts.map +1 -1
  4. package/dist/index.js +6 -1
  5. package/dist/learning/auto-weights.d.ts +31 -0
  6. package/dist/learning/auto-weights.d.ts.map +1 -0
  7. package/dist/learning/auto-weights.js +65 -0
  8. package/dist/lua/workflow-transition.lua +29 -0
  9. package/dist/managers/LearningManager.d.ts +39 -4
  10. package/dist/managers/LearningManager.d.ts.map +1 -1
  11. package/dist/managers/LearningManager.js +78 -3
  12. package/dist/managers/ReliabilityManager.d.ts +60 -2
  13. package/dist/managers/ReliabilityManager.d.ts.map +1 -1
  14. package/dist/managers/ReliabilityManager.js +190 -9
  15. package/dist/managers/TelemetryManager.d.ts.map +1 -1
  16. package/dist/managers/WorkflowManager.d.ts +78 -1
  17. package/dist/managers/WorkflowManager.d.ts.map +1 -1
  18. package/dist/managers/WorkflowManager.js +449 -77
  19. package/dist/matcher.class.d.ts +105 -8
  20. package/dist/matcher.class.d.ts.map +1 -1
  21. package/dist/matcher.class.js +307 -37
  22. package/dist/queries/pagination.d.ts.map +1 -1
  23. package/dist/queries/pagination.js +9 -6
  24. package/dist/scoring/match-score.d.ts.map +1 -1
  25. package/dist/scoring/match-score.js +1 -1
  26. package/dist/types/matcher.d.ts +139 -0
  27. package/dist/types/matcher.d.ts.map +1 -1
  28. package/dist/utils/geo.d.ts +26 -0
  29. package/dist/utils/geo.d.ts.map +1 -0
  30. package/dist/utils/geo.js +62 -0
  31. package/dist/utils/keys.d.ts +10 -0
  32. package/dist/utils/keys.d.ts.map +1 -1
  33. package/dist/utils/keys.js +11 -0
  34. package/dist/workflow-validation.d.ts.map +1 -1
  35. package/package.json +2 -2
@@ -4,6 +4,7 @@ const crypto_1 = require("crypto");
4
4
  const fs_1 = require("fs");
5
5
  const path_1 = require("path");
6
6
  const cidr_1 = require("./utils/cidr");
7
+ const geo_1 = require("./utils/geo");
7
8
  const keys_1 = require("./utils/keys");
8
9
  const pagination_1 = require("./queries/pagination");
9
10
  const match_score_1 = require("./scoring/match-score");
@@ -55,6 +56,10 @@ class AssignmentMatcher {
55
56
  this.calculatePriority = options?.prioritizationFunction ?? this.calculatePriority;
56
57
  this.usingDefaultMatchScore = !options?.matchingFunction;
57
58
  this.matchScore = options?.matchingFunction ?? this.defaultMatchScore.bind(this);
59
+ this.enableGeoMatching = options?.enableGeoMatching ?? false;
60
+ this.geoDefaultMaxDistanceKm = options?.geoDefaultMaxDistanceKm;
61
+ this.geoScoreWeight = options?.geoScoreWeight ?? 0;
62
+ this.geoMatchingFunction = options?.geoMatchingFunction;
58
63
  // Workflow options
59
64
  this.enableWorkflows = options?.enableWorkflows ?? false;
60
65
  this.streamConsumerGroup = options?.streamConsumerGroup ?? 'orchestrator';
@@ -68,10 +73,15 @@ class AssignmentMatcher {
68
73
  workflowAuditEnabled: options?.workflowAuditEnabled ?? false,
69
74
  workflowSnapshotDefinitions: options?.workflowSnapshotDefinitions ?? true,
70
75
  streamConsumerName: this.streamConsumerName,
76
+ circuitBreakerPersistState: options?.circuitBreakerPersistState ?? false,
77
+ circuitBreakerShared: options?.circuitBreakerShared ?? false,
78
+ enableReliabilityMetrics: options?.enableReliabilityMetrics ?? true,
79
+ deadLetterQueueAlertThreshold: options?.deadLetterQueueAlertThreshold ?? 100,
71
80
  });
72
81
  this.telemetry = new TelemetryManager_1.TelemetryManager(options?.enableOpenTelemetry ?? false);
73
82
  // Learning layer (opt-in contextual bandit re-ranking)
74
83
  this.enableLearning = options?.enableLearning ?? false;
84
+ this.enableAutoRoutingWeights = options?.enableAutoRoutingWeights ?? false;
75
85
  this.learningFeatureExtractor = options?.learningFeatureExtractor ?? features_1.extractMatchFeatures;
76
86
  this.learning = new LearningManager_1.LearningManager(this.redisClient, this.keys, {
77
87
  learningRate: options?.learningRate,
@@ -82,6 +92,8 @@ class AssignmentMatcher {
82
92
  decisionTtlMs: options?.learningDecisionTtlMs,
83
93
  signalWeights: options?.learningSignalWeights,
84
94
  feedbackTtlMs: options?.learningFeedbackTtlMs,
95
+ trackTagStats: this.enableAutoRoutingWeights,
96
+ autoWeights: options?.autoRoutingWeights,
85
97
  });
86
98
  this.workflow = new WorkflowManager_1.WorkflowManager(this.redisClient, this.keys, this.reliability, this.telemetry, this, {
87
99
  enableWorkflows: this.enableWorkflows,
@@ -89,6 +101,11 @@ class AssignmentMatcher {
89
101
  streamConsumerName: this.streamConsumerName,
90
102
  reclaimIntervalMs: options?.workflowReclaimPollIntervalMs ?? 5000,
91
103
  reclaimMinIdleMs: options?.workflowOrphanReclaimMs ?? 60000,
104
+ retentionMs: options?.workflowInstanceRetentionMs,
105
+ retryBackoffMs: options?.workflowRetryBackoffMs,
106
+ eventBatchSize: options?.workflowEventBatchSize,
107
+ pollBlockMs: options?.workflowPollBlockMs,
108
+ maxEventsPerSecond: options?.workflowMaxEventsPerSecond,
92
109
  });
93
110
  this.readyPromise = this.initRedis();
94
111
  }
@@ -106,6 +123,8 @@ class AssignmentMatcher {
106
123
  if (!this.redisClient.isOpen) {
107
124
  await this.redisClient.connect();
108
125
  }
126
+ // Initialize reliability manager (load persisted circuit breaker state if enabled)
127
+ await this.reliability.init();
109
128
  // Initialize workflow stream consumer group if workflows are enabled
110
129
  if (this.enableWorkflows) {
111
130
  await this.workflow.init();
@@ -185,6 +204,66 @@ class AssignmentMatcher {
185
204
  return this.reliability.getAuditEvents(count);
186
205
  }
187
206
  // ============================================================================
207
+ // Reliability & Health Check Methods
208
+ // ============================================================================
209
+ /**
210
+ * Get comprehensive reliability metrics including circuit breaker state,
211
+ * Dead Letter Queue size, and Redis health status.
212
+ */
213
+ async getReliabilityMetrics() {
214
+ await this.readyPromise;
215
+ return this.reliability.getMetrics();
216
+ }
217
+ /**
218
+ * Get current circuit breaker state
219
+ */
220
+ async getCircuitBreakerState() {
221
+ await this.readyPromise;
222
+ return this.reliability.getCircuitBreakerState();
223
+ }
224
+ /**
225
+ * Check if Dead Letter Queue size exceeds alert threshold
226
+ */
227
+ async checkDeadLetterQueueAlert() {
228
+ await this.readyPromise;
229
+ return this.reliability.checkDeadLetterQueueAlert();
230
+ }
231
+ /**
232
+ * Perform a health check on Redis connection
233
+ * Returns true if Redis is healthy, false otherwise
234
+ */
235
+ async healthCheck() {
236
+ await this.readyPromise;
237
+ const details = {
238
+ timestamp: Date.now(),
239
+ };
240
+ try {
241
+ // Check if Redis client is connected
242
+ details.redisConnected = this.redisClient.isOpen;
243
+ // Try to ping Redis
244
+ const pingResult = await this.redisClient.ping();
245
+ details.redisPing = pingResult;
246
+ // Get reliability metrics
247
+ const metrics = await this.getReliabilityMetrics();
248
+ details.circuitBreakerState = metrics.circuitBreakerState;
249
+ details.deadLetterQueueSize = metrics.deadLetterQueueSize;
250
+ details.circuitBreakerAllowingRequests = metrics.circuitBreakerAllowingRequests;
251
+ // Check if circuit breaker is allowing requests
252
+ const healthy = details.redisConnected && pingResult === 'PONG' && details.circuitBreakerAllowingRequests;
253
+ return {
254
+ healthy,
255
+ details,
256
+ };
257
+ }
258
+ catch (err) {
259
+ details.error = err instanceof Error ? err.message : String(err);
260
+ return {
261
+ healthy: false,
262
+ details,
263
+ };
264
+ }
265
+ }
266
+ // ============================================================================
188
267
  // Learning (Contextual Bandit) Methods
189
268
  // ============================================================================
190
269
  /**
@@ -237,6 +316,102 @@ class AssignmentMatcher {
237
316
  await this.readyPromise;
238
317
  return this.learning.resetModel();
239
318
  }
319
+ /**
320
+ * Toggle learning shadow mode at runtime without losing model/state.
321
+ *
322
+ * `true`: learn-only, ranking unaffected.
323
+ * `false`: learning predictions can influence ranking.
324
+ */
325
+ async setLearningShadowMode(enabled) {
326
+ await this.readyPromise;
327
+ this.learning.setShadowMode(enabled);
328
+ }
329
+ /** Current runtime shadow mode state. */
330
+ async getLearningShadowMode() {
331
+ await this.readyPromise;
332
+ return this.learning.shadowMode;
333
+ }
334
+ // ============================================================================
335
+ // Auto Routing Weights (RL-generated tags/weights)
336
+ // ============================================================================
337
+ /**
338
+ * Per-user, per-tag reward statistics aggregated from learned outcomes.
339
+ * Requires `enableLearning` and `enableAutoRoutingWeights`.
340
+ */
341
+ async getLearnedTagStats(userId) {
342
+ await this.readyPromise;
343
+ return this.learning.getUserTagStats(userId);
344
+ }
345
+ /**
346
+ * Synthesize a routingWeights map for a user from learned tag statistics
347
+ * using a UCB1 bandit policy: high weights for rewarding tags, weight 0
348
+ * (hard veto) for consistently bad tags, and optimistic priors for
349
+ * under-explored tags. Does not persist anything.
350
+ *
351
+ * @param opts.includeUnexploredTags also assign the exploration prior to
352
+ * every known tag in the system the user has no data for yet
353
+ */
354
+ async getLearnedRoutingWeights(userId, opts) {
355
+ await this.readyPromise;
356
+ const knownTags = opts?.includeUnexploredTags ? await this.getKnownTagsForAutoWeights() : undefined;
357
+ const userJson = await this.redisClient.hGet(this.usersKey, userId);
358
+ const existingWeights = userJson ? JSON.parse(userJson).routingWeights : undefined;
359
+ return this.learning.getLearnedRoutingWeights(userId, knownTags, existingWeights);
360
+ }
361
+ /**
362
+ * Apply learned routing weights to one user (or every tracked user when
363
+ * no id is given), automating tags/weights generation from RL outcomes.
364
+ *
365
+ * Merge semantics: learned tags always take their learned value; manual
366
+ * routingWeights entries for tags the learner has no data on are
367
+ * preserved (set `opts.overrideManual` to replace the map entirely).
368
+ * The applied learned map is stored on the user as `learnedRoutingWeights`
369
+ * for observability.
370
+ *
371
+ * Returns the applied weights per user id.
372
+ */
373
+ async syncLearnedRoutingWeights(userId, opts) {
374
+ await this.readyPromise;
375
+ const targets = userId ? [userId] : await this.learning.listTrackedUsers();
376
+ const knownTags = opts?.includeUnexploredTags ? await this.getKnownTagsForAutoWeights() : undefined;
377
+ const applied = {};
378
+ for (const id of targets) {
379
+ const userJson = await this.redisClient.hGet(this.usersKey, id);
380
+ if (!userJson)
381
+ continue;
382
+ const user = JSON.parse(userJson);
383
+ // Pass the user's current routingWeights as warm per-tag priors
384
+ // so under-sampled tags start from the existing value rather than
385
+ // the flat priorWeight.
386
+ const previousLearned = user.learnedRoutingWeights ?? {};
387
+ const existingForSynthesis = user.routingWeights
388
+ ? Object.fromEntries(Object.entries(user.routingWeights).filter(([tag]) => !(tag in previousLearned)))
389
+ : undefined;
390
+ const learned = await this.learning.getLearnedRoutingWeights(id, knownTags, existingForSynthesis);
391
+ if (Object.keys(learned).length === 0)
392
+ continue;
393
+ let routingWeights;
394
+ if (opts?.overrideManual) {
395
+ routingWeights = learned;
396
+ }
397
+ else {
398
+ const manualEntries = {};
399
+ for (const [tag, weight] of Object.entries(user.routingWeights ?? {})) {
400
+ if (!(tag in previousLearned) && !(tag in learned))
401
+ manualEntries[tag] = weight;
402
+ }
403
+ routingWeights = { ...manualEntries, ...learned };
404
+ }
405
+ await this.redisClient.hSet(this.usersKey, id, JSON.stringify({ ...user, routingWeights, learnedRoutingWeights: learned }));
406
+ applied[id] = routingWeights;
407
+ }
408
+ return applied;
409
+ }
410
+ /** All known tags except the internal 'default' tag (for exploration priors) */
411
+ async getKnownTagsForAutoWeights() {
412
+ const tags = await this.redisClient.sMembers(this.allTagsKey);
413
+ return tags.filter((t) => t !== 'default');
414
+ }
240
415
  // ============================================================================
241
416
  // OpenTelemetry Tracing Hooks
242
417
  // ============================================================================
@@ -292,7 +467,7 @@ class AssignmentMatcher {
292
467
  score: priority,
293
468
  value: id,
294
469
  });
295
- if (latitude && longitude) {
470
+ if ((0, geo_1.isValidLatitude)(latitude) && (0, geo_1.isValidLongitude)(longitude)) {
296
471
  multi.geoAdd(assignmentGeoKey, {
297
472
  longitude,
298
473
  latitude,
@@ -320,7 +495,7 @@ class AssignmentMatcher {
320
495
  // Fetch tags and owner in case it's pending
321
496
  const [tagsCsv, owner] = await Promise.all([
322
497
  this.redisClient.hGet(assignmentTagsKey, 'tags'),
323
- this.redisClient.hGet(this.assignmentOwnerKey, id)
498
+ this.redisClient.hGet(this.assignmentOwnerKey, id),
324
499
  ]);
325
500
  let tags = [];
326
501
  if (tagsCsv && tagsCsv.length > 0) {
@@ -371,10 +546,7 @@ class AssignmentMatcher {
371
546
  * Get assignments with pagination support for efficient querying of large datasets.
372
547
  * Uses cursor-based pagination across statuses.
373
548
  *
374
- * @param options.cursor - Cursor for pagination (null/undefined for first page)
375
- * @param options.limit - Maximum number of assignments to return per page (default: 100)
376
- * @param options.status - Filter by status: 'queued' | 'pending' | 'accepted' | 'all' (default: 'all')
377
- * @param options.includeTotal - Whether to include total count (slower for large datasets)
549
+ * @param options - Pagination options.
378
550
  */
379
551
  async getAssignmentsPaginated(options) {
380
552
  await this.readyPromise;
@@ -449,6 +621,29 @@ class AssignmentMatcher {
449
621
  defaultMatchScore(user, assignmentTags, assignmentPriority, _assignmentId, skillThresholds) {
450
622
  return Promise.resolve((0, match_score_1.calculateMatchScore)(user, assignmentTags, assignmentPriority, this.enableDefaultMatching, skillThresholds));
451
623
  }
624
+ async evaluateGeoMatch(user, assignment) {
625
+ if (this.geoMatchingFunction) {
626
+ return this.geoMatchingFunction({
627
+ user,
628
+ assignment,
629
+ defaultMaxDistanceKm: this.geoDefaultMaxDistanceKm,
630
+ });
631
+ }
632
+ return (0, geo_1.checkGeoMatch)(user, assignment, {
633
+ enabled: this.enableGeoMatching,
634
+ defaultMaxDistanceKm: this.geoDefaultMaxDistanceKm,
635
+ });
636
+ }
637
+ calculateGeoBoost(geoMatch) {
638
+ if (!this.enableGeoMatching || this.geoScoreWeight <= 0)
639
+ return 0;
640
+ if (typeof geoMatch.distanceKm !== 'number' || typeof geoMatch.effectiveMaxDistanceKm !== 'number')
641
+ return 0;
642
+ if (geoMatch.effectiveMaxDistanceKm <= 0)
643
+ return 0;
644
+ const ratio = 1 - geoMatch.distanceKm / geoMatch.effectiveMaxDistanceKm;
645
+ return this.geoScoreWeight * Math.max(0, ratio);
646
+ }
452
647
  async calculatePriority(...args) {
453
648
  const [assignment] = args;
454
649
  return (0, match_score_1.calculateDefaultPriority)(assignment?.createdAt);
@@ -482,11 +677,11 @@ class AssignmentMatcher {
482
677
  const assignmentPriorityKey = this.keys.assignmentPriority(id);
483
678
  // Fetch tags to update per-tag indices
484
679
  const assignmentTagsKey = this.keys.assignmentTags(id);
485
- const [existsRef, tagsCsv] = await this.redisClient
680
+ const [existsRef, tagsCsv] = (await this.redisClient
486
681
  .multi()
487
682
  .hExists(this.assignmentsRefKey, id)
488
683
  .hGet(assignmentTagsKey, 'tags')
489
- .exec();
684
+ .exec());
490
685
  const tags = (tagsCsv && tagsCsv.length > 0 ? tagsCsv.split(',') : []);
491
686
  const multi = this.redisClient.multi();
492
687
  multi.hSet(assignmentPriorityKey, 'priority', priority);
@@ -541,6 +736,10 @@ class AssignmentMatcher {
541
736
  }
542
737
  }
543
738
  }
739
+ // Workflow-targeted assignments above are deterministically targeted at this
740
+ // user (not drawn from the shared tag pool below), so the claim-race filtering
741
+ // at the end of this function must never strip them out.
742
+ const workflowTargetedCount = userAssignments.length;
544
743
  // Priority 2: Build candidate assignments using per-tag zset union with user weights for scalability.
545
744
  const positiveWeights = [];
546
745
  const zeroWeightTags = [];
@@ -587,7 +786,7 @@ class AssignmentMatcher {
587
786
  const rejectedKey = this.keys.userRejected(user.id);
588
787
  const unionKeysWithWeights = expandedPositive.map((pw) => ({
589
788
  key: this.keys.tagAssignments(pw.tag),
590
- weight: pw.weight
789
+ weight: pw.weight,
591
790
  }));
592
791
  const multi = this.redisClient.multi();
593
792
  // Weighted union of positive tag assignment zsets
@@ -623,7 +822,7 @@ class AssignmentMatcher {
623
822
  // Also fetch assignment JSON to access allowedCidrs for network matching
624
823
  batched.hGet(this.assignmentsRefKey, assignmentId);
625
824
  }
626
- const flat = await batched.exec();
825
+ const flat = (await batched.exec());
627
826
  const details = [];
628
827
  for (let i = 0; i < top.length; i++) {
629
828
  const assignmentId = top[i].value;
@@ -657,9 +856,13 @@ class AssignmentMatcher {
657
856
  for (const d of details) {
658
857
  if (!(0, cidr_1.checkCidrMatch)(user.ip, d.allowedCidrs))
659
858
  continue;
859
+ const geoMatch = await this.evaluateGeoMatch(user, d.raw ?? { id: d.id, tags: [] });
860
+ if (!geoMatch.eligible)
861
+ continue;
660
862
  const [score, combinedPriority] = await this.matchScore(user, d.tags, d.basePriority, d.id, d.skillThresholds);
661
863
  if (!score || !combinedPriority)
662
864
  continue;
865
+ const geoAdjustedPriority = combinedPriority + this.calculateGeoBoost(geoMatch);
663
866
  const context = {
664
867
  ...(d.raw ?? {}),
665
868
  id: d.id,
@@ -673,8 +876,8 @@ class AssignmentMatcher {
673
876
  ? Math.random() * this.learning.boostFactor
674
877
  : 0;
675
878
  const effectivePriority = this.learning.shadowMode
676
- ? combinedPriority
677
- : combinedPriority + this.learning.boostFactor * predicted + exploration;
879
+ ? geoAdjustedPriority
880
+ : geoAdjustedPriority + this.learning.boostFactor * predicted + exploration;
678
881
  eligible.push({ detail: d, combinedPriority, features, predicted, effectivePriority });
679
882
  }
680
883
  eligible.sort((a, b) => b.effectivePriority - a.effectivePriority);
@@ -683,7 +886,7 @@ class AssignmentMatcher {
683
886
  break;
684
887
  userAssignments.push({ id: c.detail.id, priority: c.effectivePriority });
685
888
  selected.push({ id: c.detail.id, tags: c.detail.tags });
686
- await this.learning.recordDecision(user.id, c.detail.id, c.features, c.predicted);
889
+ await this.learning.recordDecision(user.id, c.detail.id, c.features, c.predicted, c.detail.tags ? c.detail.tags.split(',').filter(Boolean) : undefined);
687
890
  }
688
891
  }
689
892
  else {
@@ -694,45 +897,72 @@ class AssignmentMatcher {
694
897
  if (!(0, cidr_1.checkCidrMatch)(user.ip, d.allowedCidrs)) {
695
898
  continue; // Skip this assignment - user IP doesn't match allowed CIDRs
696
899
  }
900
+ const geoMatch = await this.evaluateGeoMatch(user, d.raw ?? { id: d.id, tags: [] });
901
+ if (!geoMatch.eligible) {
902
+ continue;
903
+ }
697
904
  // Use custom matchScore (supports weights and thresholds) for a final check and tie-break
698
905
  const [score, combinedPriority] = await this.matchScore(user, d.tags, d.basePriority, d.id, d.skillThresholds);
699
906
  if (score && combinedPriority) {
700
- userAssignments.push({ id: d.id, priority: combinedPriority });
907
+ userAssignments.push({ id: d.id, priority: combinedPriority + this.calculateGeoBoost(geoMatch) });
701
908
  selected.push({ id: d.id, tags: d.tags });
702
909
  }
703
910
  }
704
911
  }
705
- // Batch-remove all selected assignments from indexes and references to reduce round trips
912
+ // Claim, then clean up. The candidate read above (zDiffStore/zRangeWithScores)
913
+ // is a snapshot taken before this point, and getUserRelatedAssignments runs
914
+ // concurrently across users - matchUsersAssignments() Promise.all's the bulk
915
+ // path, and a per-user matchUsersAssignments(userId) call can race a bulk
916
+ // pass too. Without a single atomic gate, two concurrent callers can both
917
+ // still see the same assignment as available and both hand it to their user.
918
+ // HDEL on assignmentsRefKey is atomic and idempotent (returns 1 only for
919
+ // whichever caller actually deletes the field), so it's used here as that
920
+ // gate: only assignments this call actually wins are kept: anything already
921
+ // claimed by a concurrent caller since the snapshot read is dropped instead
922
+ // of being double-assigned.
923
+ const claimedIds = new Set();
706
924
  if (selected.length > 0) {
707
- // Fetch JSONs first to store in pending
708
925
  const jsonPromises = selected.map((s) => this.redisClient.hGet(this.assignmentsRefKey, s.id));
709
926
  const jsons = await Promise.all(jsonPromises);
710
927
  const now = Date.now();
711
- const rm = this.redisClient.multi();
928
+ const claimMulti = this.redisClient.multi();
929
+ for (const s of selected) {
930
+ claimMulti.hDel(this.assignmentsRefKey, s.id);
931
+ }
932
+ const claimResults = (await claimMulti.exec());
712
933
  for (let i = 0; i < selected.length; i++) {
713
- const s = selected[i];
714
- const json = jsons[i];
715
- // Remove from reference and per-assignment hashes
716
- rm.hDel(this.assignmentsRefKey, s.id);
717
- rm.del(this.keys.assignmentPriority(s.id));
718
- rm.del(this.keys.assignmentTags(s.id));
719
- // Remove from global zset
720
- rm.zRem(this.assignmentsKey, s.id);
721
- // Remove from per-tag zsets
722
- const tags = (s.tags ? s.tags.split(',').filter(Boolean) : []);
723
- for (const tag of tags) {
724
- rm.zRem(this.keys.tagAssignments(tag), s.id);
725
- }
726
- // Add to pending structures
727
- if (json) {
728
- rm.hSet(this.pendingAssignmentsKey, s.id, json);
729
- rm.zAdd(this.pendingAssignmentsExpiryKey, { score: now + this.matchExpirationMs, value: s.id });
730
- rm.hSet(this.assignmentOwnerKey, s.id, user.id);
934
+ if (Number(claimResults[i]) > 0)
935
+ claimedIds.add(selected[i].id);
936
+ }
937
+ if (claimedIds.size > 0) {
938
+ const rm = this.redisClient.multi();
939
+ for (let i = 0; i < selected.length; i++) {
940
+ const s = selected[i];
941
+ if (!claimedIds.has(s.id))
942
+ continue; // lost the race - already claimed elsewhere
943
+ const json = jsons[i];
944
+ rm.del(this.keys.assignmentPriority(s.id));
945
+ rm.del(this.keys.assignmentTags(s.id));
946
+ // Remove from global zset
947
+ rm.zRem(this.assignmentsKey, s.id);
948
+ // Remove from per-tag zsets
949
+ const tags = (s.tags ? s.tags.split(',').filter(Boolean) : []);
950
+ for (const tag of tags) {
951
+ rm.zRem(this.keys.tagAssignments(tag), s.id);
952
+ }
953
+ // Add to pending structures
954
+ if (json) {
955
+ rm.hSet(this.pendingAssignmentsKey, s.id, json);
956
+ rm.zAdd(this.pendingAssignmentsExpiryKey, { score: now + this.matchExpirationMs, value: s.id });
957
+ rm.hSet(this.assignmentOwnerKey, s.id, user.id);
958
+ }
731
959
  }
960
+ await rm.exec();
732
961
  }
733
- await rm.exec();
734
962
  }
735
- return userAssignments;
963
+ const workflowTargeted = userAssignments.slice(0, workflowTargetedCount);
964
+ const tagScored = userAssignments.slice(workflowTargetedCount).filter((ua) => claimedIds.has(ua.id));
965
+ return [...workflowTargeted, ...tagScored];
736
966
  }
737
967
  async matchUsersAssignments(userId) {
738
968
  await this.readyPromise;
@@ -1022,6 +1252,46 @@ class AssignmentMatcher {
1022
1252
  await this.readyPromise;
1023
1253
  return this.workflow.stopOrchestrator();
1024
1254
  }
1255
+ /**
1256
+ * Register a machine task handler by name. Machine steps with a matching
1257
+ * machineTask.handler run through this handler; unmatched handlers fall
1258
+ * back to the executeMachineTask host hook.
1259
+ */
1260
+ registerMachineHandler(name, handler) {
1261
+ this.workflow.registerMachineHandler(name, handler);
1262
+ }
1263
+ /**
1264
+ * Process due delayed event retries. Called automatically by the
1265
+ * orchestrator; exposed for deployments that run their own schedulers.
1266
+ */
1267
+ async drainScheduledRetries() {
1268
+ await this.readyPromise;
1269
+ return this.workflow.drainScheduledRetries();
1270
+ }
1271
+ /**
1272
+ * Backfill workflow indexes (active-instance index) from records created
1273
+ * before these indexes existed. Safe to run multiple times.
1274
+ */
1275
+ async backfillWorkflowIndexes() {
1276
+ await this.readyPromise;
1277
+ return this.workflow.backfillWorkflowIndexes();
1278
+ }
1279
+ /**
1280
+ * Remove terminal workflow instances last updated more than olderThanMs
1281
+ * ago, including registry, per-user, and index entries.
1282
+ */
1283
+ async pruneWorkflowInstances(olderThanMs) {
1284
+ await this.readyPromise;
1285
+ return this.workflow.pruneWorkflowInstances(olderThanMs);
1286
+ }
1287
+ /**
1288
+ * Operational metrics for the workflow engine: active instances, retry
1289
+ * queue depth, DLQ size, and event stream statistics.
1290
+ */
1291
+ async getWorkflowMetrics() {
1292
+ await this.readyPromise;
1293
+ return this.workflow.getWorkflowMetrics();
1294
+ }
1025
1295
  async processExpiredMatches() {
1026
1296
  await this.readyPromise;
1027
1297
  const now = Date.now();
@@ -1 +1 @@
1
- {"version":3,"file":"pagination.d.ts","sourceRoot":"","sources":["../../src/queries/pagination.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,OAAO,KAAK,EAAE,eAAe,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAEpE,MAAM,MAAM,gBAAgB,GAAG,QAAQ,GAAG,SAAS,GAAG,UAAU,CAAC;AAEjE,MAAM,WAAW,iBAAiB;IAC9B,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACvB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,MAAM,CAAC,EAAE,gB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iBAAiB,CACnC,WAAW,EAAE,eAAe,EAC5B,IAAI,EAAE,cAAc,EACpB,EAAE,EAAE,MAAM,GACX,OAAO,CAAC,CAAC,UAAU,GAAG;IAAE,OAAO,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC,GAAG,IAAI,CAAC,CAwBrD;AAED;;GAEG;AACH,wBAAsB,wBAAwB,CAC1C,WAAW,EAAE,eAAe,EAC5B,IAAI,EAAE,cAAc,EACpB,GAAG,EAAE,MAAM,EAAE,GACd,OAAO,CAAC,UAAU,EAAE,CAAC,CA+BvB;AAED;;GAEG;AACH,wBAAsB,iCAAiC,CACnD,WAAW,EAAE,eAAe,EAC5B,IAAI,EAAE,cAAc,EACpB,OAAO,CAAC,EAAE,iBAAiB,GAC5B,OAAO,CAAC,gBAAgB,CAAC,CA2H3B"}
@@ -70,7 +70,7 @@ async function getAssignmentsByIdsBatch(redisClient, keys, ids) {
70
70
  multi.hGet(keys.pending, id);
71
71
  multi.hGet(keys.accepted, id);
72
72
  }
73
- const results = await multi.exec();
73
+ const results = (await multi.exec());
74
74
  const assignments = [];
75
75
  for (let i = 0; i < ids.length; i++) {
76
76
  const queued = results[i * 3];
@@ -100,9 +100,12 @@ async function getAssignmentsPaginatedFromStores(redisClient, keys, options) {
100
100
  const includeTotal = options?.includeTotal ?? false;
101
101
  const getKeyForStatus = (s) => {
102
102
  switch (s) {
103
- case 'queued': return keys.queued;
104
- case 'pending': return keys.pending;
105
- case 'accepted': return keys.accepted;
103
+ case 'queued':
104
+ return keys.queued;
105
+ case 'pending':
106
+ return keys.pending;
107
+ case 'accepted':
108
+ return keys.accepted;
106
109
  }
107
110
  };
108
111
  const statusOrder = status === 'all' ? ['queued', 'pending', 'accepted'] : [status];
@@ -144,7 +147,7 @@ async function getAssignmentsPaginatedFromStores(redisClient, keys, options) {
144
147
  continue;
145
148
  }
146
149
  if (assignments.length >= limit) {
147
- nextCursor = `${statusIndex}:${offset + (assignments.length - (assignments.filter(a => a._status === scanStatus).length - 1))}`;
150
+ nextCursor = `${statusIndex}:${offset + (assignments.length - (assignments.filter((a) => a._status === scanStatus).length - 1))}`;
148
151
  hasMore = true;
149
152
  break;
150
153
  }
@@ -161,7 +164,7 @@ async function getAssignmentsPaginatedFromStores(redisClient, keys, options) {
161
164
  cursor = newCursor;
162
165
  } while (cursor !== '0' && assignments.length < limit);
163
166
  if (assignments.length >= limit) {
164
- const countFromCurrentStatus = assignments.filter(a => a._status === scanStatus).length;
167
+ const countFromCurrentStatus = assignments.filter((a) => a._status === scanStatus).length;
165
168
  nextCursor = `${statusIndex}:${offset + countFromCurrentStatus}`;
166
169
  hasMore = true;
167
170
  break;
@@ -1 +1 @@
1
- {"version":3,"file":"match-score.d.ts","sourceRoot":"","sources":["../../src/scoring/match-score.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,kBAAkB,CAAC;AAE7C;;GAEG;AACH,wBAAgB,cAAc,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,OAAO,CAOpE;AAED;;;GAGG;AACH,wBAAgB,kBAAkB,CAC9B,cAAc,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,EACtC,GAAG,EAAE,MAAM,GACZ,MAAM,CAYR;AAED;;;GAGG;AACH,wBAAgB,oBAAoB,CAChC,cAAc,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,SAAS,EAClD,eAAe,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,SAAS,GACpD,OAAO,CAeT;AAED;;;GAGG;AACH,wBAAgB,mBAAmB,CAC/B,IAAI,EAAE,IAAI,EACV,cAAc,EAAE,MAAM,EACtB,kBAAkB,EAAE,MAAM,GAAG,MAAM,EACnC,qBAAqB,EAAE,OAAO,EAC9B,eAAe,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GACzC,CAAC,MAAM,EAAE,MAAM,CAAC,CAoElB;AAED;;;GAGG;AACH,wBAAgB,wBAAwB,CAAC,SAAS,CAAC,EAAE,MAAM,GAAG,MAAM,CAGnE"}
1
+ {"version":3,"file":"match-score.d.ts","sourceRoot":"","sources":["../../src/scoring/match-score.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,kBAAkB,CAAC;AAE7C;;GAEG;AACH,wBAAgB,cAAc,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,OAAO,CAOpE;AAED;;;GAGG;AACH,wBAAgB,kBAAkB,CAAC,cAAc,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,EAAE,GAAG,EAAE,MAAM,GAAG,MAAM,CAY9F;AAED;;;GAGG;AACH,wBAAgB,oBAAoB,CAChC,cAAc,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,SAAS,EAClD,eAAe,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,SAAS,GACpD,OAAO,CAeT;AAED;;;GAGG;AACH,wBAAgB,mBAAmB,CAC/B,IAAI,EAAE,IAAI,EACV,cAAc,EAAE,MAAM,EACtB,kBAAkB,EAAE,MAAM,GAAG,MAAM,EACnC,qBAAqB,EAAE,OAAO,EAC9B,eAAe,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GACzC,CAAC,MAAM,EAAE,MAAM,CAAC,CAoElB;AAED;;;GAGG;AACH,wBAAgB,wBAAwB,CAAC,SAAS,CAAC,EAAE,MAAM,GAAG,MAAM,CAGnE"}
@@ -85,7 +85,7 @@ function calculateMatchScore(user, assignmentTags, assignmentPriority, enableDef
85
85
  }
86
86
  }
87
87
  }
88
- // If enableDefaultMatching is true, and the tag is 'default',
88
+ // If enableDefaultMatching is true, and the tag is 'default',
89
89
  // and it wasn't matched by any routing weight, give it default weight 1
90
90
  if (enableDefaultMatching && t === 'default' && !matchedByRouting) {
91
91
  weightSum += 1;