assignment-user-matcher 1.6.0 → 1.8.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 (43) hide show
  1. package/README.md +177 -11
  2. package/dist/escalation/policy.d.ts +65 -0
  3. package/dist/escalation/policy.d.ts.map +1 -0
  4. package/dist/escalation/policy.js +120 -0
  5. package/dist/index.d.ts +2 -2
  6. package/dist/index.d.ts.map +1 -1
  7. package/dist/learning/auto-weights.d.ts +18 -8
  8. package/dist/learning/auto-weights.d.ts.map +1 -1
  9. package/dist/learning/auto-weights.js +120 -18
  10. package/dist/learning/features.d.ts +2 -2
  11. package/dist/learning/features.d.ts.map +1 -1
  12. package/dist/learning/features.js +10 -2
  13. package/dist/managers/LearningManager.d.ts +7 -0
  14. package/dist/managers/LearningManager.d.ts.map +1 -1
  15. package/dist/managers/LearningManager.js +85 -11
  16. package/dist/managers/WorkflowManager.d.ts +10 -0
  17. package/dist/managers/WorkflowManager.d.ts.map +1 -1
  18. package/dist/managers/WorkflowManager.js +57 -2
  19. package/dist/matcher.class.d.ts +141 -4
  20. package/dist/matcher.class.d.ts.map +1 -1
  21. package/dist/matcher.class.js +801 -27
  22. package/dist/queries/pagination.d.ts +5 -0
  23. package/dist/queries/pagination.d.ts.map +1 -1
  24. package/dist/queries/pagination.js +13 -1
  25. package/dist/scoring/match-score.d.ts +6 -0
  26. package/dist/scoring/match-score.d.ts.map +1 -1
  27. package/dist/scoring/match-score.js +17 -2
  28. package/dist/sla/policy.d.ts +49 -0
  29. package/dist/sla/policy.d.ts.map +1 -0
  30. package/dist/sla/policy.js +96 -0
  31. package/dist/tracing/decision-trace.d.ts.map +1 -1
  32. package/dist/tracing/decision-trace.js +4 -2
  33. package/dist/types/matcher.d.ts +395 -2
  34. package/dist/types/matcher.d.ts.map +1 -1
  35. package/dist/utils/keys.d.ts +8 -0
  36. package/dist/utils/keys.d.ts.map +1 -1
  37. package/dist/utils/keys.js +16 -0
  38. package/dist/workflow-builder.d.ts +22 -0
  39. package/dist/workflow-builder.d.ts.map +1 -1
  40. package/dist/workflow-builder.js +29 -0
  41. package/dist/workflow-validation.d.ts.map +1 -1
  42. package/dist/workflow-validation.js +32 -0
  43. package/package.json +2 -1
package/README.md CHANGED
@@ -212,6 +212,35 @@ console.log(instance.id, instance.currentStepId);
212
212
 
213
213
  You can still call `registerWorkflow()` and `startWorkflow()` separately if you want explicit lifecycle control.
214
214
 
215
+ #### Escalation ladders (`escalateTo`)
216
+
217
+ A step whose timeout expires normally fails the run (after any `maxRetries`). `escalateTo(stepId)` turns that timeout into a forward hop instead — the classic page-the-primary-then-the-secondary ladder:
218
+
219
+ ```typescript
220
+ const escalation = workflow('oncall', 'On-call escalation')
221
+ .step('page-primary')
222
+ .assignment({ tags: ['sev:1', 'oncall-primary'] })
223
+ .targetUser({ tag: 'oncall-primary' })
224
+ .timeout(60_000)
225
+ .escalateTo('page-secondary')
226
+ .route('result.acked === true', 'mitigate')
227
+ .done()
228
+ .step('page-secondary')
229
+ .assignment({ tags: ['sev:1', 'oncall-secondary'] })
230
+ .targetUser({ tag: 'oncall-secondary' })
231
+ .timeout(300_000)
232
+ .escalateTo('page-manager')
233
+ .done();
234
+ // … 'page-manager' has no escalateTo: the ladder ends and the run fails,
235
+ // which is the honest "escalated to the top and nobody answered" state.
236
+ ```
237
+
238
+ When a step escalates, its outstanding assignment is removed so a late responder cannot act on a superseded tier, `context._escalatedFrom` and `context._escalationDepth` are set, and a `step.escalated` transition is emitted (in addition to `step.expired`). Escalating does **not** consume `maxRetries` — a different person getting the work is not another attempt at the same one. `maxEscalationDepth(n)` (default 10) stops a mis-wired cycle from climbing forever.
239
+
240
+ Registration rejects an escalation target that doesn't exist, a step escalating to itself, escalation without a resolvable timeout, and escalation from inside a parallel group.
241
+
242
+ Targeting matters: `targetUser({ tag: '…' })` routes the step's assignment through ordinary tag matching (so fairness, backlog caps, and the rolling-window grant cap all apply), while `targetUser('<userId>')` makes it workflow-targeted and therefore exempt from the fairness window cap. For tiered escalation you almost always want the tag form.
243
+
215
244
  Plain object workflow definitions are also accepted. The library now fills in sensible defaults:
216
245
 
217
246
  - `version` defaults to `1`
@@ -322,6 +351,94 @@ Operator override: hand an assignment directly to a user, bypassing tag/weight s
322
351
 
323
352
  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.
324
353
 
354
+ ### Response deadlines & escalation (`Assignment.escalation`)
355
+
356
+ 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.**
357
+
358
+ ```ts
359
+ await matcher.addAssignment({
360
+ id: 'incident-1',
361
+ tags: ['sev:1', 'oncall-primary'],
362
+ priority: 1000,
363
+ escalation: {
364
+ respondWithinMs: 60_000,
365
+ onNoResponse: 'block', // don't offer it back to whoever ignored it
366
+ priorityBoost: 500, // ignored work climbs the queue
367
+ tiers: [['oncall-primary'], ['oncall-secondary'], ['oncall-manager']],
368
+ onExhausted: 'park', // nobody answered, all the way up
369
+ },
370
+ });
371
+
372
+ matcher.startMaintenance(); // deadlines don't fire unless something sweeps them
373
+ ```
374
+
375
+ | Field | Meaning | Default |
376
+ | ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------- |
377
+ | `respondWithinMs` | Per-assignment response deadline, overriding `matchExpirationMs` | required |
378
+ | `onNoResponse` | `'block'` treats a non-response as a soft rejection (same rejected set an explicit reject writes to); `'allow'` keeps the historical behaviour | `'allow'` |
379
+ | `priorityBoost` | Priority delta applied on each hop | `0` |
380
+ | `tiers` | Tag ladder. Tier tags are swapped per hop; tags not named by any tier survive untouched | none |
381
+ | `maxEscalations` | Hop ceiling | `tiers.length - 1`, else unlimited |
382
+ | `onExhausted` | `'queue'` keeps recirculating; `'park'` holds it out of matching | `'queue'` |
383
+
384
+ 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.
385
+
386
+ 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.
387
+
388
+ ### SLA policies (`Assignment.sla`)
389
+
390
+ Escalation owns the *response* side (how long a matched user has to accept). `SlaPolicy` owns everything after that: how long the accepting user has to finish, how many times the work may be refused before it is pulled from rotation, and an absolute freshness cutoff after which the work is moot.
391
+
392
+ ```ts
393
+ await matcher.addAssignment({
394
+ id: 'order-42',
395
+ tags: ['fulfillment'],
396
+ sla: {
397
+ completeWithinMs: 30 * 60_000, // finish within 30 min of accepting
398
+ onCompletionBreach: 'requeue', // take it back if they don't
399
+ maxRejections: 3, // after 3 refusals, stop offering it
400
+ expireAfterMs: 24 * 3600_000, // moot after 24h no matter what
401
+ },
402
+ });
403
+
404
+ matcher.startMaintenance(); // SLA clocks are swept by the maintenance tick
405
+ ```
406
+
407
+ | Field | Meaning | Default |
408
+ | -------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------- |
409
+ | `completeWithinMs` | Completion deadline, measured from `acceptAssignment()`. Swept by `processCompletionDeadlines()` | none |
410
+ | `expireAfterMs` | Absolute freshness cutoff from **first enqueue** — survives requeues and applies in every state (queued, pending, accepted). Swept by `processSlaExpiries()` | none |
411
+ | `maxRejections` | Refusal budget. Explicit `rejectAssignment()` calls **and** blocking no-response expiries (`escalation.onNoResponse: 'block'`) count; idle/operator releases don't | none |
412
+ | `onCompletionBreach` | `'notify'` (event only, worker keeps it) / `'requeue'` (take back, block breacher) / `'fail'` / `'park'` | `'notify'` |
413
+ | `onMaxRejections` | `'park'` / `'fail'` / `'keep'` (keep offering; budget becomes measurement-only) | `'park'` |
414
+ | `onExpire` | `'drop'` (remove entirely) / `'park'` (retain for inspection) | `'drop'` |
415
+
416
+ Semantics worth knowing:
417
+
418
+ - **Fire-once.** A breached completion deadline is removed from the deadline index before the action runs, so a `'notify'` breach doesn't re-fire every tick; a requeued-after-breach assignment gets a fresh completion clock only on its next accept.
419
+ - **The TTL never extends.** Rejection ping-pong re-adds the same JSON, whose `_enqueuedAt` keeps the original first-enqueue time — the freshness cutoff is a hard wall, not a sliding window.
420
+ - **Rejection budget outranks escalation.** Once `maxRejections` is exhausted the assignment is parked/failed instead of climbing further tiers.
421
+ - **Sweep granularity.** Like response deadlines, SLA clocks fire on the maintenance tick, not at the exact deadline.
422
+ - **Unparking.** `unparkAssignment(id, { resetSla: true })` clears the first-enqueue clock and rejection counter; without it an unparked TTL-expired item simply expires again on the next sweep.
423
+
424
+ Lifecycle events: `completionBreached` (`{ workerId, action }`), `slaExpired` (`{ ownerId, action }`), `rejectionBudgetExhausted` (`{ rejections, action }`).
425
+
426
+ **SLO measurement.** `getSlaStats(tag?)` returns aggregate attainment counters — global, or for one tag: `offers`, `acceptedInTime`, `acceptanceBreaches`, `completionBreaches`, `ttlExpiries`, `rejectionParked`, plus `meanAcceptLatencyMs` (matched→accepted) and `meanCompleteLatencyMs` (accepted→completed). Counters are best-effort `HINCRBY`s piggybacking paths that already touch Redis; only SLA-bearing assignments are measured.
427
+
428
+ **Learning integration.** Breach outcomes flow into the contextual bandit as ordinary rewards (TTL expiry and completion breach → `expire`; completion breach with `'fail'` → `fail`), so per-user/per-tag stats and the automatic routing-weight vetoes pick up chronic breachers with no extra configuration. The default feature extractor also emits `sla:hasDeadline` and `sla:tightness` (normalized against `learningSlaTightnessReferenceMs`, default 1h) for assignments with a completion deadline, letting the model learn that tight-deadline work needs fast finishers. Custom feature extractors are unaffected.
429
+
430
+ ### `startMaintenance(options?)` / `stopMaintenance()` / `runMaintenanceOnce(options?)`
431
+
432
+ Deadlines are not self-firing — something has to sweep them. `startMaintenance()` runs every enabled sweep on one tick:
433
+
434
+ - `responseDeadlines` (default on) — expiry, escalation, parking.
435
+ - `completionDeadlines` (default on) — SLA completion deadlines (`sla.completeWithinMs`).
436
+ - `slaExpiries` (default on) — SLA freshness TTLs (`sla.expireAfterMs`).
437
+ - `workflowStepTimeouts` (default on when `enableWorkflows`) — the step-timeout index. **Note:** `startOrchestrator()` consumes the event stream but does not sweep step timeouts; without maintenance, `timeoutMs` on a workflow step never fires.
438
+ - `idleUsers` (default on when `idleUserTimeoutMs` is set).
439
+
440
+ `runMaintenanceOnce()` does one pass and returns a `MaintenanceReport` (`expiredMatches`, `escalations`, `parked`, `completionBreaches`, `slaExpiries`, `expiredSteps`, `releasedIdleUsers`, `tookMs`) — use it from a host that already owns a tick (a multi-tenant worker, a serverless schedule) instead of holding a timer per matcher. `startAutoReleaseInterval()` remains as a deprecated alias that sweeps response deadlines only.
441
+
325
442
  ### `getQueueStats(): Promise<QueueStats>`
326
443
 
327
444
  Live operational snapshot for dashboards:
@@ -512,6 +629,10 @@ type Options = {
512
629
  // tag-overlap-ratio and embedding-similarity features.
513
630
  learningFeatureExtractor?: (user: User, assignment: { id: string; tags: string[] }) => Record<string, number>;
514
631
 
632
+ // Reference duration (ms) used to normalize the `sla:tightness` feature
633
+ // emitted by the default extractor for assignments with sla.completeWithinMs.
634
+ learningSlaTightnessReferenceMs?: number; // Default: 3600000 (1 hour)
635
+
515
636
  // TTL for stored decision contexts in ms.
516
637
  learningDecisionTtlMs?: number; // Default: 604800000 (7 days)
517
638
 
@@ -585,6 +706,11 @@ What a trace contains:
585
706
  `assignmentVeto` (the assignment's `vetoedUsers`), and `rejectedPreviously` —
586
707
  are struck out in the trace even though the Redis-side prefilter kept them
587
708
  out of the scoring pass entirely.
709
+ - Where a veto came from. For users carrying `learnedRoutingWeights`, each
710
+ `veto` reason also has `source: 'learned' | 'manual'`, separating a veto the
711
+ automatic routing-weight sync synthesized from one an operator configured.
712
+ The field is absent for users with no learned weights, so traces are
713
+ unchanged when the learning layer is off.
588
714
 
589
715
  Honesty notes: in the default `'first-come'` mode users evaluate and claim in
590
716
  parallel, so a candidate whose snapshot read happened after the winner's claim
@@ -736,26 +862,53 @@ Beyond re-ranking, the learning layer can fully automate `routingWeights`
736
862
  authoring. With `enableAutoRoutingWeights: true` (requires `enableLearning`),
737
863
  every reward observation also updates per-user, per-tag statistics in Redis
738
864
  (atomic `HINCRBY`/`HINCRBYFLOAT` — O(tags) per outcome, no scans, no
739
- read-modify-write), and weights are synthesized on demand with a UCB1 bandit
740
- policy:
741
-
742
- - tags with a high mean reward get proportionally high weights (UCB
743
- exploration bonus favors less-sampled tags),
744
- - tags with a mean reward at/below `vetoThreshold` (after `minSamples`
745
- observations) get weight `0` — the matcher's hard-veto semantics,
746
- - under-sampled or unobserved known tags get an optimistic `priorWeight` so
747
- the system keeps exploring them.
865
+ read-modify-write), and weights are synthesized on demand with a configurable
866
+ bandit policy.
867
+
868
+ **Policies:**
869
+
870
+ - `policy: 'ucb1'` (default): high-mean tags get high weights, an exploration
871
+ bonus favors less-sampled tags, and bad tags are hard-vetoed at weight `0`.
872
+ - `policy: 'confidence'`: uses upper-confidence-bound for the weight and a
873
+ conservative lower-confidence-bound for the veto decision, so uncertainty
874
+ works against exclusion.
875
+ - `policy: 'thompson'`: samples from the per-tag posterior when mapping to a
876
+ weight.
877
+
878
+ **Guardrails (all opt-in):**
879
+
880
+ - `minSamplesForVeto`: a learned weight-0 may only override a _manual_
881
+ (non-learned) weight after this many observations, preventing a few bad
882
+ rolls from silently starving a user. Defaults to `minSamples` (5) for
883
+ backward compatibility; 20 is a reasonable production floor.
884
+ - `maxDeltaPerSync`: clamps how far any single learned weight can move per
885
+ sync, avoiding oscillation.
886
+ - `minTotalSamples`: skip users whose total evidence is still too thin.
887
+ - `decayHalfLifeMs`: exponentially decay older observations on read so stale
888
+ history cannot veto a user's improving skills.
889
+ - `terminalOnlyTagStats`: when `true`, only terminal outcomes
890
+ (complete/reject/expire/fail plus manual rewards/feedback) feed tag stats;
891
+ the non-terminal `accept` update is skipped.
748
892
 
749
893
  ```typescript
750
894
  const matcher = new AssignmentMatcher(redisClient, {
751
895
  enableLearning: true,
752
896
  enableAutoRoutingWeights: true,
897
+ // Optional: run the guarded sync automatically on one replica.
898
+ // A Redis lock prevents overlapping runs across replicas.
899
+ autoRoutingWeightsSyncIntervalMs: 60_000,
753
900
  autoRoutingWeights: {
754
901
  minSamples: 5, // observations before a tag's stats are trusted
755
902
  vetoThreshold: -0.5, // mean reward at/below this → weight 0 (hard veto)
756
903
  maxWeight: 100, // top of the synthesized weight scale
757
904
  explorationBonus: 0.5, // UCB coefficient; higher → more exploration
758
905
  priorWeight: 50, // optimistic weight for unexplored tags
906
+ policy: 'confidence', // or 'ucb1' (default) / 'thompson'
907
+ confidenceZ: 1.5, // z-score for the confidence policy
908
+ minSamplesForVeto: 20, // stricter bar for overriding manual weights
909
+ maxDeltaPerSync: 25, // max change per sync on a single weight
910
+ decayHalfLifeMs: 24 * 60 * 60 * 1000, // 24h half-life
911
+ terminalOnlyTagStats: false,
759
912
  },
760
913
  });
761
914
 
@@ -771,15 +924,28 @@ await matcher.syncLearnedRoutingWeights(); // all tracked users
771
924
 
772
925
  // Include exploration priors for known tags the user has never seen:
773
926
  await matcher.syncLearnedRoutingWeights('user-1', { includeUnexploredTags: true });
927
+
928
+ // Preview the would-be map without writing anything:
929
+ const wouldBe = await matcher.syncLearnedRoutingWeights('user-1', { dryRun: true });
930
+
931
+ // Undo the last sync if the result looks wrong:
932
+ await matcher.revertLearnedRoutingWeights('user-1');
774
933
  ```
775
934
 
776
935
  Synthesis happens outside the matching hot path — matching itself reads the
777
936
  user's stored `routingWeights` exactly as before, so the per-match cost is
778
937
  unchanged. The last-applied learned map is stored on the user as
779
- `learnedRoutingWeights` for observability, and `resetLearningModel()` clears
780
- all per-user tag statistics. The pure synthesis function is exported as
938
+ `learnedRoutingWeights` for observability, the previous map is snapshotted as
939
+ `routingWeightsSnapshot` for rollback, and `resetLearningModel()` clears all
940
+ per-user tag statistics. The pure synthesis function is exported as
781
941
  `synthesizeRoutingWeights` for offline pipelines.
782
942
 
943
+ Run the regression gate to validate a new policy before shipping it:
944
+
945
+ ```bash
946
+ ./node_modules/.bin/ts-node benchmark-weights.ts
947
+ ```
948
+
783
949
  ### RL Scalability & Redis Constraints
784
950
 
785
951
  The RL layer adds controlled overhead: decision recording, outcome archival,
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Escalation policy — pure logic.
3
+ *
4
+ * An assignment carries an optional `escalation` policy describing what should
5
+ * happen when the user it was matched to lets the response deadline run out.
6
+ * Everything here is deliberately side-effect free: `AssignmentMatcher` owns
7
+ * the Redis writes, this module owns the decisions.
8
+ *
9
+ * The same primitive backs both plain (non-workflow) escalation ladders and,
10
+ * via synthesised policies, workflow steps that escalate on timeout.
11
+ */
12
+ import type { Assignment, EscalationPolicy } from '../types/matcher';
13
+ /** A policy with every optional field resolved. */
14
+ export interface NormalizedEscalationPolicy {
15
+ respondWithinMs: number;
16
+ onNoResponse: 'block' | 'allow';
17
+ priorityBoost: number;
18
+ tiers?: string[][];
19
+ maxEscalations: number;
20
+ onExhausted: 'queue' | 'park';
21
+ }
22
+ /** Internal marker the matcher persists on the assignment between hops. */
23
+ export declare const ESCALATION_LEVEL_FIELD = "_escalationLevel";
24
+ /**
25
+ * Resolve an assignment's policy, or `null` when it has none (the overwhelming
26
+ * majority of assignments — callers use the null to stay on the untouched
27
+ * legacy path).
28
+ */
29
+ export declare function normalizeEscalationPolicy(policy: EscalationPolicy | undefined | null): NormalizedEscalationPolicy | null;
30
+ /** Current escalation level of an assignment (0 = never escalated). */
31
+ export declare function escalationLevelOf(assignment: Assignment): number;
32
+ /**
33
+ * How long the matched user has to respond, in ms. Falls back to the
34
+ * matcher-wide `matchExpirationMs` when the assignment declares no policy.
35
+ */
36
+ export declare function responseDeadlineMs(assignment: Assignment | null | undefined, fallbackMs: number): number;
37
+ /**
38
+ * Same question, answered from the stored JSON without paying for a parse on
39
+ * the claim hot path. Assignments without a policy — effectively all of them
40
+ * in a typical deployment — cost one `indexOf` and nothing else.
41
+ */
42
+ export declare function responseDeadlineFromJson(json: string | null | undefined, fallbackMs: number): number;
43
+ export interface EscalationDecision {
44
+ /** The assignment as it should be re-queued (tier tags + boosted priority + bumped level). */
45
+ assignment: Assignment;
46
+ /** Level after this hop (1 = first escalation). Equals the previous level when exhausted. */
47
+ level: number;
48
+ /** True when the ladder had no hop left — `assignment` is unchanged in that case. */
49
+ exhausted: boolean;
50
+ /** Whether the timed-out owner should be blocked from winning it back. */
51
+ blockPreviousOwner: boolean;
52
+ /** What to do with an exhausted assignment. */
53
+ onExhausted: 'queue' | 'park';
54
+ }
55
+ /**
56
+ * Decide the next state of an assignment whose response deadline elapsed.
57
+ *
58
+ * Tier tags are swapped rather than appended: the vocabulary of every tag
59
+ * named by any tier is removed first, then the target tier's tags are added,
60
+ * so a ladder like `[['oncall-primary'], ['oncall-secondary']]` moves the
61
+ * assignment cleanly from one tier to the next while non-tier tags
62
+ * (`sev:1`, `service:checkout`, …) survive untouched.
63
+ */
64
+ export declare function escalateAssignment(assignment: Assignment, policy: NormalizedEscalationPolicy): EscalationDecision;
65
+ //# sourceMappingURL=policy.d.ts.map
@@ -0,0 +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"}
@@ -0,0 +1,120 @@
1
+ "use strict";
2
+ /**
3
+ * Escalation policy — pure logic.
4
+ *
5
+ * An assignment carries an optional `escalation` policy describing what should
6
+ * happen when the user it was matched to lets the response deadline run out.
7
+ * Everything here is deliberately side-effect free: `AssignmentMatcher` owns
8
+ * the Redis writes, this module owns the decisions.
9
+ *
10
+ * The same primitive backs both plain (non-workflow) escalation ladders and,
11
+ * via synthesised policies, workflow steps that escalate on timeout.
12
+ */
13
+ Object.defineProperty(exports, "__esModule", { value: true });
14
+ exports.escalateAssignment = exports.responseDeadlineFromJson = exports.responseDeadlineMs = exports.escalationLevelOf = exports.normalizeEscalationPolicy = exports.ESCALATION_LEVEL_FIELD = void 0;
15
+ /** Internal marker the matcher persists on the assignment between hops. */
16
+ exports.ESCALATION_LEVEL_FIELD = '_escalationLevel';
17
+ /**
18
+ * Resolve an assignment's policy, or `null` when it has none (the overwhelming
19
+ * majority of assignments — callers use the null to stay on the untouched
20
+ * legacy path).
21
+ */
22
+ function normalizeEscalationPolicy(policy) {
23
+ if (!policy || typeof policy !== 'object')
24
+ return null;
25
+ const respondWithinMs = Number(policy.respondWithinMs);
26
+ if (!Number.isFinite(respondWithinMs) || respondWithinMs <= 0)
27
+ return null;
28
+ const tiers = Array.isArray(policy.tiers)
29
+ ? policy.tiers.filter((tier) => Array.isArray(tier) && tier.length > 0)
30
+ : undefined;
31
+ const declaredMax = Number(policy.maxEscalations);
32
+ // With a tier ladder the natural ceiling is "one hop per remaining tier".
33
+ const defaultMax = tiers && tiers.length > 0 ? tiers.length - 1 : Number.POSITIVE_INFINITY;
34
+ return {
35
+ respondWithinMs,
36
+ onNoResponse: policy.onNoResponse === 'block' ? 'block' : 'allow',
37
+ priorityBoost: Number.isFinite(Number(policy.priorityBoost)) ? Number(policy.priorityBoost) : 0,
38
+ tiers: tiers && tiers.length > 0 ? tiers : undefined,
39
+ maxEscalations: Number.isFinite(declaredMax) && declaredMax >= 0 ? declaredMax : defaultMax,
40
+ onExhausted: policy.onExhausted === 'park' ? 'park' : 'queue',
41
+ };
42
+ }
43
+ exports.normalizeEscalationPolicy = normalizeEscalationPolicy;
44
+ /** Current escalation level of an assignment (0 = never escalated). */
45
+ function escalationLevelOf(assignment) {
46
+ const raw = Number(assignment[exports.ESCALATION_LEVEL_FIELD]);
47
+ return Number.isFinite(raw) && raw > 0 ? Math.floor(raw) : 0;
48
+ }
49
+ exports.escalationLevelOf = escalationLevelOf;
50
+ /**
51
+ * How long the matched user has to respond, in ms. Falls back to the
52
+ * matcher-wide `matchExpirationMs` when the assignment declares no policy.
53
+ */
54
+ function responseDeadlineMs(assignment, fallbackMs) {
55
+ if (!assignment)
56
+ return fallbackMs;
57
+ const policy = normalizeEscalationPolicy(assignment.escalation);
58
+ return policy ? policy.respondWithinMs : fallbackMs;
59
+ }
60
+ exports.responseDeadlineMs = responseDeadlineMs;
61
+ /**
62
+ * Same question, answered from the stored JSON without paying for a parse on
63
+ * the claim hot path. Assignments without a policy — effectively all of them
64
+ * in a typical deployment — cost one `indexOf` and nothing else.
65
+ */
66
+ function responseDeadlineFromJson(json, fallbackMs) {
67
+ if (!json || json.indexOf('"escalation"') === -1)
68
+ return fallbackMs;
69
+ try {
70
+ return responseDeadlineMs(JSON.parse(json), fallbackMs);
71
+ }
72
+ catch {
73
+ return fallbackMs;
74
+ }
75
+ }
76
+ exports.responseDeadlineFromJson = responseDeadlineFromJson;
77
+ /**
78
+ * Decide the next state of an assignment whose response deadline elapsed.
79
+ *
80
+ * Tier tags are swapped rather than appended: the vocabulary of every tag
81
+ * named by any tier is removed first, then the target tier's tags are added,
82
+ * so a ladder like `[['oncall-primary'], ['oncall-secondary']]` moves the
83
+ * assignment cleanly from one tier to the next while non-tier tags
84
+ * (`sev:1`, `service:checkout`, …) survive untouched.
85
+ */
86
+ function escalateAssignment(assignment, policy) {
87
+ const currentLevel = escalationLevelOf(assignment);
88
+ const nextLevel = currentLevel + 1;
89
+ const outOfHops = nextLevel > policy.maxEscalations;
90
+ const outOfTiers = policy.tiers ? nextLevel >= policy.tiers.length : false;
91
+ if (outOfHops || outOfTiers) {
92
+ return {
93
+ assignment,
94
+ level: currentLevel,
95
+ exhausted: true,
96
+ // The non-responder is still blocked on the final hop: an exhausted
97
+ // ladder means nobody answered, not that the last person gets it back.
98
+ blockPreviousOwner: policy.onNoResponse === 'block',
99
+ onExhausted: policy.onExhausted,
100
+ };
101
+ }
102
+ const next = { ...assignment, [exports.ESCALATION_LEVEL_FIELD]: nextLevel };
103
+ if (policy.priorityBoost !== 0 && typeof assignment.priority === 'number') {
104
+ next.priority = assignment.priority + policy.priorityBoost;
105
+ }
106
+ if (policy.tiers) {
107
+ const tierVocabulary = new Set(policy.tiers.flat());
108
+ const preserved = (assignment.tags ?? []).filter((tag) => !tierVocabulary.has(tag));
109
+ const tierTags = policy.tiers[nextLevel];
110
+ next.tags = [...preserved, ...tierTags.filter((tag) => !preserved.includes(tag))];
111
+ }
112
+ return {
113
+ assignment: next,
114
+ level: nextLevel,
115
+ exhausted: false,
116
+ blockPreviousOwner: policy.onNoResponse === 'block',
117
+ onExhausted: policy.onExhausted,
118
+ };
119
+ }
120
+ exports.escalateAssignment = escalateAssignment;
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import AssignmentMatcher from './matcher.class';
2
- export type { Assignment, MatcherOptions, options, Stats, QueueStats, UserLoadInfo, User, GeoMatchResult, GeoMatchingFunction, ReliabilityMetrics, AssignmentStatus, FairnessMode, FairnessConfig, MatchTraceReason, MatchCandidateTrace, MatchDecisionTrace, MatchDecisionMode, MatchExplanation, MatchPreview, MatchPreviewInput, DecisionTraceQuery, AssignmentLifecycleEvent, } from './matcher.class';
3
- export type { WorkflowDefinition, WorkflowDefinitionInput, WorkflowDefinitionSummary, WorkflowInstance, WorkflowInstanceStatus, WorkflowStep, WorkflowRouting, WorkflowTargetUser, WorkflowMachineTask, WorkflowExternalTask, WorkflowTaskType, WorkflowEvent, WorkflowEventType, AssignmentResult, ParallelBranchState, DeadLetterEntry, AuditEntry, CircuitBreakerState, WorkflowInstanceWithSnapshot, WorkflowInstanceQuery, WorkflowInstancePage, WorkflowTransition, LearningOutcome, LearningRewards, LearningFeatures, LearningAssignmentContext, LearningFeatureExtractor, LearningDecisionRecord, LearningEpisodeRecord, LearningSignals, LearningSample, LearningStats, LearningTagStat, AutoRoutingWeightsOptions, PendingAssignmentInfo, WorkflowEngineMetrics, MachineTaskHandler, WorkflowHost, PaginationOptions, PaginationResult, AssignmentCounts, } from './matcher.class';
2
+ export type { Assignment, MatcherOptions, options, Stats, QueueStats, UserLoadInfo, User, GeoMatchResult, GeoMatchingFunction, ReliabilityMetrics, AssignmentStatus, FairnessMode, FairnessConfig, MatchTraceReason, MatchCandidateTrace, MatchDecisionTrace, MatchDecisionMode, MatchExplanation, MatchPreview, MatchPreviewInput, DecisionTraceQuery, AssignmentLifecycleEvent, EscalationPolicy, EscalationSweepResult, CompletionDeadlineSweepResult, SlaExpirySweepResult, SlaPolicy, SlaStats, MaintenanceOptions, MaintenanceReport, } from './matcher.class';
3
+ export type { WorkflowDefinition, WorkflowDefinitionInput, WorkflowDefinitionSummary, WorkflowInstance, WorkflowInstanceStatus, WorkflowStep, WorkflowRouting, WorkflowTargetUser, WorkflowMachineTask, WorkflowExternalTask, WorkflowTaskType, WorkflowEvent, WorkflowEventType, AssignmentResult, ParallelBranchState, DeadLetterEntry, AuditEntry, CircuitBreakerState, WorkflowInstanceWithSnapshot, WorkflowInstanceQuery, WorkflowInstancePage, WorkflowTransition, LearningOutcome, LearningRewards, LearningFeatures, LearningAssignmentContext, LearningFeatureExtractor, LearningDecisionRecord, LearningEpisodeRecord, LearningSignals, LearningSample, LearningStats, LearningTagStat, AutoRoutingWeightsOptions, AutoRoutingWeightsPolicy, PendingAssignmentInfo, WorkflowEngineMetrics, MachineTaskHandler, WorkflowHost, PaginationOptions, PaginationResult, AssignmentCounts, } from './matcher.class';
4
4
  export { explainMatchScore, type MatchScoreExplanation } from './scoring/match-score';
5
5
  export { extractMatchFeatures, cosineSimilarity } from './learning/features';
6
6
  export { synthesizeRoutingWeights, DEFAULT_AUTO_WEIGHTS_OPTIONS } from './learning/auto-weights';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,iBAAiB,MAAM,iBAAiB,CAAC;AAEhD,YAAY,EACR,UAAU,EACV,cAAc,EACd,OAAO,EACP,KAAK,EACL,UAAU,EACV,YAAY,EACZ,IAAI,EACJ,cAAc,EACd,mBAAmB,EACnB,kBAAkB,EAClB,gBAAgB,EAChB,YAAY,EACZ,cAAc,EACd,gBAAgB,EAChB,mBAAmB,EACnB,kBAAkB,EAClB,iBAAiB,EACjB,gBAAgB,EAChB,YAAY,EACZ,iBAAiB,EACjB,kBAAkB,EAClB,wBAAwB,GAC3B,MAAM,iBAAiB,CAAC;AAGzB,YAAY,EACR,kBAAkB,EAClB,uBAAuB,EACvB,yBAAyB,EACzB,gBAAgB,EAChB,sBAAsB,EACtB,YAAY,EACZ,eAAe,EACf,kBAAkB,EAClB,mBAAmB,EACnB,oBAAoB,EACpB,gBAAgB,EAChB,aAAa,EACb,iBAAiB,EACjB,gBAAgB,EAChB,mBAAmB,EACnB,eAAe,EACf,UAAU,EACV,mBAAmB,EACnB,4BAA4B,EAC5B,qBAAqB,EACrB,oBAAoB,EACpB,kBAAkB,EAClB,eAAe,EACf,eAAe,EACf,gBAAgB,EAChB,yBAAyB,EACzB,wBAAwB,EACxB,sBAAsB,EACtB,qBAAqB,EACrB,eAAe,EACf,cAAc,EACd,aAAa,EACb,eAAe,EACf,yBAAyB,EACzB,qBAAqB,EACrB,qBAAqB,EACrB,kBAAkB,EAClB,YAAY,EACZ,iBAAiB,EACjB,gBAAgB,EAChB,gBAAgB,GACnB,MAAM,iBAAiB,CAAC;AAGzB,OAAO,EAAE,iBAAiB,EAAE,KAAK,qBAAqB,EAAE,MAAM,uBAAuB,CAAC;AAGtF,OAAO,EAAE,oBAAoB,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAE7E,OAAO,EAAE,wBAAwB,EAAE,4BAA4B,EAAE,MAAM,yBAAyB,CAAC;AAGjG,OAAO,EAAE,eAAe,EAAE,mBAAmB,EAAE,QAAQ,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AACtH,OAAO,EAAE,2BAA2B,EAAE,0BAA0B,EAAE,MAAM,uBAAuB,CAAC;AAGhG,cAAc,cAAc,CAAC;AAC7B,cAAc,aAAa,CAAC;AAC5B,OAAO,EAAE,iBAAiB,EAAE,KAAK,WAAW,EAAE,KAAK,cAAc,EAAE,MAAM,cAAc,CAAC;AAExF,OAAO,EAAE,iBAAiB,EAAE,CAAC;AAC7B,eAAe,iBAAiB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,iBAAiB,MAAM,iBAAiB,CAAC;AAEhD,YAAY,EACR,UAAU,EACV,cAAc,EACd,OAAO,EACP,KAAK,EACL,UAAU,EACV,YAAY,EACZ,IAAI,EACJ,cAAc,EACd,mBAAmB,EACnB,kBAAkB,EAClB,gBAAgB,EAChB,YAAY,EACZ,cAAc,EACd,gBAAgB,EAChB,mBAAmB,EACnB,kBAAkB,EAClB,iBAAiB,EACjB,gBAAgB,EAChB,YAAY,EACZ,iBAAiB,EACjB,kBAAkB,EAClB,wBAAwB,EACxB,gBAAgB,EAChB,qBAAqB,EACrB,6BAA6B,EAC7B,oBAAoB,EACpB,SAAS,EACT,QAAQ,EACR,kBAAkB,EAClB,iBAAiB,GACpB,MAAM,iBAAiB,CAAC;AAGzB,YAAY,EACR,kBAAkB,EAClB,uBAAuB,EACvB,yBAAyB,EACzB,gBAAgB,EAChB,sBAAsB,EACtB,YAAY,EACZ,eAAe,EACf,kBAAkB,EAClB,mBAAmB,EACnB,oBAAoB,EACpB,gBAAgB,EAChB,aAAa,EACb,iBAAiB,EACjB,gBAAgB,EAChB,mBAAmB,EACnB,eAAe,EACf,UAAU,EACV,mBAAmB,EACnB,4BAA4B,EAC5B,qBAAqB,EACrB,oBAAoB,EACpB,kBAAkB,EAClB,eAAe,EACf,eAAe,EACf,gBAAgB,EAChB,yBAAyB,EACzB,wBAAwB,EACxB,sBAAsB,EACtB,qBAAqB,EACrB,eAAe,EACf,cAAc,EACd,aAAa,EACb,eAAe,EACf,yBAAyB,EACzB,wBAAwB,EACxB,qBAAqB,EACrB,qBAAqB,EACrB,kBAAkB,EAClB,YAAY,EACZ,iBAAiB,EACjB,gBAAgB,EAChB,gBAAgB,GACnB,MAAM,iBAAiB,CAAC;AAGzB,OAAO,EAAE,iBAAiB,EAAE,KAAK,qBAAqB,EAAE,MAAM,uBAAuB,CAAC;AAGtF,OAAO,EAAE,oBAAoB,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAE7E,OAAO,EAAE,wBAAwB,EAAE,4BAA4B,EAAE,MAAM,yBAAyB,CAAC;AAGjG,OAAO,EAAE,eAAe,EAAE,mBAAmB,EAAE,QAAQ,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AACtH,OAAO,EAAE,2BAA2B,EAAE,0BAA0B,EAAE,MAAM,uBAAuB,CAAC;AAGhG,cAAc,cAAc,CAAC;AAC7B,cAAc,aAAa,CAAC;AAC5B,OAAO,EAAE,iBAAiB,EAAE,KAAK,WAAW,EAAE,KAAK,cAAc,EAAE,MAAM,cAAc,CAAC;AAExF,OAAO,EAAE,iBAAiB,EAAE,CAAC;AAC7B,eAAe,iBAAiB,CAAC"}
@@ -1,26 +1,36 @@
1
1
  /**
2
2
  * Automatic routing-weight synthesis from per-user tag reward statistics.
3
3
  *
4
- * Implements a UCB1-style bandit policy over tags: each tag's score is its
5
- * mean observed reward plus an exploration bonus that shrinks as the tag is
6
- * sampled more. Scores map onto the conventional 0-100 routing-weight scale:
4
+ * Supports three policies:
7
5
  *
8
- * - tags with enough samples and a mean reward at/below `vetoThreshold` get
9
- * weight 0 (the matcher's hard-veto semantics),
6
+ * - 'ucb1' (default): mean reward plus an exploration bonus that shrinks as
7
+ * the tag is sampled more.
8
+ * - 'confidence': upper-confidence-bound for the weight, lower-confidence-bound
9
+ * for the veto decision, so vetoes are conservative and weights reflect
10
+ * uncertainty.
11
+ * - 'thompson': sample from the per-tag posterior (Gaussian approximation)
12
+ * when mapping to a weight.
13
+ *
14
+ * Scores map onto the conventional 0-100 routing-weight scale:
15
+ *
16
+ * - tags with enough samples and a sufficiently bad mean/LCB get weight 0
17
+ * (the matcher's hard-veto semantics),
10
18
  * - under-sampled or unobserved known tags get an optimistic `priorWeight`
11
19
  * so the matcher keeps exploring them,
12
- * - all other tags get a weight proportional to their UCB score, clamped to
20
+ * - all other tags get a weight proportional to their score, clamped to
13
21
  * [1, maxWeight] so eligible tags never collapse to an accidental veto.
14
22
  *
15
23
  * Pure module: no Redis access, O(number of tags) per call.
16
24
  */
17
25
  import type { AutoRoutingWeightsOptions, LearningTagStat } from '../types/matcher';
18
- export declare const DEFAULT_AUTO_WEIGHTS_OPTIONS: Required<Omit<AutoRoutingWeightsOptions, 'priorWeight'>>;
26
+ export declare const DEFAULT_AUTO_WEIGHTS_OPTIONS: Required<Omit<AutoRoutingWeightsOptions, 'priorWeight' | 'maxDeltaPerSync' | 'decayHalfLifeMs' | 'rng'>> & {
27
+ priorWeight: number;
28
+ };
19
29
  /**
20
30
  * Synthesize a routingWeights map from per-tag reward statistics.
21
31
  *
22
32
  * @param stats per-user tag reward statistics (from learned outcomes)
23
- * @param options UCB policy tuning (merged with defaults)
33
+ * @param options synthesis policy and tuning (merged with defaults)
24
34
  * @param knownTags optional tags to include even without observations;
25
35
  * unobserved known tags receive the optimistic prior weight
26
36
  * @param existingWeights optional current routingWeights of the user;
@@ -1 +1 @@
1
- {"version":3,"file":"auto-weights.d.ts","sourceRoot":"","sources":["../../src/learning/auto-weights.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AACH,OAAO,KAAK,EAAE,yBAAyB,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAEnF,eAAO,MAAM,4BAA4B,EAAE,QAAQ,CAAC,IAAI,CAAC,yBAAyB,EAAE,aAAa,CAAC,CAKjG,CAAC;AAEF;;;;;;;;;;GAUG;AACH,wBAAgB,wBAAwB,CACpC,KAAK,EAAE,eAAe,EAAE,EACxB,OAAO,CAAC,EAAE,yBAAyB,EACnC,SAAS,CAAC,EAAE,MAAM,EAAE,EACpB,eAAe,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GACzC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CA8CxB"}
1
+ {"version":3,"file":"auto-weights.d.ts","sourceRoot":"","sources":["../../src/learning/auto-weights.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,OAAO,KAAK,EAAE,yBAAyB,EAA4B,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAE7G,eAAO,MAAM,4BAA4B,EAAE,QAAQ,CAC/C,IAAI,CAAC,yBAAyB,EAAE,aAAa,GAAG,iBAAiB,GAAG,iBAAiB,GAAG,KAAK,CAAC,CACjG,GAAG;IACA,WAAW,EAAE,MAAM,CAAC;CAYvB,CAAC;AA2IF;;;;;;;;;;GAUG;AACH,wBAAgB,wBAAwB,CACpC,KAAK,EAAE,eAAe,EAAE,EACxB,OAAO,CAAC,EAAE,yBAAyB,EACnC,SAAS,CAAC,EAAE,MAAM,EAAE,EACpB,eAAe,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GACzC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CA8CxB"}