assignment-user-matcher 1.16.0 → 1.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (166) hide show
  1. package/README.md +312 -20
  2. package/dist/escalation/policy.d.ts +11 -0
  3. package/dist/escalation/policy.d.ts.map +1 -1
  4. package/dist/escalation/policy.js +22 -1
  5. package/dist/forecasting/backtest.d.ts +52 -0
  6. package/dist/forecasting/backtest.d.ts.map +1 -0
  7. package/dist/forecasting/backtest.js +195 -0
  8. package/dist/forecasting/calendar.d.ts +44 -0
  9. package/dist/forecasting/calendar.d.ts.map +1 -0
  10. package/dist/forecasting/calendar.js +85 -0
  11. package/dist/forecasting/cover.d.ts +69 -0
  12. package/dist/forecasting/cover.d.ts.map +1 -0
  13. package/dist/forecasting/cover.js +103 -0
  14. package/dist/forecasting/days.d.ts +17 -0
  15. package/dist/forecasting/days.d.ts.map +1 -0
  16. package/dist/forecasting/days.js +35 -0
  17. package/dist/forecasting/distributions.d.ts +31 -0
  18. package/dist/forecasting/distributions.d.ts.map +1 -0
  19. package/dist/forecasting/distributions.js +154 -0
  20. package/dist/forecasting/effects.d.ts +88 -0
  21. package/dist/forecasting/effects.d.ts.map +1 -0
  22. package/dist/forecasting/effects.js +303 -0
  23. package/dist/forecasting/erlang.d.ts +31 -0
  24. package/dist/forecasting/erlang.d.ts.map +1 -0
  25. package/dist/forecasting/erlang.js +86 -0
  26. package/dist/forecasting/forecast.d.ts +7 -0
  27. package/dist/forecasting/forecast.d.ts.map +1 -0
  28. package/dist/forecasting/forecast.js +221 -0
  29. package/dist/forecasting/index.d.ts +18 -0
  30. package/dist/forecasting/index.d.ts.map +1 -0
  31. package/dist/forecasting/index.js +54 -0
  32. package/dist/forecasting/model.d.ts +145 -0
  33. package/dist/forecasting/model.d.ts.map +1 -0
  34. package/dist/forecasting/model.js +583 -0
  35. package/dist/forecasting/nowcast.d.ts +26 -0
  36. package/dist/forecasting/nowcast.d.ts.map +1 -0
  37. package/dist/forecasting/nowcast.js +92 -0
  38. package/dist/forecasting/simulation.d.ts +91 -0
  39. package/dist/forecasting/simulation.d.ts.map +1 -0
  40. package/dist/forecasting/simulation.js +478 -0
  41. package/dist/forecasting/spikes.d.ts +6 -0
  42. package/dist/forecasting/spikes.d.ts.map +1 -0
  43. package/dist/forecasting/spikes.js +73 -0
  44. package/dist/forecasting/staffing.d.ts +64 -0
  45. package/dist/forecasting/staffing.d.ts.map +1 -0
  46. package/dist/forecasting/staffing.js +765 -0
  47. package/dist/forecasting/stats.d.ts +11 -0
  48. package/dist/forecasting/stats.d.ts.map +1 -0
  49. package/dist/forecasting/stats.js +45 -0
  50. package/dist/forecasting/types.d.ts +299 -0
  51. package/dist/forecasting/types.d.ts.map +1 -0
  52. package/dist/forecasting/types.js +8 -0
  53. package/dist/index.d.ts +3 -2
  54. package/dist/index.d.ts.map +1 -1
  55. package/dist/index.js +8 -1
  56. package/dist/learning/auto-weights.d.ts +1 -5
  57. package/dist/learning/auto-weights.d.ts.map +1 -1
  58. package/dist/learning/auto-weights.js +0 -3
  59. package/dist/lua/book-slot.lua +84 -0
  60. package/dist/lua/claim-queued.lua +47 -0
  61. package/dist/managers/DecisionTraceManager.d.ts +15 -0
  62. package/dist/managers/DecisionTraceManager.d.ts.map +1 -1
  63. package/dist/managers/DecisionTraceManager.js +117 -11
  64. package/dist/managers/LearningManager.d.ts +12 -0
  65. package/dist/managers/LearningManager.d.ts.map +1 -1
  66. package/dist/managers/LearningManager.js +21 -7
  67. package/dist/managers/ReliabilityManager.d.ts +1 -2
  68. package/dist/managers/ReliabilityManager.d.ts.map +1 -1
  69. package/dist/managers/ReliabilityManager.js +1 -1
  70. package/dist/managers/TelemetryManager.d.ts.map +1 -1
  71. package/dist/managers/TelemetryManager.js +9 -3
  72. package/dist/managers/WorkflowManager.d.ts.map +1 -1
  73. package/dist/managers/WorkflowManager.js +3 -4
  74. package/dist/matcher.class.d.ts +319 -4
  75. package/dist/matcher.class.d.ts.map +1 -1
  76. package/dist/matcher.class.js +1428 -102
  77. package/dist/queries/lane-stats.d.ts +51 -0
  78. package/dist/queries/lane-stats.d.ts.map +1 -0
  79. package/dist/queries/lane-stats.js +78 -0
  80. package/dist/schedule/recurrence.d.ts +11 -0
  81. package/dist/schedule/recurrence.d.ts.map +1 -1
  82. package/dist/schedule/recurrence.js +19 -2
  83. package/dist/schedule/slot.d.ts +60 -0
  84. package/dist/schedule/slot.d.ts.map +1 -0
  85. package/dist/schedule/slot.js +86 -0
  86. package/dist/scheduling/constraints/availability.d.ts +2 -14
  87. package/dist/scheduling/constraints/availability.d.ts.map +1 -1
  88. package/dist/scheduling/constraints/availability.js +14 -15
  89. package/dist/scheduling/constraints/consecutive.d.ts +10 -0
  90. package/dist/scheduling/constraints/consecutive.d.ts.map +1 -1
  91. package/dist/scheduling/constraints/consecutive.js +64 -1
  92. package/dist/scheduling/constraints/contract.d.ts.map +1 -1
  93. package/dist/scheduling/constraints/contract.js +12 -3
  94. package/dist/scheduling/constraints/employee-scope.d.ts.map +1 -1
  95. package/dist/scheduling/constraints/employee-scope.js +10 -2
  96. package/dist/scheduling/constraints/group-composition.js +2 -2
  97. package/dist/scheduling/constraints/min-staffing.d.ts.map +1 -1
  98. package/dist/scheduling/constraints/min-staffing.js +51 -8
  99. package/dist/scheduling/constraints/rolling-hours.d.ts.map +1 -1
  100. package/dist/scheduling/constraints/rolling-hours.js +29 -4
  101. package/dist/scheduling/constraints/support.d.ts +4 -8
  102. package/dist/scheduling/constraints/support.d.ts.map +1 -1
  103. package/dist/scheduling/constraints/support.js +23 -2
  104. package/dist/scheduling/constraints/weekly-rest.d.ts +28 -0
  105. package/dist/scheduling/constraints/weekly-rest.d.ts.map +1 -1
  106. package/dist/scheduling/constraints/weekly-rest.js +108 -21
  107. package/dist/scheduling/engine/construction.d.ts.map +1 -1
  108. package/dist/scheduling/engine/construction.js +56 -7
  109. package/dist/scheduling/engine/objective.d.ts +0 -1
  110. package/dist/scheduling/engine/objective.d.ts.map +1 -1
  111. package/dist/scheduling/engine/objective.js +65 -6
  112. package/dist/scheduling/engine/search.d.ts +4 -0
  113. package/dist/scheduling/engine/search.d.ts.map +1 -1
  114. package/dist/scheduling/engine/search.js +2 -1
  115. package/dist/scheduling/engine/state.d.ts +14 -0
  116. package/dist/scheduling/engine/state.d.ts.map +1 -1
  117. package/dist/scheduling/engine/state.js +7 -0
  118. package/dist/scheduling/engine/timeline.d.ts +23 -1
  119. package/dist/scheduling/engine/timeline.d.ts.map +1 -1
  120. package/dist/scheduling/engine/timeline.js +85 -27
  121. package/dist/scheduling/engine/verdicts.d.ts +40 -1
  122. package/dist/scheduling/engine/verdicts.d.ts.map +1 -1
  123. package/dist/scheduling/engine/verdicts.js +177 -17
  124. package/dist/scheduling/index.d.ts +3 -2
  125. package/dist/scheduling/index.d.ts.map +1 -1
  126. package/dist/scheduling/index.js +7 -1
  127. package/dist/scheduling/model.d.ts +8 -4
  128. package/dist/scheduling/model.d.ts.map +1 -1
  129. package/dist/scheduling/model.js +239 -23
  130. package/dist/scheduling/operations.d.ts +174 -2
  131. package/dist/scheduling/operations.d.ts.map +1 -1
  132. package/dist/scheduling/operations.js +558 -21
  133. package/dist/scheduling/preference-report.d.ts +15 -0
  134. package/dist/scheduling/preference-report.d.ts.map +1 -0
  135. package/dist/scheduling/preference-report.js +111 -0
  136. package/dist/scheduling/preferences.d.ts +30 -0
  137. package/dist/scheduling/preferences.d.ts.map +1 -0
  138. package/dist/scheduling/preferences.js +85 -0
  139. package/dist/scheduling/resilience.d.ts +46 -0
  140. package/dist/scheduling/resilience.d.ts.map +1 -0
  141. package/dist/scheduling/resilience.js +45 -0
  142. package/dist/scheduling/scheduler.class.d.ts +12 -1
  143. package/dist/scheduling/scheduler.class.d.ts.map +1 -1
  144. package/dist/scheduling/scheduler.class.js +28 -4
  145. package/dist/scheduling/sites.d.ts +1 -1
  146. package/dist/scheduling/sites.d.ts.map +1 -1
  147. package/dist/scheduling/sites.js +34 -1
  148. package/dist/scheduling/time.d.ts +28 -6
  149. package/dist/scheduling/time.d.ts.map +1 -1
  150. package/dist/scheduling/time.js +59 -17
  151. package/dist/scheduling/types.d.ts +247 -7
  152. package/dist/scheduling/types.d.ts.map +1 -1
  153. package/dist/scoring/fair-arbitration.d.ts.map +1 -1
  154. package/dist/scoring/fair-arbitration.js +2 -1
  155. package/dist/tracing/decision-trace.d.ts +5 -0
  156. package/dist/tracing/decision-trace.d.ts.map +1 -1
  157. package/dist/tracing/decision-trace.js +3 -0
  158. package/dist/types/matcher.d.ts +369 -2
  159. package/dist/types/matcher.d.ts.map +1 -1
  160. package/dist/updates/assignment-update.d.ts +93 -0
  161. package/dist/updates/assignment-update.d.ts.map +1 -0
  162. package/dist/updates/assignment-update.js +91 -0
  163. package/dist/utils/keys.d.ts +10 -0
  164. package/dist/utils/keys.d.ts.map +1 -1
  165. package/dist/utils/keys.js +43 -0
  166. package/package.json +25 -3
package/README.md CHANGED
@@ -397,13 +397,49 @@ The redistribution counterpart to `pauseUser`: requeue every pending (matched bu
397
397
 
398
398
  ### `assignToUser(assignmentId: string, userId: string, options?: { force?: boolean }): Promise<{ previousOwnerId: string | null }>`
399
399
 
400
- Operator override: hand an assignment directly to a user, bypassing tag/weight selection. Works on queued assignments and on pending assignments held by another user (the previous owner's backlog slot is released and the expiry clock restarts). Idempotent when the user already owns the assignment.
400
+ Operator override: hand an assignment directly to a user, bypassing tag/weight selection. Works on queued assignments, on pending assignments held by another user (the previous owner's backlog slot is released and the expiry clock restarts), and on **accepted** work already in progress. Idempotent when the user already owns the assignment.
401
+
402
+ Reassigning accepted work lands it as **pending**, not accepted: the new user gets a fresh offer they still have to answer, because they have agreed to nothing yet and an accepted record under somebody who never said yes is a completion deadline running against a promise nobody made. The previous owner's accepted index entry, their `sla.completeWithinMs` deadline and the `_acceptedAt` / `_acceptedBy` stamps are all cleared; the wait clock restarts at the hand-over, so queue-age dashboards can still see the work as unaccepted. The previous owner gets a `released` event with `reason: 'reassigned'` — nothing else names them, and anything mirroring their accepted work needs to hear that it moved. An offer window (`schedule.notAfter`) that the first acceptance already answered is not re-armed, and for SLA-bearing work the re-offer is counted as an offer so the acceptance rate cannot read above 100%.
401
403
 
402
404
  Hard rules still apply unless `force: true`: the user must not be paused, must have backlog headroom, must not be vetoed on the assignment, and must not have previously rejected it. The learning layer is never fed by manual assignments. When tracing is active the override is recorded as a decision trace with mode `'manual'`, so supervisor actions land in the same audit trail as organic matches.
403
405
 
406
+ ### `returnAcceptedToPending(userId: string, assignmentId: string): Promise<boolean>`
407
+
408
+ Undo an acceptance: the worker who accepted the task gets it back as a **pending** offer of their own. Nothing is refused or requeued for others, so unlike `rejectAssignment` (which only works on pending work) this works on accepted work, and the worker is not barred from accepting it again. The completion deadline and accept stamps are cleared, and the lifecycle hook sees `released` (`reassigned`) for the worker followed by `pending`. Throws unless `userId` is the worker who accepted it.
409
+
410
+ ### `updateAssignment(id: string, patch: AssignmentUpdate): Promise<UpdateAssignmentResult | null>`
411
+
412
+ Edit a task that already exists — including one somebody is holding. The patch may carry `tags`, `priority`, `title` and `meta`; a field left `undefined` is untouched, and `title` / `meta` accept `null` to clear them. Policies (`escalation`, `sla`, `schedule`, `vetoedUsers`) are chosen when the work is created and are not patched piecemeal. Returns `null` when no live record exists; terminal work is not editable.
413
+
414
+ `tags` and `priority` decide who *should* have the task, so changing them is not a metadata write. The rule, applied in every state, is **retag always, then re-check the holder**:
415
+
416
+ | State | What happens |
417
+ | --- | --- |
418
+ | `queued` | Per-tag sorted sets move: removed tags are evicted, every surviving tag is rescored. |
419
+ | `scheduled` / `parked` | The held record is rewritten in place; no indexes exist yet, and the activation or unpark builds them from the new tags. |
420
+ | `pending` / `accepted` | The record is rewritten, then the current holder is scored against the new tag set exactly as organic matching scores them. |
421
+
422
+ A holder who still scores above zero keeps the task — including accepted work, because nothing about the job changed for them. A holder who no longer matches (or whom the new tags hard-veto) loses it: the task is taken back, an `AssignmentLifecycleEvent` of kind `released` fires with `reason: 'retagged'`, and the record returns to the queue under its new tags with `requeued: true` in the result. The next matching pass offers it to somebody the new tags actually reach — this method never picks the replacement itself.
423
+
424
+ The re-check is the judgement the matching pass makes, not a smaller copy of it: a custom `matchingFunction`, the CIDR allow-list and the geo range all apply, so `explainMatch` and a retag can never disagree about the same person on the same task. Two holders are exempt. Workflow-targeted work is routed by name rather than by tags, so a tag change cannot un-route it. And a task whose holder accepted it between the read and the write is left where it is rather than requeued into a second copy.
425
+
426
+ An edit that leaves the tags alone never moves anything, whoever holds the task and however they came by it: fixing a typo in a title is not a reason to pull a job off the person doing it. Restating an identical tag set (in any order) counts as no change. Patch tags are trimmed and de-duplicated but never case-folded, because tags are compared exactly everywhere else — `Plumbing` and `plumbing` are two tags at creation, in matching and in an edit alike. An edit that omits `priority` keeps whatever the task already has, including a priority the engine derived at creation. Note that under `enableDefaultMatching` every user carries the shared `default` tag, so a retag can never strand a holder on tags alone — only an explicit zero-weight veto or a skill threshold will.
427
+
428
+ Like `assignToUser`, `updateAssignment` never feeds the learning layer: an operator changing what the work *is* says nothing about how well the worker was doing it.
429
+
430
+ ```typescript
431
+ const result = await matcher.updateAssignment('job-12', {
432
+ title: 'Leaking kitchen tap',
433
+ tags: ['plumbing', 'urgent'],
434
+ });
435
+ if (result?.requeued) {
436
+ // the previous holder no longer matches — it is back in the queue
437
+ }
438
+ ```
439
+
404
440
  ### Response deadlines & escalation (`Assignment.escalation`)
405
441
 
406
- By default an assignment nobody responds to is requeued after the matcher-wide `matchExpirationMs` — and the same user may win it straight back. Attach an `EscalationPolicy` to make that behaviour explicit: a per-assignment deadline, an optional block on the non-responder, a priority climb, and an optional tier ladder that moves the work to a different pool on each hop. **No workflow is required.**
442
+ By default an assignment nobody responds to is requeued after the matcher-wide `matchExpirationMs` — and the same user may win it straight back, on the very next pass. Attach an `EscalationPolicy` to make that behaviour explicit: a per-assignment deadline, a rest period before the same person is asked again, an optional block on the non-responder, a priority climb, and an optional tier ladder that moves the work to a different pool on each hop. **No workflow is required.**
407
443
 
408
444
  ```ts
409
445
  await matcher.addAssignment({
@@ -426,6 +462,7 @@ matcher.startMaintenance(); // deadlines don't fire unless something sweeps them
426
462
  | ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------- |
427
463
  | `respondWithinMs` | Per-assignment response deadline, overriding `matchExpirationMs` | required |
428
464
  | `onNoResponse` | `'block'` treats a non-response as a soft rejection (same rejected set an explicit reject writes to); `'allow'` keeps the historical behaviour | `'allow'` |
465
+ | `offerCooldownMs` | How long the non-responder rests before this assignment can be offered to them again. Overrides the matcher-wide `offerCooldownMs`. Ignored under `onNoResponse: 'block'` | matcher-wide value |
429
466
  | `priorityBoost` | Priority delta applied on each hop | `0` |
430
467
  | `tiers` | Tag ladder. Tier tags are swapped per hop; tags not named by any tier survive untouched | none |
431
468
  | `maxEscalations` | Hop ceiling | `tiers.length - 1`, else unlimited |
@@ -433,6 +470,34 @@ matcher.startMaintenance(); // deadlines don't fire unless something sweeps them
433
470
 
434
471
  The wait clock always survives an escalation: requeues go through `addAssignment`, whose `NX` keeps the original first-enqueue time, so `getQueueStats().oldestWaitingMs` measures the work item rather than the current tier.
435
472
 
473
+ #### Offer cooldowns (`offerCooldownMs`)
474
+
475
+ `onNoResponse` has only two settings, and neither suits work with a small eligible pool: `'allow'` hands the assignment straight back to whoever just ignored it, and `'block'` bars them permanently — which, when they are the *only* eligible worker, means the work is never assigned to anybody. A cooldown is the middle ground. The non-responder is held out of matching **for that one assignment** for a while, so anybody else gets a clear run at it, and they are asked again afterwards.
476
+
477
+ ```ts
478
+ const matcher = new AssignmentMatcher(redis, {
479
+ matchExpirationMs: 60_000,
480
+ offerCooldownMs: 60_000, // default 0 (off): historical behaviour is unchanged
481
+ });
482
+ ```
483
+
484
+ Per assignment, `escalation.offerCooldownMs` overrides it. The cooldown never applies to operator overrides (`assignToUser`) or workflow-targeted grants, is skipped entirely under `onNoResponse: 'block'` (a permanent bar makes a rest period moot), and is cleared when the user accepts the work or an operator hands it to them. A resting candidate is struck out in `explainMatch()` and in decision traces with `{ kind: 'offerCooldown', until }`, so "nobody is eligible right now" always says why.
485
+
486
+ #### Bounding an unanswered-offer loop
487
+
488
+ Cooldowns slow a loop down; they do not end one. Work that nobody ever answers should eventually stop circulating and become somebody's problem to look at. `maxEscalations` **does not need `tiers`** — with no ladder to climb, it is simply a ceiling on how many times the work is re-offered before `onExhausted` fires:
489
+
490
+ ```ts
491
+ escalation: {
492
+ respondWithinMs: 60_000,
493
+ offerCooldownMs: 60_000,
494
+ maxEscalations: 3, // three unanswered offers is enough
495
+ onExhausted: 'park', // then it is an operator's problem, not a loop
496
+ }
497
+ ```
498
+
499
+ Without a `maxEscalations` ceiling the ladder is unbounded by design, so an assignment with one eligible worker who never responds is re-offered on every sweep for as long as it exists — and every one of those offers is a real decision, with a decision trace to match. Park it instead: `getParkedAssignments()` lists what nobody answered, and `unparkAssignment(id)` puts it back.
500
+
436
501
  Subscribe via `onAssignmentLifecycle` for `escalated` (`{ fromWorkerId, level, blockedPreviousOwner }`) and `escalationExhausted` (`{ level, parked }`) events; `expired` is still emitted first, so existing consumers are unaffected. Parked assignments are reachable with `getParkedAssignments()`, returned to the queue with `unparkAssignment(id, { resetEscalation? })`, and report `_status: 'parked'` from `getAssignment()` — they never read as "not found". `getEscalationLevel(id)` reports how far an assignment has climbed.
437
502
 
438
503
  #### `failed` — the worker-reported outcome
@@ -525,6 +590,56 @@ Lifecycle events: `scheduleActivated` (`{ taskId, at }`) and `scheduleMissed` (`
525
590
 
526
591
  **Learning integration.** Misses feed the contextual bandit as `expire` outcomes — a pending-state miss penalizes the user who sat on the offer, so automatic routing-weight vetoes pick up chronic missers with no extra configuration.
527
592
 
593
+ ### Timeslots and advance booking (`Assignment.slot`)
594
+
595
+ `SchedulePolicy` says when an assignment may be **offered**; a `TimeSlot` says when the work is **performed** and for how long — a fixed appointment, the thing a calendar entry is made of. They are different clocks and deliberately different objects. A task can carry either, both, or neither.
596
+
597
+ ```ts
598
+ await matcher.addAssignment({
599
+ id: 'boiler-service-42',
600
+ tags: ['gas-safe', 'region:north'],
601
+ slot: {
602
+ startAt: Date.parse('2026-10-08T14:00:00Z'), // Thursday 14:00
603
+ durationMs: 90 * 60_000, // for an hour and a half
604
+ bookAheadMs: 14 * 24 * 3600_000, // reserve an engineer a fortnight out (default: a week)
605
+ onUnbooked: 'queue', // or 'park' / 'drop' if nobody was booked in time
606
+ },
607
+ });
608
+
609
+ matcher.startMaintenance(); // the booking sweep runs on the maintenance tick
610
+ ```
611
+
612
+ Three moments, not one:
613
+
614
+ ```
615
+ startAt − bookAheadMs the sweep may reserve a worker
616
+ ↓
617
+ reservation on their calendar; blocks the hour; no backlog place, no clocks
618
+ ↓
619
+ startAt activation: a pending offer to whoever holds the booking
620
+ ```
621
+
622
+ | Field | Meaning | Default |
623
+ | ------------- | ------------------------------------------------------------------------------------------ | --------- |
624
+ | `startAt` | Epoch ms the work is performed. Holds the assignment out of matching until then. | required |
625
+ | `durationMs` | How long it takes. Must be `> 0` and at most `maxSlotSpanMs`. | required |
626
+ | `bookAheadMs` | How far ahead of `startAt` the sweep may book. | 7 days |
627
+ | `onUnbooked` | `'queue'` (open pool, staffed late) / `'park'` / `'drop'` when `startAt` arrives unbooked. | `'queue'` |
628
+
629
+ Semantics worth knowing:
630
+
631
+ - **A reservation is not live work.** Until `startAt` a booked task occupies no backlog place and starts no clock — `accepted` keeps meaning "I am working on this". A week of booked appointments cannot fill somebody's backlog cap, and an SLA completion deadline never runs against work that has not started. The booking sweep therefore ignores today's backlog and pause state when ranking people for next Thursday.
632
+ - **Two appointments never overlap.** The clash check and the write are one Lua script (`book-slot.lua`); two sweeps cannot both book one person's 14:00. Intervals are half-open, so back-to-back appointments stand. `maxSlotSpanMs` (default 24h) bounds how far back the probe reaches, which is why a longer slot is refused at `addAssignment`.
633
+ - **The sweep books; the planner reviews.** `processSlotBookings()` reserves the best eligible worker — ranked by the same evaluator `explainMatch` uses, so routing weights, wildcards, vetoes, thresholds, CIDR and geo all apply — once the book-ahead window opens. A slot nobody can take emits `slotUnfillable` and is re-examined every `slotBookingRetryMs` (default 15 min). It never feeds or consumes the learning layer: nobody was offered anything and nobody chose.
634
+ - **Availability is your input, not the library's guess.** Give `slotAvailability(userIds, from, to)` and return per-worker `blocked` intervals (approved leave — refuses the booking) and `warnings` (outside a rostered shift, a busy personal calendar — allows it and records the reason on the booking). It is called once per pass for the whole candidate set, never per candidate. Without it, the only rule is the overlap rule.
635
+ - **Activation goes to the holder.** At `startAt` the task lands as a **pending** offer on the booked worker, through the same `assignToUser(…, { force: true })` path an operator uses — never as an acceptance, because they have not said yes yet. The booking row survives activation and is cleared only on hand-back, removal, completion or failure, so the overlap rule protects in-flight work too.
636
+ - **Handing back is not declining.** `handBackBooking(id, userId, reason)` releases the reservation and adds the worker to the assignment's rejected set, so the next sweep books somebody else rather than the same person again.
637
+ - **An explicit offer window can delay an appointment, never bring it forward.** With both `slot` and `schedule.notBefore`, activation is the later of the two.
638
+
639
+ Public surface: `bookSlot(id, userId, { force?, source? })` (the planner's manual booking through the same gate; `force` skips `blocked`, never the overlap rule), `releaseSlotBooking(id)`, `handBackBooking(id, userId, reason?)`, `getSlotBooking(id)`, `getBookings({ from, to, userId? })` (the calendar read, half-open on both sides), `rankSlotCandidates(id)` (best first, each with `bookable` and why not), and `processSlotBookings()` (also run by `runMaintenanceOnce`, before the scheduled sweep, so a slot booked in a pass activates onto its holder in the same pass). `MaintenanceReport` gains `slotsBooked` / `slotsUnfillable`; `MaintenanceOptions.slotBookings` switches the sweep off.
640
+
641
+ Lifecycle events: `slotBooked` (`{ workerId, startAt, endAt, source, warnings? }`), `slotBookingReleased` (`{ workerId, reason: 'hand-back' | 'operator' | 'terminal', detail? }`) and `slotUnfillable` (`{ startAt, endAt }`).
642
+
528
643
  ### Recurring assignments (`addRecurringAssignment`)
529
644
 
530
645
  A recurring assignment is a **standing template**, never itself matchable: the recurrence sweep cuts each occurrence from it as an ordinary assignment whose `schedule` is derived from the policy (`notBefore` = the slot's open time, `notAfter` = open + `windowMs`). Everything else the template carries — tags, priority, SLA, escalation, vetoes, geo — is inherited by every occurrence.
@@ -534,7 +649,8 @@ await matcher.addRecurringAssignment({
534
649
  id: 'blog-draft',
535
650
  tags: ['blog'],
536
651
  recurrence: {
537
- everyMs: 14 * 24 * 3600_000, // biweekly
652
+ everyMs: 7 * 24 * 3600_000, // the period …
653
+ times: 2, // … and two occurrences in it, spread evenly: twice a week
538
654
  startAt: Date.parse('2026-09-07T09:00:00Z'), // first window opens here (default: now)
539
655
  windowMs: 3 * 24 * 3600_000, // each occurrence offered for 3 days
540
656
  onMiss: 'park', // an unserved window parks the occurrence for inspection
@@ -546,7 +662,8 @@ matcher.startMaintenance(); // the recurrence sweep rides the maintenance tick
546
662
 
547
663
  | Field | Meaning | Default |
548
664
  | ---------------- | ----------------------------------------------------------------------------------------------------------------------------------- | -------- |
549
- | `everyMs` | Interval between window opens. Minimum 1000 | required |
665
+ | `everyMs` | The repeating period. With `times: 1` this is simply the interval between window opens | required |
666
+ | `times` | Occurrences per period, spread evenly across it (`gap = everyMs / times`). The **gap** is what must be at least 1000 ms | `1` |
550
667
  | `startAt` | Epoch ms the first window opens | now |
551
668
  | `windowMs` | Offer window per occurrence (`schedule.notAfter = open + windowMs`). Omitted: occurrences never expire off the offer clock | none |
552
669
  | `onMiss` | Per-occurrence miss policy, as in `SchedulePolicy` | `'park'` |
@@ -557,7 +674,8 @@ matcher.startMaintenance(); // the recurrence sweep rides the maintenance tick
557
674
  Semantics worth knowing:
558
675
 
559
676
  - **Occurrence ids are deterministic** — `<templateId>@<openEpochMs>` — so a crashed sweep re-materializing a slot is an idempotent re-add, and any occurrence traces back to its template with no extra state.
560
- - **Slots never drift.** They align to `startAt + k × everyMs` whatever the sweep cadence; the tick decides when a slot is _noticed_, never where it sits.
677
+ - **Slots never drift.** They align to `startAt + k × gap` whatever the sweep cadence; the tick decides when a slot is _noticed_, never where it sits.
678
+ - **`times` is sugar with teeth.** It is resolved once into the gap, and every other field is then measured in gaps rather than periods: `windowMs` is one occurrence's offer window, the sweep looks one gap ahead, and `until` / `maxOccurrences` stay totals — so a budget can run out part-way through a period. A period that does not divide evenly rounds the gap to the nearest millisecond; slots stay exactly one gap apart rather than re-anchoring to each period.
561
679
  - **One occurrence ahead.** The sweep materializes each occurrence one interval before its window opens, so upcoming work is already visible in the scheduled store (`getScheduledAssignments()`, `getQueueStats().scheduled`).
562
680
  - **Skipped slots are free.** Under `catchUp: 'skip'`, slots that fully elapsed during downtime never existed: they don't count against `maxOccurrences` and don't flood the queue on revival. Under `'all'` they materialize and are immediately missed by the schedule sweep (parked/dropped per `onMiss`) — the audit-trail reading of a dead interval.
563
681
  - **Re-adding updates the template, not the clock.** Occurrences already cut and the next slot are facts about the past; remove and re-add to restart.
@@ -591,9 +709,26 @@ Live operational snapshot for dashboards:
591
709
  - `oldestWaitingMs`: age of the longest-waiting unaccepted assignment, or `null`. The wait clock starts at first enqueue and survives reject/expiry requeues; it stops when a user accepts the assignment or it is removed. Held (scheduled) assignments have no wait clock yet.
592
710
  - `perUser`: every user's `backlog` depth, effective `maxBacklogSize` cap, and `paused` state.
593
711
 
594
- ### `removeUser(userId: string): Promise<void>`
712
+ ### `getLaneStats(options?: LaneStatsOptions): Promise<LaneStatsReport>`
713
+
714
+ The queue grouped by routing tag, for floors where listing tasks tells nobody anything (hundreds of thousands waiting):
715
+
716
+ - `lanes`: one entry per tag with queued work, deepest first — `queued` (not yet offered), and `oldestWaitingMs` for the lane's oldest queued assignment. That age is exact (`oldestExact: true`) when the lane's work is among the `oldestSampleSize` oldest waiting assignments (default 2000); otherwise it is an upper bound, flagged rather than presented as exact. `alsoTagged` names the other tags the lane's work carries, most frequent first — a task is a candidate for anyone covering *any* of its tags, so a tag nobody covers is only stuck work when nothing it travels with is covered either.
717
+ - `waits`: the wait-clock distribution over every unaccepted assignment (queued or pending) — `waiting`, `p50Ms`, `p95Ms`, `oldestMs` — read by rank from the wait-clock index, so it is exact rather than sampled.
595
718
 
596
- Removes a user from the system and clears their assignment backlog.
719
+ Cost is one `ZCARD` per known tag plus one tag read per sampled assignment, all pipelined; nothing scales with queue depth. The injected `default` tag is never a lane.
720
+
721
+ ### `getOldestQueuedInLane(tag: string, options?: { limit?: number; scanLimit?: number }): Promise<{ id: string; waitingMs: number }[]>`
722
+
723
+ The oldest queued assignments carrying `tag`, oldest first — the "waiting longest" list under one lane. It walks the wait-clock index from the oldest end and reads at most `scanLimit` entries (default 5000), so a lane whose work is all younger than that returns fewer.
724
+
725
+ ### `removeUser(userId: string): Promise<string>`
726
+
727
+ Removes a user and hands back everything they held: pending offers **and accepted work** go back to the queue (a `released` lifecycle event with `reason: 'removed'`, the acceptance stamps and completion clock cleared, the learning attempt closed as a system fault), and slot bookings are dropped back onto the booking sweep. Earlier versions deleted only the user's own indexes, which left their held tasks stranded under a user who no longer existed.
728
+
729
+ ### `getUserHeldWork(userId: string): Promise<{ pending: string[]; accepted: string[]; booked: string[] }>`
730
+
731
+ What a user holds right now, as assignment ids — the read an offboarding preview shows before `removeUser`.
597
732
 
598
733
  ### `removeAssignment(assignmentId: string, tags: string[]): Promise<void>`
599
734
 
@@ -603,6 +738,10 @@ Removes a specific assignment from the system. Requires tags to efficiently loca
603
738
 
604
739
  Marks an assignment as completed by a user, removing it from their backlog and potentially making them available for new assignments.
605
740
 
741
+ ### Finishing work that moved on
742
+
743
+ `completeAssignment` and `failAssignment` check that the caller is the worker who accepted the task, and throw otherwise. Accepted work can change hands — a supervisor reassigning it, or an edit that retags it away — and the person who used to hold it may still have it on screen. Without the check, finishing it would delete the current holder's record, clear the wrong per-user index and attribute the outcome to the wrong worker. Work accepted before this index existed carries no holder and is left alone.
744
+
606
745
  ### `waitUntilReady(): Promise<AssignmentMatcher>`
607
746
 
608
747
  Waits for the matcher to finish connecting and initializing internal Redis and workflow resources.
@@ -641,6 +780,13 @@ type Options = {
641
780
  // If set to false, you should provide a custom `matchingFunction`.
642
781
  enableDefaultMatching?: boolean; // Default: true
643
782
 
783
+ // How long a user who let a response deadline lapse is held out of matching
784
+ // for *that* assignment. The middle ground between letting them win it back
785
+ // on the next pass (the default) and barring them permanently with
786
+ // `escalation.onNoResponse: 'block'`. Per-assignment override:
787
+ // `escalation.offerCooldownMs`.
788
+ offerCooldownMs?: number; // Default: 0 (off)
789
+
644
790
  // Opt-in idle user auto-rejection. When set, users holding pending
645
791
  // (not yet accepted/rejected) assignments with no activity for this many
646
792
  // milliseconds are removed from the matching pool by `processIdleUsers()`,
@@ -897,7 +1043,10 @@ Traces are appended to a capped Redis stream (`decisionTraceMaxEntries`,
897
1043
  default 1000), so the audit record survives restarts and is shared across
898
1044
  replicas. Query with `getDecisionTraces({ assignmentId?, userId?, limit? })`
899
1045
  (newest first), wipe with `clearDecisionTraces()`, and toggle at runtime with
900
- `setDecisionTraces(enabled)` / `isDecisionTracesEnabled()`.
1046
+ `setDecisionTraces(enabled)` / `isDecisionTracesEnabled()`. A lookup by
1047
+ `assignmentId` reads that assignment's entries through a per-assignment index
1048
+ kept in step with the capped stream, rather than scanning the stream; a
1049
+ `userId` filter on its own still scans it.
901
1050
 
902
1051
  What a trace contains:
903
1052
 
@@ -1072,7 +1221,7 @@ correctness rests on:
1072
1221
  - **One decision per committed attempt.** A candidate that was scored but lost
1073
1222
  the assignment — to another worker under fair arbitration, or to another
1074
1223
  process at the claim gate — leaves no decision behind. An assignment that is
1075
- rejected and rematched opens a *second, independent* attempt with its own id;
1224
+ rejected and rematched opens a _second, independent_ attempt with its own id;
1076
1225
  feedback for the first can never reach the second.
1077
1226
  - **Ingestion is idempotent.** Every outcome and every feedback call is gated
1078
1227
  on the attempt's applied-event set, so a redelivered message applies once and
@@ -1225,15 +1374,15 @@ const matcher = new AssignmentMatcher(redisClient, {
1225
1374
 
1226
1375
  Each target gets its own model hash and its own label timing:
1227
1376
 
1228
- | Target | Denominator | Label | Missing data |
1229
- | --- | --- | --- | --- |
1230
- | `acceptance` | one per committed attempt | 1 on accept; 0 on reject or **pre-acceptance** response expiry | attempt still open |
1231
- | `successGivenAcceptance` | one per *accepted* attempt | 1 on complete; 0 on fail or **post-acceptance** expiry | no label when flagged a system fault |
1232
- | `quality` | one per quality observation | normalized `quality` signal, clamped to [0, 1] | **no update at all** |
1377
+ | Target | Denominator | Label | Missing data |
1378
+ | ------------------------ | --------------------------- | -------------------------------------------------------------- | ------------------------------------ |
1379
+ | `acceptance` | one per committed attempt | 1 on accept; 0 on reject or **pre-acceptance** response expiry | attempt still open |
1380
+ | `successGivenAcceptance` | one per _accepted_ attempt | 1 on complete; 0 on fail or **post-acceptance** expiry | no label when flagged a system fault |
1381
+ | `quality` | one per quality observation | normalized `quality` signal, clamped to [0, 1] | **no update at all** |
1233
1382
 
1234
1383
  Component predictions come back as calibrated probabilities; the combined
1235
1384
  utility is `acceptanceWeight * P(accept) + P(accept) * (successWeight *
1236
- P(success|accept) + qualityWeight * E[quality])` and is deliberately *not*
1385
+ P(success|accept) + qualityWeight * E[quality])` and is deliberately _not_
1237
1386
  presented as a probability. Corrections revise a label rather than adding a
1238
1387
  second one — see `learningRewardAccounting` below.
1239
1388
 
@@ -1249,7 +1398,7 @@ statistics that drive automatic routing weights:
1249
1398
  call is one observation. An attempt that accepts, completes and then receives
1250
1399
  a CSAT score counts three times.
1251
1400
  - `'per-attempt'`: one observation per committed attempt, written at the
1252
- terminal outcome with the attempt's accrued reward. Late feedback *revises*
1401
+ terminal outcome with the attempt's accrued reward. Late feedback _revises_
1253
1402
  that observation instead of adding another.
1254
1403
 
1255
1404
  `'per-attempt'` is what the veto sample floors actually assume — they are
@@ -1283,7 +1432,7 @@ any recoverable probability, so the logs it produces cannot be evaluated
1283
1432
  offline at all. `'jitter'` remains the default for backward compatibility.
1284
1433
 
1285
1434
  One honest caveat: under `fairness: 'best-match'` and the other fair modes,
1286
- allocation is a constrained *joint* decision across workers, and a per-worker
1435
+ allocation is a constrained _joint_ decision across workers, and a per-worker
1287
1436
  epsilon-greedy probability is not the probability of the final allocation.
1288
1437
  Treat fair-mode logs as needing an allocation-aware estimator or a randomized
1289
1438
  online comparison, not as ordinary contextual-bandit logs.
@@ -1293,9 +1442,9 @@ passed every hard rule, and it is disabled entirely in shadow mode.
1293
1442
 
1294
1443
  ### Worker Performance Features
1295
1444
 
1296
- By default the feature vector is assignment-side plus the worker's *declared*
1445
+ By default the feature vector is assignment-side plus the worker's _declared_
1297
1446
  tags, which means two workers with identical declared tags produce identical
1298
- features for a given assignment — the model has nothing to learn about *who*
1447
+ features for a given assignment — the model has nothing to learn about _who_
1299
1448
  should get the work. `enableLearningPerformanceFeatures` adds observed
1300
1449
  behaviour:
1301
1450
 
@@ -1371,7 +1520,7 @@ arbitrary continuous rewards is the error the explicit option exists to make
1371
1520
  visible rather than implicit.
1372
1521
 
1373
1522
  **Evidence is counted in independent attempts, not observations.** With
1374
- `decayHalfLifeMs` set, the decayed weight sum is *not* a sample size: scaling
1523
+ `decayHalfLifeMs` set, the decayed weight sum is _not_ a sample size: scaling
1375
1524
  every weight equally leaves it looking like fewer observations than were
1376
1525
  actually seen. `LearningTagStat` therefore carries `attempts` (never decayed)
1377
1526
  and `effectiveSampleSize` (the Kish quantity `sum(w)² / sum(w²)`), and sample
@@ -2025,12 +2174,64 @@ const result = solveSchedule({
2025
2174
 
2026
2175
  Rules cover: daily rest (rolling window, reduction allowances, clock-band containment), weekly rest (two-level floor plus average), rolling working-time averages with absence neutralisation, overtime (ordinary-vs-overtime split, consent, per-day and per-window caps, time-off-in-lieu), duty-type volume quotas, night work (configurable band, per-shift cap, averaging, hazardous absolute cap, volume quotas, prohibited bands), in-shift breaks, consecutive days and nights, forbidden shift successions, minimum start interval, Sunday and holiday rules, minimum engagement, publication and change notice, availability and preferences, date-valid qualifications, group composition, statutory protections, contract limits, and fairness.
2027
2176
 
2177
+ **Worker preferences.** `preferred` / `avoid` availability rules are soft wishes, scored at the soft level, so they never outrank cover or a legal limit.
2178
+
2179
+ - **Matching.** `shiftTypeTags: ['night']` matches by shift type rather than by clock window.
2180
+ - **Priority.** `priority: 'important'` is multiplied by `objectives.preferences.importantWeight`. Under a budget this shifts weight among one person's own rules; it gives them no more total pull than anyone else.
2181
+ - **Budget.** `objectives.preferences.budget` scales each person's wishes to the same total, so someone who states twenty does not out-pull someone who states one. Rules touching no shift in the period cost nothing. Mark imported facts such as calendar busy time `outsideBudget: true`.
2182
+ - **Report.** `result.preferences` (omitted when there is nothing to report) and `checkCompliance(...).preferences` (always present) report per person which wishes were met. A missed `avoid` asks whether someone else could have taken *this person's place*; a missed `preferred` asks the reverse, whether this person could have taken *a holder's place*. The occupant is vacated for the check, so a full shift never reads as cover, and another contract for the same person is never "someone else". For each miss it gives a reason:
2183
+ - `cover` (avoid): nobody else could have taken their place;
2184
+ - `blocked` (preferred): the person could not legally have taken the shift they wanted, including being blocked by their own other assignments;
2185
+ - `tradeoff` (either): the swap was possible, and the solver balanced it against the team.
2186
+
2187
+ ```ts
2188
+ const result = solveSchedule({
2189
+ period,
2190
+ shifts,
2191
+ employees: [
2192
+ {
2193
+ id: 'ana',
2194
+ tags: [],
2195
+ timeOff: [],
2196
+ availability: [
2197
+ { id: 'nights', kind: 'preferred', shiftTypeTags: ['night'] },
2198
+ { id: 'wedding', kind: 'avoid', priority: 'important', fromDate: '2026-06-13', toDate: '2026-06-13' },
2199
+ ],
2200
+ },
2201
+ ],
2202
+ objectives: { preferences: { budget: 10, importantWeight: 4 } },
2203
+ });
2204
+ result.preferences; // [{ employeeId: 'ana', rules: [{ ruleId: 'nights', ... }, { ruleId: 'wedding', outcome: 'met', ... }] }]
2205
+ ```
2206
+
2028
2207
  `Employee.rules` overrides the global set per person — that is how age classes, individual opt-outs and hazardous-work status are expressed. `Employee.personId` aggregates several contracts onto one natural person, which rest and window rules require: overlap (`no-overlap`) and inter-assignment rest (`min-rest`, `dailyRest`) are judged on the person timeline — spanning sibling contracts and supplied `history` — so two contracts cannot double-book a person or dodge a rest floor at the period boundary. Contract hour/day **maxima** are the opposite: per employee record, like the minimum and the `timeOffInLieu` ledger — one contract's cap is never consumed by a sibling's hours. Rolling volume windows (night-shift quotas, weekly-rest averaging) probe true rolling windows anchored on entry boundaries, never a day grid. Declared `available` windows are credited as a **union**: a shift spanning two contiguous windows is inside the declaration.
2029
2208
 
2030
2209
  Break entitlements are checked against shift design: `unpaidBreakMinutes` (deducted from working time) and `paidBreakMinutes` (working time, and the only thing that discharges a `paid: true` break rule). Deadline arithmetic that needs a "now" — notably whether a cancellation of a published assignment fell inside `notice.cancellationDeadlineMinutes` — is anchored by the optional `asOf` input; without it every cancellation is treated as late, the conservative reading.
2031
2210
 
2032
2211
  **Overtime** is regulated separately from total working time where national law does so. `rules.overtime` defines the ordinary baseline (`ordinaryPerDayMinutes` / `ordinaryPerWeekMinutes`; a person's `contract.weeklyMinutes` overrides the weekly figure, so a part-timer's overtime starts at their agreed hours), caps the overtime portion per rolling 24h or per rolling window, and with `requiresConsent` makes any overtime conditional on the employee's recorded `overtimeConsent`. With `compensation: 'timeOff'`, each employee's period overtime accrues a `timeOffInLieu` entry in `result.ledger`.
2033
2212
 
2213
+ **Skill mix — how good the people on a shift are, and in what proportion.** `tagRequirements` counts heads holding a tag, which answers "two nurses" and neither of the two questions operational buyers ask first. The **object form** adds a grade floor: `tagRequirements: { nurse: { min: 1, level: 3 } }` is "at least one senior on every shift", satisfied only by a dated `Qualification` at or above that level — a plain `Employee.tags` entry carries no grade, so it cannot answer a question about seniority. `tagRatios: { nurse: 0.6 }` is the **proportion** form: a floor, rounded up (60% of four people is 2.4, and nobody staffs 2.4, so it means three), and silent on an empty shift because a proportion of nobody is undefined rather than zero. Both count through the same dated check `requiredTags` uses, so a lapsed certificate satisfies neither. The plain number form is unchanged and means exactly what it always meant.
2214
+
2215
+ **Weekend sequencing.** `consecutive.maxConsecutiveWeekends: 1` is "every second weekend off" — the most commonly negotiated scheduling term in Europe and the one shape fairness cannot hold, because equalising _counts_ is satisfied exactly as well by three weekends in a row as by alternating ones, and the arrangement is what people agreed to. It is a sequence rule beside consecutive days and nights, and a Saturday and the Sunday after it are one weekend; counting them as two would make an ordinary weekend breach the term.
2216
+
2217
+ **Contracts that do not span the period.** `contract.startDate` gates eligibility at the head as `endDate` does at the tail, and both **pro-rate what the person is owed**: somebody joining on day fifteen of a four-week period is owed a fortnight, not a month. Without it the contract-hours objective spent the solve closing a shortfall that was an artefact of the arithmetic, loading a new starter past everybody who had been there all month. `contract.openingBalanceMinutes` carries hours already worked into every rolling average — the scalar a twelve-month reference period needs instead of replaying a year of shift-level history on every solve.
2218
+
2219
+ **Sites carry their own calendar and clock.** `Site.publicHolidays` replaces `calendar.publicHolidays` for that site's shifts, which is what lets one roster read a border correctly: Midsummer is a public holiday on one side of it and an ordinary Friday on the other, and both are true at once. An empty array means "no holidays here"; omit the field to inherit. `Site.timeZone` is declared for **validation, not arithmetic** — instances resolve once against the period's single `PeriodClock`, so a roster whose sites span zones would place one site's night band, breaks and day boundaries an hour out and still report itself compliant. The engine refuses that input rather than answering it wrongly; solve one roster per zone.
2220
+
2221
+ **Seniority** (`Employee.seniority`) orders `rankCandidates` between otherwise indistinguishable candidates, which is what a collective agreement ordering offers by seniority actually says. It never outranks cost, travel or contract debt, and it stays inside the profiling-free boundary — a declared contractual fact of the same class as a qualification, not reliability, acceptance history or anything learned.
2222
+
2223
+ **Progress and stopping early.** `onSearch(progress)` is called once when the first complete draft exists (`phase: 'draft'`) and after every search round (`phase: 'improving'`), with counts about the best roster so far — `assigned`, `unfilledSlots`, `evaluatedVariants`, `elapsedMs` — cheap enough to drive a progress bar. (`onProgress` still hands over a full result per improvement, which judges every rule on every pair and costs real search time on a large roster.) `shouldStop()` is asked between rounds; returning `true` ends the search and returns the best roster so far, which is always complete, so a caller can offer "use the draft now". Construction itself is not interrupted.
2224
+
2225
+ **Shifts nobody may lawfully work.** `diagnoseInfeasibility` reports `kind: 'noLawfulEmployee'` for an occurrence that people are eligible for but none may lawfully take even on an empty roster — typically a shift that breaks a rule on its own, like a 22:00–06:00 night the clocks go back in (9 real hours against an 8-hour cap). The finding carries `blockers` (rule, how many people it stops, an example verdict), `durationMinutes` and `workingMinutes`, and makes the report infeasible.
2226
+
2227
+ **One person, many shifts.** `rankShiftsFor(input, employeeId, shiftInstanceIds, roster)` answers "which of these could *this* person take?" — the question a worker's list of open shifts asks. It is `rankCandidates` turned on its side: one model build, one person scored per shift, and each returned `RepairCandidate` is exactly that person's row in `rankCandidates` for the same shift. Shifts they already hold and ids that name no shift are left out; results keep the order of `shiftInstanceIds`. Use it instead of calling `rankCandidates` per shift and picking one row out of each.
2228
+
2229
+ **Shift swaps between workers.** `rankSwapPartners(input, shiftInstanceId, fromEmployeeId, roster, { trades, tradesFrom })` answers "who could take my shift, and what could I take back?". It is `rankCandidates` asked about a shift somebody is *in*: the proposer is taken off it first (asked with them still on it, a shift at its `maxEmployees` reads "no room" for everybody), and ordering, site fields and blockers are `rankCandidates`' own. With `trades: true` each partner carries the shifts of theirs that make a lawful trade — judged with **both** people off the shift they give up, in **both** directions, on one model build. `checkSwap(input, { fromEmployeeId, fromShiftInstanceId, toEmployeeId, toShiftInstanceId }, roster)` judges one proposed give-away (`toShiftInstanceId: null`) or trade the same way and returns `{ fits, blockers }`, each blocker naming the person it applies to. Neither judges rules that span a whole shift or period (tag counts and ratios, aggregates): re-check the resulting roster with `checkCompliance` before applying it.
2230
+
2231
+ **Skill cover.** `diagnoseInfeasibility(input).tagCover` lists, per skill the roster asks for, its demand against the people who hold it: `shifts` asking for it, `seats` (people-shifts), `holders` (anyone holding it on a day it is wanted), `shortDates` — days it asks for more holders than are free (holding it that day, not on time off, inside their contract; one person counts once a day, so an early and a late both wanting a key-holder need two) — and `tightDates`, days with no spare. `kind` is `'mix'` for `tagRequirements`/`tagRatios` and `'everyone'` for `requiredTags`. It is informational and never makes the report infeasible on its own. Each `RepairCandidate` from `rankCandidates` and `rankSwapPartners` carries `tagsHeld`: which of the shift's `tagRequirements` that person holds on its date, at the level asked for — declared qualifications only, so the ranking stays profiling-free.
2232
+
2233
+ **Shift resilience.** `assessShiftResilience(input, roster, { shiftInstanceIds?, expectedDropouts?, topBackups? })` answers, for every shift in a window, whether it is short and who could legally step in if someone drops out. Absence is decided by the engine's own `time-off` constraint, not a separate rule: a rostered person is reported `absent` and removed before anyone is judged whenever that constraint would flag them — declared `Employee.timeOff`, an `input.absences` span, or an overlapping `externalCommitments` entry, including an overnight shift that spills into next-day time off. `backups` are counted through the same eligibility path as `rankCandidates`, overall and per required skill, and judged with one seat vacated: a backup replaces a dropout, so a shift at its `maxEmployees` or a `tagMaximums` cap still counts who could step in (a shift over its maximum needs no cover and is tiered by shortfall alone). Each skill tier is judged against its own share of the expected dropouts — `expectedDropouts × held / assigned` — so a skill only a few holders carry is not judged against the whole shift's dropout expectation. The tier is `critical` (short, nobody can fill it), `at-risk` (short but fillable, or fewer backups than expected dropouts), `watch` (one dropout beyond expectation would hurt) or `ok`. `expectedDropouts` is an aggregate number the caller supplies, such as headcount × a site's absence rate. The engine never predicts an individual. Raise the need by adding `demandOverrides` to the input, not by passing a separate need.
2234
+
2034
2235
  **Temporary demand.** A shift template is the standing rule; `demandOverrides` are the temporary ones — each bounded to an inclusive `from`/`to` date range (optionally to `daysOfWeek` inside it) and applied to every occurrence whose date falls in it. An override can replace `minEmployees`, `maxEmployees` (`null` removes it), `tagRequirements`, `tagMaximums` or `requiredTags`, add `extraEmployees` on top of whatever is in force, or set `runs` — whether the shift happens on those dates at all. `runs` works in **both** directions: `false` is a closure, and `true` opens the shift on dates the template's own `dates`/`daysOfWeek` excludes, so a weekday-only shift can take one weekend without widening the template and opening every weekend from then on. A date opened this way inherits the template's own shape unless the override states otherwise. Overrides fold in array order, later wins field by field, `extraEmployees` accumulates, and a minimum raised above the standing maximum lifts the maximum with it — "three at the peak" means three. The result is an ordinary `ShiftInstance` (with `demandLabel` naming the last labelled override that touched it), so the solver, `checkCompliance`, `explainCandidate`, `rankCandidates` and `expandShiftInstances` all read one headcount and none of them knows an override exists. The day after `to`, the shift is back to its standing shape without anybody editing it.
2035
2236
 
2036
2237
  ```ts
@@ -2133,6 +2334,97 @@ Infeasibility is never silent: understaffed periods return a best-effort partial
2133
2334
 
2134
2335
  Scale (500 employees × 31 days × 3 shifts/day, full EU rule set — `pnpm benchmark:scheduling`): first feasible ~0.4s, converged within the time budget, compliance re-check ~0.1s, repair ~0.15s.
2135
2336
 
2337
+ ## Forecasting (`forecasting` module)
2338
+
2339
+ How much work is coming, and how many people it takes. Like the scheduler, this module is **pure, Redis-free and deterministic** (same inputs and seed, same numbers) and ships only from its own subpath:
2340
+
2341
+ ```ts
2342
+ import {
2343
+ forecastWorkspace,
2344
+ applyNowcast,
2345
+ staffingNeed,
2346
+ staffingBudgetMs,
2347
+ coverNeed,
2348
+ } from 'assignment-user-matcher/forecasting';
2349
+ ```
2350
+
2351
+ It never describes a person. A series is a volume of work (a routing tag, a site, an imported series); a pool member is a declared skill profile with a head count. Nothing here takes per-person rates, speed, reliability or learned routing weights.
2352
+
2353
+ ### Volume: `forecastWorkspace`
2354
+
2355
+ ```ts
2356
+ const { series, spikes } = forecastWorkspace({
2357
+ timeZone: 'Europe/Tallinn',
2358
+ now: Date.now(),
2359
+ series: [
2360
+ { series: '*', hourly, daily }, // the workspace total — always pass it
2361
+ { series: 'lang:en', hourly: enHourly, daily: enDaily },
2362
+ ],
2363
+ occurrences: [{ label: 'winter-sale', kind: 'sale', from: '2026-12-01', to: '2026-12-03' }],
2364
+ });
2365
+ ```
2366
+
2367
+ Every series is forecast hourly for 28 days (from local midnight today) and weekly for 26 weeks. Each hour is `base × trend × season × holiday × Π events × nowcast`, and every factor comes back in `components` so a planner can read why a number is what it is:
2368
+
2369
+ - **Level and trend** — a recency-weighted weekly level with a damped trend, fitted on the daily history. In-sample levels are one step ahead, and unexplained outlier days are left out on a refit, so a spike cannot hide in the level before somebody names it. A large step (about ×2 or ×0.5) that has held for a week and still holds over the last two days is read as a **level shift**: the level is re-anchored on it. A moderate step is followed by the smoothing alone and lags it by 2–4 weeks. A week-long burst that ended within the last ~2 days cannot be told apart from a shift yet, and reads as one until more ordinary days arrive.
2370
+ - **Shape** — each weekday's share of the week and each hour's share of the day, read on **local** days through `PeriodClock` (so a DST week keeps its 10am peak at 10am, and a UTC day is never mistaken for a local one). Shares are pooled ratios over the last 8 clean weeks, and each weekday's hour shape is shrunk towards the all-weekday shape by its own volume, so a sparse series keeps its quiet hours instead of reading them as zero.
2371
+ - **Season** — a week-of-year factor once there are 56 weeks of daily history, shrunk towards 1 by the years of evidence behind it (one year cannot tell a season from a step).
2372
+ - **Holidays and events** — past occurrences are divided out of history and teach an effect per `label`: its size, a day-by-day shape and a knock-on wave in the 14 days after. Learned sizes are shrunk towards 1 by the evidence behind them, a knock-on day must clear the series' own day-to-day noise (Poisson plus the day-level scatter of recent ordinary days) in a run of at least two days off the same way to count, and days the baseline expects fewer than 5 tasks on teach nothing. Without history for the label the planner's own percent (`planned`) is used, then what other events of the same `kind` did, then a wide first-time default that marks the forecast low confidence (`first-time-event:<label>`). `closed: true` forecasts zero. `suggestEffect(occurrence, forecast.effects)` answers "what will this do?" before an occurrence is saved.
2373
+ - **Nowcast** — the next 72 hours rescaled by how today has gone, fading to nothing over those 72 hours. The ratio is shrunk by 25 tasks on each side, held to 0.5–3 and ignored under 5 expected, so twelve tasks against six at 7am does not double the afternoon. Only **drained** hours count: hours after the latest one present in the feed are not read as zero, and a feed more than 3 hours behind gets no nowcast at all. `applyNowcast(hours, actual, now)` re-applies it to a stored forecast as the day goes on.
2374
+
2375
+ **Ranges and accuracy.** The model is refit at six rolling origins (one a week back from `now`) and compared with what happened. An hour's range is the p10/p90 of a negative binomial around the forecast — Poisson counting noise plus a relative model error fitted per lead bucket (24 h, 72 h, 7 d, 28 d) and never narrowing with lead — so the range is never narrower than counting noise. Week rows are the exact sum of their 167, 168 or 169 local hours, with a band from complete backtested weeks. WAPE is reported per lead bucket on local-day totals. The total and the 10 busiest series are backtested; the rest borrow the total's ranges. A forecast is flagged low confidence (`accuracy.lowConfidence`) for fewer than 4 weeks of history, a 72-hour WAPE above 35 %, or a first-time event. A series with no hourly history is listed with the reason `no-hourly-shape` but is not low confidence on that alone: its day and week totals stand, while its hours are an even spread of the day (`hasHourlyShape: false`) — convert its day totals with `coverPersonHours` rather than reading its hours.
2376
+
2377
+ **What was this?** Recent days (16 weeks) far outside the forecast that no known occurrence explains come back as `spikes` on the total, each broken down by the series that moved. A span's `from`/`to` are UTC days (the daily history's grain), not local ones. Naming one as an occurrence divides it out and teaches its effect. A level shift shows here too, as its first days.
2378
+
2379
+ **The total series matters.** Pass the workspace total as series `'*'` (or name another with `totalSeries`). Spikes are found on it, and the long tail of series outside the busiest ten borrow its ranges; without it every series pays for its own backtests and there is no "What was this?".
2380
+
2381
+ `pnpm benchmark:forecast -- [series] [weeks] [seed]` replays a seeded synthetic workspace (by default the worst case the platform stores: the total plus 50 tags, three years of daily and 16 weeks of hourly history) and reports WAPE by lead and the median time per workspace. It exits 1 over 200 ms.
2382
+
2383
+ ### People: `staffingNeed`
2384
+
2385
+ ```ts
2386
+ const result = staffingNeed(
2387
+ hours.map((h) => ({ startMs: h.at, arrivals: { 'lang:en': h.likely } })),
2388
+ [
2389
+ {
2390
+ tag: 'lang:en',
2391
+ handleMs: { q: measuredHandleQuantiles }, // quantiles, never a mean
2392
+ patienceMs: { q: measuredPatienceQuantiles }, // omit when nobody gives up
2393
+ concurrency: 2,
2394
+ targetWaitMs: 60_000,
2395
+ targetShare: 0.8,
2396
+ },
2397
+ ],
2398
+ [
2399
+ { tags: ['lang:en'], count: 12 },
2400
+ { tags: ['lang:en', 'lang:fi'], count: 4 },
2401
+ ],
2402
+ { shrinkage: 0.3, budgetMs: staffingBudgetMs(peakArrivalsPerHour) },
2403
+ );
2404
+ // result.intervals[i]: { productive, onShift, serviceByTag, uncovered, exceedsPool, method, capped }
2405
+ ```
2406
+
2407
+ How many people each hour needs so every tag meets its service target (a share picked up within a wait) comes from a **discrete-event simulation of the router itself**, not from Erlang C:
2408
+
2409
+ - A person takes and ranks a tag exactly as the router scores it (`calculateMatchScore`: positive routing weights, suffix wildcards, weight 0 a veto, and without weights the share of their tags the task matches). A freed person takes the waiting task with the highest `priority + score`, oldest first; an arriving task goes to the best-scoring person who can fit it, onto someone part-busy before someone idle.
2410
+ - Each tag has its own concurrency: a task of a tag with concurrency c takes 1/c of a person.
2411
+ - Handle times and patience are drawn from measured quantiles. A task that gives up waiting counts as **not served**, also when it gives up before the target wait — so short patience shows up as lost work, not as a free pass.
2412
+ - The pool is the declared skill mix, and a multi-skilled person is one head serving every tag they cover. For each head count the team follows the work: one person on every busy tag first (rarest first), then each next head to the tag furthest from its target, placed on the coverer that gains most across the short tags (a specialist on a tie); before a rare skill goes short, a generalist placed for other work is swapped for a spare specialist. `exceedsPool` says the likely team needs more of some declared profile than the pool has: the extra heads are people to hire or borrow with that profile's skills.
2413
+ - Arrivals are Poisson around a Gamma-noised rate (forecast error, `overdispersion`, default k = 20), stratified across the seeds. Each interval opens with the work a floor at that rate already has in hand.
2414
+
2415
+ **What `likely` means.** `productive.likely` is the fewest people whose share served in time, pooled over all seeds, meets the target: it **likely meets the target on average, allowing for forecast error**. `low`/`high` are the p10/p90 of each seed's own answer. Without forecast error it agrees with Erlang C on the one case Erlang C models exactly (one tag, concurrency 1, nobody leaves); with patience it is fewer, with concurrency far fewer, with a shared multi-skill pool fewer than the tags staffed apart. For short-target work, a seed whose forecast error puts more never-abandoning work on the floor than the people can handle counts as unserved, so a sustained peak is staffed for its busy days rather than its average one. Erlang A only brackets the search and is never returned as the answer. `onShift = ⌈productive ÷ (1 − shrinkage)⌉`.
2416
+
2417
+ **Long targets.** When a tag's target is at least 15 minutes or two mean handle times (email, back office), back-to-back intervals are simulated in sequence: each hour opens with what the previous one left queued or in progress at its planned head count, and work still inside its target at the hour's end is judged in the hour that inherits it. Hours whose work is mostly inherited backlog, and the hours that built it, are read on 80 seeds. Staffing is planned **hour by hour**, so a peak is held at its own floor and the backlog is paid for in the hour after; on a test day that came out about 8 % more person-hours than the best whole-day plan.
2418
+
2419
+ **Budget.** The run's wall-clock budget scales with volume: `staffingBudgetMs(peakPerHour)` is 6 s per 300 arrivals an hour at the peak, at least 6 s and at most 20 s. Intervals left when it runs out come back `method: 'skipped'` and the result `incomplete`. `pnpm benchmark:staffing -- [peakPerHour] [days] [seed]` times a nightly run (14 days hourly, chat with concurrency 2 and abandonment, phone, a 30-minute-target email, a three-profile pool) against that budget and exits 1 over it or incomplete.
2420
+
2421
+ ### Other conversions and people per shift
2422
+
2423
+ - `rateNeed(unitsPerHour, unitsPerPersonHour, shrinkage)` — volume that is not a queue (picking, production): units ÷ units per person-hour ÷ (1 − shrinkage).
2424
+ - `headcountNeed(value)` — the series already counts people.
2425
+ - `coverNeed(need, shifts)` turns hourly need (`{ at, people }`) into people per shift: greedy left to right, adding at each short hour to the covering shift that runs latest. Each shift's `min` is a floor and `max` a ceiling; `max: null` (or omitted) is **no ceiling** — unlike the scheduler, where an unstated maximum is no room. `counts` are capped at each shift's `max`, so every hour whose need exceeds what its overlapping shifts can hold is in `unmet` as `{ at, short, reason, atMax }`: `reason: 'no-shift'` when nothing overlaps the hour, `'at-max'` when every covering shift is full, with `atMax` listing those shift ids. `counts` alone reads as covered on a day that is not — **show `unmet` wherever you show `counts`**.
2426
+ - `coverPersonHours(personHours, shifts)` spreads a day's person-hours over its shifts, longest shift first; its `unmet` has the same shape (one entry for the day). Use it for a series without hourly history (`hasHourlyShape: false`), whose hours are an even spread.
2427
+
2136
2428
  ## Important Considerations (Disclaimer)
2137
2429
 
2138
2430
  - **Optimized for a Specific Use Case:** `assignment-user-matcher` is primarily designed and optimized for scenarios with a **relatively small set of active users processing a large volume of incoming assignments** (e.g., call centers, customer support teams, back-office operations). While it might work for other scenarios, its performance characteristics are best suited for this model.
@@ -14,6 +14,8 @@ import type { Assignment, EscalationPolicy } from '../types/matcher';
14
14
  export interface NormalizedEscalationPolicy {
15
15
  respondWithinMs: number;
16
16
  onNoResponse: 'block' | 'allow';
17
+ /** 0 when the policy declares none — the caller then falls back to the matcher-wide value. */
18
+ offerCooldownMs: number;
17
19
  priorityBoost: number;
18
20
  tiers?: string[][];
19
21
  maxEscalations: number;
@@ -40,6 +42,15 @@ export declare function responseDeadlineMs(assignment: Assignment | null | undef
40
42
  * in a typical deployment — cost one `indexOf` and nothing else.
41
43
  */
42
44
  export declare function responseDeadlineFromJson(json: string | null | undefined, fallbackMs: number): number;
45
+ /**
46
+ * How long the non-responder rests before this assignment can be offered to
47
+ * them again, in ms. `0` means no cooldown — the historical behaviour, where
48
+ * the requeue may land straight back on them.
49
+ *
50
+ * A blocking policy returns 0: the owner is barred outright, and a rest period
51
+ * on top of a permanent bar would be redundant bookkeeping.
52
+ */
53
+ export declare function offerCooldownMs(assignment: Assignment | null | undefined, fallbackMs: number): number;
43
54
  export interface EscalationDecision {
44
55
  /** The assignment as it should be re-queued (tier tags + boosted priority + bumped level). */
45
56
  assignment: Assignment;
@@ -1 +1 @@
1
- {"version":3,"file":"policy.d.ts","sourceRoot":"","sources":["../../src/escalation/policy.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,KAAK,EAAE,UAAU,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AAErE,mDAAmD;AACnD,MAAM,WAAW,0BAA0B;IACvC,eAAe,EAAE,MAAM,CAAC;IACxB,YAAY,EAAE,OAAO,GAAG,OAAO,CAAC;IAChC,aAAa,EAAE,MAAM,CAAC;IACtB,KAAK,CAAC,EAAE,MAAM,EAAE,EAAE,CAAC;IACnB,cAAc,EAAE,MAAM,CAAC;IACvB,WAAW,EAAE,OAAO,GAAG,MAAM,CAAC;CACjC;AAED,2EAA2E;AAC3E,eAAO,MAAM,sBAAsB,qBAAqB,CAAC;AAEzD;;;;GAIG;AACH,wBAAgB,yBAAyB,CAAC,MAAM,EAAE,gBAAgB,GAAG,SAAS,GAAG,IAAI,GAAG,0BAA0B,GAAG,IAAI,CAsBxH;AAED,uEAAuE;AACvE,wBAAgB,iBAAiB,CAAC,UAAU,EAAE,UAAU,GAAG,MAAM,CAGhE;AAED;;;GAGG;AACH,wBAAgB,kBAAkB,CAAC,UAAU,EAAE,UAAU,GAAG,IAAI,GAAG,SAAS,EAAE,UAAU,EAAE,MAAM,GAAG,MAAM,CAIxG;AAED;;;;GAIG;AACH,wBAAgB,wBAAwB,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,EAAE,UAAU,EAAE,MAAM,GAAG,MAAM,CAOpG;AAED,MAAM,WAAW,kBAAkB;IAC/B,8FAA8F;IAC9F,UAAU,EAAE,UAAU,CAAC;IACvB,6FAA6F;IAC7F,KAAK,EAAE,MAAM,CAAC;IACd,qFAAqF;IACrF,SAAS,EAAE,OAAO,CAAC;IACnB,0EAA0E;IAC1E,kBAAkB,EAAE,OAAO,CAAC;IAC5B,+CAA+C;IAC/C,WAAW,EAAE,OAAO,GAAG,MAAM,CAAC;CACjC;AAED;;;;;;;;GAQG;AACH,wBAAgB,kBAAkB,CAAC,UAAU,EAAE,UAAU,EAAE,MAAM,EAAE,0BAA0B,GAAG,kBAAkB,CAuCjH"}
1
+ {"version":3,"file":"policy.d.ts","sourceRoot":"","sources":["../../src/escalation/policy.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,KAAK,EAAE,UAAU,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AAErE,mDAAmD;AACnD,MAAM,WAAW,0BAA0B;IACvC,eAAe,EAAE,MAAM,CAAC;IACxB,YAAY,EAAE,OAAO,GAAG,OAAO,CAAC;IAChC,8FAA8F;IAC9F,eAAe,EAAE,MAAM,CAAC;IACxB,aAAa,EAAE,MAAM,CAAC;IACtB,KAAK,CAAC,EAAE,MAAM,EAAE,EAAE,CAAC;IACnB,cAAc,EAAE,MAAM,CAAC;IACvB,WAAW,EAAE,OAAO,GAAG,MAAM,CAAC;CACjC;AAED,2EAA2E;AAC3E,eAAO,MAAM,sBAAsB,qBAAqB,CAAC;AAEzD;;;;GAIG;AACH,wBAAgB,yBAAyB,CAAC,MAAM,EAAE,gBAAgB,GAAG,SAAS,GAAG,IAAI,GAAG,0BAA0B,GAAG,IAAI,CAyBxH;AAED,uEAAuE;AACvE,wBAAgB,iBAAiB,CAAC,UAAU,EAAE,UAAU,GAAG,MAAM,CAGhE;AAED;;;GAGG;AACH,wBAAgB,kBAAkB,CAAC,UAAU,EAAE,UAAU,GAAG,IAAI,GAAG,SAAS,EAAE,UAAU,EAAE,MAAM,GAAG,MAAM,CAIxG;AAED;;;;GAIG;AACH,wBAAgB,wBAAwB,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,EAAE,UAAU,EAAE,MAAM,GAAG,MAAM,CAOpG;AAED;;;;;;;GAOG;AACH,wBAAgB,eAAe,CAAC,UAAU,EAAE,UAAU,GAAG,IAAI,GAAG,SAAS,EAAE,UAAU,EAAE,MAAM,GAAG,MAAM,CAMrG;AAED,MAAM,WAAW,kBAAkB;IAC/B,8FAA8F;IAC9F,UAAU,EAAE,UAAU,CAAC;IACvB,6FAA6F;IAC7F,KAAK,EAAE,MAAM,CAAC;IACd,qFAAqF;IACrF,SAAS,EAAE,OAAO,CAAC;IACnB,0EAA0E;IAC1E,kBAAkB,EAAE,OAAO,CAAC;IAC5B,+CAA+C;IAC/C,WAAW,EAAE,OAAO,GAAG,MAAM,CAAC;CACjC;AAED;;;;;;;;GAQG;AACH,wBAAgB,kBAAkB,CAAC,UAAU,EAAE,UAAU,EAAE,MAAM,EAAE,0BAA0B,GAAG,kBAAkB,CAuCjH"}
@@ -11,7 +11,7 @@
11
11
  * via synthesised policies, workflow steps that escalate on timeout.
12
12
  */
13
13
  Object.defineProperty(exports, "__esModule", { value: true });
14
- exports.escalateAssignment = exports.responseDeadlineFromJson = exports.responseDeadlineMs = exports.escalationLevelOf = exports.normalizeEscalationPolicy = exports.ESCALATION_LEVEL_FIELD = void 0;
14
+ exports.escalateAssignment = exports.offerCooldownMs = exports.responseDeadlineFromJson = exports.responseDeadlineMs = exports.escalationLevelOf = exports.normalizeEscalationPolicy = exports.ESCALATION_LEVEL_FIELD = void 0;
15
15
  /** Internal marker the matcher persists on the assignment between hops. */
16
16
  exports.ESCALATION_LEVEL_FIELD = '_escalationLevel';
17
17
  /**
@@ -28,12 +28,14 @@ function normalizeEscalationPolicy(policy) {
28
28
  const tiers = Array.isArray(policy.tiers)
29
29
  ? policy.tiers.filter((tier) => Array.isArray(tier) && tier.length > 0)
30
30
  : undefined;
31
+ const declaredCooldown = Number(policy.offerCooldownMs);
31
32
  const declaredMax = Number(policy.maxEscalations);
32
33
  // With a tier ladder the natural ceiling is "one hop per remaining tier".
33
34
  const defaultMax = tiers && tiers.length > 0 ? tiers.length - 1 : Number.POSITIVE_INFINITY;
34
35
  return {
35
36
  respondWithinMs,
36
37
  onNoResponse: policy.onNoResponse === 'block' ? 'block' : 'allow',
38
+ offerCooldownMs: Number.isFinite(declaredCooldown) && declaredCooldown > 0 ? declaredCooldown : 0,
37
39
  priorityBoost: Number.isFinite(Number(policy.priorityBoost)) ? Number(policy.priorityBoost) : 0,
38
40
  tiers: tiers && tiers.length > 0 ? tiers : undefined,
39
41
  maxEscalations: Number.isFinite(declaredMax) && declaredMax >= 0 ? declaredMax : defaultMax,
@@ -74,6 +76,25 @@ function responseDeadlineFromJson(json, fallbackMs) {
74
76
  }
75
77
  }
76
78
  exports.responseDeadlineFromJson = responseDeadlineFromJson;
79
+ /**
80
+ * How long the non-responder rests before this assignment can be offered to
81
+ * them again, in ms. `0` means no cooldown — the historical behaviour, where
82
+ * the requeue may land straight back on them.
83
+ *
84
+ * A blocking policy returns 0: the owner is barred outright, and a rest period
85
+ * on top of a permanent bar would be redundant bookkeeping.
86
+ */
87
+ function offerCooldownMs(assignment, fallbackMs) {
88
+ if (!assignment)
89
+ return fallbackMs;
90
+ const policy = normalizeEscalationPolicy(assignment.escalation);
91
+ if (!policy)
92
+ return fallbackMs;
93
+ if (policy.onNoResponse === 'block')
94
+ return 0;
95
+ return policy.offerCooldownMs > 0 ? policy.offerCooldownMs : fallbackMs;
96
+ }
97
+ exports.offerCooldownMs = offerCooldownMs;
77
98
  /**
78
99
  * Decide the next state of an assignment whose response deadline elapsed.
79
100
  *