assignment-user-matcher 1.2.2 → 1.2.5

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 (38) hide show
  1. package/README.md +243 -91
  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 +195 -8
  20. package/dist/matcher.class.d.ts.map +1 -1
  21. package/dist/matcher.class.js +619 -36
  22. package/dist/queries/pagination.d.ts.map +1 -1
  23. package/dist/queries/pagination.js +9 -6
  24. package/dist/scoring/fair-arbitration.d.ts +68 -0
  25. package/dist/scoring/fair-arbitration.d.ts.map +1 -0
  26. package/dist/scoring/fair-arbitration.js +151 -0
  27. package/dist/scoring/match-score.d.ts.map +1 -1
  28. package/dist/scoring/match-score.js +1 -1
  29. package/dist/types/matcher.d.ts +258 -0
  30. package/dist/types/matcher.d.ts.map +1 -1
  31. package/dist/utils/geo.d.ts +26 -0
  32. package/dist/utils/geo.d.ts.map +1 -0
  33. package/dist/utils/geo.js +62 -0
  34. package/dist/utils/keys.d.ts +13 -0
  35. package/dist/utils/keys.d.ts.map +1 -1
  36. package/dist/utils/keys.js +14 -0
  37. package/dist/workflow-validation.d.ts.map +1 -1
  38. package/package.json +58 -57
@@ -4,9 +4,11 @@ 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");
11
+ const fair_arbitration_1 = require("./scoring/fair-arbitration");
10
12
  const features_1 = require("./learning/features");
11
13
  const LearningManager_1 = require("./managers/LearningManager");
12
14
  const ReliabilityManager_1 = require("./managers/ReliabilityManager");
@@ -55,6 +57,18 @@ class AssignmentMatcher {
55
57
  this.calculatePriority = options?.prioritizationFunction ?? this.calculatePriority;
56
58
  this.usingDefaultMatchScore = !options?.matchingFunction;
57
59
  this.matchScore = options?.matchingFunction ?? this.defaultMatchScore.bind(this);
60
+ this.enableGeoMatching = options?.enableGeoMatching ?? false;
61
+ this.geoDefaultMaxDistanceKm = options?.geoDefaultMaxDistanceKm;
62
+ this.geoScoreWeight = options?.geoScoreWeight ?? 0;
63
+ this.geoMatchingFunction = options?.geoMatchingFunction;
64
+ this.enableFairTiebreaker = options?.enableFairTiebreaker ?? false;
65
+ this.fairnessMode = options?.fairness;
66
+ if (this.fairnessMode)
67
+ this.enableFairTiebreaker = this.fairnessMode !== 'first-come';
68
+ this.fairnessLoadPenalty = options?.fairnessLoadPenalty ?? 0;
69
+ this.fairnessTieBand = options?.fairnessTieBand ?? 0;
70
+ this.fairnessMaxPerWindow = options?.fairnessMaxPerWindow;
71
+ this.fairnessWindowMs = options?.fairnessWindowMs ?? 3600000;
58
72
  // Workflow options
59
73
  this.enableWorkflows = options?.enableWorkflows ?? false;
60
74
  this.streamConsumerGroup = options?.streamConsumerGroup ?? 'orchestrator';
@@ -68,10 +82,15 @@ class AssignmentMatcher {
68
82
  workflowAuditEnabled: options?.workflowAuditEnabled ?? false,
69
83
  workflowSnapshotDefinitions: options?.workflowSnapshotDefinitions ?? true,
70
84
  streamConsumerName: this.streamConsumerName,
85
+ circuitBreakerPersistState: options?.circuitBreakerPersistState ?? false,
86
+ circuitBreakerShared: options?.circuitBreakerShared ?? false,
87
+ enableReliabilityMetrics: options?.enableReliabilityMetrics ?? true,
88
+ deadLetterQueueAlertThreshold: options?.deadLetterQueueAlertThreshold ?? 100,
71
89
  });
72
90
  this.telemetry = new TelemetryManager_1.TelemetryManager(options?.enableOpenTelemetry ?? false);
73
91
  // Learning layer (opt-in contextual bandit re-ranking)
74
92
  this.enableLearning = options?.enableLearning ?? false;
93
+ this.enableAutoRoutingWeights = options?.enableAutoRoutingWeights ?? false;
75
94
  this.learningFeatureExtractor = options?.learningFeatureExtractor ?? features_1.extractMatchFeatures;
76
95
  this.learning = new LearningManager_1.LearningManager(this.redisClient, this.keys, {
77
96
  learningRate: options?.learningRate,
@@ -82,6 +101,8 @@ class AssignmentMatcher {
82
101
  decisionTtlMs: options?.learningDecisionTtlMs,
83
102
  signalWeights: options?.learningSignalWeights,
84
103
  feedbackTtlMs: options?.learningFeedbackTtlMs,
104
+ trackTagStats: this.enableAutoRoutingWeights,
105
+ autoWeights: options?.autoRoutingWeights,
85
106
  });
86
107
  this.workflow = new WorkflowManager_1.WorkflowManager(this.redisClient, this.keys, this.reliability, this.telemetry, this, {
87
108
  enableWorkflows: this.enableWorkflows,
@@ -89,6 +110,11 @@ class AssignmentMatcher {
89
110
  streamConsumerName: this.streamConsumerName,
90
111
  reclaimIntervalMs: options?.workflowReclaimPollIntervalMs ?? 5000,
91
112
  reclaimMinIdleMs: options?.workflowOrphanReclaimMs ?? 60000,
113
+ retentionMs: options?.workflowInstanceRetentionMs,
114
+ retryBackoffMs: options?.workflowRetryBackoffMs,
115
+ eventBatchSize: options?.workflowEventBatchSize,
116
+ pollBlockMs: options?.workflowPollBlockMs,
117
+ maxEventsPerSecond: options?.workflowMaxEventsPerSecond,
92
118
  });
93
119
  this.readyPromise = this.initRedis();
94
120
  }
@@ -106,6 +132,8 @@ class AssignmentMatcher {
106
132
  if (!this.redisClient.isOpen) {
107
133
  await this.redisClient.connect();
108
134
  }
135
+ // Initialize reliability manager (load persisted circuit breaker state if enabled)
136
+ await this.reliability.init();
109
137
  // Initialize workflow stream consumer group if workflows are enabled
110
138
  if (this.enableWorkflows) {
111
139
  await this.workflow.init();
@@ -185,6 +213,66 @@ class AssignmentMatcher {
185
213
  return this.reliability.getAuditEvents(count);
186
214
  }
187
215
  // ============================================================================
216
+ // Reliability & Health Check Methods
217
+ // ============================================================================
218
+ /**
219
+ * Get comprehensive reliability metrics including circuit breaker state,
220
+ * Dead Letter Queue size, and Redis health status.
221
+ */
222
+ async getReliabilityMetrics() {
223
+ await this.readyPromise;
224
+ return this.reliability.getMetrics();
225
+ }
226
+ /**
227
+ * Get current circuit breaker state
228
+ */
229
+ async getCircuitBreakerState() {
230
+ await this.readyPromise;
231
+ return this.reliability.getCircuitBreakerState();
232
+ }
233
+ /**
234
+ * Check if Dead Letter Queue size exceeds alert threshold
235
+ */
236
+ async checkDeadLetterQueueAlert() {
237
+ await this.readyPromise;
238
+ return this.reliability.checkDeadLetterQueueAlert();
239
+ }
240
+ /**
241
+ * Perform a health check on Redis connection
242
+ * Returns true if Redis is healthy, false otherwise
243
+ */
244
+ async healthCheck() {
245
+ await this.readyPromise;
246
+ const details = {
247
+ timestamp: Date.now(),
248
+ };
249
+ try {
250
+ // Check if Redis client is connected
251
+ details.redisConnected = this.redisClient.isOpen;
252
+ // Try to ping Redis
253
+ const pingResult = await this.redisClient.ping();
254
+ details.redisPing = pingResult;
255
+ // Get reliability metrics
256
+ const metrics = await this.getReliabilityMetrics();
257
+ details.circuitBreakerState = metrics.circuitBreakerState;
258
+ details.deadLetterQueueSize = metrics.deadLetterQueueSize;
259
+ details.circuitBreakerAllowingRequests = metrics.circuitBreakerAllowingRequests;
260
+ // Check if circuit breaker is allowing requests
261
+ const healthy = details.redisConnected && pingResult === 'PONG' && details.circuitBreakerAllowingRequests;
262
+ return {
263
+ healthy,
264
+ details,
265
+ };
266
+ }
267
+ catch (err) {
268
+ details.error = err instanceof Error ? err.message : String(err);
269
+ return {
270
+ healthy: false,
271
+ details,
272
+ };
273
+ }
274
+ }
275
+ // ============================================================================
188
276
  // Learning (Contextual Bandit) Methods
189
277
  // ============================================================================
190
278
  /**
@@ -237,6 +325,163 @@ class AssignmentMatcher {
237
325
  await this.readyPromise;
238
326
  return this.learning.resetModel();
239
327
  }
328
+ /**
329
+ * Toggle learning shadow mode at runtime without losing model/state.
330
+ *
331
+ * `true`: learn-only, ranking unaffected.
332
+ * `false`: learning predictions can influence ranking.
333
+ */
334
+ async setLearningShadowMode(enabled) {
335
+ await this.readyPromise;
336
+ this.learning.setShadowMode(enabled);
337
+ }
338
+ /** Current runtime shadow mode state. */
339
+ async getLearningShadowMode() {
340
+ await this.readyPromise;
341
+ return this.learning.shadowMode;
342
+ }
343
+ /**
344
+ * Toggle fair-tiebreaker global best-match arbitration at runtime.
345
+ * See `MatcherOptions.enableFairTiebreaker` for what this changes.
346
+ */
347
+ setFairTiebreaker(enabled) {
348
+ this.enableFairTiebreaker = !!enabled;
349
+ }
350
+ /** Current runtime fair-tiebreaker state. */
351
+ isFairTiebreakerEnabled() {
352
+ return this.enableFairTiebreaker;
353
+ }
354
+ /**
355
+ * Switch the bulk-matching fairness policy at runtime — shorthand for
356
+ * `setFairnessConfig({ fairness: mode })`. See `MatcherOptions.fairness`
357
+ * for what each mode does.
358
+ */
359
+ setFairness(mode) {
360
+ this.setFairnessConfig({ fairness: mode });
361
+ }
362
+ /**
363
+ * Retune any subset of the bulk-matching fairness knobs at runtime without
364
+ * reconstructing the matcher. Absent fields are left unchanged; the new
365
+ * values take effect on the next `matchUsersAssignments()` call (a match
366
+ * already in flight keeps the values it started with). Merge semantics
367
+ * mirror the constructor exactly — in particular, an explicit `fairness`
368
+ * overrides `enableFairTiebreaker`. See `MatcherOptions` for each field.
369
+ */
370
+ setFairnessConfig(config) {
371
+ if ('enableFairTiebreaker' in config)
372
+ this.enableFairTiebreaker = !!config.enableFairTiebreaker;
373
+ if ('fairness' in config) {
374
+ this.fairnessMode = config.fairness;
375
+ if (this.fairnessMode)
376
+ this.enableFairTiebreaker = this.fairnessMode !== 'first-come';
377
+ }
378
+ if ('fairnessLoadPenalty' in config)
379
+ this.fairnessLoadPenalty = config.fairnessLoadPenalty ?? 0;
380
+ if ('fairnessTieBand' in config)
381
+ this.fairnessTieBand = config.fairnessTieBand ?? 0;
382
+ if ('fairnessMaxPerWindow' in config)
383
+ this.fairnessMaxPerWindow = config.fairnessMaxPerWindow;
384
+ if ('fairnessWindowMs' in config)
385
+ this.fairnessWindowMs = config.fairnessWindowMs ?? 3600000;
386
+ }
387
+ /** Current runtime fairness policy. */
388
+ getFairness() {
389
+ if (!this.enableFairTiebreaker)
390
+ return 'first-come';
391
+ return this.fairnessMode ?? 'best-match';
392
+ }
393
+ /** Snapshot of the live fairness configuration. */
394
+ getFairnessConfig() {
395
+ return {
396
+ fairness: this.getFairness(),
397
+ enableFairTiebreaker: this.enableFairTiebreaker,
398
+ fairnessLoadPenalty: this.fairnessLoadPenalty,
399
+ fairnessTieBand: this.fairnessTieBand,
400
+ fairnessMaxPerWindow: this.fairnessMaxPerWindow,
401
+ fairnessWindowMs: this.fairnessWindowMs,
402
+ };
403
+ }
404
+ // ============================================================================
405
+ // Auto Routing Weights (RL-generated tags/weights)
406
+ // ============================================================================
407
+ /**
408
+ * Per-user, per-tag reward statistics aggregated from learned outcomes.
409
+ * Requires `enableLearning` and `enableAutoRoutingWeights`.
410
+ */
411
+ async getLearnedTagStats(userId) {
412
+ await this.readyPromise;
413
+ return this.learning.getUserTagStats(userId);
414
+ }
415
+ /**
416
+ * Synthesize a routingWeights map for a user from learned tag statistics
417
+ * using a UCB1 bandit policy: high weights for rewarding tags, weight 0
418
+ * (hard veto) for consistently bad tags, and optimistic priors for
419
+ * under-explored tags. Does not persist anything.
420
+ *
421
+ * @param opts.includeUnexploredTags also assign the exploration prior to
422
+ * every known tag in the system the user has no data for yet
423
+ */
424
+ async getLearnedRoutingWeights(userId, opts) {
425
+ await this.readyPromise;
426
+ const knownTags = opts?.includeUnexploredTags ? await this.getKnownTagsForAutoWeights() : undefined;
427
+ const userJson = await this.redisClient.hGet(this.usersKey, userId);
428
+ const existingWeights = userJson ? JSON.parse(userJson).routingWeights : undefined;
429
+ return this.learning.getLearnedRoutingWeights(userId, knownTags, existingWeights);
430
+ }
431
+ /**
432
+ * Apply learned routing weights to one user (or every tracked user when
433
+ * no id is given), automating tags/weights generation from RL outcomes.
434
+ *
435
+ * Merge semantics: learned tags always take their learned value; manual
436
+ * routingWeights entries for tags the learner has no data on are
437
+ * preserved (set `opts.overrideManual` to replace the map entirely).
438
+ * The applied learned map is stored on the user as `learnedRoutingWeights`
439
+ * for observability.
440
+ *
441
+ * Returns the applied weights per user id.
442
+ */
443
+ async syncLearnedRoutingWeights(userId, opts) {
444
+ await this.readyPromise;
445
+ const targets = userId ? [userId] : await this.learning.listTrackedUsers();
446
+ const knownTags = opts?.includeUnexploredTags ? await this.getKnownTagsForAutoWeights() : undefined;
447
+ const applied = {};
448
+ for (const id of targets) {
449
+ const userJson = await this.redisClient.hGet(this.usersKey, id);
450
+ if (!userJson)
451
+ continue;
452
+ const user = JSON.parse(userJson);
453
+ // Pass the user's current routingWeights as warm per-tag priors
454
+ // so under-sampled tags start from the existing value rather than
455
+ // the flat priorWeight.
456
+ const previousLearned = user.learnedRoutingWeights ?? {};
457
+ const existingForSynthesis = user.routingWeights
458
+ ? Object.fromEntries(Object.entries(user.routingWeights).filter(([tag]) => !(tag in previousLearned)))
459
+ : undefined;
460
+ const learned = await this.learning.getLearnedRoutingWeights(id, knownTags, existingForSynthesis);
461
+ if (Object.keys(learned).length === 0)
462
+ continue;
463
+ let routingWeights;
464
+ if (opts?.overrideManual) {
465
+ routingWeights = learned;
466
+ }
467
+ else {
468
+ const manualEntries = {};
469
+ for (const [tag, weight] of Object.entries(user.routingWeights ?? {})) {
470
+ if (!(tag in previousLearned) && !(tag in learned))
471
+ manualEntries[tag] = weight;
472
+ }
473
+ routingWeights = { ...manualEntries, ...learned };
474
+ }
475
+ await this.redisClient.hSet(this.usersKey, id, JSON.stringify({ ...user, routingWeights, learnedRoutingWeights: learned }));
476
+ applied[id] = routingWeights;
477
+ }
478
+ return applied;
479
+ }
480
+ /** All known tags except the internal 'default' tag (for exploration priors) */
481
+ async getKnownTagsForAutoWeights() {
482
+ const tags = await this.redisClient.sMembers(this.allTagsKey);
483
+ return tags.filter((t) => t !== 'default');
484
+ }
240
485
  // ============================================================================
241
486
  // OpenTelemetry Tracing Hooks
242
487
  // ============================================================================
@@ -292,13 +537,21 @@ class AssignmentMatcher {
292
537
  score: priority,
293
538
  value: id,
294
539
  });
295
- if (latitude && longitude) {
540
+ if ((0, geo_1.isValidLatitude)(latitude) && (0, geo_1.isValidLongitude)(longitude)) {
296
541
  multi.geoAdd(assignmentGeoKey, {
297
542
  longitude,
298
543
  latitude,
299
544
  member: id,
300
545
  });
301
546
  }
547
+ // Index hard vetoes both ways: assignment -> users for cleanup,
548
+ // user -> assignments for exclusion via ZDIFFSTORE during matching.
549
+ if (assignment.vetoedUsers && assignment.vetoedUsers.length > 0) {
550
+ multi.sAdd(this.keys.assignmentVetoed(id), assignment.vetoedUsers);
551
+ for (const vetoedUserId of assignment.vetoedUsers) {
552
+ multi.sAdd(this.keys.userVetoed(vetoedUserId), id);
553
+ }
554
+ }
302
555
  // Also index assignment into per-tag sorted sets (by priority)
303
556
  // This enables efficient weighted matching via ZUNIONSTORE.
304
557
  const indexTags = [...tags, ...(this.enableDefaultMatching ? ['default'] : [])];
@@ -317,10 +570,11 @@ class AssignmentMatcher {
317
570
  const assignmentPriorityKey = this.keys.assignmentPriority(id);
318
571
  const assignmentTagsKey = this.keys.assignmentTags(id);
319
572
  const assignmentGeoKey = this.keys.assignmentsGeo();
320
- // Fetch tags and owner in case it's pending
321
- const [tagsCsv, owner] = await Promise.all([
573
+ // Fetch tags, owner (in case it's pending), and vetoed users for index cleanup
574
+ const [tagsCsv, owner, vetoedUsers] = await Promise.all([
322
575
  this.redisClient.hGet(assignmentTagsKey, 'tags'),
323
- this.redisClient.hGet(this.assignmentOwnerKey, id)
576
+ this.redisClient.hGet(this.assignmentOwnerKey, id),
577
+ this.redisClient.sMembers(this.keys.assignmentVetoed(id)),
324
578
  ]);
325
579
  let tags = [];
326
580
  if (tagsCsv && tagsCsv.length > 0) {
@@ -336,6 +590,10 @@ class AssignmentMatcher {
336
590
  multi.zRem(this.keys.tagAssignments(tag), id.toString());
337
591
  }
338
592
  multi.zRem(assignmentGeoKey, id.toString());
593
+ multi.del(this.keys.assignmentVetoed(id));
594
+ for (const vetoedUserId of vetoedUsers) {
595
+ multi.sRem(this.keys.userVetoed(vetoedUserId), id);
596
+ }
339
597
  // 2. Remove from Pending state
340
598
  multi.hDel(this.pendingAssignmentsKey, id);
341
599
  multi.zRem(this.pendingAssignmentsExpiryKey, id);
@@ -354,6 +612,7 @@ class AssignmentMatcher {
354
612
  .multi()
355
613
  .del(this.keys.userAssignments(userId))
356
614
  .del(this.keys.userRejected(userId))
615
+ .del(this.keys.userVetoed(userId))
357
616
  .zRem(this.keys.userActivity(), userId)
358
617
  .hDel(this.usersKey, userId);
359
618
  await multi.exec();
@@ -371,10 +630,7 @@ class AssignmentMatcher {
371
630
  * Get assignments with pagination support for efficient querying of large datasets.
372
631
  * Uses cursor-based pagination across statuses.
373
632
  *
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)
633
+ * @param options - Pagination options.
378
634
  */
379
635
  async getAssignmentsPaginated(options) {
380
636
  await this.readyPromise;
@@ -449,6 +705,29 @@ class AssignmentMatcher {
449
705
  defaultMatchScore(user, assignmentTags, assignmentPriority, _assignmentId, skillThresholds) {
450
706
  return Promise.resolve((0, match_score_1.calculateMatchScore)(user, assignmentTags, assignmentPriority, this.enableDefaultMatching, skillThresholds));
451
707
  }
708
+ async evaluateGeoMatch(user, assignment) {
709
+ if (this.geoMatchingFunction) {
710
+ return this.geoMatchingFunction({
711
+ user,
712
+ assignment,
713
+ defaultMaxDistanceKm: this.geoDefaultMaxDistanceKm,
714
+ });
715
+ }
716
+ return (0, geo_1.checkGeoMatch)(user, assignment, {
717
+ enabled: this.enableGeoMatching,
718
+ defaultMaxDistanceKm: this.geoDefaultMaxDistanceKm,
719
+ });
720
+ }
721
+ calculateGeoBoost(geoMatch) {
722
+ if (!this.enableGeoMatching || this.geoScoreWeight <= 0)
723
+ return 0;
724
+ if (typeof geoMatch.distanceKm !== 'number' || typeof geoMatch.effectiveMaxDistanceKm !== 'number')
725
+ return 0;
726
+ if (geoMatch.effectiveMaxDistanceKm <= 0)
727
+ return 0;
728
+ const ratio = 1 - geoMatch.distanceKm / geoMatch.effectiveMaxDistanceKm;
729
+ return this.geoScoreWeight * Math.max(0, ratio);
730
+ }
452
731
  async calculatePriority(...args) {
453
732
  const [assignment] = args;
454
733
  return (0, match_score_1.calculateDefaultPriority)(assignment?.createdAt);
@@ -482,11 +761,11 @@ class AssignmentMatcher {
482
761
  const assignmentPriorityKey = this.keys.assignmentPriority(id);
483
762
  // Fetch tags to update per-tag indices
484
763
  const assignmentTagsKey = this.keys.assignmentTags(id);
485
- const [existsRef, tagsCsv] = await this.redisClient
764
+ const [existsRef, tagsCsv] = (await this.redisClient
486
765
  .multi()
487
766
  .hExists(this.assignmentsRefKey, id)
488
767
  .hGet(assignmentTagsKey, 'tags')
489
- .exec();
768
+ .exec());
490
769
  const tags = (tagsCsv && tagsCsv.length > 0 ? tagsCsv.split(',') : []);
491
770
  const multi = this.redisClient.multi();
492
771
  multi.hSet(assignmentPriorityKey, 'priority', priority);
@@ -526,7 +805,23 @@ class AssignmentMatcher {
526
805
  }
527
806
  return relevantAssignments.map((assignment) => ({ id: assignment.id, priority }));
528
807
  }
529
- async getUserRelatedAssignments(user) {
808
+ /**
809
+ * Read-only candidate discovery for one user: workflow-targeted lookups,
810
+ * the weighted per-tag zset union/diff, and per-candidate scoring
811
+ * (learning-influenced or plain, matching the existing behavior exactly).
812
+ * Does NOT claim anything - see claimSelected() for that. Split out so
813
+ * matchAllUsersFair() can evaluate every user's candidates before any of
814
+ * them claim, enabling global (cross-user) score comparison.
815
+ *
816
+ * `capToBacklog` (default true, matching prior inline behavior): stop
817
+ * scoring once this user's own maxUserBacklogSize worth of candidates has
818
+ * been found. matchAllUsersFair() passes false - capping per-user during
819
+ * discovery would silently drop a user's lower-priority candidates before
820
+ * global arbitration ever runs, e.g. a user whose top picks all lose to a
821
+ * higher scorer should still be considered for their next-best options,
822
+ * not left with nothing because discovery stopped early.
823
+ */
824
+ async computeCandidatesForUser(user, capToBacklog = true) {
530
825
  const userAssignments = [];
531
826
  const routingWeights = user.routingWeights;
532
827
  const hasRoutingWeights = Boolean(routingWeights && Object.keys(routingWeights).length > 0);
@@ -537,10 +832,14 @@ class AssignmentMatcher {
537
832
  // Workflow assignments take precedence - add them first with highest priority
538
833
  userAssignments.push(...workflowAssignments);
539
834
  if (userAssignments.length >= this.maxUserBacklogSize) {
540
- return userAssignments;
835
+ return { userAssignments, selected: [], workflowTargetedCount: userAssignments.length };
541
836
  }
542
837
  }
543
838
  }
839
+ // Workflow-targeted assignments above are deterministically targeted at this
840
+ // user (not drawn from the shared tag pool below), so the claim-race filtering
841
+ // at the end of this function must never strip them out.
842
+ const workflowTargetedCount = userAssignments.length;
544
843
  // Priority 2: Build candidate assignments using per-tag zset union with user weights for scalability.
545
844
  const positiveWeights = [];
546
845
  const zeroWeightTags = [];
@@ -569,10 +868,10 @@ class AssignmentMatcher {
569
868
  // In weighted default matching, users must define at least one positive weight.
570
869
  // If they don't, nothing should be assigned and queue remains intact.
571
870
  if (hasRoutingWeights && this.usingDefaultMatchScore && positiveWeights.length === 0) {
572
- return userAssignments;
871
+ return { userAssignments, selected: [], workflowTargetedCount };
573
872
  }
574
873
  if (positiveWeights.length === 0)
575
- return userAssignments;
874
+ return { userAssignments, selected: [], workflowTargetedCount };
576
875
  // Expand wildcards
577
876
  const expandedPositive = await this.expandTagWildcards(positiveWeights);
578
877
  const expandedZero = this.usingDefaultMatchScore
@@ -580,14 +879,14 @@ class AssignmentMatcher {
580
879
  : [];
581
880
  const finalZeroTags = expandedZero.map((t) => t.tag);
582
881
  if (expandedPositive.length === 0)
583
- return userAssignments;
882
+ return { userAssignments, selected: [], workflowTargetedCount };
584
883
  const tempKey = this.keys.tempUserCandidates(user.id);
585
884
  const tempZeroKey = this.keys.tempUserExclude(user.id);
586
885
  const tempFinalKey = this.keys.tempUserFinal(user.id);
587
886
  const rejectedKey = this.keys.userRejected(user.id);
588
887
  const unionKeysWithWeights = expandedPositive.map((pw) => ({
589
888
  key: this.keys.tagAssignments(pw.tag),
590
- weight: pw.weight
889
+ weight: pw.weight,
591
890
  }));
592
891
  const multi = this.redisClient.multi();
593
892
  // Weighted union of positive tag assignment zsets
@@ -602,9 +901,10 @@ class AssignmentMatcher {
602
901
  multi.expire(tempZeroKey, 5);
603
902
  excludeKeys.push(tempZeroKey);
604
903
  }
605
- // Always exclude rejected assignments
904
+ // Always exclude rejected and vetoed assignments
606
905
  excludeKeys.push(rejectedKey);
607
- // Final = candidates - exclude (zero weights + rejected)
906
+ excludeKeys.push(this.keys.userVetoed(user.id));
907
+ // Final = candidates - exclude (zero weights + rejected + vetoed)
608
908
  multi.zDiffStore(tempFinalKey, [tempKey, ...excludeKeys]);
609
909
  // Set short TTLs to clean up
610
910
  multi.expire(tempKey, 5);
@@ -613,7 +913,7 @@ class AssignmentMatcher {
613
913
  // Pull top-N in ascending score to preserve previous behavior on ties (lex ascending)
614
914
  const top = await this.redisClient.zRangeWithScores(tempFinalKey, 0, this.relevantBatchSize - 1);
615
915
  if (top.length === 0)
616
- return userAssignments;
916
+ return { userAssignments, selected: [], workflowTargetedCount };
617
917
  // Fetch per-assignment stored (base) priority and tags in a single pipeline (fewer round trips)
618
918
  const batched = this.redisClient.multi();
619
919
  for (const entry of top) {
@@ -623,7 +923,7 @@ class AssignmentMatcher {
623
923
  // Also fetch assignment JSON to access allowedCidrs for network matching
624
924
  batched.hGet(this.assignmentsRefKey, assignmentId);
625
925
  }
626
- const flat = await batched.exec();
926
+ const flat = (await batched.exec());
627
927
  const details = [];
628
928
  for (let i = 0; i < top.length; i++) {
629
929
  const assignmentId = top[i].value;
@@ -657,9 +957,13 @@ class AssignmentMatcher {
657
957
  for (const d of details) {
658
958
  if (!(0, cidr_1.checkCidrMatch)(user.ip, d.allowedCidrs))
659
959
  continue;
960
+ const geoMatch = await this.evaluateGeoMatch(user, d.raw ?? { id: d.id, tags: [] });
961
+ if (!geoMatch.eligible)
962
+ continue;
660
963
  const [score, combinedPriority] = await this.matchScore(user, d.tags, d.basePriority, d.id, d.skillThresholds);
661
964
  if (!score || !combinedPriority)
662
965
  continue;
966
+ const geoAdjustedPriority = combinedPriority + this.calculateGeoBoost(geoMatch);
663
967
  const context = {
664
968
  ...(d.raw ?? {}),
665
969
  id: d.id,
@@ -673,47 +977,80 @@ class AssignmentMatcher {
673
977
  ? Math.random() * this.learning.boostFactor
674
978
  : 0;
675
979
  const effectivePriority = this.learning.shadowMode
676
- ? combinedPriority
677
- : combinedPriority + this.learning.boostFactor * predicted + exploration;
980
+ ? geoAdjustedPriority
981
+ : geoAdjustedPriority + this.learning.boostFactor * predicted + exploration;
678
982
  eligible.push({ detail: d, combinedPriority, features, predicted, effectivePriority });
679
983
  }
680
984
  eligible.sort((a, b) => b.effectivePriority - a.effectivePriority);
681
985
  for (const c of eligible) {
682
- if (userAssignments.length >= this.maxUserBacklogSize)
986
+ if (capToBacklog && userAssignments.length >= this.maxUserBacklogSize)
683
987
  break;
684
988
  userAssignments.push({ id: c.detail.id, priority: c.effectivePriority });
685
989
  selected.push({ id: c.detail.id, tags: c.detail.tags });
686
- await this.learning.recordDecision(user.id, c.detail.id, c.features, c.predicted);
990
+ await this.learning.recordDecision(user.id, c.detail.id, c.features, c.predicted, c.detail.tags ? c.detail.tags.split(',').filter(Boolean) : undefined);
687
991
  }
688
992
  }
689
993
  else {
690
994
  for (const d of details) {
691
- if (userAssignments.length >= this.maxUserBacklogSize)
995
+ if (capToBacklog && userAssignments.length >= this.maxUserBacklogSize)
692
996
  break;
693
997
  // Check CIDR restrictions: if assignment has allowedCidrs, user must have matching IP
694
998
  if (!(0, cidr_1.checkCidrMatch)(user.ip, d.allowedCidrs)) {
695
999
  continue; // Skip this assignment - user IP doesn't match allowed CIDRs
696
1000
  }
1001
+ const geoMatch = await this.evaluateGeoMatch(user, d.raw ?? { id: d.id, tags: [] });
1002
+ if (!geoMatch.eligible) {
1003
+ continue;
1004
+ }
697
1005
  // Use custom matchScore (supports weights and thresholds) for a final check and tie-break
698
1006
  const [score, combinedPriority] = await this.matchScore(user, d.tags, d.basePriority, d.id, d.skillThresholds);
699
1007
  if (score && combinedPriority) {
700
- userAssignments.push({ id: d.id, priority: combinedPriority });
1008
+ userAssignments.push({ id: d.id, priority: combinedPriority + this.calculateGeoBoost(geoMatch) });
701
1009
  selected.push({ id: d.id, tags: d.tags });
702
1010
  }
703
1011
  }
704
1012
  }
705
- // Batch-remove all selected assignments from indexes and references to reduce round trips
706
- if (selected.length > 0) {
707
- // Fetch JSONs first to store in pending
708
- const jsonPromises = selected.map((s) => this.redisClient.hGet(this.assignmentsRefKey, s.id));
709
- const jsons = await Promise.all(jsonPromises);
710
- const now = Date.now();
1013
+ return { userAssignments, selected, workflowTargetedCount };
1014
+ }
1015
+ /**
1016
+ * Atomically claims a set of tag-scored candidate assignments for one
1017
+ * user and returns which ones it actually won. The candidate read that
1018
+ * produces `selected` (zDiffStore/zRangeWithScores in
1019
+ * computeCandidatesForUser) is a snapshot taken before this point, and
1020
+ * candidate computation runs concurrently across users -
1021
+ * matchUsersAssignments() Promise.all's the bulk path, and a per-user
1022
+ * matchUsersAssignments(userId) call can race a bulk pass too. Without a
1023
+ * single atomic gate, two concurrent callers can both still see the same
1024
+ * assignment as available and both hand it to their user. HDEL on
1025
+ * assignmentsRefKey is atomic and idempotent (returns 1 only for
1026
+ * whichever caller actually deletes the field), so it's used here as
1027
+ * that gate: only assignments this call actually wins are kept - anything
1028
+ * already claimed by a concurrent caller since the snapshot read is
1029
+ * dropped instead of being double-assigned.
1030
+ */
1031
+ async claimSelected(user, selected) {
1032
+ const claimedIds = new Set();
1033
+ if (selected.length === 0)
1034
+ return claimedIds;
1035
+ const jsonPromises = selected.map((s) => this.redisClient.hGet(this.assignmentsRefKey, s.id));
1036
+ const jsons = await Promise.all(jsonPromises);
1037
+ const now = Date.now();
1038
+ const claimMulti = this.redisClient.multi();
1039
+ for (const s of selected) {
1040
+ claimMulti.hDel(this.assignmentsRefKey, s.id);
1041
+ }
1042
+ const claimResults = (await claimMulti.exec());
1043
+ for (let i = 0; i < selected.length; i++) {
1044
+ if (Number(claimResults[i]) > 0)
1045
+ claimedIds.add(selected[i].id);
1046
+ }
1047
+ if (claimedIds.size > 0) {
711
1048
  const rm = this.redisClient.multi();
712
1049
  for (let i = 0; i < selected.length; i++) {
713
1050
  const s = selected[i];
1051
+ if (!claimedIds.has(s.id))
1052
+ continue; // lost the race - already claimed elsewhere
714
1053
  const json = jsons[i];
715
- // Remove from reference and per-assignment hashes
716
- rm.hDel(this.assignmentsRefKey, s.id);
717
1054
  rm.del(this.keys.assignmentPriority(s.id));
718
1055
  rm.del(this.keys.assignmentTags(s.id));
719
1056
  // Remove from global zset
@@ -732,7 +1069,207 @@ class AssignmentMatcher {
732
1069
  }
733
1070
  await rm.exec();
734
1071
  }
735
- return userAssignments;
1072
+ return claimedIds;
1073
+ }
1074
+ async getUserRelatedAssignments(user) {
1075
+ const { userAssignments, selected, workflowTargetedCount } = await this.computeCandidatesForUser(user);
1076
+ const claimedIds = await this.claimSelected(user, selected);
1077
+ const workflowTargeted = userAssignments.slice(0, workflowTargetedCount);
1078
+ const tagScored = userAssignments.slice(workflowTargetedCount).filter((ua) => claimedIds.has(ua.id));
1079
+ return [...workflowTargeted, ...tagScored];
1080
+ }
1081
+ /**
1082
+ * Opt-in alternative to the default parallel bulk path (see
1083
+ * MatcherOptions.enableFairTiebreaker): evaluates every user's eligible
1084
+ * candidates first (read-only, nobody claims yet), flattens them into one
1085
+ * global list sorted by score descending, then claims greedily in that
1086
+ * order. This guarantees the best-fit eligible candidate wins each
1087
+ * contested assignment, rather than whichever user's independent claim
1088
+ * happened to reach Redis first.
1089
+ *
1090
+ * Known limitation: when combined with enableLearning, computeCandidatesForUser
1091
+ * still records a bandit decision for every scored candidate at evaluation
1092
+ * time, including ones that lose the global tiebreak here - the learning
1093
+ * layer's per-user candidate ordering isn't itself part of the fairness
1094
+ * comparison in this mode. Fine for the common case (fairness without
1095
+ * learning), but a consumer combining both should be aware.
1096
+ */
1097
+ async matchAllUsersFair() {
1098
+ let users = [];
1099
+ let cursor = '0';
1100
+ do {
1101
+ const { cursor: nextCursor, entries } = await this.redisClient.hScan(this.usersKey, cursor, { COUNT: 500 });
1102
+ users.push(...entries.map((t) => JSON.parse(t.value)));
1103
+ cursor = nextCursor;
1104
+ } while (cursor !== '0');
1105
+ // Rolling-window grant cap: an explicit finite fairnessMaxPerWindow
1106
+ // always applies; the 'balanced' / 'spread-work' presets additionally
1107
+ // default a team-relative guardrail when no explicit cap is given
1108
+ // (fairnessMaxPerWindow: Infinity opts out of that too).
1109
+ const explicitCap = this.fairnessMaxPerWindow;
1110
+ const usesAutoCap = explicitCap === undefined && (this.fairnessMode === 'balanced' || this.fairnessMode === 'spread-work');
1111
+ const windowActive = usesAutoCap || (explicitCap !== undefined && Number.isFinite(explicitCap));
1112
+ const windowStart = Date.now() - this.fairnessWindowMs;
1113
+ // Phase 1: per-user backlog + window usage, one pipelined batch - the
1114
+ // rolling cap costs one extra command per user here, not a round trip.
1115
+ const usage = await Promise.all(users.map(async (user) => {
1116
+ const [backlog, grantsInWindow] = await Promise.all([
1117
+ this.redisClient.sCard(this.keys.userAssignments(user.id)),
1118
+ windowActive
1119
+ ? this.redisClient.zCount(this.keys.userWindowGrants(user.id), windowStart, '+inf')
1120
+ : Promise.resolve(0),
1121
+ ]);
1122
+ return { user, backlog, grantsInWindow };
1123
+ }));
1124
+ // The preset guardrail is scale-free on purpose: no fixed number fits
1125
+ // every deployment, but "nobody receives at more than double the
1126
+ // team's average rate" is safe anywhere. The maxUserBacklogSize floor
1127
+ // keeps a cold-started (empty-window) team from throttling itself.
1128
+ let windowCap = Infinity;
1129
+ if (explicitCap !== undefined && Number.isFinite(explicitCap)) {
1130
+ windowCap = explicitCap;
1131
+ }
1132
+ else if (usesAutoCap) {
1133
+ const totalGrants = usage.reduce((sum, u) => sum + u.grantsInWindow, 0);
1134
+ windowCap = Math.max(this.maxUserBacklogSize, Math.ceil((2 * totalGrants) / Math.max(1, usage.length)));
1135
+ }
1136
+ // Phase 2: read-only candidate discovery for users with headroom.
1137
+ const perUser = await Promise.all(usage.map(async ({ user, backlog, grantsInWindow }) => {
1138
+ const windowRemaining = windowActive ? Math.max(0, windowCap - grantsInWindow) : Infinity;
1139
+ if (backlog >= this.maxUserBacklogSize) {
1140
+ return {
1141
+ user,
1142
+ backlog,
1143
+ windowRemaining,
1144
+ candidates: { userAssignments: [], selected: [], workflowTargetedCount: 0 },
1145
+ };
1146
+ }
1147
+ if (windowRemaining <= 0) {
1148
+ // No tag-scored grant can land this pass, so skip candidate
1149
+ // scoring - but workflow-targeted assignments are direct
1150
+ // handoffs that bypass the window cap and must still flow.
1151
+ const workflowAssignments = this.enableWorkflows
1152
+ ? await this.getWorkflowTargetedAssignments(user.id)
1153
+ : [];
1154
+ return {
1155
+ user,
1156
+ backlog,
1157
+ windowRemaining,
1158
+ candidates: {
1159
+ userAssignments: workflowAssignments,
1160
+ selected: [],
1161
+ workflowTargetedCount: workflowAssignments.length,
1162
+ },
1163
+ };
1164
+ }
1165
+ // capToBacklog=false: this user's full candidate set is needed for
1166
+ // global arbitration below, not just as many as their own cap allows.
1167
+ const candidates = await this.computeCandidatesForUser(user, false);
1168
+ return { user, backlog, windowRemaining, candidates };
1169
+ }));
1170
+ // Workflow-targeted assignments are deterministically targeted at one
1171
+ // user each - not contested across users - so claim them immediately,
1172
+ // exactly like the non-fair path does.
1173
+ await Promise.all(perUser.map(({ user, candidates }) => {
1174
+ const workflowOnly = candidates.userAssignments.slice(0, candidates.workflowTargetedCount);
1175
+ if (workflowOnly.length === 0)
1176
+ return Promise.resolve(0);
1177
+ return this.redisClient.sAdd(this.keys.userAssignments(user.id), workflowOnly.map((a) => `assignment:${a.id}`));
1178
+ }));
1179
+ // Flatten every user's tag-scored candidates into one global list of
1180
+ // {user, assignment, score} pairs for cross-user arbitration.
1181
+ const globalPairs = [];
1182
+ for (const { user, candidates } of perUser) {
1183
+ const priorityById = new Map(candidates.userAssignments.map((ua) => [ua.id, ua.priority]));
1184
+ for (const s of candidates.selected) {
1185
+ globalPairs.push({
1186
+ user,
1187
+ userId: user.id,
1188
+ id: s.id,
1189
+ tags: s.tags,
1190
+ priority: priorityById.get(s.id) ?? 0,
1191
+ });
1192
+ }
1193
+ }
1194
+ const backlogUsed = new Map(perUser.map(({ user, backlog, candidates }) => [user.id, backlog + candidates.workflowTargetedCount]));
1195
+ // Fold the rolling-window cap into a per-user award ceiling: a user
1196
+ // may take at most min(backlog headroom, window headroom) more
1197
+ // tag-scored assignments this pass. Workflow-targeted grants above
1198
+ // are exempt from the window but still occupy backlog.
1199
+ let maxByUser;
1200
+ if (windowActive) {
1201
+ maxByUser = new Map(perUser.map(({ user, backlog, windowRemaining, candidates }) => [
1202
+ user.id,
1203
+ backlog +
1204
+ candidates.workflowTargetedCount +
1205
+ Math.max(0, Math.min(this.maxUserBacklogSize - backlog - candidates.workflowTargetedCount, windowRemaining)),
1206
+ ]));
1207
+ }
1208
+ // Arbitrate winners in memory (see arbitrateFair for the ordering:
1209
+ // best score wins, optionally load-penalized / tie-banded), then claim
1210
+ // in one batched claimSelected() call per user (all users in parallel)
1211
+ // rather than one claim round trip per pair - arbitration already
1212
+ // decides who wins every contested assignment within this process, so
1213
+ // per-pair claims would only re-discover that same answer at O(pairs)
1214
+ // sequential Redis round trips. The atomic HDEL gate inside
1215
+ // claimSelected() still protects against claims from OTHER processes:
1216
+ // a failed claim means the assignment is gone entirely (a concurrent
1217
+ // process won it), so the tentative winner's backlog slot is released
1218
+ // and the remaining pairs are re-arbitrated in another round. In the
1219
+ // common single-process case the first round claims everything and no
1220
+ // further rounds run.
1221
+ // A fairness preset ('balanced' / 'spread-work') derives its load
1222
+ // penalty from this pass's candidate scores; explicit expert knobs
1223
+ // always win over the preset.
1224
+ const knobs = (0, fair_arbitration_1.resolveFairnessKnobs)(this.fairnessMode, globalPairs.map((p) => p.priority), { loadPenalty: this.fairnessLoadPenalty, tieBand: this.fairnessTieBand });
1225
+ const settled = new Set();
1226
+ let remaining = globalPairs;
1227
+ while (remaining.length > 0) {
1228
+ const { winners, deferred } = (0, fair_arbitration_1.arbitrateFair)(remaining, backlogUsed, settled, {
1229
+ maxUserBacklogSize: this.maxUserBacklogSize,
1230
+ maxByUser,
1231
+ loadPenalty: knobs.loadPenalty,
1232
+ tieBand: knobs.tieBand,
1233
+ });
1234
+ const tentative = new Map();
1235
+ for (const w of winners) {
1236
+ const bucket = tentative.get(w.userId) ?? { user: w.user, pairs: [] };
1237
+ bucket.pairs.push({ id: w.id, tags: w.tags });
1238
+ tentative.set(w.userId, bucket);
1239
+ }
1240
+ if (tentative.size === 0)
1241
+ break;
1242
+ let anyLost = false;
1243
+ await Promise.all(Array.from(tentative.values()).map(async ({ user, pairs }) => {
1244
+ const claimedIds = await this.claimSelected(user, pairs);
1245
+ const won = pairs.filter((p) => claimedIds.has(p.id));
1246
+ if (won.length < pairs.length) {
1247
+ anyLost = true;
1248
+ backlogUsed.set(user.id, (backlogUsed.get(user.id) ?? 0) - (pairs.length - won.length));
1249
+ }
1250
+ // Won or lost, the assignment is no longer available to anyone.
1251
+ for (const p of pairs)
1252
+ settled.add(p.id);
1253
+ if (won.length > 0) {
1254
+ const grantMulti = this.redisClient.multi();
1255
+ grantMulti.sAdd(this.keys.userAssignments(user.id), won.map((p) => `assignment:${p.id}`));
1256
+ if (windowActive) {
1257
+ // Rolling-window bookkeeping: trim entries that
1258
+ // have aged out, record these grants, and let the
1259
+ // whole set expire if the user goes idle.
1260
+ const grantsKey = this.keys.userWindowGrants(user.id);
1261
+ const now = Date.now();
1262
+ grantMulti.zRemRangeByScore(grantsKey, '-inf', now - this.fairnessWindowMs);
1263
+ grantMulti.zAdd(grantsKey, won.map((p) => ({ score: now, value: `${now}:${p.id}` })));
1264
+ grantMulti.pExpire(grantsKey, this.fairnessWindowMs);
1265
+ }
1266
+ await grantMulti.exec();
1267
+ }
1268
+ }));
1269
+ if (!anyLost)
1270
+ break;
1271
+ remaining = deferred.filter((pair) => !settled.has(pair.id));
1272
+ }
736
1273
  }
737
1274
  async matchUsersAssignments(userId) {
738
1275
  await this.readyPromise;
@@ -754,12 +1291,15 @@ class AssignmentMatcher {
754
1291
  }
755
1292
  return;
756
1293
  }
1294
+ if (this.enableFairTiebreaker) {
1295
+ return this.matchAllUsersFair();
1296
+ }
757
1297
  // Otherwise, process all users in parallel as before.
758
1298
  let users = [];
759
1299
  let cursor = '0';
760
1300
  // Fetch all users in a single loop
761
1301
  do {
762
- const { cursor: nextCursor, entries } = await this.redisClient.hScan(this.usersKey, cursor);
1302
+ const { cursor: nextCursor, entries } = await this.redisClient.hScan(this.usersKey, cursor, { COUNT: 500 });
763
1303
  users.push(...entries.map((t) => JSON.parse(t.value)));
764
1304
  cursor = nextCursor;
765
1305
  } while (cursor !== '0');
@@ -1022,6 +1562,46 @@ class AssignmentMatcher {
1022
1562
  await this.readyPromise;
1023
1563
  return this.workflow.stopOrchestrator();
1024
1564
  }
1565
+ /**
1566
+ * Register a machine task handler by name. Machine steps with a matching
1567
+ * machineTask.handler run through this handler; unmatched handlers fall
1568
+ * back to the executeMachineTask host hook.
1569
+ */
1570
+ registerMachineHandler(name, handler) {
1571
+ this.workflow.registerMachineHandler(name, handler);
1572
+ }
1573
+ /**
1574
+ * Process due delayed event retries. Called automatically by the
1575
+ * orchestrator; exposed for deployments that run their own schedulers.
1576
+ */
1577
+ async drainScheduledRetries() {
1578
+ await this.readyPromise;
1579
+ return this.workflow.drainScheduledRetries();
1580
+ }
1581
+ /**
1582
+ * Backfill workflow indexes (active-instance index) from records created
1583
+ * before these indexes existed. Safe to run multiple times.
1584
+ */
1585
+ async backfillWorkflowIndexes() {
1586
+ await this.readyPromise;
1587
+ return this.workflow.backfillWorkflowIndexes();
1588
+ }
1589
+ /**
1590
+ * Remove terminal workflow instances last updated more than olderThanMs
1591
+ * ago, including registry, per-user, and index entries.
1592
+ */
1593
+ async pruneWorkflowInstances(olderThanMs) {
1594
+ await this.readyPromise;
1595
+ return this.workflow.pruneWorkflowInstances(olderThanMs);
1596
+ }
1597
+ /**
1598
+ * Operational metrics for the workflow engine: active instances, retry
1599
+ * queue depth, DLQ size, and event stream statistics.
1600
+ */
1601
+ async getWorkflowMetrics() {
1602
+ await this.readyPromise;
1603
+ return this.workflow.getWorkflowMetrics();
1604
+ }
1025
1605
  async processExpiredMatches() {
1026
1606
  await this.readyPromise;
1027
1607
  const now = Date.now();
@@ -1171,6 +1751,9 @@ class AssignmentMatcher {
1171
1751
  for (const [assignmentId, json] of Object.entries(queuedAssignments)) {
1172
1752
  try {
1173
1753
  const assignment = JSON.parse(json);
1754
+ // Hard veto applies even to deterministic workflow targeting
1755
+ if (assignment.vetoedUsers?.includes(userId))
1756
+ continue;
1174
1757
  if (assignment._targetUserId === userId && assignment._workflowInstanceId) {
1175
1758
  // This is a workflow assignment targeted at this user
1176
1759
  targeted.push({