assignment-user-matcher 1.2.2 → 1.2.5

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 (38) hide show
  1. package/README.md +243 -91
  2. package/dist/index.d.ts +5 -3
  3. package/dist/index.d.ts.map +1 -1
  4. package/dist/index.js +6 -1
  5. package/dist/learning/auto-weights.d.ts +31 -0
  6. package/dist/learning/auto-weights.d.ts.map +1 -0
  7. package/dist/learning/auto-weights.js +65 -0
  8. package/dist/lua/workflow-transition.lua +29 -0
  9. package/dist/managers/LearningManager.d.ts +39 -4
  10. package/dist/managers/LearningManager.d.ts.map +1 -1
  11. package/dist/managers/LearningManager.js +78 -3
  12. package/dist/managers/ReliabilityManager.d.ts +60 -2
  13. package/dist/managers/ReliabilityManager.d.ts.map +1 -1
  14. package/dist/managers/ReliabilityManager.js +190 -9
  15. package/dist/managers/TelemetryManager.d.ts.map +1 -1
  16. package/dist/managers/WorkflowManager.d.ts +78 -1
  17. package/dist/managers/WorkflowManager.d.ts.map +1 -1
  18. package/dist/managers/WorkflowManager.js +449 -77
  19. package/dist/matcher.class.d.ts +195 -8
  20. package/dist/matcher.class.d.ts.map +1 -1
  21. package/dist/matcher.class.js +619 -36
  22. package/dist/queries/pagination.d.ts.map +1 -1
  23. package/dist/queries/pagination.js +9 -6
  24. package/dist/scoring/fair-arbitration.d.ts +68 -0
  25. package/dist/scoring/fair-arbitration.d.ts.map +1 -0
  26. package/dist/scoring/fair-arbitration.js +151 -0
  27. package/dist/scoring/match-score.d.ts.map +1 -1
  28. package/dist/scoring/match-score.js +1 -1
  29. package/dist/types/matcher.d.ts +258 -0
  30. package/dist/types/matcher.d.ts.map +1 -1
  31. package/dist/utils/geo.d.ts +26 -0
  32. package/dist/utils/geo.d.ts.map +1 -0
  33. package/dist/utils/geo.js +62 -0
  34. package/dist/utils/keys.d.ts +13 -0
  35. package/dist/utils/keys.d.ts.map +1 -1
  36. package/dist/utils/keys.js +14 -0
  37. package/dist/workflow-validation.d.ts.map +1 -1
  38. package/package.json +58 -57
@@ -1 +1 @@
1
- {"version":3,"file":"pagination.d.ts","sourceRoot":"","sources":["../../src/queries/pagination.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,OAAO,KAAK,EAAE,eAAe,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAEpE,MAAM,MAAM,gBAAgB,GAAG,QAAQ,GAAG,SAAS,GAAG,UAAU,CAAC;AAEjE,MAAM,WAAW,iBAAiB;IAC9B,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACvB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,MAAM,CAAC,EAAE,gBAAgB,GAAG,KAAK,CAAC;IAClC,YAAY,CAAC,EAAE,OAAO,CAAC;CAC1B;AAED,MAAM,WAAW,gBAAgB;IAC7B,WAAW,EAAE,UAAU,EAAE,CAAC;IAC1B,UAAU,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1B,OAAO,EAAE,OAAO,CAAC;IACjB,KAAK,CAAC,EAAE,MAAM,CAAC;CAClB;AAED,MAAM,WAAW,gBAAgB;IAC7B,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,MAAM,CAAC;IAChB,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,cAAc;IAC3B,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,MAAM,CAAC;IAChB,QAAQ,EAAE,MAAM,CAAC;CACpB;AAED;;GAEG;AACH,wBAAsB,2BAA2B,CAC7C,WAAW,EAAE,eAAe,EAC5B,IAAI,EAAE,cAAc,GACrB,OAAO,CAAC,UAAU,EAAE,CAAC,CASvB;AAED;;GAEG;AACH,wBAAsB,6BAA6B,CAC/C,WAAW,EAAE,eAAe,EAC5B,IAAI,EAAE,cAAc,GACrB,OAAO,CAAC,gBAAgB,CAAC,CAa3B;AAED;;GAEG;AACH,wBAAsB,iBAAiB,CACnC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AK,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,cAAc;IAC3B,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,MAAM,CAAC;IAChB,QAAQ,EAAE,MAAM,CAAC;CACpB;AAED;;GAEG;AACH,wBAAsB,2BAA2B,CAC7C,WAAW,EAAE,eAAe,EAC5B,IAAI,EAAE,cAAc,GACrB,OAAO,CAAC,UAAU,EAAE,CAAC,CASvB;AAED;;GAEG;AACH,wBAAsB,6BAA6B,CAC/C,WAAW,EAAE,eAAe,EAC5B,IAAI,EAAE,cAAc,GACrB,OAAO,CAAC,gBAAgB,CAAC,CAa3B;AAED;;GAEG;AACH,wBAAsB,iBAAiB,CACnC,WAAW,EAAE,eAAe,EAC5B,IAAI,EAAE,cAAc,EACpB,EAAE,EAAE,MAAM,GACX,OAAO,CAAC,CAAC,UAAU,GAAG;IAAE,OAAO,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC,GAAG,IAAI,CAAC,CAwBrD;AAED;;GAEG;AACH,wBAAsB,wBAAwB,CAC1C,WAAW,EAAE,eAAe,EAC5B,IAAI,EAAE,cAAc,EACpB,GAAG,EAAE,MAAM,EAAE,GACd,OAAO,CAAC,UAAU,EAAE,CAAC,CA+BvB;AAED;;GAEG;AACH,wBAAsB,iCAAiC,CACnD,WAAW,EAAE,eAAe,EAC5B,IAAI,EAAE,cAAc,EACpB,OAAO,CAAC,EAAE,iBAAiB,GAC5B,OAAO,CAAC,gBAAgB,CAAC,CA2H3B"}
@@ -70,7 +70,7 @@ async function getAssignmentsByIdsBatch(redisClient, keys, ids) {
70
70
  multi.hGet(keys.pending, id);
71
71
  multi.hGet(keys.accepted, id);
72
72
  }
73
- const results = await multi.exec();
73
+ const results = (await multi.exec());
74
74
  const assignments = [];
75
75
  for (let i = 0; i < ids.length; i++) {
76
76
  const queued = results[i * 3];
@@ -100,9 +100,12 @@ async function getAssignmentsPaginatedFromStores(redisClient, keys, options) {
100
100
  const includeTotal = options?.includeTotal ?? false;
101
101
  const getKeyForStatus = (s) => {
102
102
  switch (s) {
103
- case 'queued': return keys.queued;
104
- case 'pending': return keys.pending;
105
- case 'accepted': return keys.accepted;
103
+ case 'queued':
104
+ return keys.queued;
105
+ case 'pending':
106
+ return keys.pending;
107
+ case 'accepted':
108
+ return keys.accepted;
106
109
  }
107
110
  };
108
111
  const statusOrder = status === 'all' ? ['queued', 'pending', 'accepted'] : [status];
@@ -144,7 +147,7 @@ async function getAssignmentsPaginatedFromStores(redisClient, keys, options) {
144
147
  continue;
145
148
  }
146
149
  if (assignments.length >= limit) {
147
- nextCursor = `${statusIndex}:${offset + (assignments.length - (assignments.filter(a => a._status === scanStatus).length - 1))}`;
150
+ nextCursor = `${statusIndex}:${offset + (assignments.length - (assignments.filter((a) => a._status === scanStatus).length - 1))}`;
148
151
  hasMore = true;
149
152
  break;
150
153
  }
@@ -161,7 +164,7 @@ async function getAssignmentsPaginatedFromStores(redisClient, keys, options) {
161
164
  cursor = newCursor;
162
165
  } while (cursor !== '0' && assignments.length < limit);
163
166
  if (assignments.length >= limit) {
164
- const countFromCurrentStatus = assignments.filter(a => a._status === scanStatus).length;
167
+ const countFromCurrentStatus = assignments.filter((a) => a._status === scanStatus).length;
165
168
  nextCursor = `${statusIndex}:${offset + countFromCurrentStatus}`;
166
169
  hasMore = true;
167
170
  break;
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Global arbitration for fair-tiebreaker bulk matching: decides which user
3
+ * tentatively wins each contested candidate assignment. Pure logic - no Redis.
4
+ * See MatcherOptions.enableFairTiebreaker / fairnessLoadPenalty /
5
+ * fairnessTieBand for the behavior each knob selects.
6
+ */
7
+ import type { FairnessMode } from '../types/matcher';
8
+ /**
9
+ * Turns a fairness preset into concrete arbitration knobs, scaled to the
10
+ * median candidate score of the current matching pass so consumers never
11
+ * have to know their own score scale. Explicitly-set expert knobs
12
+ * (fairnessLoadPenalty / fairnessTieBand > 0) always win over the preset.
13
+ */
14
+ export declare function resolveFairnessKnobs(mode: FairnessMode | undefined, pairPriorities: number[], explicit: {
15
+ loadPenalty: number;
16
+ tieBand: number;
17
+ }): {
18
+ loadPenalty: number;
19
+ tieBand: number;
20
+ };
21
+ export interface FairArbitrationOptions {
22
+ maxUserBacklogSize: number;
23
+ /**
24
+ * Per-user override of the award ceiling (compared against the same
25
+ * `backlogUsed` counter as `maxUserBacklogSize`). Used to fold in
26
+ * additional limits like the rolling-window grant cap, which can leave a
27
+ * user with less headroom than their backlog alone would allow.
28
+ */
29
+ maxByUser?: Map<string, number>;
30
+ /**
31
+ * Score subtracted per assignment already on (or won this pass into) a
32
+ * user's backlog. 0 disables load-penalized scoring.
33
+ */
34
+ loadPenalty?: number;
35
+ /**
36
+ * Width of the score bucket within which candidates count as tied; ties
37
+ * go to the less-loaded user. 0 disables tie-band arbitration.
38
+ */
39
+ tieBand?: number;
40
+ }
41
+ interface ArbitrablePair {
42
+ userId: string;
43
+ id: string;
44
+ priority: number;
45
+ }
46
+ /**
47
+ * Walks the candidate pairs in best-first order and awards each assignment to
48
+ * exactly one user, honoring per-user backlog caps. Mutates `backlogUsed`
49
+ * (one increment per awarded pair). `settled` marks assignments no longer
50
+ * available at all (already claimed, or lost to a concurrent process).
51
+ *
52
+ * Returns `winners` in award order and `deferred`: pairs skipped only because
53
+ * their user was at cap - a cap that the caller may roll back if the user
54
+ * loses a claim to a concurrent process, so these stay eligible for another
55
+ * arbitration round.
56
+ *
57
+ * With neither knob set the order is a plain stable sort by score descending,
58
+ * matching the pre-fairness-knob behavior exactly. With a knob set, ordering
59
+ * is load-aware and therefore dynamic - each award changes the winner's load,
60
+ * which can demote their remaining candidates - so a lazy max-heap re-ranks
61
+ * entries whose user's load has grown since they were pushed.
62
+ */
63
+ export declare function arbitrateFair<P extends ArbitrablePair>(pairs: P[], backlogUsed: Map<string, number>, settled: Set<string>, options: FairArbitrationOptions): {
64
+ winners: P[];
65
+ deferred: P[];
66
+ };
67
+ export {};
68
+ //# sourceMappingURL=fair-arbitration.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fair-arbitration.d.ts","sourceRoot":"","sources":["../../src/scoring/fair-arbitration.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAarD;;;;;GAKG;AACH,wBAAgB,oBAAoB,CAChC,IAAI,EAAE,YAAY,GAAG,SAAS,EAC9B,cAAc,EAAE,MAAM,EAAE,EACxB,QAAQ,EAAE;IAAE,WAAW,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,GACnD;IAAE,WAAW,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,CAU1C;AAED,MAAM,WAAW,sBAAsB;IACnC,kBAAkB,EAAE,MAAM,CAAC;IAC3B;;;;;OAKG;IACH,SAAS,CAAC,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAChC;;;OAGG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB;;;OAGG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;CACpB;AAED,UAAU,cAAc;IACpB,MAAM,EAAE,MAAM,CAAC;IACf,EAAE,EAAE,MAAM,CAAC;IACX,QAAQ,EAAE,MAAM,CAAC;CACpB;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,aAAa,CAAC,CAAC,SAAS,cAAc,EAClD,KAAK,EAAE,CAAC,EAAE,EACV,WAAW,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,EAChC,OAAO,EAAE,GAAG,CAAC,MAAM,CAAC,EACpB,OAAO,EAAE,sBAAsB,GAChC;IAAE,OAAO,EAAE,CAAC,EAAE,CAAC;IAAC,QAAQ,EAAE,CAAC,EAAE,CAAA;CAAE,CA6FjC"}
@@ -0,0 +1,151 @@
1
+ "use strict";
2
+ /**
3
+ * Global arbitration for fair-tiebreaker bulk matching: decides which user
4
+ * tentatively wins each contested candidate assignment. Pure logic - no Redis.
5
+ * See MatcherOptions.enableFairTiebreaker / fairnessLoadPenalty /
6
+ * fairnessTieBand for the behavior each knob selects.
7
+ */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.arbitrateFair = exports.resolveFairnessKnobs = void 0;
10
+ /**
11
+ * Per-assignment load discount each fairness preset applies, as a ratio of
12
+ * the median candidate score of the matching pass. A discount of X is itself
13
+ * a smooth tie-band: a user loses a contested assignment to a rival carrying
14
+ * one assignment less exactly when the score gap is under X.
15
+ */
16
+ const PRESET_LOAD_PENALTY_RATIO = {
17
+ balanced: 0.05,
18
+ 'spread-work': 0.5,
19
+ };
20
+ /**
21
+ * Turns a fairness preset into concrete arbitration knobs, scaled to the
22
+ * median candidate score of the current matching pass so consumers never
23
+ * have to know their own score scale. Explicitly-set expert knobs
24
+ * (fairnessLoadPenalty / fairnessTieBand > 0) always win over the preset.
25
+ */
26
+ function resolveFairnessKnobs(mode, pairPriorities, explicit) {
27
+ let { loadPenalty, tieBand } = explicit;
28
+ const ratio = mode ? PRESET_LOAD_PENALTY_RATIO[mode] : undefined;
29
+ if (ratio && loadPenalty <= 0 && pairPriorities.length > 0) {
30
+ const sorted = [...pairPriorities].sort((a, b) => a - b);
31
+ const mid = sorted.length >> 1;
32
+ const median = sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;
33
+ if (median > 0)
34
+ loadPenalty = median * ratio;
35
+ }
36
+ return { loadPenalty, tieBand };
37
+ }
38
+ exports.resolveFairnessKnobs = resolveFairnessKnobs;
39
+ /**
40
+ * Walks the candidate pairs in best-first order and awards each assignment to
41
+ * exactly one user, honoring per-user backlog caps. Mutates `backlogUsed`
42
+ * (one increment per awarded pair). `settled` marks assignments no longer
43
+ * available at all (already claimed, or lost to a concurrent process).
44
+ *
45
+ * Returns `winners` in award order and `deferred`: pairs skipped only because
46
+ * their user was at cap - a cap that the caller may roll back if the user
47
+ * loses a claim to a concurrent process, so these stay eligible for another
48
+ * arbitration round.
49
+ *
50
+ * With neither knob set the order is a plain stable sort by score descending,
51
+ * matching the pre-fairness-knob behavior exactly. With a knob set, ordering
52
+ * is load-aware and therefore dynamic - each award changes the winner's load,
53
+ * which can demote their remaining candidates - so a lazy max-heap re-ranks
54
+ * entries whose user's load has grown since they were pushed.
55
+ */
56
+ function arbitrateFair(pairs, backlogUsed, settled, options) {
57
+ const loadPenalty = options.loadPenalty ?? 0;
58
+ const tieBand = options.tieBand ?? 0;
59
+ const winners = [];
60
+ const deferred = [];
61
+ const taken = new Set();
62
+ const load = (userId) => backlogUsed.get(userId) ?? 0;
63
+ const capOf = (userId) => options.maxByUser?.get(userId) ?? options.maxUserBacklogSize;
64
+ const award = (pair) => {
65
+ // Assignments already taken this pass are settled either way by the
66
+ // caller (a failed claim means a concurrent process owns it), so
67
+ // lower-ranked pairs for them never need re-arbitration.
68
+ if (settled.has(pair.id) || taken.has(pair.id))
69
+ return;
70
+ const used = load(pair.userId);
71
+ if (used >= capOf(pair.userId)) {
72
+ deferred.push(pair);
73
+ return;
74
+ }
75
+ taken.add(pair.id);
76
+ backlogUsed.set(pair.userId, used + 1);
77
+ winners.push(pair);
78
+ };
79
+ if (loadPenalty <= 0 && tieBand <= 0) {
80
+ for (const pair of [...pairs].sort((a, b) => b.priority - a.priority)) {
81
+ award(pair);
82
+ }
83
+ return { winners, deferred };
84
+ }
85
+ const effective = (pair) => pair.priority - loadPenalty * load(pair.userId);
86
+ const rank = (pair) => (tieBand > 0 ? Math.floor(effective(pair) / tieBand) : effective(pair));
87
+ // True when a orders strictly before b: higher rank bucket, then lower
88
+ // load, then higher raw score, then ids for full determinism.
89
+ const before = (a, b) => {
90
+ if (a.rank !== b.rank)
91
+ return a.rank > b.rank;
92
+ if (a.loadAtEval !== b.loadAtEval)
93
+ return a.loadAtEval < b.loadAtEval;
94
+ if (a.pair.priority !== b.pair.priority)
95
+ return a.pair.priority > b.pair.priority;
96
+ if (a.pair.id !== b.pair.id)
97
+ return a.pair.id < b.pair.id;
98
+ return a.pair.userId < b.pair.userId;
99
+ };
100
+ const heap = [];
101
+ const push = (pair) => {
102
+ heap.push({ pair, rank: rank(pair), loadAtEval: load(pair.userId) });
103
+ let i = heap.length - 1;
104
+ while (i > 0) {
105
+ const parent = (i - 1) >> 1;
106
+ if (!before(heap[i], heap[parent]))
107
+ break;
108
+ [heap[i], heap[parent]] = [heap[parent], heap[i]];
109
+ i = parent;
110
+ }
111
+ };
112
+ const pop = () => {
113
+ const top = heap[0];
114
+ const last = heap.pop();
115
+ if (heap.length > 0) {
116
+ heap[0] = last;
117
+ let i = 0;
118
+ for (;;) {
119
+ const left = i * 2 + 1;
120
+ const right = left + 1;
121
+ let best = i;
122
+ if (left < heap.length && before(heap[left], heap[best]))
123
+ best = left;
124
+ if (right < heap.length && before(heap[right], heap[best]))
125
+ best = right;
126
+ if (best === i)
127
+ break;
128
+ [heap[i], heap[best]] = [heap[best], heap[i]];
129
+ i = best;
130
+ }
131
+ }
132
+ return top;
133
+ };
134
+ for (const pair of pairs)
135
+ push(pair);
136
+ while (heap.length > 0) {
137
+ const entry = pop();
138
+ if (settled.has(entry.pair.id) || taken.has(entry.pair.id))
139
+ continue;
140
+ // Lazy re-rank: a user's load only grows during this pass (one per
141
+ // award), which can only demote their remaining entries. Terminates
142
+ // because load is capped at maxUserBacklogSize.
143
+ if (load(entry.pair.userId) !== entry.loadAtEval) {
144
+ push(entry.pair);
145
+ continue;
146
+ }
147
+ award(entry.pair);
148
+ }
149
+ return { winners, deferred };
150
+ }
151
+ exports.arbitrateFair = arbitrateFair;
@@ -1 +1 @@
1
- {"version":3,"file":"match-score.d.ts","sourceRoot":"","sources":["../../src/scoring/match-score.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,kBAAkB,CAAC;AAE7C;;GAEG;AACH,wBAAgB,cAAc,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,OAAO,CAOpE;AAED;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,wBAAgB,mBAAmB,CAC/B,IAAI,EAAE,IAAI,EACV,cAAc,EAAE,MAAM,EACtB,kBAAkB,EAAE,MAAM,GAAG,MAAM,EACnC,qBAAqB,EAAE,OAAO,EAC9B,eAAe,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GACzC,CAAC,MAAM,EAAE,MAAM,CAAC,CAoElB;AAED;;;GAGG;AACH,wBAAgB,wBAAwB,CAAC,SAAS,CAAC,EAAE,MAAM,GAAG,MAAM,CAGnE"}
@@ -85,7 +85,7 @@ function calculateMatchScore(user, assignmentTags, assignmentPriority, enableDef
85
85
  }
86
86
  }
87
87
  }
88
- // If enableDefaultMatching is true, and the tag is 'default',
88
+ // If enableDefaultMatching is true, and the tag is 'default',
89
89
  // and it wasn't matched by any routing weight, give it default weight 1
90
90
  if (enableDefaultMatching && t === 'default' && !matchedByRouting) {
91
91
  weightSum += 1;
@@ -5,6 +5,9 @@ export interface User {
5
5
  tags: string[];
6
6
  routingWeights?: Record<string, number>;
7
7
  ip?: string;
8
+ latitude?: number;
9
+ longitude?: number;
10
+ maxTravelDistanceKm?: number;
8
11
  [key: string]: any;
9
12
  }
10
13
  export type Assignment = {
@@ -13,8 +16,23 @@ export type Assignment = {
13
16
  priority?: number;
14
17
  allowedCidrs?: string[];
15
18
  skillThresholds?: Record<string, number>;
19
+ vetoedUsers?: string[];
20
+ latitude?: number;
21
+ longitude?: number;
22
+ maxDistanceKm?: number;
23
+ requireGeo?: boolean;
16
24
  [key: string]: any;
17
25
  };
26
+ export type GeoMatchResult = {
27
+ eligible: boolean;
28
+ distanceKm?: number;
29
+ effectiveMaxDistanceKm?: number;
30
+ };
31
+ export type GeoMatchingFunction = (args: {
32
+ user: User;
33
+ assignment: Assignment;
34
+ defaultMaxDistanceKm?: number;
35
+ }) => Promise<GeoMatchResult>;
18
36
  export type Stats = {
19
37
  users?: number;
20
38
  usersWithoutAssignment?: string[];
@@ -27,6 +45,28 @@ export type PendingAssignmentInfo = {
27
45
  pendingSince: number | null;
28
46
  expiresAt: number | null;
29
47
  };
48
+ /**
49
+ * Bulk-matching fairness policy. See `MatcherOptions.fairness` for what each
50
+ * value does.
51
+ */
52
+ export type FairnessMode = 'first-come' | 'best-match' | 'balanced' | 'spread-work';
53
+ /**
54
+ * Runtime-mutable subset of the bulk-matching fairness knobs. Pass any subset
55
+ * to `AssignmentMatcher.setFairnessConfig()` to retune fairness without
56
+ * reconstructing the matcher; each field carries the same semantics as the
57
+ * identically-named `MatcherOptions` field and is picked up on the next
58
+ * `matchUsersAssignments()` call. Absent fields are left unchanged; pass
59
+ * `fairness` or `fairnessMaxPerWindow` as `undefined` explicitly to clear them
60
+ * back to their auto-derived behavior.
61
+ */
62
+ export interface FairnessConfig {
63
+ fairness?: FairnessMode;
64
+ enableFairTiebreaker?: boolean;
65
+ fairnessLoadPenalty?: number;
66
+ fairnessTieBand?: number;
67
+ fairnessMaxPerWindow?: number;
68
+ fairnessWindowMs?: number;
69
+ }
30
70
  export type MatcherOptions = {
31
71
  relevantBatchSize?: number;
32
72
  redisPrefix?: string;
@@ -43,12 +83,132 @@ export type MatcherOptions = {
43
83
  idleUserTimeoutMs?: number;
44
84
  prioritizationFunction?: (...args: (Assignment | undefined)[]) => Promise<number>;
45
85
  matchingFunction?: (user: User, assignmentTags: string, assignmentPriority: number | string, assignmentId?: string, skillThresholds?: Record<string, number>) => Promise<[number, number]>;
86
+ /**
87
+ * Opt-in global best-match arbitration for bulk matching (default: false,
88
+ * preserving existing behavior). When `matchUsersAssignments()` is called
89
+ * with no userId, every eligible user is normally evaluated in parallel
90
+ * and independently claims every assignment they qualify for — when two
91
+ * or more users are eligible for the same assignment, whichever user's
92
+ * claim reaches Redis first wins, regardless of their relative score.
93
+ * With this enabled, candidates are instead collected across *all* users
94
+ * first, sorted by score descending, and claimed greedily in that order —
95
+ * so the best-fit eligible candidate wins each assignment deterministically.
96
+ * Uses plain weighted-tag/geo score (the same formula as the non-learning
97
+ * path) as the fairness comparator; the contextual-bandit learning layer,
98
+ * if enabled, still re-ranks each user's own accepted backlog ordering but
99
+ * does not influence which user wins a contested assignment in this mode.
100
+ */
101
+ enableFairTiebreaker?: boolean;
102
+ /**
103
+ * One-word fairness policy for bulk matching — the friendly alternative
104
+ * to tuning `enableFairTiebreaker` / `fairnessLoadPenalty` /
105
+ * `fairnessTieBand` by hand:
106
+ *
107
+ * - `'first-come'` (default): whoever's claim reaches Redis first wins a
108
+ * contested assignment — fastest, but the winner is arbitrary.
109
+ * - `'best-match'`: the highest-scoring eligible user wins every
110
+ * contested assignment, deterministically.
111
+ * - `'balanced'`: best match wins, but near-ties (scores within ~5% of
112
+ * the typical candidate score) go to whoever is carrying less work.
113
+ * - `'spread-work'`: work is spread as evenly as skills allow — each
114
+ * assignment already on someone's plate discounts their next bid by
115
+ * half the typical candidate score, so being good (and fast) doesn't
116
+ * mean drowning in work while capable teammates sit idle.
117
+ *
118
+ * The underlying numbers are derived automatically from the candidate
119
+ * scores of each matching pass, so there is nothing to calibrate.
120
+ * `'balanced'` and `'spread-work'` also include a rolling-window
121
+ * guardrail by default: nobody receives at more than double the team's
122
+ * average grant rate over `fairnessWindowMs` (one hour unless changed) —
123
+ * see `fairnessMaxPerWindow` to set an explicit ceiling instead, or pass
124
+ * `Infinity` there to opt out.
125
+ * Setting `fairnessLoadPenalty` / `fairnessTieBand` explicitly overrides
126
+ * the derived values; setting `fairness` overrides
127
+ * `enableFairTiebreaker`. Switchable at runtime via `setFairness(mode)`;
128
+ * every fairness knob (not just the mode) can be retuned live with
129
+ * `setFairnessConfig(config)`.
130
+ */
131
+ fairness?: FairnessMode;
132
+ /**
133
+ * Hard cap on how many assignments a single user may be granted within a
134
+ * rolling time window (default: undefined, disabled; applies in any
135
+ * `fairness` mode other than `'first-come'`). The backlog cap alone can't
136
+ * protect diligent users: someone who accepts and completes work quickly
137
+ * keeps freeing backlog slots and keeps winning, so speed is rewarded
138
+ * with ever more work. This cap counts *granted* assignments over
139
+ * `fairnessWindowMs` regardless of how fast they were cleared; once a
140
+ * user hits it, contested assignments spill to the next-best eligible
141
+ * user (or stay queued) until the window rolls. Workflow-targeted
142
+ * assignments are direct handoffs and bypass the cap so workflows never
143
+ * stall.
144
+ *
145
+ * When left undefined, the `'balanced'` / `'spread-work'` presets supply
146
+ * a team-relative guardrail automatically: `max(maxUserBacklogSize,
147
+ * 2 x the team's average grants in the window)`, recomputed each pass, so
148
+ * it adapts to any deployment's volume without configuration. Set an
149
+ * explicit number to pin the ceiling, or `Infinity` to disable the
150
+ * window cap entirely.
151
+ */
152
+ fairnessMaxPerWindow?: number;
153
+ /**
154
+ * Rolling window length in milliseconds for `fairnessMaxPerWindow`
155
+ * (default: 3600000 — one hour).
156
+ */
157
+ fairnessWindowMs?: number;
158
+ /**
159
+ * Load-penalized scoring for fair-tiebreaker arbitration (default: 0,
160
+ * disabled; requires `enableFairTiebreaker`). Each assignment already on
161
+ * a user's backlog — including ones won earlier in the same matching
162
+ * pass — subtracts this amount from their effective score when competing
163
+ * for the next contested assignment. Pure best-score-wins arbitration
164
+ * otherwise saturates the top scorer to `maxUserBacklogSize` every pass;
165
+ * a penalty makes distribution progressive: the specialist still wins
166
+ * their first picks, but once loaded they lose marginal contests to an
167
+ * idle, still-capable candidate. Pick a value relative to your score
168
+ * scale (base priority + summed routing weights).
169
+ */
170
+ fairnessLoadPenalty?: number;
171
+ /**
172
+ * Tie-band arbitration for fair-tiebreaker mode (default: 0, disabled;
173
+ * requires `enableFairTiebreaker`). Candidate scores falling in the same
174
+ * band-sized bucket (`floor(score / fairnessTieBand)`) are treated as
175
+ * tied, and the tie goes to the user currently carrying the least work.
176
+ * Scores in different buckets still resolve strictly by score, so clear
177
+ * skill differences always dominate — only near-ties get load-balanced.
178
+ * Note the bucket boundaries are fixed, so two scores less than a band
179
+ * apart can still straddle a boundary and resolve by score.
180
+ */
181
+ fairnessTieBand?: number;
182
+ /** Enable distance-based geolocation matching (default: false) */
183
+ enableGeoMatching?: boolean;
184
+ /** Global fallback cap in kilometers when assignment/user-specific caps are absent */
185
+ geoDefaultMaxDistanceKm?: number;
186
+ /** Proximity boost weight added to combined priority (default: 0) */
187
+ geoScoreWeight?: number;
188
+ /** Custom geolocation matcher override */
189
+ geoMatchingFunction?: GeoMatchingFunction;
46
190
  /** Enable workflow orchestration features */
47
191
  enableWorkflows?: boolean;
48
192
  /** Consumer group name for Redis Streams (defaults to 'orchestrator') */
49
193
  streamConsumerGroup?: string;
50
194
  /** Consumer name within the group (defaults to random UUID) */
51
195
  streamConsumerName?: string;
196
+ /** Maximum number of reconnection attempts (default: 10) */
197
+ redisMaxRetries?: number;
198
+ /** Initial delay between retries in ms (default: 50) */
199
+ redisInitialRetryDelay?: number;
200
+ /** Maximum delay between retries in ms (default: 2000) */
201
+ redisMaxRetryDelay?: number;
202
+ /** Connection timeout in ms (default: 10000) */
203
+ redisConnectTimeout?: number;
204
+ /** Command timeout in ms (default: 3000) */
205
+ redisCommandTimeout?: number;
206
+ /** Enable offline queue for commands during disconnect (default: true) */
207
+ redisEnableOfflineQueue?: boolean;
208
+ /** Enable ready check before considering connection successful (default: true) */
209
+ redisEnableReadyCheck?: boolean;
210
+ /** Health check interval in ms (default: 30000) */
211
+ redisHealthCheckInterval?: number;
52
212
  /** Maximum retries for failed workflow events before moving to DLQ (default: 3) */
53
213
  workflowMaxRetries?: number;
54
214
  /** TTL for idempotency keys in milliseconds (default: 86400000 = 24h) */
@@ -67,6 +227,37 @@ export type MatcherOptions = {
67
227
  workflowSnapshotDefinitions?: boolean;
68
228
  /** Enable OpenTelemetry tracing (default: false) */
69
229
  enableOpenTelemetry?: boolean;
230
+ /** Persist circuit breaker state to Redis for distributed awareness (default: false) */
231
+ circuitBreakerPersistState?: boolean;
232
+ /**
233
+ * Share circuit breaker failure counts across replicas via Redis so
234
+ * breakers converge in multi-orchestrator deployments (default: false).
235
+ */
236
+ circuitBreakerShared?: boolean;
237
+ /**
238
+ * TTL applied to terminal (completed/failed/cancelled) workflow instances,
239
+ * including cleanup of registry, per-user, and active-index entries.
240
+ * When unset (default), terminal instances are kept forever.
241
+ */
242
+ workflowInstanceRetentionMs?: number;
243
+ /** Initial backoff delay for scheduled workflow event retries in ms (default: 1000) */
244
+ workflowRetryBackoffMs?: number;
245
+ /** Max stream entries read per orchestrator poll (XREADGROUP COUNT, default: 10) */
246
+ workflowEventBatchSize?: number;
247
+ /** Blocking wait per orchestrator poll in ms (XREADGROUP BLOCK, default: 5000) */
248
+ workflowPollBlockMs?: number;
249
+ /**
250
+ * Per-replica throttle on workflow event processing (events per second).
251
+ * Applies to orchestrator stream consumption and scheduled-retry draining.
252
+ * When unset (default), events are processed as fast as possible.
253
+ */
254
+ workflowMaxEventsPerSecond?: number;
255
+ /** Enable circuit breaker and reliability metrics (default: true when telemetry enabled) */
256
+ enableReliabilityMetrics?: boolean;
257
+ /** Enable graceful degradation mode when Redis is unavailable (default: false) */
258
+ enableGracefulDegradation?: boolean;
259
+ /** Alert threshold for Dead Letter Queue size (default: 100) */
260
+ deadLetterQueueAlertThreshold?: number;
70
261
  /** Enable the contextual-bandit learning layer (default: false) */
71
262
  enableLearning?: boolean;
72
263
  /** SGD learning rate for online model updates (default: 0.1) */
@@ -87,9 +278,30 @@ export type MatcherOptions = {
87
278
  learningSignalWeights?: Record<string, number>;
88
279
  /** TTL for archived episodes awaiting external feedback in ms (default: 604800000 = 7 days) */
89
280
  learningFeedbackTtlMs?: number;
281
+ /**
282
+ * Track per-user, per-tag reward statistics and enable automatic
283
+ * routingWeights generation from RL outcomes (requires enableLearning).
284
+ * Default: false.
285
+ */
286
+ enableAutoRoutingWeights?: boolean;
287
+ /** Tuning for automatic routing-weight synthesis (UCB1 policy) */
288
+ autoRoutingWeights?: AutoRoutingWeightsOptions;
90
289
  };
91
290
  /** @deprecated Use MatcherOptions instead */
92
291
  export type options = MatcherOptions;
292
+ /** Operational metrics for the workflow engine */
293
+ export type WorkflowEngineMetrics = {
294
+ /** Number of active workflow instances (from the active-instance index) */
295
+ activeInstances: number;
296
+ /** Number of events waiting in the delayed-retry queue */
297
+ scheduledRetries: number;
298
+ /** Number of events in the Dead Letter Queue */
299
+ deadLetterQueueSize: number;
300
+ /** Total length of the workflow event stream */
301
+ streamLength: number;
302
+ /** Number of pending (delivered but unacknowledged) stream messages */
303
+ streamPending: number;
304
+ };
93
305
  /** Event types for workflow lifecycle */
94
306
  export type WorkflowEventType = 'STARTED' | 'COMPLETED' | 'REJECTED' | 'EXPIRED' | 'FAILED';
95
307
  /** Step execution mode */
@@ -284,6 +496,25 @@ export interface CircuitBreakerState {
284
496
  /** Timestamp of last failure */
285
497
  lastFailureTime: number;
286
498
  }
499
+ /** Reliability metrics for monitoring */
500
+ export interface ReliabilityMetrics {
501
+ /** Current circuit breaker state */
502
+ circuitBreakerState: CircuitBreakerState;
503
+ /** Current Dead Letter Queue size */
504
+ deadLetterQueueSize: number;
505
+ /** Whether Redis is considered healthy */
506
+ redisHealthy: boolean;
507
+ /** Number of reconnection attempts since start */
508
+ reconnectCount: number;
509
+ /** Last error message if any */
510
+ lastError?: string;
511
+ /** Timestamp of last successful connection */
512
+ lastConnectedAt: number;
513
+ /** Timestamp of last health check */
514
+ lastHealthCheckAt?: number;
515
+ /** Whether circuit breaker is currently allowing requests */
516
+ circuitBreakerAllowingRequests: boolean;
517
+ }
287
518
  /** Workflow instance with resolved definition for versioning */
288
519
  export interface WorkflowInstanceWithSnapshot extends WorkflowInstance {
289
520
  /** Resolved definition (from snapshot or registry) */
@@ -309,6 +540,8 @@ export interface LearningDecisionRecord {
309
540
  assignmentId: string;
310
541
  features: LearningFeatures;
311
542
  predictedReward: number;
543
+ /** Assignment tags captured at decision time (used for auto routing weights) */
544
+ tags?: string[];
312
545
  timestamp: number;
313
546
  }
314
547
  /** Archived episode retained after a terminal outcome for late external feedback */
@@ -318,6 +551,8 @@ export interface LearningEpisodeRecord {
318
551
  features: LearningFeatures;
319
552
  /** Terminal outcome that archived this episode */
320
553
  outcome?: LearningOutcome;
554
+ /** Assignment tags captured at decision time (used for auto routing weights) */
555
+ tags?: string[];
321
556
  timestamp: number;
322
557
  }
323
558
  /** Named external signal values (e.g. { accuracy: 0.95, csat: 0.8 }) */
@@ -327,6 +562,29 @@ export interface LearningSample {
327
562
  features: LearningFeatures;
328
563
  reward: number;
329
564
  }
565
+ /** Per-user, per-tag reward statistics aggregated from lifecycle outcomes */
566
+ export interface LearningTagStat {
567
+ tag: string;
568
+ /** Number of reward observations for this tag */
569
+ count: number;
570
+ /** Sum of observed rewards for this tag */
571
+ rewardSum: number;
572
+ /** rewardSum / count (0 when no observations) */
573
+ meanReward: number;
574
+ }
575
+ /** Options controlling automatic routing-weight synthesis (UCB1 policy) */
576
+ export interface AutoRoutingWeightsOptions {
577
+ /** Minimum observations before a tag's stats are trusted (default: 5) */
578
+ minSamples?: number;
579
+ /** Mean-reward UCB score at or below which a tag is hard-vetoed with weight 0 (default: -0.5) */
580
+ vetoThreshold?: number;
581
+ /** Maximum synthesized weight on the conventional 0-100 scale (default: 100) */
582
+ maxWeight?: number;
583
+ /** UCB exploration coefficient; higher favors less-sampled tags (default: 0.5) */
584
+ explorationBonus?: number;
585
+ /** Optimistic weight assigned to under-sampled or unobserved known tags (default: maxWeight / 2) */
586
+ priorWeight?: number;
587
+ }
330
588
  /** Aggregate learning statistics */
331
589
  export interface LearningStats {
332
590
  /** Number of recorded match decisions */