assignment-user-matcher 1.7.0 → 1.9.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 (42) hide show
  1. package/README.md +230 -14
  2. package/dist/index.d.ts +3 -2
  3. package/dist/index.d.ts.map +1 -1
  4. package/dist/index.js +5 -1
  5. package/dist/learning/auto-weights.d.ts +18 -8
  6. package/dist/learning/auto-weights.d.ts.map +1 -1
  7. package/dist/learning/auto-weights.js +120 -18
  8. package/dist/learning/features.d.ts +2 -2
  9. package/dist/learning/features.d.ts.map +1 -1
  10. package/dist/learning/features.js +10 -2
  11. package/dist/managers/LearningManager.d.ts +7 -0
  12. package/dist/managers/LearningManager.d.ts.map +1 -1
  13. package/dist/managers/LearningManager.js +85 -11
  14. package/dist/managers/WorkflowManager.d.ts +2 -0
  15. package/dist/managers/WorkflowManager.d.ts.map +1 -1
  16. package/dist/managers/WorkflowManager.js +3 -2
  17. package/dist/matcher.class.d.ts +121 -3
  18. package/dist/matcher.class.d.ts.map +1 -1
  19. package/dist/matcher.class.js +967 -16
  20. package/dist/queries/pagination.d.ts +5 -1
  21. package/dist/queries/pagination.d.ts.map +1 -1
  22. package/dist/queries/pagination.js +14 -3
  23. package/dist/schedule/policy.d.ts +35 -0
  24. package/dist/schedule/policy.d.ts.map +1 -0
  25. package/dist/schedule/policy.js +62 -0
  26. package/dist/scoring/match-score.d.ts +6 -0
  27. package/dist/scoring/match-score.d.ts.map +1 -1
  28. package/dist/scoring/match-score.js +15 -2
  29. package/dist/sla/policy.d.ts +49 -0
  30. package/dist/sla/policy.d.ts.map +1 -0
  31. package/dist/sla/policy.js +96 -0
  32. package/dist/tracing/decision-trace.d.ts.map +1 -1
  33. package/dist/tracing/decision-trace.js +4 -2
  34. package/dist/types/matcher.d.ts +422 -2
  35. package/dist/types/matcher.d.ts.map +1 -1
  36. package/dist/utils/keys.d.ts +10 -0
  37. package/dist/utils/keys.d.ts.map +1 -1
  38. package/dist/utils/keys.js +28 -0
  39. package/dist/validation/assignment-lint.d.ts +24 -0
  40. package/dist/validation/assignment-lint.d.ts.map +1 -0
  41. package/dist/validation/assignment-lint.js +132 -0
  42. package/package.json +2 -1
@@ -10,6 +10,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
12
  const policy_1 = require("./escalation/policy");
13
+ const policy_2 = require("./sla/policy");
14
+ const policy_3 = require("./schedule/policy");
15
+ const assignment_lint_1 = require("./validation/assignment-lint");
13
16
  const decision_trace_1 = require("./tracing/decision-trace");
14
17
  const features_1 = require("./learning/features");
15
18
  const DecisionTraceManager_1 = require("./managers/DecisionTraceManager");
@@ -38,6 +41,7 @@ class AssignmentMatcher {
38
41
  constructor(redisClient, options) {
39
42
  this.redisClient = redisClient;
40
43
  this.luaScriptSha = null;
44
+ this.autoRoutingWeightsSyncInterval = null;
41
45
  // ============================================================================
42
46
  // Maintenance — the periodic sweeps that make deadlines actually fire
43
47
  // ============================================================================
@@ -62,6 +66,11 @@ class AssignmentMatcher {
62
66
  this.assignmentOwnerKey = this.keys.assignmentOwner();
63
67
  this.allTagsKey = this.keys.allTags();
64
68
  this.acceptedAssignmentsKey = this.keys.acceptedAssignments();
69
+ this.acceptedAssignmentsExpiryKey = this.keys.acceptedAssignmentsExpiry();
70
+ this.assignmentsSlaExpiryKey = this.keys.assignmentsSlaExpiry();
71
+ this.scheduledAssignmentsKey = this.keys.scheduledAssignments();
72
+ this.scheduledActivateAtKey = this.keys.scheduledActivateAt();
73
+ this.scheduleNotAfterKey = this.keys.scheduleNotAfter();
65
74
  this.completedAssignmentsKey = this.keys.completedAssignments();
66
75
  this.calculatePriority = options?.prioritizationFunction ?? this.calculatePriority;
67
76
  this.usingDefaultMatchScore = !options?.matchingFunction;
@@ -100,7 +109,12 @@ class AssignmentMatcher {
100
109
  // Learning layer (opt-in contextual bandit re-ranking)
101
110
  this.enableLearning = options?.enableLearning ?? false;
102
111
  this.enableAutoRoutingWeights = options?.enableAutoRoutingWeights ?? false;
103
- this.learningFeatureExtractor = options?.learningFeatureExtractor ?? features_1.extractMatchFeatures;
112
+ this.learningSlaTightnessReferenceMs = options?.learningSlaTightnessReferenceMs ?? 3600000;
113
+ // The default extractor closes over the configured SLA tightness
114
+ // reference; custom extractors keep their exact signature.
115
+ this.learningFeatureExtractor =
116
+ options?.learningFeatureExtractor ??
117
+ ((user, assignment) => (0, features_1.extractMatchFeatures)(user, assignment, this.learningSlaTightnessReferenceMs));
104
118
  this.learning = new LearningManager_1.LearningManager(this.redisClient, this.keys, {
105
119
  learningRate: options?.learningRate,
106
120
  explorationRate: options?.learningExplorationRate,
@@ -134,7 +148,16 @@ class AssignmentMatcher {
134
148
  onWorkflowEvent: options?.onWorkflowEvent,
135
149
  });
136
150
  this.onAssignmentLifecycle = options?.onAssignmentLifecycle;
137
- this.readyPromise = this.initRedis();
151
+ this.autoRoutingWeightsSyncIntervalMs = options?.autoRoutingWeightsSyncIntervalMs;
152
+ if (this.enableAutoRoutingWeights && this.autoRoutingWeightsSyncIntervalMs) {
153
+ this.readyPromise = this.initRedis().then((self) => {
154
+ this.startAutoRoutingWeightsSync(this.autoRoutingWeightsSyncIntervalMs);
155
+ return self;
156
+ });
157
+ }
158
+ else {
159
+ this.readyPromise = this.initRedis();
160
+ }
138
161
  }
139
162
  /**
140
163
  * Fire the optional assignment lifecycle hook. Errors are swallowed so a
@@ -150,6 +173,92 @@ class AssignmentMatcher {
150
173
  // Best-effort hook: do not propagate.
151
174
  }
152
175
  }
176
+ // ============================================================================
177
+ // SLO stats — minimal aggregate counters (global + per-tag hashes)
178
+ // ============================================================================
179
+ /** Increment SLO counters globally and per assignment tag. Best-effort. */
180
+ async bumpSlaStats(tags, deltas) {
181
+ try {
182
+ const multi = this.redisClient.multi();
183
+ const apply = (key) => {
184
+ for (const [field, delta] of Object.entries(deltas)) {
185
+ multi.hIncrByFloat(key, field, delta);
186
+ }
187
+ };
188
+ apply(this.keys.slaStats());
189
+ for (const tag of tags ?? []) {
190
+ if (tag)
191
+ apply(this.keys.slaTagStats(tag));
192
+ }
193
+ await multi.exec();
194
+ }
195
+ catch {
196
+ // Best-effort: stats never break the lifecycle.
197
+ }
198
+ }
199
+ /**
200
+ * Accept-path stats: offers were counted at claim time; here we record
201
+ * the accept, its latency (acceptedAt - matchedAt), and whether it beat
202
+ * the response deadline that was in effect.
203
+ */
204
+ async recordSlaAccept(pendingJson, acceptedAt) {
205
+ try {
206
+ const parsed = JSON.parse(pendingJson);
207
+ const matchedAt = Number(parsed[policy_2.SLA_MATCHED_AT_FIELD]);
208
+ if (!Number.isFinite(matchedAt) || matchedAt <= 0)
209
+ return;
210
+ const latency = Math.max(0, acceptedAt - matchedAt);
211
+ const respondWithin = (0, policy_1.responseDeadlineMs)(parsed, this.matchExpirationMs);
212
+ const deltas = {
213
+ accepts: 1,
214
+ acceptLatencyMsSum: latency,
215
+ };
216
+ if (matchedAt + respondWithin >= acceptedAt)
217
+ deltas.acceptedInTime = 1;
218
+ await this.bumpSlaStats(parsed.tags, deltas);
219
+ }
220
+ catch {
221
+ // best-effort: stats never break the lifecycle
222
+ }
223
+ }
224
+ /** Completion-path stats: completion latency (completedAt - acceptedAt). */
225
+ async recordSlaComplete(acceptedJson, completedAt) {
226
+ try {
227
+ const parsed = JSON.parse(acceptedJson);
228
+ const acceptedAt = Number(parsed[policy_2.SLA_ACCEPTED_AT_FIELD]);
229
+ if (!Number.isFinite(acceptedAt) || acceptedAt <= 0)
230
+ return;
231
+ await this.bumpSlaStats(parsed.tags, {
232
+ completes: 1,
233
+ completeLatencyMsSum: Math.max(0, completedAt - acceptedAt),
234
+ });
235
+ }
236
+ catch {
237
+ // best-effort
238
+ }
239
+ }
240
+ /**
241
+ * Aggregate SLO attainment counters, globally or for a single tag.
242
+ * Means are computed from sum/count pairs; 0 when no data.
243
+ */
244
+ async getSlaStats(tag) {
245
+ await this.readyPromise;
246
+ const raw = await this.redisClient.hGetAll(tag ? this.keys.slaTagStats(tag) : this.keys.slaStats());
247
+ const num = (field) => Number(raw[field]) || 0;
248
+ const accepts = num('accepts');
249
+ const completes = num('completes');
250
+ return {
251
+ offers: num('offers'),
252
+ acceptedInTime: num('acceptedInTime'),
253
+ acceptanceBreaches: num('acceptanceBreaches'),
254
+ completionBreaches: num('completionBreaches'),
255
+ ttlExpiries: num('ttlExpiries'),
256
+ rejectionParked: num('rejectionParked'),
257
+ scheduleMisses: num('scheduleMisses'),
258
+ meanAcceptLatencyMs: accepts > 0 ? num('acceptLatencyMsSum') / accepts : 0,
259
+ meanCompleteLatencyMs: completes > 0 ? num('completeLatencyMsSum') / completes : 0,
260
+ };
261
+ }
153
262
  /** Keys for the assignment stores (used by pagination queries) */
154
263
  get assignmentStoreKeys() {
155
264
  return {
@@ -158,6 +267,7 @@ class AssignmentMatcher {
158
267
  accepted: this.acceptedAssignmentsKey,
159
268
  completed: this.completedAssignmentsKey,
160
269
  parked: this.keys.parkedAssignments(),
270
+ scheduled: this.scheduledAssignmentsKey,
161
271
  };
162
272
  }
163
273
  async initRedis() {
@@ -686,6 +796,180 @@ class AssignmentMatcher {
686
796
  (0, decision_trace_1.sortCandidates)(candidates);
687
797
  return { tags: input.tags, priority: basePriority, evaluatedAt, candidates };
688
798
  }
799
+ /**
800
+ * Pre-flight check for an assignment before (or without) adding it:
801
+ * static policy lint (schedule conflicts, policies that would be silently
802
+ * ignored, missing tags) plus live findings against the current pool —
803
+ * tags no active user can serve, ids that already exist, and whether
804
+ * anyone is eligible right now under the same rules as `previewMatch()`.
805
+ * Read-only: never claims, writes, or records decisions.
806
+ */
807
+ async checkAssignmentReadiness(assignment) {
808
+ await this.readyPromise;
809
+ const evaluatedAt = Date.now();
810
+ const tags = assignment.tags ?? [];
811
+ const issues = (0, assignment_lint_1.lintAssignment)(assignment, {
812
+ now: evaluatedAt,
813
+ matchExpirationMs: this.matchExpirationMs,
814
+ enableDefaultMatching: this.enableDefaultMatching,
815
+ });
816
+ if (assignment.id) {
817
+ const existing = await this.getAssignment(assignment.id);
818
+ if (existing) {
819
+ issues.push({
820
+ severity: 'warning',
821
+ code: 'duplicate-id',
822
+ message: `Assignment '${assignment.id}' already exists with status '${existing._status}' — re-adding keeps its original wait/TTL clocks.`,
823
+ });
824
+ }
825
+ }
826
+ const [preview, allUsers, pausedMembers] = await Promise.all([
827
+ this.previewMatch({
828
+ tags,
829
+ priority: assignment.priority,
830
+ skillThresholds: assignment.skillThresholds,
831
+ allowedCidrs: assignment.allowedCidrs,
832
+ vetoedUsers: assignment.vetoedUsers,
833
+ latitude: assignment.latitude,
834
+ longitude: assignment.longitude,
835
+ maxDistanceKm: assignment.maxDistanceKm,
836
+ requireGeo: assignment.requireGeo,
837
+ }),
838
+ this.redisClient.hGetAll(this.usersKey),
839
+ this.redisClient.sMembers(this.keys.pausedUsers()),
840
+ ]);
841
+ const eligibleUserCount = preview.candidates.filter((candidate) => candidate.eligible).length;
842
+ const paused = new Set(pausedMembers);
843
+ const activeUsers = Object.values(allUsers)
844
+ .map((json) => JSON.parse(json))
845
+ .filter((user) => !paused.has(user.id));
846
+ const uncoveredTags = tags.filter((tag) => !activeUsers.some((user) => (0, assignment_lint_1.userCoversTag)(user, tag)));
847
+ for (const tag of uncoveredTags) {
848
+ issues.push({
849
+ severity: 'warning',
850
+ code: 'tag-uncovered',
851
+ tag,
852
+ message: `No active user can currently serve tag '${tag}'.`,
853
+ });
854
+ }
855
+ if (eligibleUserCount === 0) {
856
+ issues.push({
857
+ severity: 'error',
858
+ code: 'no-eligible-users',
859
+ message: 'No user is eligible for this assignment right now; it would sit queued until the pool changes.',
860
+ });
861
+ }
862
+ return { issues, eligibleUserCount, uncoveredTags, evaluatedAt };
863
+ }
864
+ /**
865
+ * Queue-wide overlook: why is queued work not moving? Examines the
866
+ * longest-waiting queued assignments against the current pool (same hard
867
+ * rules as matching) and reports, per stuck assignment, who is blocked by
868
+ * what — plus the past-due entries sitting unswept in every deadline
869
+ * index, which is the tell-tale of a missing or lagging maintenance tick.
870
+ * Read-only and O(scanned assignments × users): a diagnostic, not a hot
871
+ * path — cap with `limit` on very large queues.
872
+ */
873
+ async auditQueue(options) {
874
+ await this.readyPromise;
875
+ const evaluatedAt = Date.now();
876
+ const limit = options?.limit ?? 100;
877
+ const minWaitingMs = options?.minWaitingMs ?? 0;
878
+ const includeHealthy = options?.includeHealthy === true;
879
+ const [queuedAll, waitEntries, allUsersHash, pausedMembers] = await Promise.all([
880
+ this.redisClient.hGetAll(this.assignmentsRefKey),
881
+ this.redisClient.zRangeWithScores(this.keys.assignmentsQueuedAt(), 0, -1),
882
+ this.redisClient.hGetAll(this.usersKey),
883
+ this.redisClient.sMembers(this.keys.pausedUsers()),
884
+ ]);
885
+ // The wait clock also holds pending ids (it survives the claim), so
886
+ // membership in the queued store is what defines the audit universe.
887
+ const waitById = new Map(waitEntries.map((entry) => [entry.value, Number(entry.score)]));
888
+ const candidatesToScan = Object.keys(queuedAll)
889
+ .map((id) => {
890
+ const queuedAtMs = waitById.get(id);
891
+ const waitingMs = queuedAtMs !== undefined ? Math.max(0, evaluatedAt - queuedAtMs) : null;
892
+ return { id, waitingMs };
893
+ })
894
+ .filter(({ waitingMs }) => waitingMs === null || waitingMs >= minWaitingMs)
895
+ .sort((a, b) => (b.waitingMs ?? Number.MAX_SAFE_INTEGER) - (a.waitingMs ?? Number.MAX_SAFE_INTEGER))
896
+ .slice(0, limit);
897
+ const paused = new Set(pausedMembers);
898
+ const users = Object.values(allUsersHash).map((json) => JSON.parse(json));
899
+ const activeUsers = users.filter((user) => !paused.has(user.id));
900
+ const modelWeights = this.enableLearning ? await this.learning.getModel() : undefined;
901
+ const backlogs = new Map(await Promise.all(users.map(async (user) => [user.id, await this.redisClient.sCard(this.keys.userAssignments(user.id))])));
902
+ // Score contributions and annotations — everything else in a
903
+ // candidate's reason list marks a blocker.
904
+ const nonBlockingKinds = new Set([
905
+ 'tagWeight',
906
+ 'defaultTag',
907
+ 'tagOverlap',
908
+ 'customScore',
909
+ 'geoBoost',
910
+ 'learningBoost',
911
+ 'workflowTargeted',
912
+ 'manualAssignment',
913
+ ]);
914
+ const entries = [];
915
+ for (const { id, waitingMs } of candidatesToScan) {
916
+ const assignment = JSON.parse(queuedAll[id]);
917
+ const tags = assignment.tags ?? [];
918
+ const storedPriority = await this.redisClient.hGet(this.keys.assignmentPriority(id), 'priority');
919
+ const basePriority = Number(storedPriority ?? assignment.priority) || 0;
920
+ const tagsCsv = [...tags, ...(this.enableDefaultMatching ? ['default'] : [])].join(',');
921
+ const evaluations = await Promise.all(users.map(async (user) => {
922
+ const isRejected = await this.redisClient.sIsMember(this.keys.userRejected(user.id), id);
923
+ return this.evaluateCandidateForAssignment(user, assignment, tagsCsv, basePriority, modelWeights, {
924
+ assignmentId: id,
925
+ ownerId: null,
926
+ isRejected: Boolean(isRejected),
927
+ backlog: backlogs.get(user.id) ?? 0,
928
+ isPaused: paused.has(user.id),
929
+ });
930
+ }));
931
+ const eligibleUserCount = evaluations.filter((candidate) => candidate.eligible).length;
932
+ if (eligibleUserCount > 0 && !includeHealthy)
933
+ continue;
934
+ const blockers = {};
935
+ for (const candidate of evaluations) {
936
+ if (candidate.eligible)
937
+ continue;
938
+ const kinds = new Set(candidate.reasons
939
+ .filter((reason) => !nonBlockingKinds.has(reason.kind) &&
940
+ !(reason.kind === 'geoDistance' && reason.withinRange))
941
+ .map((reason) => reason.kind));
942
+ // A zero score with no named blocker is a plain tag/weight
943
+ // mismatch — the most common way to be stuck.
944
+ if (kinds.size === 0)
945
+ kinds.add('noTagMatch');
946
+ for (const kind of kinds)
947
+ blockers[kind] = (blockers[kind] ?? 0) + 1;
948
+ }
949
+ entries.push({
950
+ assignmentId: id,
951
+ tags,
952
+ waitingMs,
953
+ eligibleUserCount,
954
+ uncoveredTags: tags.filter((tag) => !activeUsers.some((user) => (0, assignment_lint_1.userCoversTag)(user, tag))),
955
+ blockers,
956
+ });
957
+ }
958
+ const pastDue = (key) => this.redisClient.zCount(key, '-inf', evaluatedAt);
959
+ const [scheduleActivations, scheduleMisses, responseDeadlines, completionDeadlines, slaExpiries] = await Promise.all([
960
+ pastDue(this.scheduledActivateAtKey),
961
+ pastDue(this.scheduleNotAfterKey),
962
+ pastDue(this.pendingAssignmentsExpiryKey),
963
+ pastDue(this.acceptedAssignmentsExpiryKey),
964
+ pastDue(this.assignmentsSlaExpiryKey),
965
+ ]);
966
+ return {
967
+ evaluatedAt,
968
+ scanned: candidatesToScan.length,
969
+ entries,
970
+ sweepBacklog: { scheduleActivations, scheduleMisses, responseDeadlines, completionDeadlines, slaExpiries },
971
+ };
972
+ }
689
973
  /** Build and record this pass's decision traces; failures never break matching. */
690
974
  async recordPassTraces(collector, winners, workflowGrants, mode, users) {
691
975
  if (winners.size === 0 && workflowGrants.length === 0)
@@ -816,6 +1100,11 @@ class AssignmentMatcher {
816
1100
  * The applied learned map is stored on the user as `learnedRoutingWeights`
817
1101
  * for observability.
818
1102
  *
1103
+ * Guardrails: evidence floor (`minTotalSamples`), strict veto gate for
1104
+ * manual tags (`minSamplesForVeto`), and per-sync step clamp
1105
+ * (`maxDeltaPerSync`) are applied automatically. Set `dryRun: true` to
1106
+ * compute the would-be map without writing anything.
1107
+ *
819
1108
  * Returns the applied weights per user id.
820
1109
  */
821
1110
  async syncLearnedRoutingWeights(userId, opts) {
@@ -823,6 +1112,8 @@ class AssignmentMatcher {
823
1112
  const targets = userId ? [userId] : await this.learning.listTrackedUsers();
824
1113
  const knownTags = opts?.includeUnexploredTags ? await this.getKnownTagsForAutoWeights() : undefined;
825
1114
  const applied = {};
1115
+ const maxDelta = this.learning.autoWeights.maxDeltaPerSync;
1116
+ const maxWeight = this.learning.autoWeights.maxWeight ?? 100;
826
1117
  for (const id of targets) {
827
1118
  const userJson = await this.redisClient.hGet(this.usersKey, id);
828
1119
  if (!userJson)
@@ -838,23 +1129,130 @@ class AssignmentMatcher {
838
1129
  const learned = await this.learning.getLearnedRoutingWeights(id, knownTags, existingForSynthesis);
839
1130
  if (Object.keys(learned).length === 0)
840
1131
  continue;
1132
+ // Apply per-sync step clamp. Vetoes (weight 0) that passed the
1133
+ // strict veto gate are allowed to jump despite the clamp.
1134
+ const clampedLearned = {};
1135
+ for (const [tag, weight] of Object.entries(learned)) {
1136
+ if (weight === 0 || maxDelta === undefined) {
1137
+ clampedLearned[tag] = weight;
1138
+ continue;
1139
+ }
1140
+ const previous = previousLearned[tag] ?? user.routingWeights?.[tag];
1141
+ if (previous === undefined) {
1142
+ clampedLearned[tag] = Math.min(weight, maxWeight);
1143
+ continue;
1144
+ }
1145
+ const lower = previous - maxDelta;
1146
+ const upper = previous + maxDelta;
1147
+ clampedLearned[tag] = Math.min(Math.max(weight, lower, 1), upper, maxWeight);
1148
+ }
841
1149
  let routingWeights;
842
1150
  if (opts?.overrideManual) {
843
- routingWeights = learned;
1151
+ routingWeights = { ...clampedLearned };
844
1152
  }
845
1153
  else {
846
1154
  const manualEntries = {};
847
1155
  for (const [tag, weight] of Object.entries(user.routingWeights ?? {})) {
848
- if (!(tag in previousLearned) && !(tag in learned))
1156
+ if (!(tag in previousLearned) && !(tag in clampedLearned))
849
1157
  manualEntries[tag] = weight;
850
1158
  }
851
- routingWeights = { ...manualEntries, ...learned };
1159
+ routingWeights = { ...manualEntries, ...clampedLearned };
852
1160
  }
853
- await this.redisClient.hSet(this.usersKey, id, JSON.stringify({ ...user, routingWeights, learnedRoutingWeights: learned }));
854
1161
  applied[id] = routingWeights;
1162
+ if (opts?.dryRun)
1163
+ continue;
1164
+ await this.redisClient.hSet(this.usersKey, id, JSON.stringify({
1165
+ ...user,
1166
+ routingWeights,
1167
+ routingWeightsSnapshot: user.routingWeights,
1168
+ learnedRoutingWeights: clampedLearned,
1169
+ learnedRoutingWeightsSyncedAt: Date.now(),
1170
+ }));
855
1171
  }
856
1172
  return applied;
857
1173
  }
1174
+ /**
1175
+ * Revert learned routing weights for one user (or all users with a
1176
+ * snapshot) to the map saved before the last sync. No-op when no snapshot
1177
+ * exists.
1178
+ *
1179
+ * Returns reverted user ids.
1180
+ */
1181
+ async revertLearnedRoutingWeights(userId) {
1182
+ await this.readyPromise;
1183
+ const targets = [];
1184
+ if (userId) {
1185
+ targets.push(userId);
1186
+ }
1187
+ else {
1188
+ const all = await this.redisClient.hGetAll(this.usersKey);
1189
+ for (const [id, json] of Object.entries(all)) {
1190
+ try {
1191
+ const u = JSON.parse(json);
1192
+ if (u.routingWeightsSnapshot)
1193
+ targets.push(id);
1194
+ }
1195
+ catch {
1196
+ // ignore malformed user entries
1197
+ }
1198
+ }
1199
+ }
1200
+ const reverted = [];
1201
+ for (const id of targets) {
1202
+ const userJson = await this.redisClient.hGet(this.usersKey, id);
1203
+ if (!userJson)
1204
+ continue;
1205
+ const user = JSON.parse(userJson);
1206
+ if (!user.routingWeightsSnapshot)
1207
+ continue;
1208
+ await this.redisClient.hSet(this.usersKey, id, JSON.stringify({
1209
+ ...user,
1210
+ routingWeights: user.routingWeightsSnapshot,
1211
+ routingWeightsSnapshot: undefined,
1212
+ learnedRoutingWeights: undefined,
1213
+ learnedRoutingWeightsSyncedAt: undefined,
1214
+ }));
1215
+ reverted.push(id);
1216
+ }
1217
+ return reverted;
1218
+ }
1219
+ /** Start the automatic learned-weights sync tick. Idempotent. */
1220
+ startAutoRoutingWeightsSync(intervalMs) {
1221
+ this.stopAutoRoutingWeightsSync();
1222
+ if (intervalMs)
1223
+ this.autoRoutingWeightsSyncIntervalMs = intervalMs;
1224
+ const ms = this.autoRoutingWeightsSyncIntervalMs;
1225
+ if (!ms || !this.enableAutoRoutingWeights)
1226
+ return;
1227
+ this.autoRoutingWeightsSyncInterval = setInterval(() => {
1228
+ this.runAutoRoutingWeightsSyncTick().catch((err) => console.error('Auto routing-weights sync tick failed:', err));
1229
+ }, ms);
1230
+ this.autoRoutingWeightsSyncInterval.unref?.();
1231
+ }
1232
+ /** Stop the automatic learned-weights sync tick. Safe when not started. */
1233
+ stopAutoRoutingWeightsSync() {
1234
+ if (this.autoRoutingWeightsSyncInterval) {
1235
+ clearInterval(this.autoRoutingWeightsSyncInterval);
1236
+ this.autoRoutingWeightsSyncInterval = null;
1237
+ }
1238
+ }
1239
+ /** Whether the automatic learned-weights sync tick is running. */
1240
+ isAutoRoutingWeightsSyncRunning() {
1241
+ return this.autoRoutingWeightsSyncInterval !== null;
1242
+ }
1243
+ async runAutoRoutingWeightsSyncTick() {
1244
+ const ms = this.autoRoutingWeightsSyncIntervalMs;
1245
+ if (!ms)
1246
+ return;
1247
+ const lockTtl = Math.max(1000, ms - 1000);
1248
+ const acquired = await this.redisClient.set(this.keys.autoWeightsSyncLock(), this.streamConsumerName, {
1249
+ NX: true,
1250
+ PX: lockTtl,
1251
+ });
1252
+ if (!acquired)
1253
+ return;
1254
+ await this.syncLearnedRoutingWeights();
1255
+ }
858
1256
  /** All known tags except the internal 'default' tag (for exploration priors) */
859
1257
  async getKnownTagsForAutoWeights() {
860
1258
  const tags = await this.redisClient.sMembers(this.allTagsKey);
@@ -899,9 +1297,43 @@ class AssignmentMatcher {
899
1297
  }
900
1298
  async addAssignment(assignment) {
901
1299
  await this.readyPromise;
1300
+ // Offer window: a future notBefore keeps the assignment out of the
1301
+ // queue entirely — raw JSON in the scheduled store, invisible to
1302
+ // every matching path until the scheduled sweep re-adds it here.
1303
+ // The wait clock and SLA freshness TTL therefore anchor at
1304
+ // activation, not creation.
1305
+ const schedulePolicy = (0, policy_3.normalizeSchedulePolicy)(assignment.schedule);
1306
+ if (schedulePolicy && (0, policy_3.isHeld)(schedulePolicy, Date.now())) {
1307
+ const multi = this.redisClient
1308
+ .multi()
1309
+ .hSet(this.scheduledAssignmentsKey, assignment.id, JSON.stringify(assignment))
1310
+ .zAdd(this.scheduledActivateAtKey, { score: schedulePolicy.notBefore, value: assignment.id });
1311
+ if (schedulePolicy.notAfter !== undefined) {
1312
+ multi.zAdd(this.scheduleNotAfterKey, { score: schedulePolicy.notAfter, value: assignment.id });
1313
+ }
1314
+ await multi.exec();
1315
+ return assignment;
1316
+ }
1317
+ return this.enqueueAssignment(assignment, schedulePolicy);
1318
+ }
1319
+ async enqueueAssignment(assignment, schedulePolicy) {
902
1320
  let { id, tags, priority, latitude, longitude } = assignment;
903
1321
  if (!priority)
904
1322
  priority = await this.calculatePriority(assignment);
1323
+ // First-enqueue clock for the freshness TTL: NX semantics via the
1324
+ // object itself — a requeue re-adds the same JSON (with the original
1325
+ // _enqueuedAt), so the TTL is never extended by rejection ping-pong.
1326
+ // Only stamped when the assignment actually declares a TTL, so
1327
+ // non-SLA assignments keep byte-identical stored JSON.
1328
+ const slaPolicy = (0, policy_2.normalizeSlaPolicy)(assignment.sla);
1329
+ let slaExpiry = null;
1330
+ if (slaPolicy?.expireAfterMs !== undefined) {
1331
+ const record = assignment;
1332
+ if (record[policy_2.SLA_ENQUEUED_AT_FIELD] === undefined) {
1333
+ record[policy_2.SLA_ENQUEUED_AT_FIELD] = Date.now();
1334
+ }
1335
+ slaExpiry = (0, policy_2.slaExpiryScore)(record[policy_2.SLA_ENQUEUED_AT_FIELD], slaPolicy);
1336
+ }
905
1337
  const assignmentPriorityKey = this.keys.assignmentPriority(id);
906
1338
  const assignmentTagsKey = this.keys.assignmentTags(id);
907
1339
  const assignmentGeoKey = this.keys.assignmentsGeo();
@@ -918,6 +1350,21 @@ class AssignmentMatcher {
918
1350
  score: priority,
919
1351
  value: id,
920
1352
  });
1353
+ if (slaExpiry !== null) {
1354
+ multi.zAdd(this.assignmentsSlaExpiryKey, { score: slaExpiry, value: id });
1355
+ }
1356
+ if (schedulePolicy) {
1357
+ // The offer deadline is absolute, so requeues re-add the same
1358
+ // score — the notAfter clock is never extended.
1359
+ if (schedulePolicy.notAfter !== undefined) {
1360
+ multi.zAdd(this.scheduleNotAfterKey, { score: schedulePolicy.notAfter, value: id });
1361
+ }
1362
+ // Atomic hand-off out of the scheduled store (no-ops when the
1363
+ // assignment was never held); also self-heals an activation
1364
+ // that crashed between the sweep's claim and this enqueue.
1365
+ multi.hDel(this.scheduledAssignmentsKey, id);
1366
+ multi.zRem(this.scheduledActivateAtKey, id);
1367
+ }
921
1368
  if ((0, geo_1.isValidLatitude)(latitude) && (0, geo_1.isValidLongitude)(longitude)) {
922
1369
  multi.geoAdd(assignmentGeoKey, {
923
1370
  longitude,
@@ -985,6 +1432,13 @@ class AssignmentMatcher {
985
1432
  }
986
1433
  // 3. Remove from Accepted state
987
1434
  multi.hDel(this.acceptedAssignmentsKey, id);
1435
+ // 4. Clear SLA indexes (no-ops for non-SLA assignments)
1436
+ multi.zRem(this.acceptedAssignmentsExpiryKey, id);
1437
+ multi.zRem(this.assignmentsSlaExpiryKey, id);
1438
+ // 5. Clear schedule store and indexes (no-ops for unscheduled assignments)
1439
+ multi.hDel(this.scheduledAssignmentsKey, id);
1440
+ multi.zRem(this.scheduledActivateAtKey, id);
1441
+ multi.zRem(this.scheduleNotAfterKey, id);
988
1442
  await multi.exec();
989
1443
  return id;
990
1444
  }
@@ -1160,6 +1614,7 @@ class AssignmentMatcher {
1160
1614
  return {
1161
1615
  queued: counts.queued,
1162
1616
  pending: counts.pending,
1617
+ scheduled: counts.scheduled,
1163
1618
  oldestWaitingMs: oldestEntries.length > 0 ? Date.now() - Number(oldestEntries[0].score) : null,
1164
1619
  perUser,
1165
1620
  };
@@ -1676,7 +2131,27 @@ class AssignmentMatcher {
1676
2131
  // EscalationPolicy sets its own response deadline; everything
1677
2132
  // else uses the matcher-wide one and never pays for a parse.
1678
2133
  if (json) {
1679
- rm.hSet(this.pendingAssignmentsKey, s.id, json);
2134
+ // SLA-bearing assignments get a match timestamp for
2135
+ // accept-latency SLO stats; everyone else's JSON stays
2136
+ // byte-identical (guarded by the same cheap indexOf).
2137
+ let pendingJson = json;
2138
+ if (json.indexOf('"sla"') !== -1) {
2139
+ try {
2140
+ const parsed = JSON.parse(json);
2141
+ parsed[policy_2.SLA_MATCHED_AT_FIELD] = now;
2142
+ pendingJson = JSON.stringify(parsed);
2143
+ // Count the offer (global + per-tag) in the same batch.
2144
+ rm.hIncrByFloat(this.keys.slaStats(), 'offers', 1);
2145
+ for (const tag of (parsed.tags ?? [])) {
2146
+ if (tag)
2147
+ rm.hIncrByFloat(this.keys.slaTagStats(tag), 'offers', 1);
2148
+ }
2149
+ }
2150
+ catch {
2151
+ // keep original JSON on parse failure
2152
+ }
2153
+ }
2154
+ rm.hSet(this.pendingAssignmentsKey, s.id, pendingJson);
1680
2155
  rm.zAdd(this.pendingAssignmentsExpiryKey, {
1681
2156
  score: now + (0, policy_1.responseDeadlineFromJson)(json, this.matchExpirationMs),
1682
2157
  value: s.id,
@@ -2018,14 +2493,37 @@ class AssignmentMatcher {
2018
2493
  if (!userJson)
2019
2494
  throw new Error(`User not found: ${userId}`);
2020
2495
  const user = JSON.parse(userJson);
2021
- const [queuedJson, previousOwnerId] = await Promise.all([
2496
+ let [queuedJson, previousOwnerId] = await Promise.all([
2022
2497
  this.redisClient.hGet(this.assignmentsRefKey, assignmentId),
2023
2498
  this.redisClient.hGet(this.assignmentOwnerKey, assignmentId),
2024
2499
  ]);
2025
2500
  if (previousOwnerId === userId)
2026
2501
  return { previousOwnerId: userId };
2027
2502
  if (!queuedJson && !previousOwnerId) {
2028
- throw new Error(`Assignment not found in queued or pending state: ${assignmentId}`);
2503
+ // Held by schedule.notBefore? Operators may early-activate with
2504
+ // force; without it the hold is honored like any other rule.
2505
+ const scheduledJson = await this.redisClient.hGet(this.scheduledAssignmentsKey, assignmentId);
2506
+ if (!scheduledJson) {
2507
+ throw new Error(`Assignment not found in queued or pending state: ${assignmentId}`);
2508
+ }
2509
+ const held = JSON.parse(scheduledJson);
2510
+ const heldPolicy = (0, policy_3.normalizeSchedulePolicy)(held.schedule);
2511
+ if (!force) {
2512
+ const eligibleAt = heldPolicy?.notBefore !== undefined ? new Date(heldPolicy.notBefore).toISOString() : 'activation';
2513
+ throw new Error(`Assignment is scheduled and not eligible until ${eligibleAt}: ${assignmentId}`);
2514
+ }
2515
+ // Claim the held copy first; losing the HDEL means a concurrent
2516
+ // sweep or operator just took it.
2517
+ const claimedHeld = await this.redisClient.hDel(this.scheduledAssignmentsKey, assignmentId);
2518
+ if (!claimedHeld) {
2519
+ throw new Error(`Assignment not found in queued or pending state: ${assignmentId}`);
2520
+ }
2521
+ // Early activation: enqueue past the hold guard (this also clears
2522
+ // the activation index), then continue into the normal queued
2523
+ // claim below. Wait clock and SLA TTL anchor here, and a later
2524
+ // rejection re-holds the assignment (notBefore is still future).
2525
+ await this.enqueueAssignment(held, heldPolicy);
2526
+ queuedJson = await this.redisClient.hGet(this.assignmentsRefKey, assignmentId);
2029
2527
  }
2030
2528
  if (!force) {
2031
2529
  const [isPaused, backlog, isVetoed, hasRejected] = await Promise.all([
@@ -2061,17 +2559,30 @@ class AssignmentMatcher {
2061
2559
  // response deadline when it declares one).
2062
2560
  const pendingJson = await this.redisClient.hGet(this.pendingAssignmentsKey, assignmentId);
2063
2561
  const deadlineMs = (0, policy_1.responseDeadlineFromJson)(pendingJson, this.matchExpirationMs);
2562
+ const now = Date.now();
2064
2563
  const transfer = this.redisClient
2065
2564
  .multi()
2066
2565
  .sRem(this.keys.userAssignments(previousOwnerId), `assignment:${assignmentId}`)
2067
2566
  .sAdd(this.keys.userAssignments(userId), `assignment:${assignmentId}`)
2068
2567
  .hSet(this.assignmentOwnerKey, assignmentId, userId)
2069
2568
  .zAdd(this.pendingAssignmentsExpiryKey, {
2070
- score: Date.now() + deadlineMs,
2569
+ score: now + deadlineMs,
2071
2570
  value: assignmentId,
2072
2571
  });
2572
+ // Refresh the SLA match timestamp for the new owner so accept
2573
+ // latency is measured against the transfer, not the original claim.
2574
+ if (pendingJson && pendingJson.indexOf('"sla"') !== -1) {
2575
+ try {
2576
+ const parsed = JSON.parse(pendingJson);
2577
+ parsed[policy_2.SLA_MATCHED_AT_FIELD] = now;
2578
+ transfer.hSet(this.pendingAssignmentsKey, assignmentId, JSON.stringify(parsed));
2579
+ }
2580
+ catch {
2581
+ // keep original JSON on parse failure
2582
+ }
2583
+ }
2073
2584
  await transfer.exec();
2074
- const reassignedAt = Date.now();
2585
+ const reassignedAt = now;
2075
2586
  this.emitAssignmentLifecycle({
2076
2587
  kind: 'pending',
2077
2588
  taskId: assignmentId,
@@ -2120,6 +2631,7 @@ class AssignmentMatcher {
2120
2631
  throw new Error('Assignment not found for user');
2121
2632
  // Get the assignment JSON before removing from pending
2122
2633
  const json = await this.redisClient.hGet(this.pendingAssignmentsKey, assignmentId);
2634
+ const now = Date.now();
2123
2635
  const multi = this.redisClient.multi();
2124
2636
  multi.sRem(this.keys.userAssignments(userId), `assignment:${assignmentId}`);
2125
2637
  multi.hDel(this.pendingAssignmentsKey, assignmentId);
@@ -2127,11 +2639,41 @@ class AssignmentMatcher {
2127
2639
  multi.hDel(this.assignmentOwnerKey, assignmentId);
2128
2640
  // The wait clock stops when a user takes the work
2129
2641
  multi.zRem(this.keys.assignmentsQueuedAt(), assignmentId);
2130
- // Store in accepted assignments
2642
+ // Acceptance ends the offer window: the notAfter clock dies here, so
2643
+ // no post-accept path ever needs to clear it. One indexOf keeps
2644
+ // schedule-less assignments free of any extra cost.
2645
+ if (json && json.indexOf('"schedule"') !== -1) {
2646
+ multi.zRem(this.scheduleNotAfterKey, assignmentId);
2647
+ }
2648
+ // Store in accepted assignments. SLA-bearing assignments are stamped
2649
+ // with the accept timestamp/owner and registered on the completion-
2650
+ // deadline index when they declare completeWithinMs.
2131
2651
  if (json) {
2132
- multi.hSet(this.acceptedAssignmentsKey, assignmentId, json);
2652
+ const slaPolicy = (0, policy_2.slaFromJson)(json);
2653
+ let acceptedJson = json;
2654
+ if (slaPolicy) {
2655
+ try {
2656
+ const parsed = JSON.parse(json);
2657
+ parsed[policy_2.SLA_ACCEPTED_AT_FIELD] = now;
2658
+ parsed[policy_2.SLA_ACCEPTED_BY_FIELD] = userId;
2659
+ acceptedJson = JSON.stringify(parsed);
2660
+ const deadline = (0, policy_2.completionDeadlineScore)(now, slaPolicy);
2661
+ if (deadline !== null) {
2662
+ multi.zAdd(this.acceptedAssignmentsExpiryKey, { score: deadline, value: assignmentId });
2663
+ }
2664
+ }
2665
+ catch {
2666
+ // keep original JSON on parse failure
2667
+ }
2668
+ }
2669
+ multi.hSet(this.acceptedAssignmentsKey, assignmentId, acceptedJson);
2133
2670
  }
2134
2671
  await multi.exec();
2672
+ // SLO accept stats piggyback the accept path (internally guarded:
2673
+ // stats errors never break the lifecycle).
2674
+ if (json && json.indexOf('"sla"') !== -1) {
2675
+ await this.recordSlaAccept(json, now);
2676
+ }
2135
2677
  if (this.enableLearning) {
2136
2678
  await this.learning.applyOutcome(assignmentId, 'accept');
2137
2679
  }
@@ -2139,7 +2681,7 @@ class AssignmentMatcher {
2139
2681
  kind: 'accepted',
2140
2682
  taskId: assignmentId,
2141
2683
  workerId: userId,
2142
- acceptedAt: Date.now(),
2684
+ acceptedAt: now,
2143
2685
  });
2144
2686
  await this.touchUser(userId);
2145
2687
  return true;
@@ -2169,10 +2711,70 @@ class AssignmentMatcher {
2169
2711
  });
2170
2712
  await this.touchUser(userId);
2171
2713
  if (json) {
2172
- await this.addAssignment(JSON.parse(json));
2714
+ await this.requeueAfterRefusal(JSON.parse(json), 'reject');
2173
2715
  }
2174
2716
  return true;
2175
2717
  }
2718
+ /**
2719
+ * Shared requeue path for refusals (explicit rejects and blocking
2720
+ * no-response expiries): increments the SLA rejection counter and, when
2721
+ * the budget is exhausted, applies `onMaxRejections` instead of
2722
+ * requeueing. Non-SLA assignments take the untouched legacy path.
2723
+ */
2724
+ async requeueAfterRefusal(assignment, cause) {
2725
+ const policy = (0, policy_2.normalizeSlaPolicy)(assignment.sla);
2726
+ if (!policy) {
2727
+ await this.addAssignment(assignment);
2728
+ return;
2729
+ }
2730
+ const record = assignment;
2731
+ const rejections = (0, policy_2.rejectionCountOf)(assignment) + 1;
2732
+ record[policy_2.SLA_REJECTION_COUNT_FIELD] = rejections;
2733
+ // 'keep' makes the budget measurement-only: the counter keeps
2734
+ // accumulating so stats stay honest, but the assignment is requeued.
2735
+ if (!(0, policy_2.rejectionBudgetExhausted)(assignment, policy) || policy.onMaxRejections === 'keep') {
2736
+ await this.addAssignment(assignment);
2737
+ return;
2738
+ }
2739
+ await this.applyRejectionExhaustion(assignment, policy, rejections, cause);
2740
+ }
2741
+ /**
2742
+ * Terminal step for an assignment whose rejection budget is exhausted:
2743
+ * parked or failed per `onMaxRejections`. The caller must already have
2744
+ * removed it from the pending structures.
2745
+ */
2746
+ async applyRejectionExhaustion(assignment, policy, rejections, cause) {
2747
+ const action = policy.onMaxRejections === 'fail' ? 'fail' : 'park';
2748
+ const now = Date.now();
2749
+ // The assignment leaves the queued/pending universe: stop every clock.
2750
+ const multi = this.redisClient
2751
+ .multi()
2752
+ .zRem(this.keys.assignmentsQueuedAt(), assignment.id)
2753
+ .zRem(this.assignmentsSlaExpiryKey, assignment.id)
2754
+ .zRem(this.scheduleNotAfterKey, assignment.id);
2755
+ if (action === 'park') {
2756
+ multi.hSet(this.keys.parkedAssignments(), assignment.id, JSON.stringify(assignment));
2757
+ }
2758
+ else {
2759
+ multi.hSet(this.completedAssignmentsKey, assignment.id, JSON.stringify({
2760
+ ...assignment,
2761
+ _failedAt: now,
2762
+ _failureReason: `rejection-budget-exhausted:${cause}`,
2763
+ }));
2764
+ }
2765
+ await multi.exec();
2766
+ this.emitAssignmentLifecycle({
2767
+ kind: 'rejectionBudgetExhausted',
2768
+ taskId: assignment.id,
2769
+ rejections,
2770
+ action,
2771
+ assignment,
2772
+ at: now,
2773
+ });
2774
+ if (action === 'park') {
2775
+ await this.bumpSlaStats(assignment.tags, { rejectionParked: 1 });
2776
+ }
2777
+ }
2176
2778
  /**
2177
2779
  * Complete an assignment with a result payload.
2178
2780
  * Moves the assignment from 'accepted' to 'completed' state and publishes an event
@@ -2194,6 +2796,9 @@ class AssignmentMatcher {
2194
2796
  // Move from accepted to completed
2195
2797
  const multi = this.redisClient.multi();
2196
2798
  multi.hDel(this.acceptedAssignmentsKey, assignmentId);
2799
+ // Clear SLA indexes (no-ops for non-SLA assignments)
2800
+ multi.zRem(this.acceptedAssignmentsExpiryKey, assignmentId);
2801
+ multi.zRem(this.assignmentsSlaExpiryKey, assignmentId);
2197
2802
  // Store in completed with result metadata
2198
2803
  const completedData = {
2199
2804
  ...assignment,
@@ -2203,6 +2808,9 @@ class AssignmentMatcher {
2203
2808
  };
2204
2809
  multi.hSet(this.completedAssignmentsKey, assignmentId, JSON.stringify(completedData));
2205
2810
  await multi.exec();
2811
+ if (json.indexOf('"sla"') !== -1) {
2812
+ await this.recordSlaComplete(json, now);
2813
+ }
2206
2814
  if (this.enableLearning) {
2207
2815
  await this.learning.applyOutcome(assignmentId, 'complete');
2208
2816
  }
@@ -2243,6 +2851,9 @@ class AssignmentMatcher {
2243
2851
  // Move from accepted to completed (with failed status)
2244
2852
  const multi = this.redisClient.multi();
2245
2853
  multi.hDel(this.acceptedAssignmentsKey, assignmentId);
2854
+ // Clear SLA indexes (no-ops for non-SLA assignments)
2855
+ multi.zRem(this.acceptedAssignmentsExpiryKey, assignmentId);
2856
+ multi.zRem(this.assignmentsSlaExpiryKey, assignmentId);
2246
2857
  const failedData = {
2247
2858
  ...assignment,
2248
2859
  _failedBy: userId,
@@ -2473,6 +3084,15 @@ class AssignmentMatcher {
2473
3084
  const json = await this.redisClient.hGet(this.pendingAssignmentsKey, id);
2474
3085
  const assignment = json ? JSON.parse(json) : null;
2475
3086
  const policy = assignment ? (0, policy_1.normalizeEscalationPolicy)(assignment.escalation) : null;
3087
+ const slaPolicy = assignment ? (0, policy_2.normalizeSlaPolicy)(assignment.sla) : null;
3088
+ // A blocking no-response expiry counts as a refusal against the
3089
+ // SLA rejection budget (same as an explicit reject). Increment
3090
+ // before escalateAssignment() spreads the object so the decision
3091
+ // carries the bumped count.
3092
+ const countsAsRefusal = Boolean(policy && policy.onNoResponse === 'block' && owner);
3093
+ if (assignment && slaPolicy && countsAsRefusal) {
3094
+ assignment[policy_2.SLA_REJECTION_COUNT_FIELD] = (0, policy_2.rejectionCountOf)(assignment) + 1;
3095
+ }
2476
3096
  const decision = assignment && policy ? (0, policy_1.escalateAssignment)(assignment, policy) : null;
2477
3097
  const multi = this.redisClient.multi();
2478
3098
  if (owner) {
@@ -2494,6 +3114,9 @@ class AssignmentMatcher {
2494
3114
  workerId: owner ?? null,
2495
3115
  expiredAt: now,
2496
3116
  });
3117
+ if (assignment && slaPolicy) {
3118
+ await this.bumpSlaStats(assignment.tags, { acceptanceBreaches: 1 });
3119
+ }
2497
3120
  if (this.enableLearning) {
2498
3121
  await this.learning.applyOutcome(id, 'expire');
2499
3122
  }
@@ -2509,6 +3132,15 @@ class AssignmentMatcher {
2509
3132
  }
2510
3133
  if (!assignment)
2511
3134
  continue;
3135
+ // The SLA rejection budget outranks the escalation ladder: once
3136
+ // nobody will take the work, tier hops are moot.
3137
+ if (slaPolicy &&
3138
+ countsAsRefusal &&
3139
+ (0, policy_2.rejectionBudgetExhausted)(assignment, slaPolicy) &&
3140
+ slaPolicy.onMaxRejections !== 'keep') {
3141
+ await this.applyRejectionExhaustion(assignment, slaPolicy, (0, policy_2.rejectionCountOf)(assignment), 'blocking-expiry');
3142
+ continue;
3143
+ }
2512
3144
  if (decision && decision.exhausted) {
2513
3145
  this.emitAssignmentLifecycle({
2514
3146
  kind: 'escalationExhausted',
@@ -2525,6 +3157,7 @@ class AssignmentMatcher {
2525
3157
  .multi()
2526
3158
  .hSet(this.keys.parkedAssignments(), id, JSON.stringify(assignment))
2527
3159
  .zRem(this.keys.assignmentsQueuedAt(), id)
3160
+ .zRem(this.scheduleNotAfterKey, id)
2528
3161
  .exec();
2529
3162
  parked++;
2530
3163
  continue;
@@ -2558,6 +3191,273 @@ class AssignmentMatcher {
2558
3191
  const { expired } = await this.processResponseDeadlines();
2559
3192
  return expired;
2560
3193
  }
3194
+ /**
3195
+ * Sweep accepted assignments whose completion deadline
3196
+ * (`sla.completeWithinMs`, measured from accept) has elapsed.
3197
+ *
3198
+ * Each breached entry is removed from the deadline index before the
3199
+ * action runs, so a breach fires exactly once: a `'notify'` breach does
3200
+ * not re-fire every tick, and a `'requeue'`d assignment only gets a
3201
+ * fresh completion clock on its next accept.
3202
+ */
3203
+ async processCompletionDeadlines() {
3204
+ await this.readyPromise;
3205
+ const now = Date.now();
3206
+ const breachedIds = await this.redisClient.zRangeByScore(this.acceptedAssignmentsExpiryKey, '-inf', now);
3207
+ let breached = 0;
3208
+ for (const id of breachedIds) {
3209
+ const json = await this.redisClient.hGet(this.acceptedAssignmentsKey, id);
3210
+ // Fire-once: drop the index entry first. If the assignment is
3211
+ // gone (completed/failed/removed between the zRange and now)
3212
+ // there is nothing to do.
3213
+ await this.redisClient.zRem(this.acceptedAssignmentsExpiryKey, id);
3214
+ if (!json)
3215
+ continue;
3216
+ const assignment = JSON.parse(json);
3217
+ const policy = (0, policy_2.normalizeSlaPolicy)(assignment.sla);
3218
+ if (!policy)
3219
+ continue;
3220
+ breached++;
3221
+ const record = assignment;
3222
+ const workerId = record[policy_2.SLA_ACCEPTED_BY_FIELD] ?? null;
3223
+ const action = policy.onCompletionBreach;
3224
+ this.emitAssignmentLifecycle({
3225
+ kind: 'completionBreached',
3226
+ taskId: id,
3227
+ workerId,
3228
+ action,
3229
+ assignment,
3230
+ at: now,
3231
+ });
3232
+ await this.bumpSlaStats(assignment.tags, { completionBreaches: 1 });
3233
+ if (this.enableLearning) {
3234
+ await this.learning.applyOutcome(id, action === 'fail' ? 'fail' : 'expire');
3235
+ }
3236
+ if (action === 'notify') {
3237
+ // Worker keeps the assignment; the event + learning outcome
3238
+ // above are the whole breach response.
3239
+ continue;
3240
+ }
3241
+ if (action === 'requeue') {
3242
+ const multi = this.redisClient.multi().hDel(this.acceptedAssignmentsKey, id);
3243
+ if (workerId)
3244
+ multi.sAdd(this.keys.userRejected(workerId), id);
3245
+ await multi.exec();
3246
+ // The JSON still carries _enqueuedAt, so the freshness TTL
3247
+ // keeps ticking across the requeue. A requeue after a
3248
+ // completion breach is not a refusal: _rejectionCount is
3249
+ // untouched.
3250
+ await this.addAssignment(assignment);
3251
+ continue;
3252
+ }
3253
+ if (action === 'fail') {
3254
+ await this.redisClient
3255
+ .multi()
3256
+ .hDel(this.acceptedAssignmentsKey, id)
3257
+ .hSet(this.completedAssignmentsKey, id, JSON.stringify({
3258
+ ...assignment,
3259
+ _failedBy: workerId,
3260
+ _failedAt: now,
3261
+ _failureReason: 'completion-sla-breach',
3262
+ }))
3263
+ // Terminal: the freshness TTL no longer applies.
3264
+ .zRem(this.assignmentsSlaExpiryKey, id)
3265
+ .exec();
3266
+ continue;
3267
+ }
3268
+ // 'park'
3269
+ await this.redisClient
3270
+ .multi()
3271
+ .hDel(this.acceptedAssignmentsKey, id)
3272
+ .hSet(this.keys.parkedAssignments(), id, JSON.stringify(assignment))
3273
+ .zRem(this.assignmentsSlaExpiryKey, id)
3274
+ .exec();
3275
+ }
3276
+ return { breached };
3277
+ }
3278
+ /**
3279
+ * Sweep assignments whose freshness TTL (`sla.expireAfterMs`, measured
3280
+ * from first enqueue) has elapsed. Applies in every state — queued,
3281
+ * pending, accepted — because stale work is stale regardless of who
3282
+ * holds it.
3283
+ */
3284
+ async processSlaExpiries() {
3285
+ await this.readyPromise;
3286
+ const now = Date.now();
3287
+ const expiredIds = await this.redisClient.zRangeByScore(this.assignmentsSlaExpiryKey, '-inf', now);
3288
+ let expired = 0;
3289
+ for (const id of expiredIds) {
3290
+ // Locate the current store: pending (with owner), accepted, or queued.
3291
+ const [pendingJson, acceptedJson, queuedJson] = await Promise.all([
3292
+ this.redisClient.hGet(this.pendingAssignmentsKey, id),
3293
+ this.redisClient.hGet(this.acceptedAssignmentsKey, id),
3294
+ this.redisClient.hGet(this.assignmentsRefKey, id),
3295
+ ]);
3296
+ const json = pendingJson ?? acceptedJson ?? queuedJson;
3297
+ // Stale index entry (already completed/failed/removed): just clean it.
3298
+ if (!json) {
3299
+ await this.redisClient.zRem(this.assignmentsSlaExpiryKey, id);
3300
+ continue;
3301
+ }
3302
+ const assignment = JSON.parse(json);
3303
+ const policy = (0, policy_2.normalizeSlaPolicy)(assignment.sla);
3304
+ if (!policy || policy.expireAfterMs === undefined) {
3305
+ await this.redisClient.zRem(this.assignmentsSlaExpiryKey, id);
3306
+ continue;
3307
+ }
3308
+ const ownerId = pendingJson
3309
+ ? await this.redisClient.hGet(this.assignmentOwnerKey, id)
3310
+ : (assignment[policy_2.SLA_ACCEPTED_BY_FIELD] ?? null);
3311
+ const action = policy.onExpire;
3312
+ expired++;
3313
+ if (action === 'park') {
3314
+ await this.redisClient.hSet(this.keys.parkedAssignments(), id, JSON.stringify(assignment));
3315
+ }
3316
+ // Remove from whichever store it occupies, with full index cleanup.
3317
+ if (pendingJson) {
3318
+ const multi = this.redisClient.multi();
3319
+ if (ownerId)
3320
+ multi.sRem(this.keys.userAssignments(ownerId), `assignment:${id}`);
3321
+ multi.hDel(this.pendingAssignmentsKey, id);
3322
+ multi.zRem(this.pendingAssignmentsExpiryKey, id);
3323
+ multi.hDel(this.assignmentOwnerKey, id);
3324
+ multi.zRem(this.assignmentsSlaExpiryKey, id);
3325
+ multi.zRem(this.scheduleNotAfterKey, id);
3326
+ // Leaving the queued/pending universe: the wait clock stops.
3327
+ multi.zRem(this.keys.assignmentsQueuedAt(), id);
3328
+ await multi.exec();
3329
+ }
3330
+ else if (acceptedJson) {
3331
+ await this.redisClient
3332
+ .multi()
3333
+ .hDel(this.acceptedAssignmentsKey, id)
3334
+ .zRem(this.acceptedAssignmentsExpiryKey, id)
3335
+ .zRem(this.assignmentsSlaExpiryKey, id)
3336
+ .exec();
3337
+ }
3338
+ else {
3339
+ // Queued: full index cleanup via removeAssignment (also zRems
3340
+ // the SLA expiry index).
3341
+ await this.removeAssignment(id);
3342
+ }
3343
+ this.emitAssignmentLifecycle({
3344
+ kind: 'slaExpired',
3345
+ taskId: id,
3346
+ ownerId,
3347
+ action,
3348
+ // Emitted after the removal above, so this snapshot is the only
3349
+ // remaining copy on the 'drop' path.
3350
+ assignment,
3351
+ at: now,
3352
+ });
3353
+ await this.bumpSlaStats(assignment.tags, { ttlExpiries: 1 });
3354
+ if (this.enableLearning) {
3355
+ await this.learning.applyOutcome(id, 'expire');
3356
+ }
3357
+ }
3358
+ return { expired };
3359
+ }
3360
+ /**
3361
+ * Sweep the schedule clocks: close offer windows (`schedule.notAfter`)
3362
+ * that elapsed while un-accepted, then enqueue held assignments whose
3363
+ * `notBefore` arrived. Misses run first so an assignment whose whole
3364
+ * window is already past parks/drops directly instead of transiting the
3365
+ * queue. Each zset entry fires once: the zRem claim makes concurrent
3366
+ * replicas skip entries another sweep already took.
3367
+ */
3368
+ async processScheduledAssignments() {
3369
+ await this.readyPromise;
3370
+ const now = Date.now();
3371
+ let activated = 0;
3372
+ let missed = 0;
3373
+ const missedIds = await this.redisClient.zRangeByScore(this.scheduleNotAfterKey, '-inf', now);
3374
+ for (const id of missedIds) {
3375
+ const claimed = await this.redisClient.zRem(this.scheduleNotAfterKey, id);
3376
+ if (!claimed)
3377
+ continue;
3378
+ // Locate the un-accepted store the assignment occupies. Anything
3379
+ // else (accepted, parked, completed, removed) means the offer
3380
+ // clock is dead and the claim above was the whole cleanup.
3381
+ const [scheduledJson, queuedJson, pendingJson] = await Promise.all([
3382
+ this.redisClient.hGet(this.scheduledAssignmentsKey, id),
3383
+ this.redisClient.hGet(this.assignmentsRefKey, id),
3384
+ this.redisClient.hGet(this.pendingAssignmentsKey, id),
3385
+ ]);
3386
+ const json = scheduledJson ?? queuedJson ?? pendingJson;
3387
+ if (!json)
3388
+ continue;
3389
+ const assignment = JSON.parse(json);
3390
+ const policy = (0, policy_3.normalizeSchedulePolicy)(assignment.schedule);
3391
+ if (!policy || policy.notAfter === undefined)
3392
+ continue;
3393
+ const state = scheduledJson
3394
+ ? 'scheduled'
3395
+ : queuedJson
3396
+ ? 'queued'
3397
+ : 'pending';
3398
+ const ownerId = pendingJson ? ((await this.redisClient.hGet(this.assignmentOwnerKey, id)) ?? null) : null;
3399
+ const action = policy.onMiss;
3400
+ missed++;
3401
+ if (action === 'park') {
3402
+ await this.redisClient.hSet(this.keys.parkedAssignments(), id, JSON.stringify(assignment));
3403
+ }
3404
+ if (scheduledJson) {
3405
+ await this.redisClient
3406
+ .multi()
3407
+ .hDel(this.scheduledAssignmentsKey, id)
3408
+ .zRem(this.scheduledActivateAtKey, id)
3409
+ .exec();
3410
+ }
3411
+ else if (pendingJson) {
3412
+ const multi = this.redisClient.multi();
3413
+ if (ownerId)
3414
+ multi.sRem(this.keys.userAssignments(ownerId), `assignment:${id}`);
3415
+ multi.hDel(this.pendingAssignmentsKey, id);
3416
+ multi.zRem(this.pendingAssignmentsExpiryKey, id);
3417
+ multi.hDel(this.assignmentOwnerKey, id);
3418
+ multi.zRem(this.assignmentsSlaExpiryKey, id);
3419
+ // Leaving the queued/pending universe: the wait clock stops.
3420
+ multi.zRem(this.keys.assignmentsQueuedAt(), id);
3421
+ await multi.exec();
3422
+ }
3423
+ else {
3424
+ // Queued: full index cleanup via removeAssignment.
3425
+ await this.removeAssignment(id);
3426
+ }
3427
+ this.emitAssignmentLifecycle({
3428
+ kind: 'scheduleMissed',
3429
+ taskId: id,
3430
+ ownerId,
3431
+ state,
3432
+ action,
3433
+ // Emitted after the removal above, so this snapshot is the only
3434
+ // remaining copy on the 'drop' path.
3435
+ assignment,
3436
+ at: now,
3437
+ });
3438
+ await this.bumpSlaStats(assignment.tags, { scheduleMisses: 1 });
3439
+ if (this.enableLearning) {
3440
+ await this.learning.applyOutcome(id, 'expire');
3441
+ }
3442
+ }
3443
+ const dueIds = await this.redisClient.zRangeByScore(this.scheduledActivateAtKey, '-inf', now);
3444
+ for (const id of dueIds) {
3445
+ const claimed = await this.redisClient.zRem(this.scheduledActivateAtKey, id);
3446
+ if (!claimed)
3447
+ continue;
3448
+ const json = await this.redisClient.hGet(this.scheduledAssignmentsKey, id);
3449
+ // Force-assigned or removed since the range read.
3450
+ if (!json)
3451
+ continue;
3452
+ // A due notBefore falls straight through addAssignment's hold
3453
+ // guard into the normal enqueue, which also clears the scheduled
3454
+ // hash atomically with the queued write.
3455
+ await this.addAssignment(JSON.parse(json));
3456
+ activated++;
3457
+ this.emitAssignmentLifecycle({ kind: 'scheduleActivated', taskId: id, at: now });
3458
+ }
3459
+ return { activated, missed };
3460
+ }
2561
3461
  /**
2562
3462
  * Assignments held out of matching because their escalation ladder was
2563
3463
  * exhausted under `onExhausted: 'park'` — nobody answered, all the way up.
@@ -2567,10 +3467,27 @@ class AssignmentMatcher {
2567
3467
  const all = await this.redisClient.hGetAll(this.keys.parkedAssignments());
2568
3468
  return Object.values(all).map((json) => JSON.parse(json));
2569
3469
  }
3470
+ /**
3471
+ * Assignments held out of the queue by `schedule.notBefore`, waiting for
3472
+ * the scheduled sweep to activate them.
3473
+ */
3474
+ async getScheduledAssignments() {
3475
+ await this.readyPromise;
3476
+ const all = await this.redisClient.hGetAll(this.scheduledAssignmentsKey);
3477
+ return Object.values(all).map((json) => JSON.parse(json));
3478
+ }
2570
3479
  /**
2571
3480
  * Return a parked assignment to the queue, optionally resetting its
2572
3481
  * escalation level so the ladder can run again from the top.
2573
3482
  *
3483
+ * `resetSla` clears the first-enqueue clock and rejection counter.
3484
+ * Without it an unparked assignment whose freshness TTL already elapsed
3485
+ * will simply expire again on the next TTL sweep.
3486
+ *
3487
+ * `resetSchedule` strips the schedule policy. Without it an assignment
3488
+ * parked by a missed offer window (`schedule.notAfter`) will simply
3489
+ * miss again on the next scheduled sweep.
3490
+ *
2574
3491
  * @returns false when the id was not parked
2575
3492
  */
2576
3493
  async unparkAssignment(id, opts) {
@@ -2579,8 +3496,18 @@ class AssignmentMatcher {
2579
3496
  if (!json)
2580
3497
  return false;
2581
3498
  const assignment = JSON.parse(json);
3499
+ const record = assignment;
2582
3500
  if (opts?.resetEscalation)
2583
- delete assignment._escalationLevel;
3501
+ delete record._escalationLevel;
3502
+ if (opts?.resetSchedule)
3503
+ delete record.schedule;
3504
+ if (opts?.resetSla) {
3505
+ delete record[policy_2.SLA_ENQUEUED_AT_FIELD];
3506
+ delete record[policy_2.SLA_REJECTION_COUNT_FIELD];
3507
+ delete record[policy_2.SLA_MATCHED_AT_FIELD];
3508
+ delete record[policy_2.SLA_ACCEPTED_AT_FIELD];
3509
+ delete record[policy_2.SLA_ACCEPTED_BY_FIELD];
3510
+ }
2584
3511
  await this.redisClient.hDel(this.keys.parkedAssignments(), id);
2585
3512
  await this.addAssignment(assignment);
2586
3513
  return true;
@@ -2609,12 +3536,29 @@ class AssignmentMatcher {
2609
3536
  let parked = 0;
2610
3537
  let expiredSteps = 0;
2611
3538
  let releasedIdleUsers = 0;
3539
+ let completionBreaches = 0;
3540
+ let slaExpiries = 0;
3541
+ let scheduleActivations = 0;
3542
+ let scheduleMisses = 0;
3543
+ // Schedule first: a just-activated assignment's response/SLA clocks
3544
+ // then start from this same tick's state.
3545
+ if (opts.scheduled) {
3546
+ const result = await this.processScheduledAssignments();
3547
+ scheduleActivations = result.activated;
3548
+ scheduleMisses = result.missed;
3549
+ }
2612
3550
  if (opts.responseDeadlines) {
2613
3551
  const result = await this.processResponseDeadlines();
2614
3552
  expiredMatches = result.expired;
2615
3553
  escalations = result.escalations;
2616
3554
  parked = result.parked;
2617
3555
  }
3556
+ if (opts.completionDeadlines) {
3557
+ completionBreaches = (await this.processCompletionDeadlines()).breached;
3558
+ }
3559
+ if (opts.slaExpiries) {
3560
+ slaExpiries = (await this.processSlaExpiries()).expired;
3561
+ }
2618
3562
  if (opts.workflowStepTimeouts && this.enableWorkflows) {
2619
3563
  expiredSteps = await this.processExpiredWorkflowSteps();
2620
3564
  }
@@ -2627,6 +3571,10 @@ class AssignmentMatcher {
2627
3571
  parked,
2628
3572
  expiredSteps,
2629
3573
  releasedIdleUsers,
3574
+ completionBreaches,
3575
+ slaExpiries,
3576
+ scheduleActivations,
3577
+ scheduleMisses,
2630
3578
  tookMs: Date.now() - startedAt,
2631
3579
  };
2632
3580
  }
@@ -2669,6 +3617,9 @@ class AssignmentMatcher {
2669
3617
  resolveMaintenanceOptions(options) {
2670
3618
  return {
2671
3619
  responseDeadlines: options?.responseDeadlines ?? true,
3620
+ completionDeadlines: options?.completionDeadlines ?? true,
3621
+ slaExpiries: options?.slaExpiries ?? true,
3622
+ scheduled: options?.scheduled ?? true,
2672
3623
  workflowStepTimeouts: options?.workflowStepTimeouts ?? this.enableWorkflows,
2673
3624
  idleUsers: options?.idleUsers ?? this.idleUserTimeoutMs !== null,
2674
3625
  };