assignment-user-matcher 1.2.5 → 1.3.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.
@@ -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,
@@ -402,6 +411,287 @@ class AssignmentMatcher {
402
411
  };
403
412
  }
404
413
  // ============================================================================
414
+ // Decision Traces & Explainability
415
+ // ============================================================================
416
+ /** Whether trace capture should run this pass (persistence flag or real-time hook). */
417
+ get tracingActive() {
418
+ return this.enableDecisionTraces || this.decisionTraces.hasDecisionHook;
419
+ }
420
+ /**
421
+ * Toggle decision-trace persistence at runtime without reconstructing the
422
+ * matcher. Takes effect on the next matching pass (a pass already in
423
+ * flight keeps the value it started with).
424
+ */
425
+ setDecisionTraces(enabled) {
426
+ this.enableDecisionTraces = !!enabled;
427
+ }
428
+ /** Current runtime decision-trace persistence state. */
429
+ isDecisionTracesEnabled() {
430
+ return this.enableDecisionTraces;
431
+ }
432
+ /**
433
+ * Query recorded decision traces, newest first. Only decisions made while
434
+ * `enableDecisionTraces` was active are stored — traces are captured as
435
+ * decisions happen, never reconstructed after the fact.
436
+ */
437
+ async getDecisionTraces(query) {
438
+ await this.readyPromise;
439
+ return this.decisionTraces.getTraces(query);
440
+ }
441
+ /** Delete all recorded decision traces. */
442
+ async clearDecisionTraces() {
443
+ await this.readyPromise;
444
+ return this.decisionTraces.clear();
445
+ }
446
+ /**
447
+ * Explain, from live state, which users could receive an assignment and
448
+ * why each one is or is not eligible: vetoes, prior rejections, skill
449
+ * thresholds, CIDR and geo constraints, backlog, the full score breakdown,
450
+ * and learning influence. Works for assignments in any lifecycle state;
451
+ * for matched assignments the current owner is flagged `chosen` (accepted
452
+ * assignments report `ownerId: null` because ownership metadata is
453
+ * released on acceptance — decision traces retain the full history).
454
+ *
455
+ * This is an on-demand recomputation against current state. For the
456
+ * auditable record of a decision as it actually happened, use
457
+ * `getDecisionTraces()`.
458
+ */
459
+ async explainMatch(assignmentId, opts) {
460
+ await this.readyPromise;
461
+ const evaluatedAt = Date.now();
462
+ let found = await (0, pagination_1.getAssignmentById)(this.redisClient, this.assignmentStoreKeys, assignmentId);
463
+ let status;
464
+ if (found) {
465
+ status = (found._status ?? 'queued');
466
+ }
467
+ else {
468
+ // getAssignmentById only covers queued/pending/accepted
469
+ const completedJson = await this.redisClient.hGet(this.completedAssignmentsKey, assignmentId);
470
+ if (!completedJson) {
471
+ return { assignmentId, status: 'not_found', ownerId: null, evaluatedAt, candidates: [] };
472
+ }
473
+ found = JSON.parse(completedJson);
474
+ status = 'completed';
475
+ }
476
+ const assignment = found;
477
+ let ownerId = null;
478
+ if (status === 'pending') {
479
+ ownerId = (await this.redisClient.hGet(this.assignmentOwnerKey, assignmentId)) ?? null;
480
+ }
481
+ else if (status === 'completed') {
482
+ ownerId = assignment._completedBy ?? assignment._failedBy ?? null;
483
+ }
484
+ // Queued assignments may have had their priority retuned since creation
485
+ let basePriority = Number(assignment.priority) || 0;
486
+ if (status === 'queued') {
487
+ const stored = await this.redisClient.hGet(this.keys.assignmentPriority(assignmentId), 'priority');
488
+ if (stored !== null && stored !== undefined)
489
+ basePriority = Number(stored) || 0;
490
+ }
491
+ // Mirror the tags CSV the scoring path sees (the stored tags hash appends 'default')
492
+ const tagsCsv = [...assignment.tags, ...(this.enableDefaultMatching ? ['default'] : [])].join(',');
493
+ let userList;
494
+ if (opts?.userIds && opts.userIds.length > 0) {
495
+ const jsons = await this.redisClient.hmGet(this.usersKey, opts.userIds);
496
+ userList = jsons.filter((json) => Boolean(json)).map((json) => JSON.parse(json));
497
+ }
498
+ else {
499
+ const all = await this.redisClient.hGetAll(this.usersKey);
500
+ userList = Object.values(all).map((json) => JSON.parse(json));
501
+ }
502
+ const modelWeights = this.enableLearning ? await this.learning.getModel() : undefined;
503
+ const candidates = await Promise.all(userList.map((user) => this.explainCandidate(user, assignment, assignmentId, tagsCsv, basePriority, ownerId, modelWeights)));
504
+ (0, decision_trace_1.sortCandidates)(candidates);
505
+ return { assignmentId, status, ownerId, evaluatedAt, candidates };
506
+ }
507
+ /** One user's full eligibility/score evaluation for explainMatch(). */
508
+ async explainCandidate(user, assignment, assignmentId, tagsCsv, basePriority, ownerId, modelWeights) {
509
+ const reasons = [];
510
+ let eligible = true;
511
+ if (assignment.vetoedUsers?.includes(user.id)) {
512
+ reasons.push({ kind: 'assignmentVeto' });
513
+ eligible = false;
514
+ }
515
+ const [isRejected, backlog, isPaused] = await Promise.all([
516
+ this.redisClient.sIsMember(this.keys.userRejected(user.id), assignmentId),
517
+ this.redisClient.sCard(this.keys.userAssignments(user.id)),
518
+ this.redisClient.sIsMember(this.keys.pausedUsers(), user.id),
519
+ ]);
520
+ if (isRejected) {
521
+ reasons.push({ kind: 'rejectedPreviously' });
522
+ eligible = false;
523
+ }
524
+ if (isPaused) {
525
+ reasons.push({ kind: 'paused' });
526
+ eligible = false;
527
+ }
528
+ const backlogLimit = this.backlogLimitFor(user);
529
+ if (backlog >= backlogLimit) {
530
+ reasons.push({ kind: 'backlogFull', backlog, limit: backlogLimit });
531
+ eligible = false;
532
+ }
533
+ const routingWeights = user.routingWeights;
534
+ const hasRoutingWeights = Boolean(routingWeights && Object.keys(routingWeights).length > 0);
535
+ if (hasRoutingWeights &&
536
+ this.usingDefaultMatchScore &&
537
+ !Object.values(routingWeights).some((w) => typeof w === 'number' && w > 0)) {
538
+ reasons.push({ kind: 'noPositiveWeights' });
539
+ eligible = false;
540
+ }
541
+ if (!(0, cidr_1.checkCidrMatch)(user.ip, assignment.allowedCidrs)) {
542
+ reasons.push({ kind: 'cidrMismatch', ip: user.ip });
543
+ eligible = false;
544
+ }
545
+ const geoMatch = await this.evaluateGeoMatch(user, assignment);
546
+ let geoBoost = 0;
547
+ if (!geoMatch.eligible) {
548
+ reasons.push({
549
+ kind: 'geoDistance',
550
+ distanceKm: geoMatch.distanceKm,
551
+ maxDistanceKm: geoMatch.effectiveMaxDistanceKm,
552
+ withinRange: false,
553
+ });
554
+ eligible = false;
555
+ }
556
+ else {
557
+ geoBoost = this.calculateGeoBoost(geoMatch);
558
+ if (typeof geoMatch.distanceKm === 'number') {
559
+ reasons.push({
560
+ kind: 'geoDistance',
561
+ distanceKm: geoMatch.distanceKm,
562
+ maxDistanceKm: geoMatch.effectiveMaxDistanceKm,
563
+ withinRange: true,
564
+ });
565
+ }
566
+ if (geoBoost > 0)
567
+ reasons.push({ kind: 'geoBoost', boost: geoBoost });
568
+ }
569
+ let score;
570
+ let combinedPriority;
571
+ if (this.usingDefaultMatchScore) {
572
+ const explained = (0, match_score_1.explainMatchScore)(user, tagsCsv, basePriority, this.enableDefaultMatching, assignment.skillThresholds);
573
+ score = explained.score;
574
+ combinedPriority = explained.combinedPriority;
575
+ reasons.push(...explained.reasons);
576
+ }
577
+ else {
578
+ [score, combinedPriority] = await this.matchScore(user, tagsCsv, basePriority, assignmentId, assignment.skillThresholds);
579
+ reasons.push({ kind: 'customScore', score });
580
+ }
581
+ if (!score)
582
+ eligible = false;
583
+ let learningBoost = 0;
584
+ if (this.enableLearning && modelWeights) {
585
+ const context = { ...assignment, id: assignmentId, tags: assignment.tags };
586
+ const features = this.learningFeatureExtractor(user, context);
587
+ const predicted = this.learning.predict(features, modelWeights);
588
+ const shadowMode = this.learning.shadowMode;
589
+ learningBoost = shadowMode ? 0 : this.learning.boostFactor * predicted;
590
+ reasons.push({ kind: 'learningBoost', predicted, boost: learningBoost, shadowMode });
591
+ }
592
+ return {
593
+ userId: user.id,
594
+ eligible,
595
+ chosen: ownerId === user.id,
596
+ score,
597
+ effectivePriority: combinedPriority + geoBoost + learningBoost,
598
+ reasons,
599
+ };
600
+ }
601
+ /** Build and record this pass's decision traces; failures never break matching. */
602
+ async recordPassTraces(collector, winners, workflowGrants, mode, users) {
603
+ if (winners.size === 0 && workflowGrants.length === 0)
604
+ return;
605
+ try {
606
+ // A workflow-targeted assignment is also tag-indexed, so the
607
+ // tag-scored path can claim it in the same pass. One decision,
608
+ // one trace: the deterministic targeting is the authoritative
609
+ // story, so the 'workflow' record wins.
610
+ for (const grant of workflowGrants)
611
+ winners.delete(grant.assignmentId);
612
+ const matchedAt = Date.now();
613
+ const contexts = await this.getTraceUserContexts(users);
614
+ const traces = [
615
+ ...(0, decision_trace_1.buildDecisionTraces)({
616
+ collector,
617
+ winners,
618
+ mode,
619
+ users: contexts,
620
+ maxCandidates: this.decisionTraceMaxCandidates,
621
+ matchedAt,
622
+ }),
623
+ ...(0, decision_trace_1.buildWorkflowTraces)(workflowGrants, matchedAt),
624
+ ];
625
+ await this.decisionTraces.record(traces, this.enableDecisionTraces);
626
+ }
627
+ catch (err) {
628
+ console.error('Failed to record decision traces:', err);
629
+ }
630
+ }
631
+ /** Exclusion sets used to enrich traces with prefiltered (vetoed/rejected/paused) users. */
632
+ async getTraceUserContexts(users) {
633
+ const paused = new Set(await this.redisClient.sMembers(this.keys.pausedUsers()));
634
+ return Promise.all(users.map(async (user) => {
635
+ const [rejected, vetoed] = await Promise.all([
636
+ this.redisClient.sMembers(this.keys.userRejected(user.id)),
637
+ this.redisClient.sMembers(this.keys.userVetoed(user.id)),
638
+ ]);
639
+ return {
640
+ user,
641
+ rejected: new Set(rejected),
642
+ vetoed: new Set(vetoed),
643
+ paused: paused.has(user.id),
644
+ };
645
+ }));
646
+ }
647
+ /** One sMembers per pass: the user list minus currently paused users. */
648
+ async filterPausedUsers(users) {
649
+ const paused = await this.redisClient.sMembers(this.keys.pausedUsers());
650
+ if (paused.length === 0)
651
+ return users;
652
+ const pausedSet = new Set(paused);
653
+ return users.filter((user) => !pausedSet.has(user.id));
654
+ }
655
+ /**
656
+ * Workflow-targeted assignments are re-granted idempotently on every
657
+ * matching pass until actioned; only first-time grants deserve a decision
658
+ * trace. Reads membership before the sAdd that follows.
659
+ */
660
+ async filterNewWorkflowGrants(user, workflowTargeted) {
661
+ if (workflowTargeted.length === 0)
662
+ return [];
663
+ const memberships = await this.redisClient.smIsMember(this.keys.userAssignments(user.id), workflowTargeted.map((w) => `assignment:${w.id}`));
664
+ return workflowTargeted
665
+ .filter((_, i) => !memberships[i])
666
+ .map((w) => ({ assignmentId: w.id, userId: user.id, priority: w.priority }));
667
+ }
668
+ /** Reasons for one scored candidate evaluation (trace capture only). */
669
+ traceScoreReasons(user, detail, score, geoMatch, geoBoost, learning) {
670
+ const reasons = this.usingDefaultMatchScore
671
+ ? (0, match_score_1.explainMatchScore)(user, detail.tags, detail.basePriority, this.enableDefaultMatching, detail.skillThresholds)
672
+ .reasons
673
+ : [{ kind: 'customScore', score }];
674
+ if (typeof geoMatch.distanceKm === 'number') {
675
+ reasons.push({
676
+ kind: 'geoDistance',
677
+ distanceKm: geoMatch.distanceKm,
678
+ maxDistanceKm: geoMatch.effectiveMaxDistanceKm,
679
+ withinRange: true,
680
+ });
681
+ }
682
+ if (geoBoost > 0)
683
+ reasons.push({ kind: 'geoBoost', boost: geoBoost });
684
+ if (learning) {
685
+ reasons.push({
686
+ kind: 'learningBoost',
687
+ predicted: learning.predicted,
688
+ boost: learning.boost,
689
+ shadowMode: learning.shadowMode,
690
+ });
691
+ }
692
+ return reasons;
693
+ }
694
+ // ============================================================================
405
695
  // Auto Routing Weights (RL-generated tags/weights)
406
696
  // ============================================================================
407
697
  /**
@@ -530,6 +820,9 @@ class AssignmentMatcher {
530
820
  const multi = this.redisClient
531
821
  .multi()
532
822
  .hSet(this.assignmentsRefKey, id, JSON.stringify(assignment))
823
+ // NX: a requeue (reject/expiry re-adds via this method) keeps the
824
+ // original first-enqueue wait clock.
825
+ .zAdd(this.keys.assignmentsQueuedAt(), { score: Date.now(), value: id }, { NX: true })
533
826
  .hSet(assignmentPriorityKey, 'priority', priority)
534
827
  // Ensure 'default' tag is persisted consistently when enabled
535
828
  .hSet(assignmentTagsKey, 'tags', tags.join(',') + (this.enableDefaultMatching ? ',default' : ''))
@@ -586,6 +879,7 @@ class AssignmentMatcher {
586
879
  multi.del(assignmentPriorityKey);
587
880
  multi.del(assignmentTagsKey);
588
881
  multi.zRem(this.assignmentsKey, id.toString());
882
+ multi.zRem(this.keys.assignmentsQueuedAt(), id.toString());
589
883
  for (const tag of tags) {
590
884
  multi.zRem(this.keys.tagAssignments(tag), id.toString());
591
885
  }
@@ -614,10 +908,76 @@ class AssignmentMatcher {
614
908
  .del(this.keys.userRejected(userId))
615
909
  .del(this.keys.userVetoed(userId))
616
910
  .zRem(this.keys.userActivity(), userId)
911
+ .sRem(this.keys.pausedUsers(), userId)
617
912
  .hDel(this.usersKey, userId);
618
913
  await multi.exec();
619
914
  return userId;
620
915
  }
916
+ /**
917
+ * Get one stored user as last written by addUser (including the injected
918
+ * 'default' tag when enableDefaultMatching is on), or null.
919
+ */
920
+ async getUser(userId) {
921
+ await this.readyPromise;
922
+ const json = await this.redisClient.hGet(this.usersKey, userId);
923
+ return json ? JSON.parse(json) : null;
924
+ }
925
+ /** All stored users. The pool is small by design; for load metadata see getQueueStats(). */
926
+ async getUsers() {
927
+ await this.readyPromise;
928
+ const users = [];
929
+ let cursor = '0';
930
+ do {
931
+ const { cursor: nextCursor, entries } = await this.redisClient.hScan(this.usersKey, cursor, { COUNT: 500 });
932
+ users.push(...entries.map((t) => JSON.parse(t.value)));
933
+ cursor = nextCursor;
934
+ } while (cursor !== '0');
935
+ return users;
936
+ }
937
+ // ============================================================================
938
+ // Worker Availability (pause/resume)
939
+ // ============================================================================
940
+ /**
941
+ * Pause a user: they stop receiving new assignments in every matching path
942
+ * until resumed, but keep their pending backlog and can still accept,
943
+ * complete, reject, or fail work they already hold. Paused users are also
944
+ * exempt from idle auto-removal (pausing is deliberate absence, not
945
+ * idleness). Idempotent.
946
+ *
947
+ * @returns false when the user is not in the pool (nothing is recorded)
948
+ */
949
+ async pauseUser(userId) {
950
+ await this.readyPromise;
951
+ const exists = await this.redisClient.hExists(this.usersKey, userId);
952
+ if (!exists)
953
+ return false;
954
+ await this.redisClient.sAdd(this.keys.pausedUsers(), userId);
955
+ return true;
956
+ }
957
+ /**
958
+ * Resume a paused user so matching considers them again on the next pass.
959
+ * Also records activity (resets the idle clock).
960
+ *
961
+ * @returns false when the user was not paused
962
+ */
963
+ async resumeUser(userId) {
964
+ await this.readyPromise;
965
+ const wasPaused = await this.redisClient.sRem(this.keys.pausedUsers(), userId);
966
+ if (wasPaused)
967
+ await this.touchUser(userId);
968
+ return wasPaused > 0;
969
+ }
970
+ /** Whether a user is currently paused. */
971
+ async isUserPaused(userId) {
972
+ await this.readyPromise;
973
+ return Boolean(await this.redisClient.sIsMember(this.keys.pausedUsers(), userId));
974
+ }
975
+ /** IDs of all currently paused users. */
976
+ async getPausedUsers() {
977
+ await this.readyPromise;
978
+ const members = await this.redisClient.sMembers(this.keys.pausedUsers());
979
+ return members.sort();
980
+ }
621
981
  /**
622
982
  * Get all assignments (queued, pending, and accepted).
623
983
  * For large datasets, prefer using getAssignmentsPaginated() instead.
@@ -658,6 +1018,42 @@ class AssignmentMatcher {
658
1018
  await this.readyPromise;
659
1019
  return (0, pagination_1.getAssignmentsByIdsBatch)(this.redisClient, this.assignmentStoreKeys, ids);
660
1020
  }
1021
+ /**
1022
+ * Live operational snapshot for dashboards: queued/pending counts, the
1023
+ * age of the longest-waiting unaccepted assignment, and every user's
1024
+ * backlog depth, effective cap, and paused state. The wait clock starts
1025
+ * at first enqueue and survives reject/expiry requeues; it stops on
1026
+ * accept or removal.
1027
+ */
1028
+ async getQueueStats() {
1029
+ await this.readyPromise;
1030
+ const [counts, oldestEntries, pausedMembers] = await Promise.all([
1031
+ (0, pagination_1.getAssignmentCountsFromStores)(this.redisClient, this.assignmentStoreKeys),
1032
+ this.redisClient.zRangeWithScores(this.keys.assignmentsQueuedAt(), 0, 0),
1033
+ this.redisClient.sMembers(this.keys.pausedUsers()),
1034
+ ]);
1035
+ const paused = new Set(pausedMembers);
1036
+ const users = [];
1037
+ let cursor = '0';
1038
+ do {
1039
+ const { cursor: nextCursor, entries } = await this.redisClient.hScan(this.usersKey, cursor, { COUNT: 500 });
1040
+ users.push(...entries.map((t) => JSON.parse(t.value)));
1041
+ cursor = nextCursor;
1042
+ } while (cursor !== '0');
1043
+ const perUser = await Promise.all(users.map(async (user) => ({
1044
+ userId: user.id,
1045
+ backlog: await this.redisClient.sCard(this.keys.userAssignments(user.id)),
1046
+ maxBacklogSize: this.backlogLimitFor(user),
1047
+ paused: paused.has(user.id),
1048
+ })));
1049
+ perUser.sort((a, b) => a.userId.localeCompare(b.userId));
1050
+ return {
1051
+ queued: counts.queued,
1052
+ pending: counts.pending,
1053
+ oldestWaitingMs: oldestEntries.length > 0 ? Date.now() - Number(oldestEntries[0].score) : null,
1054
+ perUser,
1055
+ };
1056
+ }
661
1057
  /**
662
1058
  * Get all pending assignments with owner and pending duration metadata.
663
1059
  */
@@ -761,22 +1157,37 @@ class AssignmentMatcher {
761
1157
  const assignmentPriorityKey = this.keys.assignmentPriority(id);
762
1158
  // Fetch tags to update per-tag indices
763
1159
  const assignmentTagsKey = this.keys.assignmentTags(id);
764
- const [existsRef, tagsCsv] = (await this.redisClient
1160
+ const [refJson, tagsCsv] = (await this.redisClient
765
1161
  .multi()
766
- .hExists(this.assignmentsRefKey, id)
1162
+ .hGet(this.assignmentsRefKey, id)
767
1163
  .hGet(assignmentTagsKey, 'tags')
768
1164
  .exec());
769
1165
  const tags = (tagsCsv && tagsCsv.length > 0 ? tagsCsv.split(',') : []);
770
1166
  const multi = this.redisClient.multi();
771
1167
  multi.hSet(assignmentPriorityKey, 'priority', priority);
772
- if (existsRef) {
773
- // Update global zset score and per-tag zset scores only if assignment still exists
1168
+ if (refJson) {
1169
+ // Update global zset score and per-tag zset scores only if assignment still exists,
1170
+ // plus the stored record itself so reads see the new priority.
1171
+ multi.hSet(this.assignmentsRefKey, id, JSON.stringify({ ...JSON.parse(refJson), priority }));
774
1172
  multi.zAdd(this.assignmentsKey, { score: Number(priority), value: id });
775
1173
  for (const tag of tags) {
776
1174
  multi.zAdd(this.keys.tagAssignments(tag), { score: Number(priority), value: id });
777
1175
  }
778
1176
  }
779
1177
  await multi.exec();
1178
+ if (refJson) {
1179
+ // The snapshot read above races the atomic claim gate: if a claim
1180
+ // HDELed the record between our read and write, the writes above
1181
+ // resurrected a ghost queued entry. Detect and undo.
1182
+ const owner = await this.redisClient.hGet(this.assignmentOwnerKey, id);
1183
+ if (owner) {
1184
+ const cleanup = this.redisClient.multi().hDel(this.assignmentsRefKey, id).zRem(this.assignmentsKey, id);
1185
+ for (const tag of tags) {
1186
+ cleanup.zRem(this.keys.tagAssignments(tag), id);
1187
+ }
1188
+ await cleanup.exec();
1189
+ }
1190
+ }
780
1191
  return { id, priority };
781
1192
  }
782
1193
  async setAssignmentPriorityByTags(tags, priority) {
@@ -821,7 +1232,17 @@ class AssignmentMatcher {
821
1232
  * higher scorer should still be considered for their next-best options,
822
1233
  * not left with nothing because discovery stopped early.
823
1234
  */
824
- async computeCandidatesForUser(user, capToBacklog = true) {
1235
+ /**
1236
+ * Effective backlog cap for one user: `user.maxBacklogSize` when it is a
1237
+ * valid non-negative number, else the matcher-wide `maxUserBacklogSize`.
1238
+ * The fairness window auto-cap derivation (team-level) deliberately keeps
1239
+ * using the global value.
1240
+ */
1241
+ backlogLimitFor(user) {
1242
+ const own = user.maxBacklogSize;
1243
+ return typeof own === 'number' && Number.isFinite(own) && own >= 0 ? own : this.maxUserBacklogSize;
1244
+ }
1245
+ async computeCandidatesForUser(user, capToBacklog = true, collector) {
825
1246
  const userAssignments = [];
826
1247
  const routingWeights = user.routingWeights;
827
1248
  const hasRoutingWeights = Boolean(routingWeights && Object.keys(routingWeights).length > 0);
@@ -831,7 +1252,7 @@ class AssignmentMatcher {
831
1252
  if (workflowAssignments.length > 0) {
832
1253
  // Workflow assignments take precedence - add them first with highest priority
833
1254
  userAssignments.push(...workflowAssignments);
834
- if (userAssignments.length >= this.maxUserBacklogSize) {
1255
+ if (userAssignments.length >= this.backlogLimitFor(user)) {
835
1256
  return { userAssignments, selected: [], workflowTargetedCount: userAssignments.length };
836
1257
  }
837
1258
  }
@@ -955,15 +1376,47 @@ class AssignmentMatcher {
955
1376
  const modelWeights = await this.learning.getModel();
956
1377
  const eligible = [];
957
1378
  for (const d of details) {
958
- if (!(0, cidr_1.checkCidrMatch)(user.ip, d.allowedCidrs))
1379
+ if (!(0, cidr_1.checkCidrMatch)(user.ip, d.allowedCidrs)) {
1380
+ collector?.record(d.id, d.tags, {
1381
+ userId: user.id,
1382
+ eligible: false,
1383
+ score: 0,
1384
+ effectivePriority: 0,
1385
+ reasons: [{ kind: 'cidrMismatch', ip: user.ip }],
1386
+ });
959
1387
  continue;
1388
+ }
960
1389
  const geoMatch = await this.evaluateGeoMatch(user, d.raw ?? { id: d.id, tags: [] });
961
- if (!geoMatch.eligible)
1390
+ if (!geoMatch.eligible) {
1391
+ collector?.record(d.id, d.tags, {
1392
+ userId: user.id,
1393
+ eligible: false,
1394
+ score: 0,
1395
+ effectivePriority: 0,
1396
+ reasons: [
1397
+ {
1398
+ kind: 'geoDistance',
1399
+ distanceKm: geoMatch.distanceKm,
1400
+ maxDistanceKm: geoMatch.effectiveMaxDistanceKm,
1401
+ withinRange: false,
1402
+ },
1403
+ ],
1404
+ });
962
1405
  continue;
1406
+ }
963
1407
  const [score, combinedPriority] = await this.matchScore(user, d.tags, d.basePriority, d.id, d.skillThresholds);
964
- if (!score || !combinedPriority)
1408
+ if (!score || !combinedPriority) {
1409
+ collector?.record(d.id, d.tags, {
1410
+ userId: user.id,
1411
+ eligible: false,
1412
+ score: 0,
1413
+ effectivePriority: Number(d.basePriority) || 0,
1414
+ reasons: this.traceScoreReasons(user, d, score, geoMatch, 0),
1415
+ });
965
1416
  continue;
966
- const geoAdjustedPriority = combinedPriority + this.calculateGeoBoost(geoMatch);
1417
+ }
1418
+ const traceGeoBoost = this.calculateGeoBoost(geoMatch);
1419
+ const geoAdjustedPriority = combinedPriority + traceGeoBoost;
967
1420
  const context = {
968
1421
  ...(d.raw ?? {}),
969
1422
  id: d.id,
@@ -980,10 +1433,21 @@ class AssignmentMatcher {
980
1433
  ? geoAdjustedPriority
981
1434
  : geoAdjustedPriority + this.learning.boostFactor * predicted + exploration;
982
1435
  eligible.push({ detail: d, combinedPriority, features, predicted, effectivePriority });
1436
+ collector?.record(d.id, d.tags, {
1437
+ userId: user.id,
1438
+ eligible: true,
1439
+ score,
1440
+ effectivePriority,
1441
+ reasons: this.traceScoreReasons(user, d, score, geoMatch, traceGeoBoost, {
1442
+ predicted,
1443
+ boost: effectivePriority - geoAdjustedPriority,
1444
+ shadowMode: this.learning.shadowMode,
1445
+ }),
1446
+ });
983
1447
  }
984
1448
  eligible.sort((a, b) => b.effectivePriority - a.effectivePriority);
985
1449
  for (const c of eligible) {
986
- if (capToBacklog && userAssignments.length >= this.maxUserBacklogSize)
1450
+ if (capToBacklog && userAssignments.length >= this.backlogLimitFor(user))
987
1451
  break;
988
1452
  userAssignments.push({ id: c.detail.id, priority: c.effectivePriority });
989
1453
  selected.push({ id: c.detail.id, tags: c.detail.tags });
@@ -992,21 +1456,59 @@ class AssignmentMatcher {
992
1456
  }
993
1457
  else {
994
1458
  for (const d of details) {
995
- if (capToBacklog && userAssignments.length >= this.maxUserBacklogSize)
1459
+ if (capToBacklog && userAssignments.length >= this.backlogLimitFor(user))
996
1460
  break;
997
1461
  // Check CIDR restrictions: if assignment has allowedCidrs, user must have matching IP
998
1462
  if (!(0, cidr_1.checkCidrMatch)(user.ip, d.allowedCidrs)) {
1463
+ collector?.record(d.id, d.tags, {
1464
+ userId: user.id,
1465
+ eligible: false,
1466
+ score: 0,
1467
+ effectivePriority: 0,
1468
+ reasons: [{ kind: 'cidrMismatch', ip: user.ip }],
1469
+ });
999
1470
  continue; // Skip this assignment - user IP doesn't match allowed CIDRs
1000
1471
  }
1001
1472
  const geoMatch = await this.evaluateGeoMatch(user, d.raw ?? { id: d.id, tags: [] });
1002
1473
  if (!geoMatch.eligible) {
1474
+ collector?.record(d.id, d.tags, {
1475
+ userId: user.id,
1476
+ eligible: false,
1477
+ score: 0,
1478
+ effectivePriority: 0,
1479
+ reasons: [
1480
+ {
1481
+ kind: 'geoDistance',
1482
+ distanceKm: geoMatch.distanceKm,
1483
+ maxDistanceKm: geoMatch.effectiveMaxDistanceKm,
1484
+ withinRange: false,
1485
+ },
1486
+ ],
1487
+ });
1003
1488
  continue;
1004
1489
  }
1005
1490
  // Use custom matchScore (supports weights and thresholds) for a final check and tie-break
1006
1491
  const [score, combinedPriority] = await this.matchScore(user, d.tags, d.basePriority, d.id, d.skillThresholds);
1007
1492
  if (score && combinedPriority) {
1008
- userAssignments.push({ id: d.id, priority: combinedPriority + this.calculateGeoBoost(geoMatch) });
1493
+ const geoBoost = this.calculateGeoBoost(geoMatch);
1494
+ userAssignments.push({ id: d.id, priority: combinedPriority + geoBoost });
1009
1495
  selected.push({ id: d.id, tags: d.tags });
1496
+ collector?.record(d.id, d.tags, {
1497
+ userId: user.id,
1498
+ eligible: true,
1499
+ score,
1500
+ effectivePriority: combinedPriority + geoBoost,
1501
+ reasons: this.traceScoreReasons(user, d, score, geoMatch, geoBoost),
1502
+ });
1503
+ }
1504
+ else {
1505
+ collector?.record(d.id, d.tags, {
1506
+ userId: user.id,
1507
+ eligible: false,
1508
+ score: 0,
1509
+ effectivePriority: Number(d.basePriority) || 0,
1510
+ reasons: this.traceScoreReasons(user, d, score, geoMatch, 0),
1511
+ });
1010
1512
  }
1011
1513
  }
1012
1514
  }
@@ -1071,12 +1573,12 @@ class AssignmentMatcher {
1071
1573
  }
1072
1574
  return claimedIds;
1073
1575
  }
1074
- async getUserRelatedAssignments(user) {
1075
- const { userAssignments, selected, workflowTargetedCount } = await this.computeCandidatesForUser(user);
1576
+ async getUserRelatedAssignments(user, collector) {
1577
+ const { userAssignments, selected, workflowTargetedCount } = await this.computeCandidatesForUser(user, true, collector);
1076
1578
  const claimedIds = await this.claimSelected(user, selected);
1077
1579
  const workflowTargeted = userAssignments.slice(0, workflowTargetedCount);
1078
1580
  const tagScored = userAssignments.slice(workflowTargetedCount).filter((ua) => claimedIds.has(ua.id));
1079
- return [...workflowTargeted, ...tagScored];
1581
+ return { assignments: [...workflowTargeted, ...tagScored], claimedIds, workflowTargeted };
1080
1582
  }
1081
1583
  /**
1082
1584
  * Opt-in alternative to the default parallel bulk path (see
@@ -1102,6 +1604,12 @@ class AssignmentMatcher {
1102
1604
  users.push(...entries.map((t) => JSON.parse(t.value)));
1103
1605
  cursor = nextCursor;
1104
1606
  } while (cursor !== '0');
1607
+ // Paused users sit out the pass entirely but stay in `users` so traces
1608
+ // can show them struck out.
1609
+ const activeUsers = await this.filterPausedUsers(users);
1610
+ const collector = this.tracingActive ? new decision_trace_1.TraceCollector() : undefined;
1611
+ const traceWinners = new Map();
1612
+ const workflowGrants = [];
1105
1613
  // Rolling-window grant cap: an explicit finite fairnessMaxPerWindow
1106
1614
  // always applies; the 'balanced' / 'spread-work' presets additionally
1107
1615
  // default a team-relative guardrail when no explicit cap is given
@@ -1112,7 +1620,7 @@ class AssignmentMatcher {
1112
1620
  const windowStart = Date.now() - this.fairnessWindowMs;
1113
1621
  // Phase 1: per-user backlog + window usage, one pipelined batch - the
1114
1622
  // rolling cap costs one extra command per user here, not a round trip.
1115
- const usage = await Promise.all(users.map(async (user) => {
1623
+ const usage = await Promise.all(activeUsers.map(async (user) => {
1116
1624
  const [backlog, grantsInWindow] = await Promise.all([
1117
1625
  this.redisClient.sCard(this.keys.userAssignments(user.id)),
1118
1626
  windowActive
@@ -1136,7 +1644,7 @@ class AssignmentMatcher {
1136
1644
  // Phase 2: read-only candidate discovery for users with headroom.
1137
1645
  const perUser = await Promise.all(usage.map(async ({ user, backlog, grantsInWindow }) => {
1138
1646
  const windowRemaining = windowActive ? Math.max(0, windowCap - grantsInWindow) : Infinity;
1139
- if (backlog >= this.maxUserBacklogSize) {
1647
+ if (backlog >= this.backlogLimitFor(user)) {
1140
1648
  return {
1141
1649
  user,
1142
1650
  backlog,
@@ -1164,17 +1672,21 @@ class AssignmentMatcher {
1164
1672
  }
1165
1673
  // capToBacklog=false: this user's full candidate set is needed for
1166
1674
  // global arbitration below, not just as many as their own cap allows.
1167
- const candidates = await this.computeCandidatesForUser(user, false);
1675
+ const candidates = await this.computeCandidatesForUser(user, false, collector);
1168
1676
  return { user, backlog, windowRemaining, candidates };
1169
1677
  }));
1170
1678
  // Workflow-targeted assignments are deterministically targeted at one
1171
1679
  // user each - not contested across users - so claim them immediately,
1172
1680
  // exactly like the non-fair path does.
1173
- await Promise.all(perUser.map(({ user, candidates }) => {
1681
+ await Promise.all(perUser.map(async ({ user, candidates }) => {
1174
1682
  const workflowOnly = candidates.userAssignments.slice(0, candidates.workflowTargetedCount);
1175
1683
  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}`));
1684
+ return;
1685
+ if (collector) {
1686
+ // Membership must be read before the sAdd below
1687
+ workflowGrants.push(...(await this.filterNewWorkflowGrants(user, workflowOnly)));
1688
+ }
1689
+ await this.redisClient.sAdd(this.keys.userAssignments(user.id), workflowOnly.map((a) => `assignment:${a.id}`));
1178
1690
  }));
1179
1691
  // Flatten every user's tag-scored candidates into one global list of
1180
1692
  // {user, assignment, score} pairs for cross-user arbitration.
@@ -1196,15 +1708,15 @@ class AssignmentMatcher {
1196
1708
  // may take at most min(backlog headroom, window headroom) more
1197
1709
  // tag-scored assignments this pass. Workflow-targeted grants above
1198
1710
  // 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
- }
1711
+ // Always built (not only when the window is active) so per-user
1712
+ // backlog caps (user.maxBacklogSize) reach arbitration too;
1713
+ // windowRemaining is Infinity when the window is inactive.
1714
+ const maxByUser = new Map(perUser.map(({ user, backlog, windowRemaining, candidates }) => [
1715
+ user.id,
1716
+ backlog +
1717
+ candidates.workflowTargetedCount +
1718
+ Math.max(0, Math.min(this.backlogLimitFor(user) - backlog - candidates.workflowTargetedCount, windowRemaining)),
1719
+ ]));
1208
1720
  // Arbitrate winners in memory (see arbitrateFair for the ordering:
1209
1721
  // best score wins, optionally load-penalized / tie-banded), then claim
1210
1722
  // in one batched claimSelected() call per user (all users in parallel)
@@ -1243,6 +1755,10 @@ class AssignmentMatcher {
1243
1755
  await Promise.all(Array.from(tentative.values()).map(async ({ user, pairs }) => {
1244
1756
  const claimedIds = await this.claimSelected(user, pairs);
1245
1757
  const won = pairs.filter((p) => claimedIds.has(p.id));
1758
+ if (collector) {
1759
+ for (const p of won)
1760
+ traceWinners.set(p.id, user.id);
1761
+ }
1246
1762
  if (won.length < pairs.length) {
1247
1763
  anyLost = true;
1248
1764
  backlogUsed.set(user.id, (backlogUsed.get(user.id) ?? 0) - (pairs.length - won.length));
@@ -1270,6 +1786,9 @@ class AssignmentMatcher {
1270
1786
  break;
1271
1787
  remaining = deferred.filter((pair) => !settled.has(pair.id));
1272
1788
  }
1789
+ if (collector) {
1790
+ await this.recordPassTraces(collector, traceWinners, workflowGrants, this.getFairness(), users);
1791
+ }
1273
1792
  }
1274
1793
  async matchUsersAssignments(userId) {
1275
1794
  await this.readyPromise;
@@ -1278,17 +1797,28 @@ class AssignmentMatcher {
1278
1797
  const userJson = await this.redisClient.hGet(this.usersKey, userId);
1279
1798
  if (!userJson)
1280
1799
  return;
1800
+ if (await this.redisClient.sIsMember(this.keys.pausedUsers(), userId))
1801
+ return;
1281
1802
  const user = JSON.parse(userJson);
1282
1803
  const userMatchesCount = await this.redisClient.sCard(this.keys.userAssignments(user.id));
1283
- if (userMatchesCount >= this.maxUserBacklogSize)
1804
+ if (userMatchesCount >= this.backlogLimitFor(user))
1284
1805
  return;
1285
- const relevantAssignments = await this.getUserRelatedAssignments(user);
1286
- const relevantAssignmentKeys = relevantAssignments
1806
+ const collector = this.tracingActive ? new decision_trace_1.TraceCollector() : undefined;
1807
+ const { assignments, claimedIds, workflowTargeted } = await this.getUserRelatedAssignments(user, collector);
1808
+ // Membership must be read before the sAdd below
1809
+ const newWorkflowGrants = collector ? await this.filterNewWorkflowGrants(user, workflowTargeted) : [];
1810
+ const relevantAssignmentKeys = assignments
1287
1811
  .sort((a, b) => b.priority - a.priority)
1288
1812
  .map((a) => `assignment:${a.id}`);
1289
1813
  if (relevantAssignmentKeys.length > 0) {
1290
1814
  await this.redisClient.sAdd(this.keys.userAssignments(user.id), relevantAssignmentKeys);
1291
1815
  }
1816
+ if (collector) {
1817
+ const winners = new Map();
1818
+ for (const id of claimedIds)
1819
+ winners.set(id, user.id);
1820
+ await this.recordPassTraces(collector, winners, newWorkflowGrants, 'direct', [user]);
1821
+ }
1292
1822
  return;
1293
1823
  }
1294
1824
  if (this.enableFairTiebreaker) {
@@ -1303,26 +1833,148 @@ class AssignmentMatcher {
1303
1833
  users.push(...entries.map((t) => JSON.parse(t.value)));
1304
1834
  cursor = nextCursor;
1305
1835
  } while (cursor !== '0');
1836
+ // Paused users sit out the pass entirely but stay in `users` so traces
1837
+ // can show them struck out.
1838
+ const activeUsers = await this.filterPausedUsers(users);
1306
1839
  // Process users in parallel
1307
- await Promise.all(users.map(async (user) => {
1840
+ const collector = this.tracingActive ? new decision_trace_1.TraceCollector() : undefined;
1841
+ const winners = new Map();
1842
+ const workflowGrants = [];
1843
+ await Promise.all(activeUsers.map(async (user) => {
1308
1844
  const userMatchesCount = await this.redisClient.sCard(this.keys.userAssignments(user.id));
1309
- if (userMatchesCount >= this.maxUserBacklogSize) {
1845
+ if (userMatchesCount >= this.backlogLimitFor(user)) {
1310
1846
  return;
1311
1847
  }
1312
- const relevantAssignments = await this.getUserRelatedAssignments(user);
1313
- const relevantAssignmentKeys = relevantAssignments
1848
+ const { assignments, claimedIds, workflowTargeted } = await this.getUserRelatedAssignments(user, collector);
1849
+ if (collector) {
1850
+ for (const id of claimedIds)
1851
+ winners.set(id, user.id);
1852
+ // Membership must be read before the sAdd below
1853
+ workflowGrants.push(...(await this.filterNewWorkflowGrants(user, workflowTargeted)));
1854
+ }
1855
+ const relevantAssignmentKeys = assignments
1314
1856
  .sort((a, b) => b.priority - a.priority)
1315
1857
  .map((a) => `assignment:${a.id}`);
1316
1858
  if (relevantAssignmentKeys.length > 0) {
1317
1859
  await this.redisClient.sAdd(this.keys.userAssignments(user.id), relevantAssignmentKeys);
1318
1860
  }
1319
1861
  }));
1862
+ if (collector) {
1863
+ await this.recordPassTraces(collector, winners, workflowGrants, 'first-come', users);
1864
+ }
1320
1865
  }
1321
1866
  async getCurrentAssignmentsForUser(userId) {
1322
1867
  await this.readyPromise;
1323
1868
  const userAssignments = await this.redisClient.sMembers(this.keys.userAssignments(userId));
1324
1869
  return userAssignments.map((el) => el.split(':')[1]);
1325
1870
  }
1871
+ /**
1872
+ * Operator override: hand an assignment directly to a user, bypassing
1873
+ * tag/weight selection. Works on queued assignments and on pending ones
1874
+ * held by another user (the previous owner's backlog slot is released).
1875
+ * Idempotent when the user already owns the assignment.
1876
+ *
1877
+ * Hard rules still apply unless `force`: the user must not be paused,
1878
+ * their backlog must have headroom, they must not be vetoed on the
1879
+ * assignment, and they must not have previously rejected it. `force`
1880
+ * bypasses those checks (the user must always exist). The learning layer
1881
+ * is never fed by manual assignments.
1882
+ *
1883
+ * When tracing is active the override is recorded as a decision trace
1884
+ * with mode `'manual'`, so supervisor actions show up in the same audit
1885
+ * trail as organic matches.
1886
+ */
1887
+ async assignToUser(assignmentId, userId, options) {
1888
+ await this.readyPromise;
1889
+ const force = options?.force === true;
1890
+ const userJson = await this.redisClient.hGet(this.usersKey, userId);
1891
+ if (!userJson)
1892
+ throw new Error(`User not found: ${userId}`);
1893
+ const user = JSON.parse(userJson);
1894
+ const [queuedJson, previousOwnerId] = await Promise.all([
1895
+ this.redisClient.hGet(this.assignmentsRefKey, assignmentId),
1896
+ this.redisClient.hGet(this.assignmentOwnerKey, assignmentId),
1897
+ ]);
1898
+ if (previousOwnerId === userId)
1899
+ return { previousOwnerId: userId };
1900
+ if (!queuedJson && !previousOwnerId) {
1901
+ throw new Error(`Assignment not found in queued or pending state: ${assignmentId}`);
1902
+ }
1903
+ if (!force) {
1904
+ const [isPaused, backlog, isVetoed, hasRejected] = await Promise.all([
1905
+ this.redisClient.sIsMember(this.keys.pausedUsers(), userId),
1906
+ this.redisClient.sCard(this.keys.userAssignments(userId)),
1907
+ this.redisClient.sIsMember(this.keys.assignmentVetoed(assignmentId), userId),
1908
+ this.redisClient.sIsMember(this.keys.userRejected(userId), assignmentId),
1909
+ ]);
1910
+ if (isPaused)
1911
+ throw new Error(`User is paused: ${userId}`);
1912
+ if (backlog >= this.backlogLimitFor(user)) {
1913
+ throw new Error(`User backlog is full (${backlog}/${this.backlogLimitFor(user)}): ${userId}`);
1914
+ }
1915
+ if (isVetoed)
1916
+ throw new Error(`User is vetoed from this assignment: ${userId}`);
1917
+ if (hasRejected)
1918
+ throw new Error(`User previously rejected this assignment: ${userId}`);
1919
+ }
1920
+ if (queuedJson) {
1921
+ // Queued -> pending through the same atomic claim gate as organic
1922
+ // matching; losing it means a concurrent pass just took the
1923
+ // assignment.
1924
+ const tagsCsv = (await this.redisClient.hGet(this.keys.assignmentTags(assignmentId), 'tags')) ?? '';
1925
+ const claimed = await this.claimSelected(user, [{ id: assignmentId, tags: tagsCsv }]);
1926
+ if (!claimed.has(assignmentId)) {
1927
+ throw new Error(`Assignment is no longer available: ${assignmentId}`);
1928
+ }
1929
+ await this.redisClient.sAdd(this.keys.userAssignments(userId), `assignment:${assignmentId}`);
1930
+ }
1931
+ else {
1932
+ // Pending under another user: transfer ownership and restart the
1933
+ // expiry clock for the new owner.
1934
+ const transfer = this.redisClient
1935
+ .multi()
1936
+ .sRem(this.keys.userAssignments(previousOwnerId), `assignment:${assignmentId}`)
1937
+ .sAdd(this.keys.userAssignments(userId), `assignment:${assignmentId}`)
1938
+ .hSet(this.assignmentOwnerKey, assignmentId, userId)
1939
+ .zAdd(this.pendingAssignmentsExpiryKey, {
1940
+ score: Date.now() + this.matchExpirationMs,
1941
+ value: assignmentId,
1942
+ });
1943
+ await transfer.exec();
1944
+ }
1945
+ await this.touchUser(userId);
1946
+ await this.recordManualAssignTrace(assignmentId, userId, force, previousOwnerId ?? null);
1947
+ return { previousOwnerId: previousOwnerId ?? null };
1948
+ }
1949
+ /** Audit record for an assignToUser() override; failures never break the assignment. */
1950
+ async recordManualAssignTrace(assignmentId, userId, force, previousOwnerId) {
1951
+ if (!this.tracingActive)
1952
+ return;
1953
+ try {
1954
+ await this.decisionTraces.record([
1955
+ {
1956
+ id: (0, crypto_1.randomUUID)(),
1957
+ assignmentId,
1958
+ chosenUserId: userId,
1959
+ matchedAt: Date.now(),
1960
+ mode: 'manual',
1961
+ candidates: [
1962
+ {
1963
+ userId,
1964
+ eligible: true,
1965
+ chosen: true,
1966
+ score: 0,
1967
+ effectivePriority: 0,
1968
+ reasons: [{ kind: 'manualAssignment', force, previousOwnerId }],
1969
+ },
1970
+ ],
1971
+ },
1972
+ ], this.enableDecisionTraces);
1973
+ }
1974
+ catch (err) {
1975
+ console.error('Failed to record manual assignment trace:', err);
1976
+ }
1977
+ }
1326
1978
  async acceptAssignment(userId, assignmentId) {
1327
1979
  await this.readyPromise;
1328
1980
  const isAssigned = await this.redisClient.sIsMember(this.keys.userAssignments(userId), `assignment:${assignmentId}`);
@@ -1335,6 +1987,8 @@ class AssignmentMatcher {
1335
1987
  multi.hDel(this.pendingAssignmentsKey, assignmentId);
1336
1988
  multi.zRem(this.pendingAssignmentsExpiryKey, assignmentId);
1337
1989
  multi.hDel(this.assignmentOwnerKey, assignmentId);
1990
+ // The wait clock stops when a user takes the work
1991
+ multi.zRem(this.keys.assignmentsQueuedAt(), assignmentId);
1338
1992
  // Store in accepted assignments
1339
1993
  if (json) {
1340
1994
  multi.hSet(this.acceptedAssignmentsKey, assignmentId, json);
@@ -1486,6 +2140,14 @@ class AssignmentMatcher {
1486
2140
  await this.readyPromise;
1487
2141
  return this.workflow.listWorkflowDefinitions();
1488
2142
  }
2143
+ /**
2144
+ * Delete a workflow definition by ID. Running instances are unaffected
2145
+ * (they carry their own snapshot). Returns `false` if it did not exist.
2146
+ */
2147
+ async deleteWorkflowDefinition(id) {
2148
+ await this.readyPromise;
2149
+ return this.workflow.deleteWorkflowDefinition(id);
2150
+ }
1489
2151
  /**
1490
2152
  * Register and start a workflow in one call, or start an already-registered workflow by ID.
1491
2153
  */
@@ -1677,8 +2339,12 @@ class AssignmentMatcher {
1677
2339
  return [];
1678
2340
  const cutoff = Date.now() - this.idleUserTimeoutMs;
1679
2341
  const idleCandidates = await this.redisClient.zRangeByScore(this.keys.userActivity(), '-inf', cutoff);
2342
+ // Paused users are deliberately absent, not idle - never auto-remove them.
2343
+ const paused = new Set(await this.redisClient.sMembers(this.keys.pausedUsers()));
1680
2344
  const removed = [];
1681
2345
  for (const userId of idleCandidates) {
2346
+ if (paused.has(userId))
2347
+ continue;
1682
2348
  // Skip users no longer in the pool (clean up stale activity entry)
1683
2349
  const exists = await this.redisClient.hExists(this.usersKey, userId);
1684
2350
  if (!exists) {