assignment-user-matcher 1.9.0 → 1.11.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 (166) hide show
  1. package/README.md +164 -10
  2. package/dist/index.d.ts +2 -1
  3. package/dist/index.d.ts.map +1 -1
  4. package/dist/index.js +19 -1
  5. package/dist/learning/auto-weights.d.ts +7 -4
  6. package/dist/learning/auto-weights.d.ts.map +1 -1
  7. package/dist/learning/auto-weights.js +7 -6
  8. package/dist/lua/workflow-transition.lua +8 -2
  9. package/dist/managers/LearningManager.d.ts.map +1 -1
  10. package/dist/managers/LearningManager.js +47 -0
  11. package/dist/managers/WorkflowManager.d.ts +7 -1
  12. package/dist/managers/WorkflowManager.d.ts.map +1 -1
  13. package/dist/managers/WorkflowManager.js +85 -12
  14. package/dist/matcher.class.d.ts +35 -3
  15. package/dist/matcher.class.d.ts.map +1 -1
  16. package/dist/matcher.class.js +319 -76
  17. package/dist/queries/users.d.ts +34 -0
  18. package/dist/queries/users.d.ts.map +1 -0
  19. package/dist/queries/users.js +227 -0
  20. package/dist/scheduling/constraints/availability.d.ts +43 -0
  21. package/dist/scheduling/constraints/availability.d.ts.map +1 -0
  22. package/dist/scheduling/constraints/availability.js +165 -0
  23. package/dist/scheduling/constraints/consecutive.d.ts +25 -0
  24. package/dist/scheduling/constraints/consecutive.d.ts.map +1 -0
  25. package/dist/scheduling/constraints/consecutive.js +215 -0
  26. package/dist/scheduling/constraints/constraint.d.ts +35 -0
  27. package/dist/scheduling/constraints/constraint.d.ts.map +1 -0
  28. package/dist/scheduling/constraints/constraint.js +97 -0
  29. package/dist/scheduling/constraints/contract.d.ts +21 -0
  30. package/dist/scheduling/constraints/contract.d.ts.map +1 -0
  31. package/dist/scheduling/constraints/contract.js +120 -0
  32. package/dist/scheduling/constraints/cost.d.ts +18 -0
  33. package/dist/scheduling/constraints/cost.d.ts.map +1 -0
  34. package/dist/scheduling/constraints/cost.js +65 -0
  35. package/dist/scheduling/constraints/daily-rest.d.ts +22 -0
  36. package/dist/scheduling/constraints/daily-rest.d.ts.map +1 -0
  37. package/dist/scheduling/constraints/daily-rest.js +123 -0
  38. package/dist/scheduling/constraints/duty-quota.d.ts +20 -0
  39. package/dist/scheduling/constraints/duty-quota.d.ts.map +1 -0
  40. package/dist/scheduling/constraints/duty-quota.js +95 -0
  41. package/dist/scheduling/constraints/engagement-floor.d.ts +28 -0
  42. package/dist/scheduling/constraints/engagement-floor.d.ts.map +1 -0
  43. package/dist/scheduling/constraints/engagement-floor.js +79 -0
  44. package/dist/scheduling/constraints/fairness.d.ts +34 -0
  45. package/dist/scheduling/constraints/fairness.d.ts.map +1 -0
  46. package/dist/scheduling/constraints/fairness.js +149 -0
  47. package/dist/scheduling/constraints/group-composition.d.ts +19 -0
  48. package/dist/scheduling/constraints/group-composition.d.ts.map +1 -0
  49. package/dist/scheduling/constraints/group-composition.js +92 -0
  50. package/dist/scheduling/constraints/hour-budget.d.ts +13 -0
  51. package/dist/scheduling/constraints/hour-budget.d.ts.map +1 -0
  52. package/dist/scheduling/constraints/hour-budget.js +65 -0
  53. package/dist/scheduling/constraints/in-shift-breaks.d.ts +24 -0
  54. package/dist/scheduling/constraints/in-shift-breaks.d.ts.map +1 -0
  55. package/dist/scheduling/constraints/in-shift-breaks.js +99 -0
  56. package/dist/scheduling/constraints/intervals.d.ts +5 -0
  57. package/dist/scheduling/constraints/intervals.d.ts.map +1 -0
  58. package/dist/scheduling/constraints/intervals.js +17 -0
  59. package/dist/scheduling/constraints/max-shift-duration.d.ts +7 -0
  60. package/dist/scheduling/constraints/max-shift-duration.d.ts.map +1 -0
  61. package/dist/scheduling/constraints/max-shift-duration.js +38 -0
  62. package/dist/scheduling/constraints/min-rest.d.ts +22 -0
  63. package/dist/scheduling/constraints/min-rest.d.ts.map +1 -0
  64. package/dist/scheduling/constraints/min-rest.js +49 -0
  65. package/dist/scheduling/constraints/min-staffing.d.ts +14 -0
  66. package/dist/scheduling/constraints/min-staffing.d.ts.map +1 -0
  67. package/dist/scheduling/constraints/min-staffing.js +59 -0
  68. package/dist/scheduling/constraints/night-work.d.ts +24 -0
  69. package/dist/scheduling/constraints/night-work.d.ts.map +1 -0
  70. package/dist/scheduling/constraints/night-work.js +179 -0
  71. package/dist/scheduling/constraints/no-overlap.d.ts +11 -0
  72. package/dist/scheduling/constraints/no-overlap.d.ts.map +1 -0
  73. package/dist/scheduling/constraints/no-overlap.js +35 -0
  74. package/dist/scheduling/constraints/notice.d.ts +44 -0
  75. package/dist/scheduling/constraints/notice.d.ts.map +1 -0
  76. package/dist/scheduling/constraints/notice.js +140 -0
  77. package/dist/scheduling/constraints/one-shift-per-day.d.ts +7 -0
  78. package/dist/scheduling/constraints/one-shift-per-day.d.ts.map +1 -0
  79. package/dist/scheduling/constraints/one-shift-per-day.js +35 -0
  80. package/dist/scheduling/constraints/overtime.d.ts +47 -0
  81. package/dist/scheduling/constraints/overtime.d.ts.map +1 -0
  82. package/dist/scheduling/constraints/overtime.js +149 -0
  83. package/dist/scheduling/constraints/protections.d.ts +21 -0
  84. package/dist/scheduling/constraints/protections.d.ts.map +1 -0
  85. package/dist/scheduling/constraints/protections.js +93 -0
  86. package/dist/scheduling/constraints/qualification.d.ts +18 -0
  87. package/dist/scheduling/constraints/qualification.d.ts.map +1 -0
  88. package/dist/scheduling/constraints/qualification.js +78 -0
  89. package/dist/scheduling/constraints/rest-days.d.ts +30 -0
  90. package/dist/scheduling/constraints/rest-days.d.ts.map +1 -0
  91. package/dist/scheduling/constraints/rest-days.js +133 -0
  92. package/dist/scheduling/constraints/rolling-hours.d.ts +24 -0
  93. package/dist/scheduling/constraints/rolling-hours.d.ts.map +1 -0
  94. package/dist/scheduling/constraints/rolling-hours.js +147 -0
  95. package/dist/scheduling/constraints/start-interval.d.ts +20 -0
  96. package/dist/scheduling/constraints/start-interval.d.ts.map +1 -0
  97. package/dist/scheduling/constraints/start-interval.js +53 -0
  98. package/dist/scheduling/constraints/support.d.ts +48 -0
  99. package/dist/scheduling/constraints/support.d.ts.map +1 -0
  100. package/dist/scheduling/constraints/support.js +97 -0
  101. package/dist/scheduling/constraints/time-off.d.ts +7 -0
  102. package/dist/scheduling/constraints/time-off.d.ts.map +1 -0
  103. package/dist/scheduling/constraints/time-off.js +42 -0
  104. package/dist/scheduling/constraints/weekly-rest.d.ts +22 -0
  105. package/dist/scheduling/constraints/weekly-rest.d.ts.map +1 -0
  106. package/dist/scheduling/constraints/weekly-rest.js +103 -0
  107. package/dist/scheduling/cost.d.ts +56 -0
  108. package/dist/scheduling/cost.d.ts.map +1 -0
  109. package/dist/scheduling/cost.js +120 -0
  110. package/dist/scheduling/engine/construction.d.ts +22 -0
  111. package/dist/scheduling/engine/construction.d.ts.map +1 -0
  112. package/dist/scheduling/engine/construction.js +104 -0
  113. package/dist/scheduling/engine/explain.d.ts +12 -0
  114. package/dist/scheduling/engine/explain.d.ts.map +1 -0
  115. package/dist/scheduling/engine/explain.js +24 -0
  116. package/dist/scheduling/engine/objective.d.ts +73 -0
  117. package/dist/scheduling/engine/objective.d.ts.map +1 -0
  118. package/dist/scheduling/engine/objective.js +164 -0
  119. package/dist/scheduling/engine/prng.d.ts +5 -0
  120. package/dist/scheduling/engine/prng.d.ts.map +1 -0
  121. package/dist/scheduling/engine/prng.js +24 -0
  122. package/dist/scheduling/engine/propagation.d.ts +19 -0
  123. package/dist/scheduling/engine/propagation.d.ts.map +1 -0
  124. package/dist/scheduling/engine/propagation.js +40 -0
  125. package/dist/scheduling/engine/search.d.ts +50 -0
  126. package/dist/scheduling/engine/search.d.ts.map +1 -0
  127. package/dist/scheduling/engine/search.js +127 -0
  128. package/dist/scheduling/engine/state.d.ts +28 -0
  129. package/dist/scheduling/engine/state.d.ts.map +1 -0
  130. package/dist/scheduling/engine/state.js +96 -0
  131. package/dist/scheduling/engine/timeline.d.ts +179 -0
  132. package/dist/scheduling/engine/timeline.d.ts.map +1 -0
  133. package/dist/scheduling/engine/timeline.js +416 -0
  134. package/dist/scheduling/engine/verdicts.d.ts +18 -0
  135. package/dist/scheduling/engine/verdicts.d.ts.map +1 -0
  136. package/dist/scheduling/engine/verdicts.js +74 -0
  137. package/dist/scheduling/index.d.ts +10 -0
  138. package/dist/scheduling/index.d.ts.map +1 -0
  139. package/dist/scheduling/index.js +29 -0
  140. package/dist/scheduling/model.d.ts +53 -0
  141. package/dist/scheduling/model.d.ts.map +1 -0
  142. package/dist/scheduling/model.js +380 -0
  143. package/dist/scheduling/operations.d.ts +134 -0
  144. package/dist/scheduling/operations.d.ts.map +1 -0
  145. package/dist/scheduling/operations.js +376 -0
  146. package/dist/scheduling/provenance.d.ts +33 -0
  147. package/dist/scheduling/provenance.d.ts.map +1 -0
  148. package/dist/scheduling/provenance.js +70 -0
  149. package/dist/scheduling/rules.d.ts +23 -0
  150. package/dist/scheduling/rules.d.ts.map +1 -0
  151. package/dist/scheduling/rules.js +37 -0
  152. package/dist/scheduling/scheduler.class.d.ts +24 -0
  153. package/dist/scheduling/scheduler.class.d.ts.map +1 -0
  154. package/dist/scheduling/scheduler.class.js +150 -0
  155. package/dist/scheduling/time.d.ts +138 -0
  156. package/dist/scheduling/time.d.ts.map +1 -0
  157. package/dist/scheduling/time.js +267 -0
  158. package/dist/scheduling/types.d.ts +938 -0
  159. package/dist/scheduling/types.d.ts.map +1 -0
  160. package/dist/scheduling/types.js +19 -0
  161. package/dist/types/matcher.d.ts +86 -2
  162. package/dist/types/matcher.d.ts.map +1 -1
  163. package/dist/utils/keys.d.ts +1 -0
  164. package/dist/utils/keys.d.ts.map +1 -1
  165. package/dist/utils/keys.js +6 -0
  166. package/package.json +4 -2
@@ -7,6 +7,7 @@ const cidr_1 = require("./utils/cidr");
7
7
  const geo_1 = require("./utils/geo");
8
8
  const keys_1 = require("./utils/keys");
9
9
  const pagination_1 = require("./queries/pagination");
10
+ const users_1 = require("./queries/users");
10
11
  const match_score_1 = require("./scoring/match-score");
11
12
  const fair_arbitration_1 = require("./scoring/fair-arbitration");
12
13
  const policy_1 = require("./escalation/policy");
@@ -297,7 +298,9 @@ class AssignmentMatcher {
297
298
  async loadLuaScripts() {
298
299
  try {
299
300
  this.luaScriptSha = await this.redisClient.scriptLoad(WORKFLOW_TRANSITION_LUA);
300
- this.workflow.setLuaScriptSha(this.luaScriptSha);
301
+ // The source rides along so a NOSCRIPT after a Redis restart can
302
+ // be answered with a re-load instead of bricking every transition.
303
+ this.workflow.setLuaScriptSha(this.luaScriptSha, WORKFLOW_TRANSITION_LUA);
301
304
  }
302
305
  catch (err) {
303
306
  console.error('Failed to load Lua scripts:', err);
@@ -1126,7 +1129,13 @@ class AssignmentMatcher {
1126
1129
  const existingForSynthesis = user.routingWeights
1127
1130
  ? Object.fromEntries(Object.entries(user.routingWeights).filter(([tag]) => !(tag in previousLearned)))
1128
1131
  : undefined;
1129
- const learned = await this.learning.getLearnedRoutingWeights(id, knownTags, existingForSynthesis);
1132
+ // The user's own declared tags are always known: once the sync
1133
+ // installs a routingWeights map, only positive entries match, so a
1134
+ // declared tag the learner has no data for would silently stop
1135
+ // matching forever. Including it here gives it the exploration
1136
+ // prior instead.
1137
+ const userKnownTags = [...new Set([...(knownTags ?? []), ...(user.tags ?? [])])];
1138
+ const learned = await this.learning.getLearnedRoutingWeights(id, userKnownTags.length > 0 ? userKnownTags : undefined, existingForSynthesis);
1130
1139
  if (Object.keys(learned).length === 0)
1131
1140
  continue;
1132
1141
  // Apply per-sync step clamp. Vetoes (weight 0) that passed the
@@ -1164,7 +1173,11 @@ class AssignmentMatcher {
1164
1173
  await this.redisClient.hSet(this.usersKey, id, JSON.stringify({
1165
1174
  ...user,
1166
1175
  routingWeights,
1167
- routingWeightsSnapshot: user.routingWeights,
1176
+ // `null` (not undefined) for a previously weightless user:
1177
+ // undefined is dropped by JSON, which made the sync
1178
+ // irreversible for exactly the tag-based users it affects
1179
+ // the most. Revert restores tag-based matching from null.
1180
+ routingWeightsSnapshot: user.routingWeights ?? null,
1168
1181
  learnedRoutingWeights: clampedLearned,
1169
1182
  learnedRoutingWeightsSyncedAt: Date.now(),
1170
1183
  }));
@@ -1189,7 +1202,7 @@ class AssignmentMatcher {
1189
1202
  for (const [id, json] of Object.entries(all)) {
1190
1203
  try {
1191
1204
  const u = JSON.parse(json);
1192
- if (u.routingWeightsSnapshot)
1205
+ if (u.routingWeightsSnapshot !== undefined)
1193
1206
  targets.push(id);
1194
1207
  }
1195
1208
  catch {
@@ -1203,11 +1216,13 @@ class AssignmentMatcher {
1203
1216
  if (!userJson)
1204
1217
  continue;
1205
1218
  const user = JSON.parse(userJson);
1206
- if (!user.routingWeightsSnapshot)
1219
+ // A `null` snapshot means "had no routingWeights before the sync"
1220
+ // — reverting restores tag-based matching by dropping the map.
1221
+ if (user.routingWeightsSnapshot === undefined)
1207
1222
  continue;
1208
1223
  await this.redisClient.hSet(this.usersKey, id, JSON.stringify({
1209
1224
  ...user,
1210
- routingWeights: user.routingWeightsSnapshot,
1225
+ routingWeights: user.routingWeightsSnapshot ?? undefined,
1211
1226
  routingWeightsSnapshot: undefined,
1212
1227
  learnedRoutingWeights: undefined,
1213
1228
  learnedRoutingWeightsSyncedAt: undefined,
@@ -1255,7 +1270,10 @@ class AssignmentMatcher {
1255
1270
  }
1256
1271
  /** All known tags except the internal 'default' tag (for exploration priors) */
1257
1272
  async getKnownTagsForAutoWeights() {
1258
- const tags = await this.redisClient.sMembers(this.allTagsKey);
1273
+ // allTags is a ZSET (zAdd in enqueueAssignment, zRangeByLex in wildcard
1274
+ // expansion) — an SMEMBERS read threw WRONGTYPE on any deployment that
1275
+ // had ever enqueued an assignment.
1276
+ const tags = await this.redisClient.zRange(this.allTagsKey, 0, -1);
1259
1277
  return tags.filter((t) => t !== 'default');
1260
1278
  }
1261
1279
  // ============================================================================
@@ -1398,12 +1416,26 @@ class AssignmentMatcher {
1398
1416
  const assignmentPriorityKey = this.keys.assignmentPriority(id);
1399
1417
  const assignmentTagsKey = this.keys.assignmentTags(id);
1400
1418
  const assignmentGeoKey = this.keys.assignmentsGeo();
1401
- // Fetch tags, owner (in case it's pending), and vetoed users for index cleanup
1402
- const [tagsCsv, owner, vetoedUsers] = await Promise.all([
1419
+ // Fetch tags, owner (in case it's pending), accepted JSON (for the
1420
+ // per-user accepted index), and vetoed users for index cleanup
1421
+ const [tagsCsv, owner, acceptedJson, vetoedUsers] = await Promise.all([
1403
1422
  this.redisClient.hGet(assignmentTagsKey, 'tags'),
1404
1423
  this.redisClient.hGet(this.assignmentOwnerKey, id),
1424
+ this.redisClient.hGet(this.acceptedAssignmentsKey, id),
1405
1425
  this.redisClient.sMembers(this.keys.assignmentVetoed(id)),
1406
1426
  ]);
1427
+ // Best-effort owner of the accepted record: only SLA-bearing items
1428
+ // carry _acceptedBy, so a non-SLA accepted assignment leaves a stale
1429
+ // per-user index member here — reads filter it out and self-heal.
1430
+ let acceptedBy = null;
1431
+ if (acceptedJson && acceptedJson.indexOf('"sla"') !== -1) {
1432
+ try {
1433
+ acceptedBy = JSON.parse(acceptedJson)[policy_2.SLA_ACCEPTED_BY_FIELD] ?? null;
1434
+ }
1435
+ catch {
1436
+ // keep null on parse failure
1437
+ }
1438
+ }
1407
1439
  let tags = [];
1408
1440
  if (tagsCsv && tagsCsv.length > 0) {
1409
1441
  tags = tagsCsv.split(',');
@@ -1432,6 +1464,9 @@ class AssignmentMatcher {
1432
1464
  }
1433
1465
  // 3. Remove from Accepted state
1434
1466
  multi.hDel(this.acceptedAssignmentsKey, id);
1467
+ if (acceptedBy) {
1468
+ multi.zRem(this.keys.userAcceptedAssignments(acceptedBy), id);
1469
+ }
1435
1470
  // 4. Clear SLA indexes (no-ops for non-SLA assignments)
1436
1471
  multi.zRem(this.acceptedAssignmentsExpiryKey, id);
1437
1472
  multi.zRem(this.assignmentsSlaExpiryKey, id);
@@ -1449,6 +1484,7 @@ class AssignmentMatcher {
1449
1484
  .del(this.keys.userAssignments(userId))
1450
1485
  .del(this.keys.userRejected(userId))
1451
1486
  .del(this.keys.userVetoed(userId))
1487
+ .del(this.keys.userAcceptedAssignments(userId))
1452
1488
  .zRem(this.keys.userActivity(), userId)
1453
1489
  .sRem(this.keys.pausedUsers(), userId)
1454
1490
  .hDel(this.usersKey, userId);
@@ -1480,11 +1516,58 @@ class AssignmentMatcher {
1480
1516
  let cursor = '0';
1481
1517
  do {
1482
1518
  const { cursor: nextCursor, entries } = await this.redisClient.hScan(this.usersKey, cursor, { COUNT: 500 });
1483
- users.push(...entries.map((t) => JSON.parse(t.value)));
1519
+ for (const entry of entries) {
1520
+ try {
1521
+ users.push(JSON.parse(entry.value));
1522
+ }
1523
+ catch {
1524
+ // Skip corrupt entries (same precedent as getAllAssignmentsFromStores)
1525
+ }
1526
+ }
1484
1527
  cursor = nextCursor;
1485
1528
  } while (cursor !== '0');
1486
1529
  return users;
1487
1530
  }
1531
+ /**
1532
+ * Paginated user query with composable status/workload filters
1533
+ * (`status`, `idleForMs`, `hasBacklog`, `atCapacity`). All reads are
1534
+ * bounded: the users hash is paged with HSCAN and per-page metadata is
1535
+ * batched into one multi(). A scan page is never split, so a page may
1536
+ * exceed `limit` by less than one scan page, and filtered scans may
1537
+ * return short pages with `hasMore: true` — keep consuming until
1538
+ * `hasMore` is false. `status: 'idle'` without an explicit `idleForMs`
1539
+ * falls back to the matcher's `idleUserTimeoutMs` (matches nobody when
1540
+ * that is not configured either).
1541
+ */
1542
+ async getUsersPaginated(options) {
1543
+ await this.readyPromise;
1544
+ const resolved = options ? { ...options } : undefined;
1545
+ if (resolved && resolved.idleForMs === undefined && resolved.status === 'idle' && this.idleUserTimeoutMs !== null) {
1546
+ resolved.idleForMs = this.idleUserTimeoutMs;
1547
+ }
1548
+ return (0, users_1.getUsersPaginatedFromStore)(this.redisClient, this.keys, resolved, (user) => this.backlogLimitFor(user));
1549
+ }
1550
+ /**
1551
+ * Order-preserving workload summaries for a known set of user ids
1552
+ * (chunked pipelined reads). Missing or corrupt user records are omitted.
1553
+ */
1554
+ async getUserSummaries(userIds) {
1555
+ await this.readyPromise;
1556
+ return (0, users_1.getUserSummariesBatch)(this.redisClient, this.keys, userIds, (user) => this.backlogLimitFor(user));
1557
+ }
1558
+ /**
1559
+ * A user's accepted (in-progress) assignments, newest first, backed by
1560
+ * the per-user accepted index. Verified against the accepted store, so
1561
+ * stale index members (e.g. left by a `removeAssignment` on a non-SLA
1562
+ * assignment, or by an older library version) are dropped and self-healed.
1563
+ *
1564
+ * Note: the index is maintained from the version that introduced it —
1565
+ * accepted work that predates it appears only after it cycles.
1566
+ */
1567
+ async getActiveAssignmentsForUser(userId) {
1568
+ await this.readyPromise;
1569
+ return (0, users_1.getActiveAssignmentsFromStore)(this.redisClient, this.keys, userId);
1570
+ }
1488
1571
  // ============================================================================
1489
1572
  // Worker Availability (pause/resume)
1490
1573
  // ============================================================================
@@ -1601,15 +1684,35 @@ class AssignmentMatcher {
1601
1684
  let cursor = '0';
1602
1685
  do {
1603
1686
  const { cursor: nextCursor, entries } = await this.redisClient.hScan(this.usersKey, cursor, { COUNT: 500 });
1604
- users.push(...entries.map((t) => JSON.parse(t.value)));
1687
+ for (const entry of entries) {
1688
+ try {
1689
+ users.push(JSON.parse(entry.value));
1690
+ }
1691
+ catch {
1692
+ // Skip corrupt entries (same precedent as getAllAssignmentsFromStores)
1693
+ }
1694
+ }
1605
1695
  cursor = nextCursor;
1606
1696
  } while (cursor !== '0');
1607
- const perUser = await Promise.all(users.map(async (user) => ({
1608
- userId: user.id,
1609
- backlog: await this.redisClient.sCard(this.keys.userAssignments(user.id)),
1610
- maxBacklogSize: this.backlogLimitFor(user),
1611
- paused: paused.has(user.id),
1612
- })));
1697
+ // Chunked pipelined backlog reads — one multi() per 500 users keeps
1698
+ // pipelines bounded when the pool grows.
1699
+ const perUser = [];
1700
+ for (let start = 0; start < users.length; start += 500) {
1701
+ const chunk = users.slice(start, start + 500);
1702
+ const multi = this.redisClient.multi();
1703
+ for (const user of chunk) {
1704
+ multi.sCard(this.keys.userAssignments(user.id));
1705
+ }
1706
+ const backlogs = (await multi.exec());
1707
+ for (let i = 0; i < chunk.length; i++) {
1708
+ perUser.push({
1709
+ userId: chunk[i].id,
1710
+ backlog: Number(backlogs[i] ?? 0),
1711
+ maxBacklogSize: this.backlogLimitFor(chunk[i]),
1712
+ paused: paused.has(chunk[i].id),
1713
+ });
1714
+ }
1715
+ }
1613
1716
  perUser.sort((a, b) => a.userId.localeCompare(b.userId));
1614
1717
  return {
1615
1718
  queued: counts.queued,
@@ -1621,43 +1724,79 @@ class AssignmentMatcher {
1621
1724
  }
1622
1725
  /**
1623
1726
  * Get all pending assignments with owner and pending duration metadata.
1727
+ * Reads are bounded: the pending hash is paged with HSCAN and each page's
1728
+ * owner/expiry lookups are batched. Pass `{ limit }` (clamped to 1000) to
1729
+ * hydrate only the top-N longest-pending assignments instead of every one.
1624
1730
  */
1625
- async getPendingAssignmentsWithAge() {
1731
+ async getPendingAssignmentsWithAge(options) {
1626
1732
  await this.readyPromise;
1627
1733
  const now = Date.now();
1628
- const pendingEntries = await this.redisClient.hGetAll(this.pendingAssignmentsKey);
1629
- const assignmentIds = Object.keys(pendingEntries);
1630
- if (assignmentIds.length === 0) {
1734
+ const metas = [];
1735
+ // HSCAN may repeat a field across pages under a concurrent rehash;
1736
+ // the listing must not repeat an assignment.
1737
+ const seen = new Set();
1738
+ let cursor = '0';
1739
+ do {
1740
+ const { cursor: nextCursor, entries: rawEntries } = await this.redisClient.hScan(this.pendingAssignmentsKey, cursor, { COUNT: 500 });
1741
+ cursor = nextCursor;
1742
+ const entries = rawEntries.filter((entry) => !seen.has(entry.field));
1743
+ if (entries.length === 0)
1744
+ continue;
1745
+ for (const entry of entries)
1746
+ seen.add(entry.field);
1747
+ const pageIds = entries.map((entry) => entry.field);
1748
+ const owners = await this.redisClient.hmGet(this.assignmentOwnerKey, pageIds);
1749
+ const multi = this.redisClient.multi();
1750
+ for (const id of pageIds) {
1751
+ multi.zScore(this.pendingAssignmentsExpiryKey, id);
1752
+ }
1753
+ const expiryScores = (await multi.exec());
1754
+ for (let i = 0; i < entries.length; i++) {
1755
+ const json = entries[i].value;
1756
+ if (!json)
1757
+ continue;
1758
+ const score = expiryScores[i];
1759
+ const expiresAt = score === null || score === undefined ? null : Number(score);
1760
+ const pendingSince = expiresAt === null ? null : expiresAt - this.matchExpirationMs;
1761
+ const pendingForMs = pendingSince === null ? null : Math.max(0, now - pendingSince);
1762
+ metas.push({ json, ownerId: owners[i] ?? null, pendingForMs, pendingSince, expiresAt });
1763
+ }
1764
+ } while (cursor !== '0');
1765
+ if (metas.length === 0) {
1631
1766
  return [];
1632
1767
  }
1633
- const [owners, expiryScores] = await Promise.all([
1634
- this.redisClient.hmGet(this.assignmentOwnerKey, assignmentIds),
1635
- Promise.all(assignmentIds.map((id) => this.redisClient.zScore(this.pendingAssignmentsExpiryKey, id))),
1636
- ]);
1637
- const results = [];
1638
- for (let i = 0; i < assignmentIds.length; i++) {
1639
- const id = assignmentIds[i];
1640
- const json = pendingEntries[id];
1641
- if (!json)
1642
- continue;
1643
- let assignment;
1768
+ const hydrate = (meta) => {
1644
1769
  try {
1645
- assignment = JSON.parse(json);
1770
+ return {
1771
+ assignment: JSON.parse(meta.json),
1772
+ ownerId: meta.ownerId,
1773
+ pendingForMs: meta.pendingForMs,
1774
+ pendingSince: meta.pendingSince,
1775
+ expiresAt: meta.expiresAt,
1776
+ };
1646
1777
  }
1647
1778
  catch {
1648
- continue;
1779
+ return null;
1649
1780
  }
1650
- const score = expiryScores[i];
1651
- const expiresAt = score === null ? null : Number(score);
1652
- const pendingSince = expiresAt === null ? null : expiresAt - this.matchExpirationMs;
1653
- const pendingForMs = pendingSince === null ? null : Math.max(0, now - pendingSince);
1654
- results.push({
1655
- assignment,
1656
- ownerId: owners[i] ?? null,
1657
- pendingForMs,
1658
- pendingSince,
1659
- expiresAt,
1660
- });
1781
+ };
1782
+ const limit = options?.limit;
1783
+ if (typeof limit === 'number' && Number.isFinite(limit)) {
1784
+ // Sort the (small) metadata first, then hydrate only the top N.
1785
+ const clamped = Math.max(1, Math.min(Math.floor(limit), 1000));
1786
+ const top = [...metas].sort((a, b) => (b.pendingForMs ?? -1) - (a.pendingForMs ?? -1)).slice(0, clamped);
1787
+ const results = [];
1788
+ for (const meta of top) {
1789
+ const hydrated = hydrate(meta);
1790
+ if (hydrated)
1791
+ results.push(hydrated);
1792
+ }
1793
+ return results;
1794
+ }
1795
+ const results = [];
1796
+ for (const meta of metas) {
1797
+ const hydrated = hydrate(meta);
1798
+ if (hydrated)
1799
+ results.push(hydrated);
1661
1800
  }
1662
1801
  results.sort((a, b) => (b.pendingForMs ?? -1) - (a.pendingForMs ?? -1));
1663
1802
  return results;
@@ -1756,12 +1895,23 @@ class AssignmentMatcher {
1756
1895
  return { id, priority };
1757
1896
  }
1758
1897
  async setAssignmentPriorityByTags(tags, priority) {
1759
- // Update priorities for all assignments that include any of the specified tags.
1760
- const assignments = await this.getAllAssignments();
1761
- const relevantAssignments = assignments.filter((assignment) => {
1762
- const assignmentTagSet = new Set(assignment.tags);
1763
- return tags.some((tag) => assignmentTagSet.has(tag));
1764
- });
1898
+ // Update priorities for QUEUED assignments that include any of the
1899
+ // specified tags. Pending/accepted assignments left the matching
1900
+ // indexes at claim time — re-zAdding them here would resurrect
1901
+ // permanent ghost candidates that crowd real work out of the batch.
1902
+ const queued = await this.redisClient.hGetAll(this.assignmentsRefKey);
1903
+ const relevantAssignments = [];
1904
+ for (const json of Object.values(queued)) {
1905
+ try {
1906
+ const assignment = JSON.parse(json);
1907
+ const assignmentTagSet = new Set(assignment.tags);
1908
+ if (tags.some((tag) => assignmentTagSet.has(tag)))
1909
+ relevantAssignments.push(assignment);
1910
+ }
1911
+ catch {
1912
+ // Skip corrupt entries (same precedent as getAllAssignmentsFromStores)
1913
+ }
1914
+ }
1765
1915
  if (relevantAssignments.length > 0) {
1766
1916
  const multi = this.redisClient.multi();
1767
1917
  for (const assignment of relevantAssignments) {
@@ -1778,6 +1928,23 @@ class AssignmentMatcher {
1778
1928
  }
1779
1929
  }
1780
1930
  await multi.exec();
1931
+ // The snapshot read above races the atomic claim gate (same
1932
+ // pattern as setAssignmentPriority): undo any ghost the writes
1933
+ // resurrected for assignments claimed since the read.
1934
+ const ids = relevantAssignments.map((a) => a.id);
1935
+ const owners = await this.redisClient.hmGet(this.assignmentOwnerKey, ids);
1936
+ const ghosts = relevantAssignments.filter((_, i) => owners[i]);
1937
+ if (ghosts.length > 0) {
1938
+ const cleanup = this.redisClient.multi();
1939
+ for (const assignment of ghosts) {
1940
+ cleanup.zRem(this.assignmentsKey, assignment.id);
1941
+ const idxTags = [...assignment.tags, ...(this.enableDefaultMatching ? ['default'] : [])];
1942
+ for (const tag of idxTags) {
1943
+ cleanup.zRem(this.keys.tagAssignments(tag), assignment.id);
1944
+ }
1945
+ }
1946
+ await cleanup.exec();
1947
+ }
1781
1948
  }
1782
1949
  return relevantAssignments.map((assignment) => ({ id: assignment.id, priority }));
1783
1950
  }
@@ -1807,17 +1974,25 @@ class AssignmentMatcher {
1807
1974
  const own = user.maxBacklogSize;
1808
1975
  return typeof own === 'number' && Number.isFinite(own) && own >= 0 ? own : this.maxUserBacklogSize;
1809
1976
  }
1810
- async computeCandidatesForUser(user, capToBacklog = true, collector) {
1977
+ async computeCandidatesForUser(user, capToBacklog = true, collector, grantBudget) {
1811
1978
  const userAssignments = [];
1812
1979
  const routingWeights = user.routingWeights;
1813
1980
  const hasRoutingWeights = Boolean(routingWeights && Object.keys(routingWeights).length > 0);
1981
+ // The cap bounds TOTAL backlog, not new grants per pass: callers that
1982
+ // know the user's current backlog pass the remaining headroom as
1983
+ // `grantBudget` (without it, a user holding work could be topped up to
1984
+ // 2×limit−1). capToBacklog=false (the fair path) keeps the full
1985
+ // candidate set for global arbitration.
1986
+ const effectiveCap = capToBacklog
1987
+ ? Math.max(0, grantBudget ?? this.backlogLimitFor(user))
1988
+ : this.backlogLimitFor(user);
1814
1989
  // Priority 1: Check for workflow-targeted assignments (deterministic matching)
1815
1990
  if (this.enableWorkflows) {
1816
1991
  const workflowAssignments = await this.getWorkflowTargetedAssignments(user.id);
1817
1992
  if (workflowAssignments.length > 0) {
1818
1993
  // Workflow assignments take precedence - add them first with highest priority
1819
1994
  userAssignments.push(...workflowAssignments);
1820
- if (userAssignments.length >= this.backlogLimitFor(user)) {
1995
+ if (userAssignments.length >= effectiveCap) {
1821
1996
  return { userAssignments, selected: [], workflowTargetedCount: userAssignments.length };
1822
1997
  }
1823
1998
  }
@@ -2012,7 +2187,7 @@ class AssignmentMatcher {
2012
2187
  }
2013
2188
  eligible.sort((a, b) => b.effectivePriority - a.effectivePriority);
2014
2189
  for (const c of eligible) {
2015
- if (capToBacklog && userAssignments.length >= this.backlogLimitFor(user))
2190
+ if (capToBacklog && userAssignments.length >= effectiveCap)
2016
2191
  break;
2017
2192
  userAssignments.push({ id: c.detail.id, priority: c.effectivePriority });
2018
2193
  selected.push({ id: c.detail.id, tags: c.detail.tags });
@@ -2021,7 +2196,7 @@ class AssignmentMatcher {
2021
2196
  }
2022
2197
  else {
2023
2198
  for (const d of details) {
2024
- if (capToBacklog && userAssignments.length >= this.backlogLimitFor(user))
2199
+ if (capToBacklog && userAssignments.length >= effectiveCap)
2025
2200
  break;
2026
2201
  // Check CIDR restrictions: if assignment has allowedCidrs, user must have matching IP
2027
2202
  if (!(0, cidr_1.checkCidrMatch)(user.ip, d.allowedCidrs)) {
@@ -2127,6 +2302,10 @@ class AssignmentMatcher {
2127
2302
  for (const tag of tags) {
2128
2303
  rm.zRem(this.keys.tagAssignments(tag), s.id);
2129
2304
  }
2305
+ // Leaving the queued universe takes the geo index entry along
2306
+ // (a requeue re-adds it via enqueue's geoAdd); without this the
2307
+ // index grows monotonically with completed work.
2308
+ rm.zRem(this.keys.assignmentsGeo(), s.id);
2130
2309
  // Add to pending structures. An assignment carrying an
2131
2310
  // EscalationPolicy sets its own response deadline; everything
2132
2311
  // else uses the matcher-wide one and never pays for a parse.
@@ -2175,11 +2354,26 @@ class AssignmentMatcher {
2175
2354
  }
2176
2355
  return claimedIds;
2177
2356
  }
2178
- async getUserRelatedAssignments(user, collector) {
2179
- const { userAssignments, selected, workflowTargetedCount } = await this.computeCandidatesForUser(user, true, collector);
2180
- const claimedIds = await this.claimSelected(user, selected);
2357
+ async getUserRelatedAssignments(user, collector, grantBudget) {
2358
+ const { userAssignments, selected, workflowTargetedCount } = await this.computeCandidatesForUser(user, true, collector, grantBudget);
2181
2359
  const workflowTargeted = userAssignments.slice(0, workflowTargetedCount);
2182
- const tagScored = userAssignments.slice(workflowTargetedCount).filter((ua) => claimedIds.has(ua.id));
2360
+ // Targeted grants go through the SAME queued→pending claim gate as
2361
+ // organic matching — a grant that only lands in the backlog set while
2362
+ // the assignment stays queued would "accept" into nothing and be
2363
+ // re-granted forever. A targeted id the tag path also selected is
2364
+ // claimed once, under its targeted entry.
2365
+ const targetedIds = new Set(workflowTargeted.map((t) => t.id));
2366
+ const claimList = [
2367
+ ...workflowTargeted.map((t) => ({ id: t.id, tags: t.tags ?? '' })),
2368
+ ...selected.filter((s) => !targetedIds.has(s.id)),
2369
+ ];
2370
+ const claimedIds = await this.claimSelected(user, claimList);
2371
+ const tagScored = userAssignments
2372
+ .slice(workflowTargetedCount)
2373
+ .filter((ua) => claimedIds.has(ua.id) && !targetedIds.has(ua.id));
2374
+ // A targeted assignment that lost the claim was already moved to
2375
+ // pending for this same user on an earlier pass — its backlog
2376
+ // membership below is an idempotent re-add, so it is never stripped.
2183
2377
  return { assignments: [...workflowTargeted, ...tagScored], claimedIds, workflowTargeted };
2184
2378
  }
2185
2379
  /**
@@ -2279,7 +2473,8 @@ class AssignmentMatcher {
2279
2473
  }));
2280
2474
  // Workflow-targeted assignments are deterministically targeted at one
2281
2475
  // user each - not contested across users - so claim them immediately,
2282
- // exactly like the non-fair path does.
2476
+ // exactly like the non-fair path does: through the claimSelected gate
2477
+ // (queued→pending with an owner), then the backlog membership.
2283
2478
  await Promise.all(perUser.map(async ({ user, candidates }) => {
2284
2479
  const workflowOnly = candidates.userAssignments.slice(0, candidates.workflowTargetedCount);
2285
2480
  if (workflowOnly.length === 0)
@@ -2288,6 +2483,7 @@ class AssignmentMatcher {
2288
2483
  // Membership must be read before the sAdd below
2289
2484
  workflowGrants.push(...(await this.filterNewWorkflowGrants(user, workflowOnly)));
2290
2485
  }
2486
+ await this.claimSelected(user, workflowOnly.map((a) => ({ id: a.id, tags: a.tags ?? '' })));
2291
2487
  await this.redisClient.sAdd(this.keys.userAssignments(user.id), workflowOnly.map((a) => `assignment:${a.id}`));
2292
2488
  }));
2293
2489
  // Flatten every user's tag-scored candidates into one global list of
@@ -2406,7 +2602,7 @@ class AssignmentMatcher {
2406
2602
  if (userMatchesCount >= this.backlogLimitFor(user))
2407
2603
  return;
2408
2604
  const collector = this.tracingActive ? new decision_trace_1.TraceCollector() : undefined;
2409
- const { assignments, claimedIds, workflowTargeted } = await this.getUserRelatedAssignments(user, collector);
2605
+ const { assignments, claimedIds, workflowTargeted } = await this.getUserRelatedAssignments(user, collector, this.backlogLimitFor(user) - userMatchesCount);
2410
2606
  // Membership must be read before the sAdd below
2411
2607
  const newWorkflowGrants = collector ? await this.filterNewWorkflowGrants(user, workflowTargeted) : [];
2412
2608
  const relevantAssignmentKeys = assignments
@@ -2447,7 +2643,7 @@ class AssignmentMatcher {
2447
2643
  if (userMatchesCount >= this.backlogLimitFor(user)) {
2448
2644
  return;
2449
2645
  }
2450
- const { assignments, claimedIds, workflowTargeted } = await this.getUserRelatedAssignments(user, collector);
2646
+ const { assignments, claimedIds, workflowTargeted } = await this.getUserRelatedAssignments(user, collector, this.backlogLimitFor(user) - userMatchesCount);
2451
2647
  if (collector) {
2452
2648
  for (const id of claimedIds)
2453
2649
  winners.set(id, user.id);
@@ -2667,6 +2863,10 @@ class AssignmentMatcher {
2667
2863
  }
2668
2864
  }
2669
2865
  multi.hSet(this.acceptedAssignmentsKey, assignmentId, acceptedJson);
2866
+ // Per-user accepted-work index (raw id, score = accept time).
2867
+ // Inside the guard: an accept whose pending JSON is missing stores
2868
+ // nothing, so it must index nothing.
2869
+ multi.zAdd(this.keys.userAcceptedAssignments(userId), { score: now, value: assignmentId });
2670
2870
  }
2671
2871
  await multi.exec();
2672
2872
  // SLO accept stats piggyback the accept path (internally guarded:
@@ -2796,6 +2996,7 @@ class AssignmentMatcher {
2796
2996
  // Move from accepted to completed
2797
2997
  const multi = this.redisClient.multi();
2798
2998
  multi.hDel(this.acceptedAssignmentsKey, assignmentId);
2999
+ multi.zRem(this.keys.userAcceptedAssignments(userId), assignmentId);
2799
3000
  // Clear SLA indexes (no-ops for non-SLA assignments)
2800
3001
  multi.zRem(this.acceptedAssignmentsExpiryKey, assignmentId);
2801
3002
  multi.zRem(this.assignmentsSlaExpiryKey, assignmentId);
@@ -2851,6 +3052,7 @@ class AssignmentMatcher {
2851
3052
  // Move from accepted to completed (with failed status)
2852
3053
  const multi = this.redisClient.multi();
2853
3054
  multi.hDel(this.acceptedAssignmentsKey, assignmentId);
3055
+ multi.zRem(this.keys.userAcceptedAssignments(userId), assignmentId);
2854
3056
  // Clear SLA indexes (no-ops for non-SLA assignments)
2855
3057
  multi.zRem(this.acceptedAssignmentsExpiryKey, assignmentId);
2856
3058
  multi.zRem(this.assignmentsSlaExpiryKey, assignmentId);
@@ -2876,6 +3078,17 @@ class AssignmentMatcher {
2876
3078
  payload: { reason },
2877
3079
  });
2878
3080
  }
3081
+ // Every other terminal transition emits one; this one did not, so a
3082
+ // worker-reported failure was invisible to lifecycle observers (and
3083
+ // therefore to the platform's webhooks, sockets and push) even though
3084
+ // the workflow stream above heard about it.
3085
+ this.emitAssignmentLifecycle({
3086
+ kind: 'failed',
3087
+ taskId: assignmentId,
3088
+ workerId: userId,
3089
+ reason,
3090
+ failedAt: now,
3091
+ });
2879
3092
  return true;
2880
3093
  }
2881
3094
  // ============================================================================
@@ -3240,8 +3453,10 @@ class AssignmentMatcher {
3240
3453
  }
3241
3454
  if (action === 'requeue') {
3242
3455
  const multi = this.redisClient.multi().hDel(this.acceptedAssignmentsKey, id);
3243
- if (workerId)
3456
+ if (workerId) {
3244
3457
  multi.sAdd(this.keys.userRejected(workerId), id);
3458
+ multi.zRem(this.keys.userAcceptedAssignments(workerId), id);
3459
+ }
3245
3460
  await multi.exec();
3246
3461
  // The JSON still carries _enqueuedAt, so the freshness TTL
3247
3462
  // keeps ticking across the requeue. A requeue after a
@@ -3251,7 +3466,7 @@ class AssignmentMatcher {
3251
3466
  continue;
3252
3467
  }
3253
3468
  if (action === 'fail') {
3254
- await this.redisClient
3469
+ const multi = this.redisClient
3255
3470
  .multi()
3256
3471
  .hDel(this.acceptedAssignmentsKey, id)
3257
3472
  .hSet(this.completedAssignmentsKey, id, JSON.stringify({
@@ -3261,17 +3476,21 @@ class AssignmentMatcher {
3261
3476
  _failureReason: 'completion-sla-breach',
3262
3477
  }))
3263
3478
  // Terminal: the freshness TTL no longer applies.
3264
- .zRem(this.assignmentsSlaExpiryKey, id)
3265
- .exec();
3479
+ .zRem(this.assignmentsSlaExpiryKey, id);
3480
+ if (workerId)
3481
+ multi.zRem(this.keys.userAcceptedAssignments(workerId), id);
3482
+ await multi.exec();
3266
3483
  continue;
3267
3484
  }
3268
3485
  // 'park'
3269
- await this.redisClient
3486
+ const parkMulti = this.redisClient
3270
3487
  .multi()
3271
3488
  .hDel(this.acceptedAssignmentsKey, id)
3272
3489
  .hSet(this.keys.parkedAssignments(), id, JSON.stringify(assignment))
3273
- .zRem(this.assignmentsSlaExpiryKey, id)
3274
- .exec();
3490
+ .zRem(this.assignmentsSlaExpiryKey, id);
3491
+ if (workerId)
3492
+ parkMulti.zRem(this.keys.userAcceptedAssignments(workerId), id);
3493
+ await parkMulti.exec();
3275
3494
  }
3276
3495
  return { breached };
3277
3496
  }
@@ -3328,12 +3547,14 @@ class AssignmentMatcher {
3328
3547
  await multi.exec();
3329
3548
  }
3330
3549
  else if (acceptedJson) {
3331
- await this.redisClient
3550
+ const multi = this.redisClient
3332
3551
  .multi()
3333
3552
  .hDel(this.acceptedAssignmentsKey, id)
3334
3553
  .zRem(this.acceptedAssignmentsExpiryKey, id)
3335
- .zRem(this.assignmentsSlaExpiryKey, id)
3336
- .exec();
3554
+ .zRem(this.assignmentsSlaExpiryKey, id);
3555
+ if (ownerId)
3556
+ multi.zRem(this.keys.userAcceptedAssignments(ownerId), id);
3557
+ await multi.exec();
3337
3558
  }
3338
3559
  else {
3339
3560
  // Queued: full index cleanup via removeAssignment (also zRems
@@ -3452,7 +3673,16 @@ class AssignmentMatcher {
3452
3673
  // A due notBefore falls straight through addAssignment's hold
3453
3674
  // guard into the normal enqueue, which also clears the scheduled
3454
3675
  // hash atomically with the queued write.
3455
- await this.addAssignment(JSON.parse(json));
3676
+ try {
3677
+ await this.addAssignment(JSON.parse(json));
3678
+ }
3679
+ catch (err) {
3680
+ // The zRem claim already consumed the only trigger; without
3681
+ // restoring it, a failed enqueue strands the assignment in the
3682
+ // scheduled store forever (nothing re-examines it).
3683
+ await this.redisClient.zAdd(this.scheduledActivateAtKey, { score: now, value: id });
3684
+ throw err;
3685
+ }
3456
3686
  activated++;
3457
3687
  this.emitAssignmentLifecycle({ kind: 'scheduleActivated', taskId: id, at: now });
3458
3688
  }
@@ -3508,8 +3738,12 @@ class AssignmentMatcher {
3508
3738
  delete record[policy_2.SLA_ACCEPTED_AT_FIELD];
3509
3739
  delete record[policy_2.SLA_ACCEPTED_BY_FIELD];
3510
3740
  }
3511
- await this.redisClient.hDel(this.keys.parkedAssignments(), id);
3741
+ // Re-enqueue BEFORE dropping the parked copy: the parked hash holds
3742
+ // the only copy of the JSON, so the reverse order loses the assignment
3743
+ // outright if the enqueue fails mid-flight. A crash between these two
3744
+ // leaves a duplicate (queued + parked), which a repeat unpark heals.
3512
3745
  await this.addAssignment(assignment);
3746
+ await this.redisClient.hDel(this.keys.parkedAssignments(), id);
3513
3747
  return true;
3514
3748
  }
3515
3749
  /** Current escalation level of an assignment (0 = never escalated). */
@@ -3750,18 +3984,27 @@ class AssignmentMatcher {
3750
3984
  async getWorkflowTargetedAssignments(userId) {
3751
3985
  const targeted = [];
3752
3986
  // Scan queued assignments for those with _targetUserId matching this user
3753
- const queuedAssignments = await this.redisClient.hGetAll(this.assignmentsRefKey);
3987
+ const [queuedAssignments, rejectedMembers] = await Promise.all([
3988
+ this.redisClient.hGetAll(this.assignmentsRefKey),
3989
+ this.redisClient.sMembers(this.keys.userRejected(userId)),
3990
+ ]);
3991
+ const rejected = new Set(rejectedMembers);
3754
3992
  for (const [assignmentId, json] of Object.entries(queuedAssignments)) {
3755
3993
  try {
3756
3994
  const assignment = JSON.parse(json);
3757
- // Hard veto applies even to deterministic workflow targeting
3995
+ // Hard veto applies even to deterministic workflow targeting,
3996
+ // and so does the user's own prior rejection — re-granting a
3997
+ // rejected assignment forever violates the rejection contract.
3758
3998
  if (assignment.vetoedUsers?.includes(userId))
3759
3999
  continue;
4000
+ if (rejected.has(assignmentId))
4001
+ continue;
3760
4002
  if (assignment._targetUserId === userId && assignment._workflowInstanceId) {
3761
4003
  // This is a workflow assignment targeted at this user
3762
4004
  targeted.push({
3763
4005
  id: assignmentId,
3764
4006
  priority: assignment.priority ?? 1000,
4007
+ tags: (assignment.tags ?? []).join(','),
3765
4008
  });
3766
4009
  }
3767
4010
  }