assignment-user-matcher 1.8.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.
@@ -11,6 +11,8 @@ 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
13
  const policy_2 = require("./sla/policy");
14
+ const policy_3 = require("./schedule/policy");
15
+ const assignment_lint_1 = require("./validation/assignment-lint");
14
16
  const decision_trace_1 = require("./tracing/decision-trace");
15
17
  const features_1 = require("./learning/features");
16
18
  const DecisionTraceManager_1 = require("./managers/DecisionTraceManager");
@@ -66,6 +68,9 @@ class AssignmentMatcher {
66
68
  this.acceptedAssignmentsKey = this.keys.acceptedAssignments();
67
69
  this.acceptedAssignmentsExpiryKey = this.keys.acceptedAssignmentsExpiry();
68
70
  this.assignmentsSlaExpiryKey = this.keys.assignmentsSlaExpiry();
71
+ this.scheduledAssignmentsKey = this.keys.scheduledAssignments();
72
+ this.scheduledActivateAtKey = this.keys.scheduledActivateAt();
73
+ this.scheduleNotAfterKey = this.keys.scheduleNotAfter();
69
74
  this.completedAssignmentsKey = this.keys.completedAssignments();
70
75
  this.calculatePriority = options?.prioritizationFunction ?? this.calculatePriority;
71
76
  this.usingDefaultMatchScore = !options?.matchingFunction;
@@ -249,6 +254,7 @@ class AssignmentMatcher {
249
254
  completionBreaches: num('completionBreaches'),
250
255
  ttlExpiries: num('ttlExpiries'),
251
256
  rejectionParked: num('rejectionParked'),
257
+ scheduleMisses: num('scheduleMisses'),
252
258
  meanAcceptLatencyMs: accepts > 0 ? num('acceptLatencyMsSum') / accepts : 0,
253
259
  meanCompleteLatencyMs: completes > 0 ? num('completeLatencyMsSum') / completes : 0,
254
260
  };
@@ -261,6 +267,7 @@ class AssignmentMatcher {
261
267
  accepted: this.acceptedAssignmentsKey,
262
268
  completed: this.completedAssignmentsKey,
263
269
  parked: this.keys.parkedAssignments(),
270
+ scheduled: this.scheduledAssignmentsKey,
264
271
  };
265
272
  }
266
273
  async initRedis() {
@@ -789,6 +796,180 @@ class AssignmentMatcher {
789
796
  (0, decision_trace_1.sortCandidates)(candidates);
790
797
  return { tags: input.tags, priority: basePriority, evaluatedAt, candidates };
791
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
+ }
792
973
  /** Build and record this pass's decision traces; failures never break matching. */
793
974
  async recordPassTraces(collector, winners, workflowGrants, mode, users) {
794
975
  if (winners.size === 0 && workflowGrants.length === 0)
@@ -1116,6 +1297,26 @@ class AssignmentMatcher {
1116
1297
  }
1117
1298
  async addAssignment(assignment) {
1118
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) {
1119
1320
  let { id, tags, priority, latitude, longitude } = assignment;
1120
1321
  if (!priority)
1121
1322
  priority = await this.calculatePriority(assignment);
@@ -1152,6 +1353,18 @@ class AssignmentMatcher {
1152
1353
  if (slaExpiry !== null) {
1153
1354
  multi.zAdd(this.assignmentsSlaExpiryKey, { score: slaExpiry, value: id });
1154
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
+ }
1155
1368
  if ((0, geo_1.isValidLatitude)(latitude) && (0, geo_1.isValidLongitude)(longitude)) {
1156
1369
  multi.geoAdd(assignmentGeoKey, {
1157
1370
  longitude,
@@ -1222,6 +1435,10 @@ class AssignmentMatcher {
1222
1435
  // 4. Clear SLA indexes (no-ops for non-SLA assignments)
1223
1436
  multi.zRem(this.acceptedAssignmentsExpiryKey, id);
1224
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);
1225
1442
  await multi.exec();
1226
1443
  return id;
1227
1444
  }
@@ -1397,6 +1614,7 @@ class AssignmentMatcher {
1397
1614
  return {
1398
1615
  queued: counts.queued,
1399
1616
  pending: counts.pending,
1617
+ scheduled: counts.scheduled,
1400
1618
  oldestWaitingMs: oldestEntries.length > 0 ? Date.now() - Number(oldestEntries[0].score) : null,
1401
1619
  perUser,
1402
1620
  };
@@ -2275,14 +2493,37 @@ class AssignmentMatcher {
2275
2493
  if (!userJson)
2276
2494
  throw new Error(`User not found: ${userId}`);
2277
2495
  const user = JSON.parse(userJson);
2278
- const [queuedJson, previousOwnerId] = await Promise.all([
2496
+ let [queuedJson, previousOwnerId] = await Promise.all([
2279
2497
  this.redisClient.hGet(this.assignmentsRefKey, assignmentId),
2280
2498
  this.redisClient.hGet(this.assignmentOwnerKey, assignmentId),
2281
2499
  ]);
2282
2500
  if (previousOwnerId === userId)
2283
2501
  return { previousOwnerId: userId };
2284
2502
  if (!queuedJson && !previousOwnerId) {
2285
- 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);
2286
2527
  }
2287
2528
  if (!force) {
2288
2529
  const [isPaused, backlog, isVetoed, hasRejected] = await Promise.all([
@@ -2398,6 +2639,12 @@ class AssignmentMatcher {
2398
2639
  multi.hDel(this.assignmentOwnerKey, assignmentId);
2399
2640
  // The wait clock stops when a user takes the work
2400
2641
  multi.zRem(this.keys.assignmentsQueuedAt(), assignmentId);
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
+ }
2401
2648
  // Store in accepted assignments. SLA-bearing assignments are stamped
2402
2649
  // with the accept timestamp/owner and registered on the completion-
2403
2650
  // deadline index when they declare completeWithinMs.
@@ -2499,11 +2746,12 @@ class AssignmentMatcher {
2499
2746
  async applyRejectionExhaustion(assignment, policy, rejections, cause) {
2500
2747
  const action = policy.onMaxRejections === 'fail' ? 'fail' : 'park';
2501
2748
  const now = Date.now();
2502
- // The assignment leaves the queued/pending universe: stop both clocks.
2749
+ // The assignment leaves the queued/pending universe: stop every clock.
2503
2750
  const multi = this.redisClient
2504
2751
  .multi()
2505
2752
  .zRem(this.keys.assignmentsQueuedAt(), assignment.id)
2506
- .zRem(this.assignmentsSlaExpiryKey, assignment.id);
2753
+ .zRem(this.assignmentsSlaExpiryKey, assignment.id)
2754
+ .zRem(this.scheduleNotAfterKey, assignment.id);
2507
2755
  if (action === 'park') {
2508
2756
  multi.hSet(this.keys.parkedAssignments(), assignment.id, JSON.stringify(assignment));
2509
2757
  }
@@ -2909,6 +3157,7 @@ class AssignmentMatcher {
2909
3157
  .multi()
2910
3158
  .hSet(this.keys.parkedAssignments(), id, JSON.stringify(assignment))
2911
3159
  .zRem(this.keys.assignmentsQueuedAt(), id)
3160
+ .zRem(this.scheduleNotAfterKey, id)
2912
3161
  .exec();
2913
3162
  parked++;
2914
3163
  continue;
@@ -3073,6 +3322,7 @@ class AssignmentMatcher {
3073
3322
  multi.zRem(this.pendingAssignmentsExpiryKey, id);
3074
3323
  multi.hDel(this.assignmentOwnerKey, id);
3075
3324
  multi.zRem(this.assignmentsSlaExpiryKey, id);
3325
+ multi.zRem(this.scheduleNotAfterKey, id);
3076
3326
  // Leaving the queued/pending universe: the wait clock stops.
3077
3327
  multi.zRem(this.keys.assignmentsQueuedAt(), id);
3078
3328
  await multi.exec();
@@ -3107,6 +3357,107 @@ class AssignmentMatcher {
3107
3357
  }
3108
3358
  return { expired };
3109
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
+ }
3110
3461
  /**
3111
3462
  * Assignments held out of matching because their escalation ladder was
3112
3463
  * exhausted under `onExhausted: 'park'` — nobody answered, all the way up.
@@ -3116,6 +3467,15 @@ class AssignmentMatcher {
3116
3467
  const all = await this.redisClient.hGetAll(this.keys.parkedAssignments());
3117
3468
  return Object.values(all).map((json) => JSON.parse(json));
3118
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
+ }
3119
3479
  /**
3120
3480
  * Return a parked assignment to the queue, optionally resetting its
3121
3481
  * escalation level so the ladder can run again from the top.
@@ -3124,6 +3484,10 @@ class AssignmentMatcher {
3124
3484
  * Without it an unparked assignment whose freshness TTL already elapsed
3125
3485
  * will simply expire again on the next TTL sweep.
3126
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
+ *
3127
3491
  * @returns false when the id was not parked
3128
3492
  */
3129
3493
  async unparkAssignment(id, opts) {
@@ -3135,6 +3499,8 @@ class AssignmentMatcher {
3135
3499
  const record = assignment;
3136
3500
  if (opts?.resetEscalation)
3137
3501
  delete record._escalationLevel;
3502
+ if (opts?.resetSchedule)
3503
+ delete record.schedule;
3138
3504
  if (opts?.resetSla) {
3139
3505
  delete record[policy_2.SLA_ENQUEUED_AT_FIELD];
3140
3506
  delete record[policy_2.SLA_REJECTION_COUNT_FIELD];
@@ -3172,6 +3538,15 @@ class AssignmentMatcher {
3172
3538
  let releasedIdleUsers = 0;
3173
3539
  let completionBreaches = 0;
3174
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
+ }
3175
3550
  if (opts.responseDeadlines) {
3176
3551
  const result = await this.processResponseDeadlines();
3177
3552
  expiredMatches = result.expired;
@@ -3198,6 +3573,8 @@ class AssignmentMatcher {
3198
3573
  releasedIdleUsers,
3199
3574
  completionBreaches,
3200
3575
  slaExpiries,
3576
+ scheduleActivations,
3577
+ scheduleMisses,
3201
3578
  tookMs: Date.now() - startedAt,
3202
3579
  };
3203
3580
  }
@@ -3242,6 +3619,7 @@ class AssignmentMatcher {
3242
3619
  responseDeadlines: options?.responseDeadlines ?? true,
3243
3620
  completionDeadlines: options?.completionDeadlines ?? true,
3244
3621
  slaExpiries: options?.slaExpiries ?? true,
3622
+ scheduled: options?.scheduled ?? true,
3245
3623
  workflowStepTimeouts: options?.workflowStepTimeouts ?? this.enableWorkflows,
3246
3624
  idleUsers: options?.idleUsers ?? this.idleUserTimeoutMs !== null,
3247
3625
  };
@@ -21,7 +21,9 @@ export interface AssignmentCounts {
21
21
  accepted: number;
22
22
  /** Assignments held out of matching by an exhausted escalation ladder */
23
23
  parked: number;
24
- /** queued + pending + accepted — parked items are counted separately */
24
+ /** Assignments held out of the queue by `schedule.notBefore` */
25
+ scheduled: number;
26
+ /** queued + pending + accepted — parked and scheduled items are counted separately */
25
27
  total: number;
26
28
  }
27
29
  export interface AssignmentKeys {
@@ -30,6 +32,8 @@ export interface AssignmentKeys {
30
32
  accepted: string;
31
33
  /** Optional parked store; omitted by callers that predate escalation policies */
32
34
  parked?: string;
35
+ /** Optional scheduled store; omitted by callers that predate schedule policies */
36
+ scheduled?: string;
33
37
  }
34
38
  /**
35
39
  * Get all assignments from all stores (queued, pending, accepted)
@@ -1 +1 @@
1
- {"version":3,"file":"pagination.d.ts","sourceRoot":"","sources":["../../src/queries/pagination.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,OAAO,KAAK,EAAE,eAAe,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAEpE,MAAM,MAAM,gBAAgB,GAAG,QAAQ,GAAG,SAAS,GAAG,UAAU,CAAC;AAEjE,MAAM,WAAW,iBAAiB;IAC9B,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACvB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,M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AChB,kFAAkF;IAClF,SAAS,CAAC,EAAE,MAAM,CAAC;CACtB;AAED;;GAEG;AACH,wBAAsB,2BAA2B,CAC7C,WAAW,EAAE,eAAe,EAC5B,IAAI,EAAE,cAAc,GACrB,OAAO,CAAC,UAAU,EAAE,CAAC,CASvB;AAED;;GAEG;AACH,wBAAsB,6BAA6B,CAC/C,WAAW,EAAE,eAAe,EAC5B,IAAI,EAAE,cAAc,GACrB,OAAO,CAAC,gBAAgB,CAAC,CAiB3B;AAED;;GAEG;AACH,wBAAsB,iBAAiB,CACnC,WAAW,EAAE,eAAe,EAC5B,IAAI,EAAE,cAAc,EACpB,EAAE,EAAE,MAAM,GACX,OAAO,CAAC,CAAC,UAAU,GAAG;IAAE,OAAO,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC,GAAG,IAAI,CAAC,CA4CrD;AAED;;GAEG;AACH,wBAAsB,wBAAwB,CAC1C,WAAW,EAAE,eAAe,EAC5B,IAAI,EAAE,cAAc,EACpB,GAAG,EAAE,MAAM,EAAE,GACd,OAAO,CAAC,UAAU,EAAE,CAAC,CA+BvB;AAED;;GAEG;AACH,wBAAsB,iCAAiC,CACnD,WAAW,EAAE,eAAe,EAC5B,IAAI,EAAE,cAAc,EACpB,OAAO,CAAC,EAAE,iBAAiB,GAC5B,OAAO,CAAC,gBAAgB,CAAC,CA2H3B"}
@@ -18,17 +18,19 @@ exports.getAllAssignmentsFromStores = getAllAssignmentsFromStores;
18
18
  * Get assignment counts by status
19
19
  */
20
20
  async function getAssignmentCountsFromStores(redisClient, keys) {
21
- const [queued, pending, accepted, parked] = await Promise.all([
21
+ const [queued, pending, accepted, parked, scheduled] = await Promise.all([
22
22
  redisClient.hLen(keys.queued),
23
23
  redisClient.hLen(keys.pending),
24
24
  redisClient.hLen(keys.accepted),
25
25
  keys.parked ? redisClient.hLen(keys.parked) : Promise.resolve(0),
26
+ keys.scheduled ? redisClient.hLen(keys.scheduled) : Promise.resolve(0),
26
27
  ]);
27
28
  return {
28
29
  queued,
29
30
  pending,
30
31
  accepted,
31
32
  parked,
33
+ scheduled,
32
34
  total: queued + pending + accepted,
33
35
  };
34
36
  }
@@ -57,8 +59,17 @@ async function getAssignmentById(redisClient, keys, id) {
57
59
  assignment._status = 'accepted';
58
60
  return assignment;
59
61
  }
60
- // Parked items are out of the matching universe but must never read as
61
- // "not found" — that would make an exhausted escalation look like data loss.
62
+ // Scheduled and parked items are out of the matching universe but must
63
+ // never read as "not found" — that would make a held assignment or an
64
+ // exhausted escalation look like data loss.
65
+ if (keys.scheduled) {
66
+ const scheduled = await redisClient.hGet(keys.scheduled, id);
67
+ if (scheduled) {
68
+ const assignment = JSON.parse(scheduled);
69
+ assignment._status = 'scheduled';
70
+ return assignment;
71
+ }
72
+ }
62
73
  if (keys.parked) {
63
74
  const parked = await redisClient.hGet(keys.parked, id);
64
75
  if (parked) {
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Schedule policy — pure logic.
3
+ *
4
+ * An assignment carries an optional `schedule` policy describing its offer
5
+ * window: `notBefore` holds it out of the queue entirely, `notAfter` expires
6
+ * it while still un-accepted. Everything here is deliberately side-effect
7
+ * free: `AssignmentMatcher` owns the Redis writes, this module owns the
8
+ * decisions.
9
+ *
10
+ * Escalation owns the response clock and SLA owns the post-accept contract;
11
+ * schedule owns the offer window. Acceptance ends its authority.
12
+ */
13
+ import type { SchedulePolicy } from '../types/matcher';
14
+ /** A policy with every optional field resolved. */
15
+ export interface NormalizedSchedulePolicy {
16
+ notBefore?: number;
17
+ notAfter?: number;
18
+ onMiss: 'park' | 'drop';
19
+ }
20
+ /**
21
+ * Resolve an assignment's schedule policy, or `null` when it has none (the
22
+ * overwhelming majority of assignments — callers use the null to stay on
23
+ * the untouched legacy path). A window with `notAfter <= notBefore` can
24
+ * never be satisfied, so the whole policy is treated as absent.
25
+ */
26
+ export declare function normalizeSchedulePolicy(policy: SchedulePolicy | undefined | null): NormalizedSchedulePolicy | null;
27
+ /**
28
+ * Same question, answered from the stored JSON without paying for a parse on
29
+ * the accept hot path. Assignments without a schedule — effectively all of
30
+ * them in a typical deployment — cost one `indexOf` and nothing else.
31
+ */
32
+ export declare function scheduleFromJson(json: string | null | undefined): NormalizedSchedulePolicy | null;
33
+ /** Whether the assignment must stay in the scheduled store at `now`. */
34
+ export declare function isHeld(policy: NormalizedSchedulePolicy, now: number): boolean;
35
+ //# sourceMappingURL=policy.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"policy.d.ts","sourceRoot":"","sources":["../../src/schedule/policy.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,KAAK,EAAc,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAEnE,mDAAmD;AACnD,MAAM,WAAW,wBAAwB;IACrC,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,MAAM,EAAE,MAAM,GAAG,MAAM,CAAC;CAC3B;AAOD;;;;;GAKG;AACH,wBAAgB,uBAAuB,CAAC,MAAM,EAAE,cAAc,GAAG,SAAS,GAAG,IAAI,GAAG,wBAAwB,GAAG,IAAI,CAclH;AAED;;;;GAIG;AACH,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,GAAG,wBAAwB,GAAG,IAAI,CAOjG;AAED,wEAAwE;AACxE,wBAAgB,MAAM,CAAC,MAAM,EAAE,wBAAwB,EAAE,GAAG,EAAE,MAAM,GAAG,OAAO,CAE7E"}