assignment-user-matcher 1.2.5 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/LICENCE +21 -53
  2. package/README.md +153 -1
  3. package/dist/index.d.ts +3 -2
  4. package/dist/index.d.ts.map +1 -1
  5. package/dist/index.js +4 -1
  6. package/dist/managers/DecisionTraceManager.d.ts +34 -0
  7. package/dist/managers/DecisionTraceManager.d.ts.map +1 -0
  8. package/dist/managers/DecisionTraceManager.js +74 -0
  9. package/dist/managers/WorkflowManager.d.ts +57 -1
  10. package/dist/managers/WorkflowManager.d.ts.map +1 -1
  11. package/dist/managers/WorkflowManager.js +296 -2
  12. package/dist/matcher.class.d.ts +186 -3
  13. package/dist/matcher.class.d.ts.map +1 -1
  14. package/dist/matcher.class.js +891 -40
  15. package/dist/scoring/match-score.d.ts +17 -1
  16. package/dist/scoring/match-score.d.ts.map +1 -1
  17. package/dist/scoring/match-score.js +81 -1
  18. package/dist/tracing/decision-trace.d.ts +48 -0
  19. package/dist/tracing/decision-trace.d.ts.map +1 -0
  20. package/dist/tracing/decision-trace.js +152 -0
  21. package/dist/types/matcher.d.ts +327 -1
  22. package/dist/types/matcher.d.ts.map +1 -1
  23. package/dist/utils/keys.d.ts +5 -0
  24. package/dist/utils/keys.d.ts.map +1 -1
  25. package/dist/utils/keys.js +17 -0
  26. package/dist/workflow-builder.d.ts +6 -0
  27. package/dist/workflow-builder.d.ts.map +1 -1
  28. package/dist/workflow-builder.js +13 -0
  29. package/dist/workflow-validation.d.ts.map +1 -1
  30. package/dist/workflow-validation.js +20 -0
  31. package/package.json +2 -2
  32. package/dist/queries/index.d.ts +0 -5
  33. package/dist/queries/index.d.ts.map +0 -1
  34. package/dist/queries/index.js +0 -20
  35. package/dist/scoring/index.d.ts +0 -5
  36. package/dist/scoring/index.d.ts.map +0 -1
  37. package/dist/scoring/index.js +0 -20
  38. package/dist/utils/index.d.ts +0 -6
  39. package/dist/utils/index.d.ts.map +0 -1
  40. package/dist/utils/index.js +0 -21
@@ -9,7 +9,9 @@ const keys_1 = require("./utils/keys");
9
9
  const pagination_1 = require("./queries/pagination");
10
10
  const match_score_1 = require("./scoring/match-score");
11
11
  const fair_arbitration_1 = require("./scoring/fair-arbitration");
12
+ const decision_trace_1 = require("./tracing/decision-trace");
12
13
  const features_1 = require("./learning/features");
14
+ const DecisionTraceManager_1 = require("./managers/DecisionTraceManager");
13
15
  const LearningManager_1 = require("./managers/LearningManager");
14
16
  const ReliabilityManager_1 = require("./managers/ReliabilityManager");
15
17
  const TelemetryManager_1 = require("./managers/TelemetryManager");
@@ -104,6 +106,13 @@ class AssignmentMatcher {
104
106
  trackTagStats: this.enableAutoRoutingWeights,
105
107
  autoWeights: options?.autoRoutingWeights,
106
108
  });
109
+ // Decision traces (opt-in explainability/audit records per routing decision)
110
+ this.enableDecisionTraces = options?.enableDecisionTraces ?? false;
111
+ this.decisionTraceMaxCandidates = options?.decisionTraceMaxCandidates ?? 25;
112
+ this.decisionTraces = new DecisionTraceManager_1.DecisionTraceManager(this.redisClient, this.keys, {
113
+ maxEntries: options?.decisionTraceMaxEntries ?? 1000,
114
+ onDecision: options?.onMatchDecision,
115
+ });
107
116
  this.workflow = new WorkflowManager_1.WorkflowManager(this.redisClient, this.keys, this.reliability, this.telemetry, this, {
108
117
  enableWorkflows: this.enableWorkflows,
109
118
  streamConsumerGroup: this.streamConsumerGroup,
@@ -115,9 +124,25 @@ class AssignmentMatcher {
115
124
  eventBatchSize: options?.workflowEventBatchSize,
116
125
  pollBlockMs: options?.workflowPollBlockMs,
117
126
  maxEventsPerSecond: options?.workflowMaxEventsPerSecond,
127
+ onWorkflowEvent: options?.onWorkflowEvent,
118
128
  });
129
+ this.onAssignmentLifecycle = options?.onAssignmentLifecycle;
119
130
  this.readyPromise = this.initRedis();
120
131
  }
132
+ /**
133
+ * Fire the optional assignment lifecycle hook. Errors are swallowed so a
134
+ * slow/failing observer can never break a lifecycle transition.
135
+ */
136
+ emitAssignmentLifecycle(event) {
137
+ if (!this.onAssignmentLifecycle)
138
+ return;
139
+ try {
140
+ this.onAssignmentLifecycle(event);
141
+ }
142
+ catch (err) {
143
+ // Best-effort hook: do not propagate.
144
+ }
145
+ }
121
146
  /** Keys for the three assignment stores (used by pagination queries) */
122
147
  get assignmentStoreKeys() {
123
148
  return {
@@ -402,6 +427,353 @@ class AssignmentMatcher {
402
427
  };
403
428
  }
404
429
  // ============================================================================
430
+ // Decision Traces & Explainability
431
+ // ============================================================================
432
+ /** Whether trace capture should run this pass (persistence flag or real-time hook). */
433
+ get tracingActive() {
434
+ return this.enableDecisionTraces || this.decisionTraces.hasDecisionHook;
435
+ }
436
+ /**
437
+ * Toggle decision-trace persistence at runtime without reconstructing the
438
+ * matcher. Takes effect on the next matching pass (a pass already in
439
+ * flight keeps the value it started with).
440
+ */
441
+ setDecisionTraces(enabled) {
442
+ this.enableDecisionTraces = !!enabled;
443
+ }
444
+ /** Current runtime decision-trace persistence state. */
445
+ isDecisionTracesEnabled() {
446
+ return this.enableDecisionTraces;
447
+ }
448
+ /**
449
+ * Query recorded decision traces, newest first. Only decisions made while
450
+ * `enableDecisionTraces` was active are stored — traces are captured as
451
+ * decisions happen, never reconstructed after the fact.
452
+ */
453
+ async getDecisionTraces(query) {
454
+ await this.readyPromise;
455
+ return this.decisionTraces.getTraces(query);
456
+ }
457
+ /** Delete all recorded decision traces. */
458
+ async clearDecisionTraces() {
459
+ await this.readyPromise;
460
+ return this.decisionTraces.clear();
461
+ }
462
+ /**
463
+ * Explain, from live state, which users could receive an assignment and
464
+ * why each one is or is not eligible: vetoes, prior rejections, skill
465
+ * thresholds, CIDR and geo constraints, backlog, the full score breakdown,
466
+ * and learning influence. Works for assignments in any lifecycle state;
467
+ * for matched assignments the current owner is flagged `chosen` (accepted
468
+ * assignments report `ownerId: null` because ownership metadata is
469
+ * released on acceptance — decision traces retain the full history).
470
+ *
471
+ * This is an on-demand recomputation against current state. For the
472
+ * auditable record of a decision as it actually happened, use
473
+ * `getDecisionTraces()`.
474
+ */
475
+ async explainMatch(assignmentId, opts) {
476
+ await this.readyPromise;
477
+ const evaluatedAt = Date.now();
478
+ let found = await (0, pagination_1.getAssignmentById)(this.redisClient, this.assignmentStoreKeys, assignmentId);
479
+ let status;
480
+ if (found) {
481
+ status = (found._status ?? 'queued');
482
+ }
483
+ else {
484
+ // getAssignmentById only covers queued/pending/accepted
485
+ const completedJson = await this.redisClient.hGet(this.completedAssignmentsKey, assignmentId);
486
+ if (!completedJson) {
487
+ return { assignmentId, status: 'not_found', ownerId: null, evaluatedAt, candidates: [] };
488
+ }
489
+ found = JSON.parse(completedJson);
490
+ status = 'completed';
491
+ }
492
+ const assignment = found;
493
+ let ownerId = null;
494
+ if (status === 'pending') {
495
+ ownerId = (await this.redisClient.hGet(this.assignmentOwnerKey, assignmentId)) ?? null;
496
+ }
497
+ else if (status === 'completed') {
498
+ ownerId = assignment._completedBy ?? assignment._failedBy ?? null;
499
+ }
500
+ // Queued assignments may have had their priority retuned since creation
501
+ let basePriority = Number(assignment.priority) || 0;
502
+ if (status === 'queued') {
503
+ const stored = await this.redisClient.hGet(this.keys.assignmentPriority(assignmentId), 'priority');
504
+ if (stored !== null && stored !== undefined)
505
+ basePriority = Number(stored) || 0;
506
+ }
507
+ // Mirror the tags CSV the scoring path sees (the stored tags hash appends 'default')
508
+ const tagsCsv = [...assignment.tags, ...(this.enableDefaultMatching ? ['default'] : [])].join(',');
509
+ let userList;
510
+ if (opts?.userIds && opts.userIds.length > 0) {
511
+ const jsons = await this.redisClient.hmGet(this.usersKey, opts.userIds);
512
+ userList = jsons.filter((json) => Boolean(json)).map((json) => JSON.parse(json));
513
+ }
514
+ else {
515
+ const all = await this.redisClient.hGetAll(this.usersKey);
516
+ userList = Object.values(all).map((json) => JSON.parse(json));
517
+ }
518
+ const modelWeights = this.enableLearning ? await this.learning.getModel() : undefined;
519
+ const candidates = await Promise.all(userList.map((user) => this.explainCandidate(user, assignment, assignmentId, tagsCsv, basePriority, ownerId, modelWeights)));
520
+ (0, decision_trace_1.sortCandidates)(candidates);
521
+ return { assignmentId, status, ownerId, evaluatedAt, candidates };
522
+ }
523
+ /** One user's full eligibility/score evaluation for explainMatch(). */
524
+ async explainCandidate(user, assignment, assignmentId, tagsCsv, basePriority, ownerId, modelWeights) {
525
+ const [isRejected, backlog, isPaused] = await Promise.all([
526
+ this.redisClient.sIsMember(this.keys.userRejected(user.id), assignmentId),
527
+ this.redisClient.sCard(this.keys.userAssignments(user.id)),
528
+ this.redisClient.sIsMember(this.keys.pausedUsers(), user.id),
529
+ ]);
530
+ return this.evaluateCandidateForAssignment(user, assignment, tagsCsv, basePriority, modelWeights, {
531
+ assignmentId,
532
+ ownerId,
533
+ isRejected: Boolean(isRejected),
534
+ backlog,
535
+ isPaused: Boolean(isPaused),
536
+ });
537
+ }
538
+ /**
539
+ * Shared eligibility/scoring evaluation used by explainMatch() and
540
+ * previewMatch(). Read-only: never claims, writes, or records decisions.
541
+ */
542
+ async evaluateCandidateForAssignment(user, assignment, tagsCsv, basePriority, modelWeights, opts) {
543
+ const reasons = [];
544
+ let eligible = true;
545
+ const assignmentId = opts.assignmentId ?? '';
546
+ const ownerId = opts.ownerId ?? null;
547
+ const isRejected = opts.isRejected ?? false;
548
+ const isPaused = opts.isPaused ?? false;
549
+ const backlog = opts.backlog ?? 0;
550
+ if (assignment.vetoedUsers?.includes(user.id)) {
551
+ reasons.push({ kind: 'assignmentVeto' });
552
+ eligible = false;
553
+ }
554
+ if (isRejected) {
555
+ reasons.push({ kind: 'rejectedPreviously' });
556
+ eligible = false;
557
+ }
558
+ if (isPaused) {
559
+ reasons.push({ kind: 'paused' });
560
+ eligible = false;
561
+ }
562
+ const backlogLimit = this.backlogLimitFor(user);
563
+ if (backlog >= backlogLimit) {
564
+ reasons.push({ kind: 'backlogFull', backlog, limit: backlogLimit });
565
+ eligible = false;
566
+ }
567
+ const routingWeights = user.routingWeights;
568
+ const hasRoutingWeights = Boolean(routingWeights && Object.keys(routingWeights).length > 0);
569
+ if (hasRoutingWeights &&
570
+ this.usingDefaultMatchScore &&
571
+ !Object.values(routingWeights).some((w) => typeof w === 'number' && w > 0)) {
572
+ reasons.push({ kind: 'noPositiveWeights' });
573
+ eligible = false;
574
+ }
575
+ if (!(0, cidr_1.checkCidrMatch)(user.ip, assignment.allowedCidrs)) {
576
+ reasons.push({ kind: 'cidrMismatch', ip: user.ip });
577
+ eligible = false;
578
+ }
579
+ const geoMatch = await this.evaluateGeoMatch(user, assignment);
580
+ let geoBoost = 0;
581
+ if (!geoMatch.eligible) {
582
+ reasons.push({
583
+ kind: 'geoDistance',
584
+ distanceKm: geoMatch.distanceKm,
585
+ maxDistanceKm: geoMatch.effectiveMaxDistanceKm,
586
+ withinRange: false,
587
+ });
588
+ eligible = false;
589
+ }
590
+ else {
591
+ geoBoost = this.calculateGeoBoost(geoMatch);
592
+ if (typeof geoMatch.distanceKm === 'number') {
593
+ reasons.push({
594
+ kind: 'geoDistance',
595
+ distanceKm: geoMatch.distanceKm,
596
+ maxDistanceKm: geoMatch.effectiveMaxDistanceKm,
597
+ withinRange: true,
598
+ });
599
+ }
600
+ if (geoBoost > 0)
601
+ reasons.push({ kind: 'geoBoost', boost: geoBoost });
602
+ }
603
+ let score;
604
+ let combinedPriority;
605
+ if (this.usingDefaultMatchScore) {
606
+ const explained = (0, match_score_1.explainMatchScore)(user, tagsCsv, basePriority, this.enableDefaultMatching, assignment.skillThresholds);
607
+ score = explained.score;
608
+ combinedPriority = explained.combinedPriority;
609
+ reasons.push(...explained.reasons);
610
+ }
611
+ else {
612
+ [score, combinedPriority] = await this.matchScore(user, tagsCsv, basePriority, assignmentId || undefined, assignment.skillThresholds);
613
+ reasons.push({ kind: 'customScore', score });
614
+ }
615
+ if (!score)
616
+ eligible = false;
617
+ let learningBoost = 0;
618
+ if (this.enableLearning && modelWeights) {
619
+ const context = { ...assignment, id: assignmentId, tags: assignment.tags };
620
+ const features = this.learningFeatureExtractor(user, context);
621
+ const predicted = this.learning.predict(features, modelWeights);
622
+ const shadowMode = this.learning.shadowMode;
623
+ learningBoost = shadowMode ? 0 : this.learning.boostFactor * predicted;
624
+ reasons.push({ kind: 'learningBoost', predicted, boost: learningBoost, shadowMode });
625
+ }
626
+ return {
627
+ userId: user.id,
628
+ eligible,
629
+ chosen: ownerId === user.id,
630
+ score,
631
+ effectivePriority: combinedPriority + geoBoost + learningBoost,
632
+ reasons,
633
+ };
634
+ }
635
+ /**
636
+ * Preview which users would be candidates for a hypothetical assignment
637
+ * without creating it or claiming anything. Uses the same scoring, hard
638
+ * rules, and learning re-ranking as real matching, so the ranked result
639
+ * matches what `explainMatch()` would report if the assignment were added.
640
+ */
641
+ async previewMatch(input, opts) {
642
+ await this.readyPromise;
643
+ const evaluatedAt = Date.now();
644
+ const assignment = {
645
+ id: '',
646
+ tags: input.tags,
647
+ priority: input.priority ?? 0,
648
+ skillThresholds: input.skillThresholds,
649
+ allowedCidrs: input.allowedCidrs,
650
+ vetoedUsers: input.vetoedUsers,
651
+ latitude: input.latitude,
652
+ longitude: input.longitude,
653
+ maxDistanceKm: input.maxDistanceKm,
654
+ requireGeo: input.requireGeo,
655
+ };
656
+ const tagsCsv = [...input.tags, ...(this.enableDefaultMatching ? ['default'] : [])].join(',');
657
+ const basePriority = Number(assignment.priority) || 0;
658
+ let userList;
659
+ if (opts?.userIds && opts.userIds.length > 0) {
660
+ const jsons = await this.redisClient.hmGet(this.usersKey, opts.userIds);
661
+ userList = jsons
662
+ .filter((json) => Boolean(json))
663
+ .map((json) => JSON.parse(json));
664
+ }
665
+ else {
666
+ const all = await this.redisClient.hGetAll(this.usersKey);
667
+ userList = Object.values(all).map((json) => JSON.parse(json));
668
+ }
669
+ const paused = new Set(await this.redisClient.sMembers(this.keys.pausedUsers()));
670
+ const modelWeights = this.enableLearning ? await this.learning.getModel() : undefined;
671
+ const candidates = await Promise.all(userList.map(async (user) => {
672
+ const backlog = await this.redisClient.sCard(this.keys.userAssignments(user.id));
673
+ return this.evaluateCandidateForAssignment(user, assignment, tagsCsv, basePriority, modelWeights, {
674
+ ownerId: null,
675
+ isRejected: false,
676
+ backlog,
677
+ isPaused: paused.has(user.id),
678
+ });
679
+ }));
680
+ (0, decision_trace_1.sortCandidates)(candidates);
681
+ return { tags: input.tags, priority: basePriority, evaluatedAt, candidates };
682
+ }
683
+ /** Build and record this pass's decision traces; failures never break matching. */
684
+ async recordPassTraces(collector, winners, workflowGrants, mode, users) {
685
+ if (winners.size === 0 && workflowGrants.length === 0)
686
+ return;
687
+ try {
688
+ // A workflow-targeted assignment is also tag-indexed, so the
689
+ // tag-scored path can claim it in the same pass. One decision,
690
+ // one trace: the deterministic targeting is the authoritative
691
+ // story, so the 'workflow' record wins.
692
+ for (const grant of workflowGrants)
693
+ winners.delete(grant.assignmentId);
694
+ const matchedAt = Date.now();
695
+ const contexts = await this.getTraceUserContexts(users);
696
+ const traces = [
697
+ ...(0, decision_trace_1.buildDecisionTraces)({
698
+ collector,
699
+ winners,
700
+ mode,
701
+ users: contexts,
702
+ maxCandidates: this.decisionTraceMaxCandidates,
703
+ matchedAt,
704
+ }),
705
+ ...(0, decision_trace_1.buildWorkflowTraces)(workflowGrants, matchedAt),
706
+ ];
707
+ await this.decisionTraces.record(traces, this.enableDecisionTraces);
708
+ }
709
+ catch (err) {
710
+ console.error('Failed to record decision traces:', err);
711
+ }
712
+ }
713
+ /** Exclusion sets used to enrich traces with prefiltered (vetoed/rejected/paused) users. */
714
+ async getTraceUserContexts(users) {
715
+ const paused = new Set(await this.redisClient.sMembers(this.keys.pausedUsers()));
716
+ return Promise.all(users.map(async (user) => {
717
+ const [rejected, vetoed] = await Promise.all([
718
+ this.redisClient.sMembers(this.keys.userRejected(user.id)),
719
+ this.redisClient.sMembers(this.keys.userVetoed(user.id)),
720
+ ]);
721
+ return {
722
+ user,
723
+ rejected: new Set(rejected),
724
+ vetoed: new Set(vetoed),
725
+ paused: paused.has(user.id),
726
+ };
727
+ }));
728
+ }
729
+ /** One sMembers per pass: the user list minus currently paused users. */
730
+ async filterPausedUsers(users) {
731
+ const paused = await this.redisClient.sMembers(this.keys.pausedUsers());
732
+ if (paused.length === 0)
733
+ return users;
734
+ const pausedSet = new Set(paused);
735
+ return users.filter((user) => !pausedSet.has(user.id));
736
+ }
737
+ /**
738
+ * Workflow-targeted assignments are re-granted idempotently on every
739
+ * matching pass until actioned; only first-time grants deserve a decision
740
+ * trace. Reads membership before the sAdd that follows.
741
+ */
742
+ async filterNewWorkflowGrants(user, workflowTargeted) {
743
+ if (workflowTargeted.length === 0)
744
+ return [];
745
+ const memberships = await this.redisClient.smIsMember(this.keys.userAssignments(user.id), workflowTargeted.map((w) => `assignment:${w.id}`));
746
+ return workflowTargeted
747
+ .filter((_, i) => !memberships[i])
748
+ .map((w) => ({ assignmentId: w.id, userId: user.id, priority: w.priority }));
749
+ }
750
+ /** Reasons for one scored candidate evaluation (trace capture only). */
751
+ traceScoreReasons(user, detail, score, geoMatch, geoBoost, learning) {
752
+ const reasons = this.usingDefaultMatchScore
753
+ ? (0, match_score_1.explainMatchScore)(user, detail.tags, detail.basePriority, this.enableDefaultMatching, detail.skillThresholds)
754
+ .reasons
755
+ : [{ kind: 'customScore', score }];
756
+ if (typeof geoMatch.distanceKm === 'number') {
757
+ reasons.push({
758
+ kind: 'geoDistance',
759
+ distanceKm: geoMatch.distanceKm,
760
+ maxDistanceKm: geoMatch.effectiveMaxDistanceKm,
761
+ withinRange: true,
762
+ });
763
+ }
764
+ if (geoBoost > 0)
765
+ reasons.push({ kind: 'geoBoost', boost: geoBoost });
766
+ if (learning) {
767
+ reasons.push({
768
+ kind: 'learningBoost',
769
+ predicted: learning.predicted,
770
+ boost: learning.boost,
771
+ shadowMode: learning.shadowMode,
772
+ });
773
+ }
774
+ return reasons;
775
+ }
776
+ // ============================================================================
405
777
  // Auto Routing Weights (RL-generated tags/weights)
406
778
  // ============================================================================
407
779
  /**
@@ -530,6 +902,9 @@ class AssignmentMatcher {
530
902
  const multi = this.redisClient
531
903
  .multi()
532
904
  .hSet(this.assignmentsRefKey, id, JSON.stringify(assignment))
905
+ // NX: a requeue (reject/expiry re-adds via this method) keeps the
906
+ // original first-enqueue wait clock.
907
+ .zAdd(this.keys.assignmentsQueuedAt(), { score: Date.now(), value: id }, { NX: true })
533
908
  .hSet(assignmentPriorityKey, 'priority', priority)
534
909
  // Ensure 'default' tag is persisted consistently when enabled
535
910
  .hSet(assignmentTagsKey, 'tags', tags.join(',') + (this.enableDefaultMatching ? ',default' : ''))
@@ -586,6 +961,7 @@ class AssignmentMatcher {
586
961
  multi.del(assignmentPriorityKey);
587
962
  multi.del(assignmentTagsKey);
588
963
  multi.zRem(this.assignmentsKey, id.toString());
964
+ multi.zRem(this.keys.assignmentsQueuedAt(), id.toString());
589
965
  for (const tag of tags) {
590
966
  multi.zRem(this.keys.tagAssignments(tag), id.toString());
591
967
  }
@@ -614,10 +990,98 @@ class AssignmentMatcher {
614
990
  .del(this.keys.userRejected(userId))
615
991
  .del(this.keys.userVetoed(userId))
616
992
  .zRem(this.keys.userActivity(), userId)
993
+ .sRem(this.keys.pausedUsers(), userId)
617
994
  .hDel(this.usersKey, userId);
618
995
  await multi.exec();
619
996
  return userId;
620
997
  }
998
+ /**
999
+ * Get one stored user as last written by addUser (including the injected
1000
+ * 'default' tag when enableDefaultMatching is on), or null.
1001
+ */
1002
+ async getUser(userId) {
1003
+ await this.readyPromise;
1004
+ const json = await this.redisClient.hGet(this.usersKey, userId);
1005
+ return json ? JSON.parse(json) : null;
1006
+ }
1007
+ /**
1008
+ * Whether a user is registered in the pool. Used by the workflow engine
1009
+ * (via the WorkflowHost interface) to validate an initiator before
1010
+ * starting a run that targets 'initiator'.
1011
+ */
1012
+ async userExists(userId) {
1013
+ await this.readyPromise;
1014
+ return Boolean(await this.redisClient.hExists(this.usersKey, userId));
1015
+ }
1016
+ /** All stored users. The pool is small by design; for load metadata see getQueueStats(). */
1017
+ async getUsers() {
1018
+ await this.readyPromise;
1019
+ const users = [];
1020
+ let cursor = '0';
1021
+ do {
1022
+ const { cursor: nextCursor, entries } = await this.redisClient.hScan(this.usersKey, cursor, { COUNT: 500 });
1023
+ users.push(...entries.map((t) => JSON.parse(t.value)));
1024
+ cursor = nextCursor;
1025
+ } while (cursor !== '0');
1026
+ return users;
1027
+ }
1028
+ // ============================================================================
1029
+ // Worker Availability (pause/resume)
1030
+ // ============================================================================
1031
+ /**
1032
+ * Pause a user: they stop receiving new assignments in every matching path
1033
+ * until resumed, but keep their pending backlog and can still accept,
1034
+ * complete, reject, or fail work they already hold. Paused users are also
1035
+ * exempt from idle auto-removal (pausing is deliberate absence, not
1036
+ * idleness). Idempotent.
1037
+ *
1038
+ * @returns false when the user is not in the pool (nothing is recorded)
1039
+ */
1040
+ async pauseUser(userId) {
1041
+ await this.readyPromise;
1042
+ const exists = await this.redisClient.hExists(this.usersKey, userId);
1043
+ if (!exists)
1044
+ return false;
1045
+ await this.redisClient.sAdd(this.keys.pausedUsers(), userId);
1046
+ return true;
1047
+ }
1048
+ /**
1049
+ * Resume a paused user so matching considers them again on the next pass.
1050
+ * Also records activity (resets the idle clock).
1051
+ *
1052
+ * @returns false when the user was not paused
1053
+ */
1054
+ async resumeUser(userId) {
1055
+ await this.readyPromise;
1056
+ const wasPaused = await this.redisClient.sRem(this.keys.pausedUsers(), userId);
1057
+ if (wasPaused)
1058
+ await this.touchUser(userId);
1059
+ return wasPaused > 0;
1060
+ }
1061
+ /**
1062
+ * Requeue every pending (matched but not yet accepted) assignment the user
1063
+ * holds so other users can pick them up — the operator's "this person is
1064
+ * gone, redistribute their work" move, typically paired with `pauseUser`
1065
+ * (which alone deliberately preserves the backlog). Accepted assignments
1066
+ * (work in progress) are never touched. Requeued assignments keep their
1067
+ * original wait clock, and a still-paused user won't win them back until
1068
+ * resumed. Returns the released assignment ids ([] when nothing was held).
1069
+ */
1070
+ async releaseUserAssignments(userId) {
1071
+ await this.readyPromise;
1072
+ return this.releaseUserPendingAssignments(userId);
1073
+ }
1074
+ /** Whether a user is currently paused. */
1075
+ async isUserPaused(userId) {
1076
+ await this.readyPromise;
1077
+ return Boolean(await this.redisClient.sIsMember(this.keys.pausedUsers(), userId));
1078
+ }
1079
+ /** IDs of all currently paused users. */
1080
+ async getPausedUsers() {
1081
+ await this.readyPromise;
1082
+ const members = await this.redisClient.sMembers(this.keys.pausedUsers());
1083
+ return members.sort();
1084
+ }
621
1085
  /**
622
1086
  * Get all assignments (queued, pending, and accepted).
623
1087
  * For large datasets, prefer using getAssignmentsPaginated() instead.
@@ -658,6 +1122,42 @@ class AssignmentMatcher {
658
1122
  await this.readyPromise;
659
1123
  return (0, pagination_1.getAssignmentsByIdsBatch)(this.redisClient, this.assignmentStoreKeys, ids);
660
1124
  }
1125
+ /**
1126
+ * Live operational snapshot for dashboards: queued/pending counts, the
1127
+ * age of the longest-waiting unaccepted assignment, and every user's
1128
+ * backlog depth, effective cap, and paused state. The wait clock starts
1129
+ * at first enqueue and survives reject/expiry requeues; it stops on
1130
+ * accept or removal.
1131
+ */
1132
+ async getQueueStats() {
1133
+ await this.readyPromise;
1134
+ const [counts, oldestEntries, pausedMembers] = await Promise.all([
1135
+ (0, pagination_1.getAssignmentCountsFromStores)(this.redisClient, this.assignmentStoreKeys),
1136
+ this.redisClient.zRangeWithScores(this.keys.assignmentsQueuedAt(), 0, 0),
1137
+ this.redisClient.sMembers(this.keys.pausedUsers()),
1138
+ ]);
1139
+ const paused = new Set(pausedMembers);
1140
+ const users = [];
1141
+ let cursor = '0';
1142
+ do {
1143
+ const { cursor: nextCursor, entries } = await this.redisClient.hScan(this.usersKey, cursor, { COUNT: 500 });
1144
+ users.push(...entries.map((t) => JSON.parse(t.value)));
1145
+ cursor = nextCursor;
1146
+ } while (cursor !== '0');
1147
+ const perUser = await Promise.all(users.map(async (user) => ({
1148
+ userId: user.id,
1149
+ backlog: await this.redisClient.sCard(this.keys.userAssignments(user.id)),
1150
+ maxBacklogSize: this.backlogLimitFor(user),
1151
+ paused: paused.has(user.id),
1152
+ })));
1153
+ perUser.sort((a, b) => a.userId.localeCompare(b.userId));
1154
+ return {
1155
+ queued: counts.queued,
1156
+ pending: counts.pending,
1157
+ oldestWaitingMs: oldestEntries.length > 0 ? Date.now() - Number(oldestEntries[0].score) : null,
1158
+ perUser,
1159
+ };
1160
+ }
661
1161
  /**
662
1162
  * Get all pending assignments with owner and pending duration metadata.
663
1163
  */
@@ -761,22 +1261,37 @@ class AssignmentMatcher {
761
1261
  const assignmentPriorityKey = this.keys.assignmentPriority(id);
762
1262
  // Fetch tags to update per-tag indices
763
1263
  const assignmentTagsKey = this.keys.assignmentTags(id);
764
- const [existsRef, tagsCsv] = (await this.redisClient
1264
+ const [refJson, tagsCsv] = (await this.redisClient
765
1265
  .multi()
766
- .hExists(this.assignmentsRefKey, id)
1266
+ .hGet(this.assignmentsRefKey, id)
767
1267
  .hGet(assignmentTagsKey, 'tags')
768
1268
  .exec());
769
1269
  const tags = (tagsCsv && tagsCsv.length > 0 ? tagsCsv.split(',') : []);
770
1270
  const multi = this.redisClient.multi();
771
1271
  multi.hSet(assignmentPriorityKey, 'priority', priority);
772
- if (existsRef) {
773
- // Update global zset score and per-tag zset scores only if assignment still exists
1272
+ if (refJson) {
1273
+ // Update global zset score and per-tag zset scores only if assignment still exists,
1274
+ // plus the stored record itself so reads see the new priority.
1275
+ multi.hSet(this.assignmentsRefKey, id, JSON.stringify({ ...JSON.parse(refJson), priority }));
774
1276
  multi.zAdd(this.assignmentsKey, { score: Number(priority), value: id });
775
1277
  for (const tag of tags) {
776
1278
  multi.zAdd(this.keys.tagAssignments(tag), { score: Number(priority), value: id });
777
1279
  }
778
1280
  }
779
1281
  await multi.exec();
1282
+ if (refJson) {
1283
+ // The snapshot read above races the atomic claim gate: if a claim
1284
+ // HDELed the record between our read and write, the writes above
1285
+ // resurrected a ghost queued entry. Detect and undo.
1286
+ const owner = await this.redisClient.hGet(this.assignmentOwnerKey, id);
1287
+ if (owner) {
1288
+ const cleanup = this.redisClient.multi().hDel(this.assignmentsRefKey, id).zRem(this.assignmentsKey, id);
1289
+ for (const tag of tags) {
1290
+ cleanup.zRem(this.keys.tagAssignments(tag), id);
1291
+ }
1292
+ await cleanup.exec();
1293
+ }
1294
+ }
780
1295
  return { id, priority };
781
1296
  }
782
1297
  async setAssignmentPriorityByTags(tags, priority) {
@@ -821,7 +1336,17 @@ class AssignmentMatcher {
821
1336
  * higher scorer should still be considered for their next-best options,
822
1337
  * not left with nothing because discovery stopped early.
823
1338
  */
824
- async computeCandidatesForUser(user, capToBacklog = true) {
1339
+ /**
1340
+ * Effective backlog cap for one user: `user.maxBacklogSize` when it is a
1341
+ * valid non-negative number, else the matcher-wide `maxUserBacklogSize`.
1342
+ * The fairness window auto-cap derivation (team-level) deliberately keeps
1343
+ * using the global value.
1344
+ */
1345
+ backlogLimitFor(user) {
1346
+ const own = user.maxBacklogSize;
1347
+ return typeof own === 'number' && Number.isFinite(own) && own >= 0 ? own : this.maxUserBacklogSize;
1348
+ }
1349
+ async computeCandidatesForUser(user, capToBacklog = true, collector) {
825
1350
  const userAssignments = [];
826
1351
  const routingWeights = user.routingWeights;
827
1352
  const hasRoutingWeights = Boolean(routingWeights && Object.keys(routingWeights).length > 0);
@@ -831,7 +1356,7 @@ class AssignmentMatcher {
831
1356
  if (workflowAssignments.length > 0) {
832
1357
  // Workflow assignments take precedence - add them first with highest priority
833
1358
  userAssignments.push(...workflowAssignments);
834
- if (userAssignments.length >= this.maxUserBacklogSize) {
1359
+ if (userAssignments.length >= this.backlogLimitFor(user)) {
835
1360
  return { userAssignments, selected: [], workflowTargetedCount: userAssignments.length };
836
1361
  }
837
1362
  }
@@ -955,15 +1480,47 @@ class AssignmentMatcher {
955
1480
  const modelWeights = await this.learning.getModel();
956
1481
  const eligible = [];
957
1482
  for (const d of details) {
958
- if (!(0, cidr_1.checkCidrMatch)(user.ip, d.allowedCidrs))
1483
+ if (!(0, cidr_1.checkCidrMatch)(user.ip, d.allowedCidrs)) {
1484
+ collector?.record(d.id, d.tags, {
1485
+ userId: user.id,
1486
+ eligible: false,
1487
+ score: 0,
1488
+ effectivePriority: 0,
1489
+ reasons: [{ kind: 'cidrMismatch', ip: user.ip }],
1490
+ });
959
1491
  continue;
1492
+ }
960
1493
  const geoMatch = await this.evaluateGeoMatch(user, d.raw ?? { id: d.id, tags: [] });
961
- if (!geoMatch.eligible)
1494
+ if (!geoMatch.eligible) {
1495
+ collector?.record(d.id, d.tags, {
1496
+ userId: user.id,
1497
+ eligible: false,
1498
+ score: 0,
1499
+ effectivePriority: 0,
1500
+ reasons: [
1501
+ {
1502
+ kind: 'geoDistance',
1503
+ distanceKm: geoMatch.distanceKm,
1504
+ maxDistanceKm: geoMatch.effectiveMaxDistanceKm,
1505
+ withinRange: false,
1506
+ },
1507
+ ],
1508
+ });
962
1509
  continue;
1510
+ }
963
1511
  const [score, combinedPriority] = await this.matchScore(user, d.tags, d.basePriority, d.id, d.skillThresholds);
964
- if (!score || !combinedPriority)
1512
+ if (!score || !combinedPriority) {
1513
+ collector?.record(d.id, d.tags, {
1514
+ userId: user.id,
1515
+ eligible: false,
1516
+ score: 0,
1517
+ effectivePriority: Number(d.basePriority) || 0,
1518
+ reasons: this.traceScoreReasons(user, d, score, geoMatch, 0),
1519
+ });
965
1520
  continue;
966
- const geoAdjustedPriority = combinedPriority + this.calculateGeoBoost(geoMatch);
1521
+ }
1522
+ const traceGeoBoost = this.calculateGeoBoost(geoMatch);
1523
+ const geoAdjustedPriority = combinedPriority + traceGeoBoost;
967
1524
  const context = {
968
1525
  ...(d.raw ?? {}),
969
1526
  id: d.id,
@@ -980,10 +1537,21 @@ class AssignmentMatcher {
980
1537
  ? geoAdjustedPriority
981
1538
  : geoAdjustedPriority + this.learning.boostFactor * predicted + exploration;
982
1539
  eligible.push({ detail: d, combinedPriority, features, predicted, effectivePriority });
1540
+ collector?.record(d.id, d.tags, {
1541
+ userId: user.id,
1542
+ eligible: true,
1543
+ score,
1544
+ effectivePriority,
1545
+ reasons: this.traceScoreReasons(user, d, score, geoMatch, traceGeoBoost, {
1546
+ predicted,
1547
+ boost: effectivePriority - geoAdjustedPriority,
1548
+ shadowMode: this.learning.shadowMode,
1549
+ }),
1550
+ });
983
1551
  }
984
1552
  eligible.sort((a, b) => b.effectivePriority - a.effectivePriority);
985
1553
  for (const c of eligible) {
986
- if (capToBacklog && userAssignments.length >= this.maxUserBacklogSize)
1554
+ if (capToBacklog && userAssignments.length >= this.backlogLimitFor(user))
987
1555
  break;
988
1556
  userAssignments.push({ id: c.detail.id, priority: c.effectivePriority });
989
1557
  selected.push({ id: c.detail.id, tags: c.detail.tags });
@@ -992,21 +1560,59 @@ class AssignmentMatcher {
992
1560
  }
993
1561
  else {
994
1562
  for (const d of details) {
995
- if (capToBacklog && userAssignments.length >= this.maxUserBacklogSize)
1563
+ if (capToBacklog && userAssignments.length >= this.backlogLimitFor(user))
996
1564
  break;
997
1565
  // Check CIDR restrictions: if assignment has allowedCidrs, user must have matching IP
998
1566
  if (!(0, cidr_1.checkCidrMatch)(user.ip, d.allowedCidrs)) {
1567
+ collector?.record(d.id, d.tags, {
1568
+ userId: user.id,
1569
+ eligible: false,
1570
+ score: 0,
1571
+ effectivePriority: 0,
1572
+ reasons: [{ kind: 'cidrMismatch', ip: user.ip }],
1573
+ });
999
1574
  continue; // Skip this assignment - user IP doesn't match allowed CIDRs
1000
1575
  }
1001
1576
  const geoMatch = await this.evaluateGeoMatch(user, d.raw ?? { id: d.id, tags: [] });
1002
1577
  if (!geoMatch.eligible) {
1578
+ collector?.record(d.id, d.tags, {
1579
+ userId: user.id,
1580
+ eligible: false,
1581
+ score: 0,
1582
+ effectivePriority: 0,
1583
+ reasons: [
1584
+ {
1585
+ kind: 'geoDistance',
1586
+ distanceKm: geoMatch.distanceKm,
1587
+ maxDistanceKm: geoMatch.effectiveMaxDistanceKm,
1588
+ withinRange: false,
1589
+ },
1590
+ ],
1591
+ });
1003
1592
  continue;
1004
1593
  }
1005
1594
  // Use custom matchScore (supports weights and thresholds) for a final check and tie-break
1006
1595
  const [score, combinedPriority] = await this.matchScore(user, d.tags, d.basePriority, d.id, d.skillThresholds);
1007
1596
  if (score && combinedPriority) {
1008
- userAssignments.push({ id: d.id, priority: combinedPriority + this.calculateGeoBoost(geoMatch) });
1597
+ const geoBoost = this.calculateGeoBoost(geoMatch);
1598
+ userAssignments.push({ id: d.id, priority: combinedPriority + geoBoost });
1009
1599
  selected.push({ id: d.id, tags: d.tags });
1600
+ collector?.record(d.id, d.tags, {
1601
+ userId: user.id,
1602
+ eligible: true,
1603
+ score,
1604
+ effectivePriority: combinedPriority + geoBoost,
1605
+ reasons: this.traceScoreReasons(user, d, score, geoMatch, geoBoost),
1606
+ });
1607
+ }
1608
+ else {
1609
+ collector?.record(d.id, d.tags, {
1610
+ userId: user.id,
1611
+ eligible: false,
1612
+ score: 0,
1613
+ effectivePriority: Number(d.basePriority) || 0,
1614
+ reasons: this.traceScoreReasons(user, d, score, geoMatch, 0),
1615
+ });
1010
1616
  }
1011
1617
  }
1012
1618
  }
@@ -1068,15 +1674,26 @@ class AssignmentMatcher {
1068
1674
  }
1069
1675
  }
1070
1676
  await rm.exec();
1677
+ for (const s of selected) {
1678
+ if (!claimedIds.has(s.id))
1679
+ continue;
1680
+ this.emitAssignmentLifecycle({
1681
+ kind: 'pending',
1682
+ taskId: s.id,
1683
+ workerId: user.id,
1684
+ matchedAt: now,
1685
+ expiresAt: now + this.matchExpirationMs,
1686
+ });
1687
+ }
1071
1688
  }
1072
1689
  return claimedIds;
1073
1690
  }
1074
- async getUserRelatedAssignments(user) {
1075
- const { userAssignments, selected, workflowTargetedCount } = await this.computeCandidatesForUser(user);
1691
+ async getUserRelatedAssignments(user, collector) {
1692
+ const { userAssignments, selected, workflowTargetedCount } = await this.computeCandidatesForUser(user, true, collector);
1076
1693
  const claimedIds = await this.claimSelected(user, selected);
1077
1694
  const workflowTargeted = userAssignments.slice(0, workflowTargetedCount);
1078
1695
  const tagScored = userAssignments.slice(workflowTargetedCount).filter((ua) => claimedIds.has(ua.id));
1079
- return [...workflowTargeted, ...tagScored];
1696
+ return { assignments: [...workflowTargeted, ...tagScored], claimedIds, workflowTargeted };
1080
1697
  }
1081
1698
  /**
1082
1699
  * Opt-in alternative to the default parallel bulk path (see
@@ -1102,6 +1719,12 @@ class AssignmentMatcher {
1102
1719
  users.push(...entries.map((t) => JSON.parse(t.value)));
1103
1720
  cursor = nextCursor;
1104
1721
  } while (cursor !== '0');
1722
+ // Paused users sit out the pass entirely but stay in `users` so traces
1723
+ // can show them struck out.
1724
+ const activeUsers = await this.filterPausedUsers(users);
1725
+ const collector = this.tracingActive ? new decision_trace_1.TraceCollector() : undefined;
1726
+ const traceWinners = new Map();
1727
+ const workflowGrants = [];
1105
1728
  // Rolling-window grant cap: an explicit finite fairnessMaxPerWindow
1106
1729
  // always applies; the 'balanced' / 'spread-work' presets additionally
1107
1730
  // default a team-relative guardrail when no explicit cap is given
@@ -1112,7 +1735,7 @@ class AssignmentMatcher {
1112
1735
  const windowStart = Date.now() - this.fairnessWindowMs;
1113
1736
  // Phase 1: per-user backlog + window usage, one pipelined batch - the
1114
1737
  // rolling cap costs one extra command per user here, not a round trip.
1115
- const usage = await Promise.all(users.map(async (user) => {
1738
+ const usage = await Promise.all(activeUsers.map(async (user) => {
1116
1739
  const [backlog, grantsInWindow] = await Promise.all([
1117
1740
  this.redisClient.sCard(this.keys.userAssignments(user.id)),
1118
1741
  windowActive
@@ -1136,7 +1759,7 @@ class AssignmentMatcher {
1136
1759
  // Phase 2: read-only candidate discovery for users with headroom.
1137
1760
  const perUser = await Promise.all(usage.map(async ({ user, backlog, grantsInWindow }) => {
1138
1761
  const windowRemaining = windowActive ? Math.max(0, windowCap - grantsInWindow) : Infinity;
1139
- if (backlog >= this.maxUserBacklogSize) {
1762
+ if (backlog >= this.backlogLimitFor(user)) {
1140
1763
  return {
1141
1764
  user,
1142
1765
  backlog,
@@ -1164,17 +1787,21 @@ class AssignmentMatcher {
1164
1787
  }
1165
1788
  // capToBacklog=false: this user's full candidate set is needed for
1166
1789
  // global arbitration below, not just as many as their own cap allows.
1167
- const candidates = await this.computeCandidatesForUser(user, false);
1790
+ const candidates = await this.computeCandidatesForUser(user, false, collector);
1168
1791
  return { user, backlog, windowRemaining, candidates };
1169
1792
  }));
1170
1793
  // Workflow-targeted assignments are deterministically targeted at one
1171
1794
  // user each - not contested across users - so claim them immediately,
1172
1795
  // exactly like the non-fair path does.
1173
- await Promise.all(perUser.map(({ user, candidates }) => {
1796
+ await Promise.all(perUser.map(async ({ user, candidates }) => {
1174
1797
  const workflowOnly = candidates.userAssignments.slice(0, candidates.workflowTargetedCount);
1175
1798
  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}`));
1799
+ return;
1800
+ if (collector) {
1801
+ // Membership must be read before the sAdd below
1802
+ workflowGrants.push(...(await this.filterNewWorkflowGrants(user, workflowOnly)));
1803
+ }
1804
+ await this.redisClient.sAdd(this.keys.userAssignments(user.id), workflowOnly.map((a) => `assignment:${a.id}`));
1178
1805
  }));
1179
1806
  // Flatten every user's tag-scored candidates into one global list of
1180
1807
  // {user, assignment, score} pairs for cross-user arbitration.
@@ -1196,15 +1823,15 @@ class AssignmentMatcher {
1196
1823
  // may take at most min(backlog headroom, window headroom) more
1197
1824
  // tag-scored assignments this pass. Workflow-targeted grants above
1198
1825
  // 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
- }
1826
+ // Always built (not only when the window is active) so per-user
1827
+ // backlog caps (user.maxBacklogSize) reach arbitration too;
1828
+ // windowRemaining is Infinity when the window is inactive.
1829
+ const maxByUser = new Map(perUser.map(({ user, backlog, windowRemaining, candidates }) => [
1830
+ user.id,
1831
+ backlog +
1832
+ candidates.workflowTargetedCount +
1833
+ Math.max(0, Math.min(this.backlogLimitFor(user) - backlog - candidates.workflowTargetedCount, windowRemaining)),
1834
+ ]));
1208
1835
  // Arbitrate winners in memory (see arbitrateFair for the ordering:
1209
1836
  // best score wins, optionally load-penalized / tie-banded), then claim
1210
1837
  // in one batched claimSelected() call per user (all users in parallel)
@@ -1243,6 +1870,10 @@ class AssignmentMatcher {
1243
1870
  await Promise.all(Array.from(tentative.values()).map(async ({ user, pairs }) => {
1244
1871
  const claimedIds = await this.claimSelected(user, pairs);
1245
1872
  const won = pairs.filter((p) => claimedIds.has(p.id));
1873
+ if (collector) {
1874
+ for (const p of won)
1875
+ traceWinners.set(p.id, user.id);
1876
+ }
1246
1877
  if (won.length < pairs.length) {
1247
1878
  anyLost = true;
1248
1879
  backlogUsed.set(user.id, (backlogUsed.get(user.id) ?? 0) - (pairs.length - won.length));
@@ -1270,6 +1901,9 @@ class AssignmentMatcher {
1270
1901
  break;
1271
1902
  remaining = deferred.filter((pair) => !settled.has(pair.id));
1272
1903
  }
1904
+ if (collector) {
1905
+ await this.recordPassTraces(collector, traceWinners, workflowGrants, this.getFairness(), users);
1906
+ }
1273
1907
  }
1274
1908
  async matchUsersAssignments(userId) {
1275
1909
  await this.readyPromise;
@@ -1278,17 +1912,28 @@ class AssignmentMatcher {
1278
1912
  const userJson = await this.redisClient.hGet(this.usersKey, userId);
1279
1913
  if (!userJson)
1280
1914
  return;
1915
+ if (await this.redisClient.sIsMember(this.keys.pausedUsers(), userId))
1916
+ return;
1281
1917
  const user = JSON.parse(userJson);
1282
1918
  const userMatchesCount = await this.redisClient.sCard(this.keys.userAssignments(user.id));
1283
- if (userMatchesCount >= this.maxUserBacklogSize)
1919
+ if (userMatchesCount >= this.backlogLimitFor(user))
1284
1920
  return;
1285
- const relevantAssignments = await this.getUserRelatedAssignments(user);
1286
- const relevantAssignmentKeys = relevantAssignments
1921
+ const collector = this.tracingActive ? new decision_trace_1.TraceCollector() : undefined;
1922
+ const { assignments, claimedIds, workflowTargeted } = await this.getUserRelatedAssignments(user, collector);
1923
+ // Membership must be read before the sAdd below
1924
+ const newWorkflowGrants = collector ? await this.filterNewWorkflowGrants(user, workflowTargeted) : [];
1925
+ const relevantAssignmentKeys = assignments
1287
1926
  .sort((a, b) => b.priority - a.priority)
1288
1927
  .map((a) => `assignment:${a.id}`);
1289
1928
  if (relevantAssignmentKeys.length > 0) {
1290
1929
  await this.redisClient.sAdd(this.keys.userAssignments(user.id), relevantAssignmentKeys);
1291
1930
  }
1931
+ if (collector) {
1932
+ const winners = new Map();
1933
+ for (const id of claimedIds)
1934
+ winners.set(id, user.id);
1935
+ await this.recordPassTraces(collector, winners, newWorkflowGrants, 'direct', [user]);
1936
+ }
1292
1937
  return;
1293
1938
  }
1294
1939
  if (this.enableFairTiebreaker) {
@@ -1303,26 +1948,156 @@ class AssignmentMatcher {
1303
1948
  users.push(...entries.map((t) => JSON.parse(t.value)));
1304
1949
  cursor = nextCursor;
1305
1950
  } while (cursor !== '0');
1951
+ // Paused users sit out the pass entirely but stay in `users` so traces
1952
+ // can show them struck out.
1953
+ const activeUsers = await this.filterPausedUsers(users);
1306
1954
  // Process users in parallel
1307
- await Promise.all(users.map(async (user) => {
1955
+ const collector = this.tracingActive ? new decision_trace_1.TraceCollector() : undefined;
1956
+ const winners = new Map();
1957
+ const workflowGrants = [];
1958
+ await Promise.all(activeUsers.map(async (user) => {
1308
1959
  const userMatchesCount = await this.redisClient.sCard(this.keys.userAssignments(user.id));
1309
- if (userMatchesCount >= this.maxUserBacklogSize) {
1960
+ if (userMatchesCount >= this.backlogLimitFor(user)) {
1310
1961
  return;
1311
1962
  }
1312
- const relevantAssignments = await this.getUserRelatedAssignments(user);
1313
- const relevantAssignmentKeys = relevantAssignments
1963
+ const { assignments, claimedIds, workflowTargeted } = await this.getUserRelatedAssignments(user, collector);
1964
+ if (collector) {
1965
+ for (const id of claimedIds)
1966
+ winners.set(id, user.id);
1967
+ // Membership must be read before the sAdd below
1968
+ workflowGrants.push(...(await this.filterNewWorkflowGrants(user, workflowTargeted)));
1969
+ }
1970
+ const relevantAssignmentKeys = assignments
1314
1971
  .sort((a, b) => b.priority - a.priority)
1315
1972
  .map((a) => `assignment:${a.id}`);
1316
1973
  if (relevantAssignmentKeys.length > 0) {
1317
1974
  await this.redisClient.sAdd(this.keys.userAssignments(user.id), relevantAssignmentKeys);
1318
1975
  }
1319
1976
  }));
1977
+ if (collector) {
1978
+ await this.recordPassTraces(collector, winners, workflowGrants, 'first-come', users);
1979
+ }
1320
1980
  }
1321
1981
  async getCurrentAssignmentsForUser(userId) {
1322
1982
  await this.readyPromise;
1323
1983
  const userAssignments = await this.redisClient.sMembers(this.keys.userAssignments(userId));
1324
1984
  return userAssignments.map((el) => el.split(':')[1]);
1325
1985
  }
1986
+ /**
1987
+ * Operator override: hand an assignment directly to a user, bypassing
1988
+ * tag/weight selection. Works on queued assignments and on pending ones
1989
+ * held by another user (the previous owner's backlog slot is released).
1990
+ * Idempotent when the user already owns the assignment.
1991
+ *
1992
+ * Hard rules still apply unless `force`: the user must not be paused,
1993
+ * their backlog must have headroom, they must not be vetoed on the
1994
+ * assignment, and they must not have previously rejected it. `force`
1995
+ * bypasses those checks (the user must always exist). The learning layer
1996
+ * is never fed by manual assignments.
1997
+ *
1998
+ * When tracing is active the override is recorded as a decision trace
1999
+ * with mode `'manual'`, so supervisor actions show up in the same audit
2000
+ * trail as organic matches.
2001
+ */
2002
+ async assignToUser(assignmentId, userId, options) {
2003
+ await this.readyPromise;
2004
+ const force = options?.force === true;
2005
+ const userJson = await this.redisClient.hGet(this.usersKey, userId);
2006
+ if (!userJson)
2007
+ throw new Error(`User not found: ${userId}`);
2008
+ const user = JSON.parse(userJson);
2009
+ const [queuedJson, previousOwnerId] = await Promise.all([
2010
+ this.redisClient.hGet(this.assignmentsRefKey, assignmentId),
2011
+ this.redisClient.hGet(this.assignmentOwnerKey, assignmentId),
2012
+ ]);
2013
+ if (previousOwnerId === userId)
2014
+ return { previousOwnerId: userId };
2015
+ if (!queuedJson && !previousOwnerId) {
2016
+ throw new Error(`Assignment not found in queued or pending state: ${assignmentId}`);
2017
+ }
2018
+ if (!force) {
2019
+ const [isPaused, backlog, isVetoed, hasRejected] = await Promise.all([
2020
+ this.redisClient.sIsMember(this.keys.pausedUsers(), userId),
2021
+ this.redisClient.sCard(this.keys.userAssignments(userId)),
2022
+ this.redisClient.sIsMember(this.keys.assignmentVetoed(assignmentId), userId),
2023
+ this.redisClient.sIsMember(this.keys.userRejected(userId), assignmentId),
2024
+ ]);
2025
+ if (isPaused)
2026
+ throw new Error(`User is paused: ${userId}`);
2027
+ if (backlog >= this.backlogLimitFor(user)) {
2028
+ throw new Error(`User backlog is full (${backlog}/${this.backlogLimitFor(user)}): ${userId}`);
2029
+ }
2030
+ if (isVetoed)
2031
+ throw new Error(`User is vetoed from this assignment: ${userId}`);
2032
+ if (hasRejected)
2033
+ throw new Error(`User previously rejected this assignment: ${userId}`);
2034
+ }
2035
+ if (queuedJson) {
2036
+ // Queued -> pending through the same atomic claim gate as organic
2037
+ // matching; losing it means a concurrent pass just took the
2038
+ // assignment.
2039
+ const tagsCsv = (await this.redisClient.hGet(this.keys.assignmentTags(assignmentId), 'tags')) ?? '';
2040
+ const claimed = await this.claimSelected(user, [{ id: assignmentId, tags: tagsCsv }]);
2041
+ if (!claimed.has(assignmentId)) {
2042
+ throw new Error(`Assignment is no longer available: ${assignmentId}`);
2043
+ }
2044
+ await this.redisClient.sAdd(this.keys.userAssignments(userId), `assignment:${assignmentId}`);
2045
+ }
2046
+ else {
2047
+ // Pending under another user: transfer ownership and restart the
2048
+ // expiry clock for the new owner.
2049
+ const transfer = this.redisClient
2050
+ .multi()
2051
+ .sRem(this.keys.userAssignments(previousOwnerId), `assignment:${assignmentId}`)
2052
+ .sAdd(this.keys.userAssignments(userId), `assignment:${assignmentId}`)
2053
+ .hSet(this.assignmentOwnerKey, assignmentId, userId)
2054
+ .zAdd(this.pendingAssignmentsExpiryKey, {
2055
+ score: Date.now() + this.matchExpirationMs,
2056
+ value: assignmentId,
2057
+ });
2058
+ await transfer.exec();
2059
+ const reassignedAt = Date.now();
2060
+ this.emitAssignmentLifecycle({
2061
+ kind: 'pending',
2062
+ taskId: assignmentId,
2063
+ workerId: userId,
2064
+ matchedAt: reassignedAt,
2065
+ expiresAt: reassignedAt + this.matchExpirationMs,
2066
+ });
2067
+ }
2068
+ await this.touchUser(userId);
2069
+ await this.recordManualAssignTrace(assignmentId, userId, force, previousOwnerId ?? null);
2070
+ return { previousOwnerId: previousOwnerId ?? null };
2071
+ }
2072
+ /** Audit record for an assignToUser() override; failures never break the assignment. */
2073
+ async recordManualAssignTrace(assignmentId, userId, force, previousOwnerId) {
2074
+ if (!this.tracingActive)
2075
+ return;
2076
+ try {
2077
+ await this.decisionTraces.record([
2078
+ {
2079
+ id: (0, crypto_1.randomUUID)(),
2080
+ assignmentId,
2081
+ chosenUserId: userId,
2082
+ matchedAt: Date.now(),
2083
+ mode: 'manual',
2084
+ candidates: [
2085
+ {
2086
+ userId,
2087
+ eligible: true,
2088
+ chosen: true,
2089
+ score: 0,
2090
+ effectivePriority: 0,
2091
+ reasons: [{ kind: 'manualAssignment', force, previousOwnerId }],
2092
+ },
2093
+ ],
2094
+ },
2095
+ ], this.enableDecisionTraces);
2096
+ }
2097
+ catch (err) {
2098
+ console.error('Failed to record manual assignment trace:', err);
2099
+ }
2100
+ }
1326
2101
  async acceptAssignment(userId, assignmentId) {
1327
2102
  await this.readyPromise;
1328
2103
  const isAssigned = await this.redisClient.sIsMember(this.keys.userAssignments(userId), `assignment:${assignmentId}`);
@@ -1335,6 +2110,8 @@ class AssignmentMatcher {
1335
2110
  multi.hDel(this.pendingAssignmentsKey, assignmentId);
1336
2111
  multi.zRem(this.pendingAssignmentsExpiryKey, assignmentId);
1337
2112
  multi.hDel(this.assignmentOwnerKey, assignmentId);
2113
+ // The wait clock stops when a user takes the work
2114
+ multi.zRem(this.keys.assignmentsQueuedAt(), assignmentId);
1338
2115
  // Store in accepted assignments
1339
2116
  if (json) {
1340
2117
  multi.hSet(this.acceptedAssignmentsKey, assignmentId, json);
@@ -1343,6 +2120,12 @@ class AssignmentMatcher {
1343
2120
  if (this.enableLearning) {
1344
2121
  await this.learning.applyOutcome(assignmentId, 'accept');
1345
2122
  }
2123
+ this.emitAssignmentLifecycle({
2124
+ kind: 'accepted',
2125
+ taskId: assignmentId,
2126
+ workerId: userId,
2127
+ acceptedAt: Date.now(),
2128
+ });
1346
2129
  await this.touchUser(userId);
1347
2130
  return true;
1348
2131
  }
@@ -1363,6 +2146,12 @@ class AssignmentMatcher {
1363
2146
  if (this.enableLearning) {
1364
2147
  await this.learning.applyOutcome(assignmentId, 'reject');
1365
2148
  }
2149
+ this.emitAssignmentLifecycle({
2150
+ kind: 'rejected',
2151
+ taskId: assignmentId,
2152
+ workerId: userId,
2153
+ rejectedAt: Date.now(),
2154
+ });
1366
2155
  await this.touchUser(userId);
1367
2156
  if (json) {
1368
2157
  await this.addAssignment(JSON.parse(json));
@@ -1413,6 +2202,12 @@ class AssignmentMatcher {
1413
2202
  payload: result?.data,
1414
2203
  });
1415
2204
  }
2205
+ this.emitAssignmentLifecycle({
2206
+ kind: 'completed',
2207
+ taskId: assignmentId,
2208
+ workerId: userId,
2209
+ completedAt: now,
2210
+ });
1416
2211
  return true;
1417
2212
  }
1418
2213
  /**
@@ -1486,6 +2281,14 @@ class AssignmentMatcher {
1486
2281
  await this.readyPromise;
1487
2282
  return this.workflow.listWorkflowDefinitions();
1488
2283
  }
2284
+ /**
2285
+ * Delete a workflow definition by ID. Running instances are unaffected
2286
+ * (they carry their own snapshot). Returns `false` if it did not exist.
2287
+ */
2288
+ async deleteWorkflowDefinition(id) {
2289
+ await this.readyPromise;
2290
+ return this.workflow.deleteWorkflowDefinition(id);
2291
+ }
1489
2292
  /**
1490
2293
  * Register and start a workflow in one call, or start an already-registered workflow by ID.
1491
2294
  */
@@ -1525,6 +2328,15 @@ class AssignmentMatcher {
1525
2328
  await this.readyPromise;
1526
2329
  return this.workflow.getActiveWorkflowsForUser(userId);
1527
2330
  }
2331
+ /**
2332
+ * List workflow instances (runs), newest-created first, optionally
2333
+ * filtered by status and/or workflow definition. Paginated via an opaque
2334
+ * cursor from the previous page's `nextCursor`.
2335
+ */
2336
+ async listWorkflowInstances(query) {
2337
+ await this.readyPromise;
2338
+ return this.workflow.listWorkflowInstances(query);
2339
+ }
1528
2340
  /**
1529
2341
  * Cancel a workflow instance.
1530
2342
  */
@@ -1532,6 +2344,16 @@ class AssignmentMatcher {
1532
2344
  await this.readyPromise;
1533
2345
  return this.workflow.cancelWorkflow(instanceId);
1534
2346
  }
2347
+ /**
2348
+ * Complete (or fail, via `outcome.success: false`) an external step from
2349
+ * outside this process — the counterpart to the `step.ready` transition
2350
+ * delivered via `onWorkflowEvent`. Throws if the step isn't the run's
2351
+ * current step (or a pending parallel branch) or isn't an external step.
2352
+ */
2353
+ async completeWorkflowStep(instanceId, stepId, outcome) {
2354
+ await this.readyPromise;
2355
+ return this.workflow.completeWorkflowStep(instanceId, stepId, outcome);
2356
+ }
1535
2357
  /**
1536
2358
  * Check and process expired workflow steps.
1537
2359
  * Should be called periodically.
@@ -1540,6 +2362,15 @@ class AssignmentMatcher {
1540
2362
  await this.readyPromise;
1541
2363
  return this.workflow.processExpiredWorkflowSteps();
1542
2364
  }
2365
+ /**
2366
+ * Non-blocking drain of up to `maxEvents` due workflow events. Intended
2367
+ * for hosts that sweep many matcher instances periodically rather than
2368
+ * running `startOrchestrator()`'s dedicated blocking loop per instance.
2369
+ */
2370
+ async processWorkflowEvents(maxEvents) {
2371
+ await this.readyPromise;
2372
+ return this.workflow.processWorkflowEvents(maxEvents);
2373
+ }
1543
2374
  /**
1544
2375
  * Publish a workflow event to the Redis Stream.
1545
2376
  */
@@ -1617,6 +2448,12 @@ class AssignmentMatcher {
1617
2448
  multi.zRem(this.pendingAssignmentsExpiryKey, id);
1618
2449
  multi.hDel(this.assignmentOwnerKey, id);
1619
2450
  await multi.exec();
2451
+ this.emitAssignmentLifecycle({
2452
+ kind: 'expired',
2453
+ taskId: id,
2454
+ workerId: owner ?? null,
2455
+ expiredAt: now,
2456
+ });
1620
2457
  if (this.enableLearning) {
1621
2458
  await this.learning.applyOutcome(id, 'expire');
1622
2459
  }
@@ -1677,8 +2514,12 @@ class AssignmentMatcher {
1677
2514
  return [];
1678
2515
  const cutoff = Date.now() - this.idleUserTimeoutMs;
1679
2516
  const idleCandidates = await this.redisClient.zRangeByScore(this.keys.userActivity(), '-inf', cutoff);
2517
+ // Paused users are deliberately absent, not idle - never auto-remove them.
2518
+ const paused = new Set(await this.redisClient.sMembers(this.keys.pausedUsers()));
1680
2519
  const removed = [];
1681
2520
  for (const userId of idleCandidates) {
2521
+ if (paused.has(userId))
2522
+ continue;
1682
2523
  // Skip users no longer in the pool (clean up stale activity entry)
1683
2524
  const exists = await this.redisClient.hExists(this.usersKey, userId);
1684
2525
  if (!exists) {
@@ -1689,7 +2530,7 @@ class AssignmentMatcher {
1689
2530
  const pendingCount = await this.redisClient.sCard(this.keys.userAssignments(userId));
1690
2531
  if (pendingCount === 0)
1691
2532
  continue;
1692
- await this.releaseUserPendingAssignments(userId);
2533
+ await this.releaseUserPendingAssignments(userId, 'idle');
1693
2534
  await this.removeUser(userId);
1694
2535
  removed.push(userId);
1695
2536
  }
@@ -1698,9 +2539,10 @@ class AssignmentMatcher {
1698
2539
  /**
1699
2540
  * Requeue all pending assignments currently held by a user.
1700
2541
  */
1701
- async releaseUserPendingAssignments(userId) {
2542
+ async releaseUserPendingAssignments(userId, reason = 'operator') {
1702
2543
  const members = await this.redisClient.sMembers(this.keys.userAssignments(userId));
1703
2544
  const now = Date.now();
2545
+ const released = [];
1704
2546
  for (const member of members) {
1705
2547
  const id = member.split(':')[1];
1706
2548
  const json = await this.redisClient.hGet(this.pendingAssignmentsKey, id);
@@ -1710,6 +2552,13 @@ class AssignmentMatcher {
1710
2552
  multi.zRem(this.pendingAssignmentsExpiryKey, id);
1711
2553
  multi.hDel(this.assignmentOwnerKey, id);
1712
2554
  await multi.exec();
2555
+ this.emitAssignmentLifecycle({
2556
+ kind: 'released',
2557
+ taskId: id,
2558
+ workerId: userId,
2559
+ reason,
2560
+ releasedAt: now,
2561
+ });
1713
2562
  if (this.enableLearning) {
1714
2563
  await this.learning.applyOutcome(id, 'expire');
1715
2564
  }
@@ -1725,7 +2574,9 @@ class AssignmentMatcher {
1725
2574
  if (json) {
1726
2575
  await this.addAssignment(JSON.parse(json));
1727
2576
  }
2577
+ released.push(id);
1728
2578
  }
2579
+ return released;
1729
2580
  }
1730
2581
  startIdleUserInterval(intervalMs = 10000) {
1731
2582
  if (this.idleUserInterval)