assignment-user-matcher 1.7.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.
@@ -6,6 +6,12 @@ import type { User, MatchTraceReason } from '../types/matcher';
6
6
  * Check if a pattern matches a tag (supports wildcard patterns ending with *)
7
7
  */
8
8
  export declare function matchesPattern(pattern: string, tag: string): boolean;
9
+ /**
10
+ * Where a zero-weight veto came from: the learning layer's last sync, or an
11
+ * operator. Returns undefined for users with no learned weights at all, which
12
+ * keeps the trace shape unchanged for everyone not using the learning layer.
13
+ */
14
+ export declare function vetoSource(user: User, pattern: string): 'manual' | 'learned' | undefined;
9
15
  /**
10
16
  * Get the effective weight for a skill tag from user's routingWeights
11
17
  * Supports wildcard patterns (e.g., 'eng*' matches 'english')
@@ -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,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AAE/D;;GAEG;AACH,wBAAgB,cAAc,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,OAAO,CAOpE;AAED;;;GAGG;AACH,wBAAgB,kBAAkB,CAAC,cAAc,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,EAAE,GAAG,EAAE,MAAM,GAAG,MAAM,CAY9F;AAED;;;GAGG;AACH,wBAAgB,oBAAoB,CAChC,cAAc,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,SAAS,EAClD,eAAe,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,SAAS,GACpD,OAAO,CAeT;AAED;;;GAGG;AACH,wBAAgB,mBAAmB,CAC/B,IAAI,EAAE,IAAI,EACV,cAAc,EAAE,MAAM,EACtB,kBAAkB,EAAE,MAAM,GAAG,MAAM,EACnC,qBAAqB,EA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AC,MAAM,EAAE,MAAM,CAAC,GAAG,SAAS,GACpD,OAAO,CAeT;AAED;;;GAGG;AACH,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,gGAAgG;AAChG,MAAM,WAAW,qBAAqB;IAClC,KAAK,EAAE,MAAM,CAAC;IACd,gBAAgB,EAAE,MAAM,CAAC;IACzB,OAAO,EAAE,gBAAgB,EAAE,CAAC;CAC/B;AAED;;;;;;;;GAQG;AACH,wBAAgB,iBAAiB,CAC7B,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,qBAAqB,CA8EvB;AAED;;;GAGG;AACH,wBAAgB,wBAAwB,CAAC,SAAS,CAAC,EAAE,MAAM,GAAG,MAAM,CAGnE"}
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.calculateDefaultPriority = exports.explainMatchScore = exports.calculateMatchScore = exports.meetsSkillThresholds = exports.getEffectiveWeight = exports.matchesPattern = void 0;
3
+ exports.calculateDefaultPriority = exports.explainMatchScore = exports.calculateMatchScore = exports.meetsSkillThresholds = exports.getEffectiveWeight = exports.vetoSource = exports.matchesPattern = void 0;
4
4
  /**
5
5
  * Check if a pattern matches a tag (supports wildcard patterns ending with *)
6
6
  */
@@ -14,6 +14,18 @@ function matchesPattern(pattern, tag) {
14
14
  return false;
15
15
  }
16
16
  exports.matchesPattern = matchesPattern;
17
+ /**
18
+ * Where a zero-weight veto came from: the learning layer's last sync, or an
19
+ * operator. Returns undefined for users with no learned weights at all, which
20
+ * keeps the trace shape unchanged for everyone not using the learning layer.
21
+ */
22
+ function vetoSource(user, pattern) {
23
+ const learned = user.learnedRoutingWeights;
24
+ if (!learned)
25
+ return undefined;
26
+ return learned[pattern] === 0 ? 'learned' : 'manual';
27
+ }
28
+ exports.vetoSource = vetoSource;
17
29
  /**
18
30
  * Get the effective weight for a skill tag from user's routingWeights
19
31
  * Supports wildcard patterns (e.g., 'eng*' matches 'english')
@@ -149,7 +161,10 @@ function explainMatchScore(user, assignmentTags, assignmentPriority, enableDefau
149
161
  if (weight === 0) {
150
162
  for (const t of aTags) {
151
163
  if (matchesPattern(pattern, t)) {
152
- reasons.push({ kind: 'veto', tag: t, pattern });
164
+ const source = vetoSource(user, pattern);
165
+ reasons.push(source
166
+ ? { kind: 'veto', tag: t, pattern, source }
167
+ : { kind: 'veto', tag: t, pattern });
153
168
  vetoed = true;
154
169
  }
155
170
  }
@@ -0,0 +1,49 @@
1
+ /**
2
+ * SLA policy — pure logic.
3
+ *
4
+ * An assignment carries an optional `sla` policy describing its service-level
5
+ * contract: completion deadline (from accept), freshness TTL (from first
6
+ * enqueue), and rejection budget. Everything here is deliberately
7
+ * side-effect free: `AssignmentMatcher` owns the Redis writes, this module
8
+ * owns the decisions.
9
+ *
10
+ * The response/acceptance side is owned by `EscalationPolicy`; SLA starts
11
+ * where escalation stops.
12
+ */
13
+ import type { Assignment, SlaPolicy } from '../types/matcher';
14
+ /** A policy with every optional field resolved. */
15
+ export interface NormalizedSlaPolicy {
16
+ completeWithinMs?: number;
17
+ expireAfterMs?: number;
18
+ maxRejections?: number;
19
+ onCompletionBreach: 'notify' | 'requeue' | 'fail' | 'park';
20
+ onMaxRejections: 'park' | 'fail' | 'keep';
21
+ onExpire: 'drop' | 'park';
22
+ }
23
+ /** Internal markers the matcher persists on the assignment JSON. */
24
+ export declare const SLA_ENQUEUED_AT_FIELD = "_enqueuedAt";
25
+ export declare const SLA_REJECTION_COUNT_FIELD = "_rejectionCount";
26
+ export declare const SLA_MATCHED_AT_FIELD = "_matchedAt";
27
+ export declare const SLA_ACCEPTED_AT_FIELD = "_acceptedAt";
28
+ export declare const SLA_ACCEPTED_BY_FIELD = "_acceptedBy";
29
+ /**
30
+ * Resolve an assignment's SLA policy, or `null` when it has none (the
31
+ * overwhelming majority of assignments — callers use the null to stay on
32
+ * the untouched legacy path).
33
+ */
34
+ export declare function normalizeSlaPolicy(policy: SlaPolicy | undefined | null): NormalizedSlaPolicy | null;
35
+ /**
36
+ * Same question, answered from the stored JSON without paying for a parse on
37
+ * the claim/accept hot path. Assignments without an SLA — effectively all of
38
+ * them in a typical deployment — cost one `indexOf` and nothing else.
39
+ */
40
+ export declare function slaFromJson(json: string | null | undefined): NormalizedSlaPolicy | null;
41
+ /** Current rejection count of an assignment (0 = never rejected). */
42
+ export declare function rejectionCountOf(assignment: Assignment): number;
43
+ /** Deadline score for the accepted-expiry zset. */
44
+ export declare function completionDeadlineScore(acceptedAt: number, policy: NormalizedSlaPolicy): number | null;
45
+ /** Deadline score for the TTL zset. */
46
+ export declare function slaExpiryScore(enqueuedAt: number, policy: NormalizedSlaPolicy): number | null;
47
+ /** Whether the rejection budget has been exhausted. */
48
+ export declare function rejectionBudgetExhausted(assignment: Assignment, policy: NormalizedSlaPolicy): boolean;
49
+ //# sourceMappingURL=policy.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"policy.d.ts","sourceRoot":"","sources":["../../src/sla/policy.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,KAAK,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAE9D,mDAAmD;AACnD,MAAM,WAAW,mBAAmB;IAChC,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,kBAAkB,EAAE,QAAQ,GAAG,SAAS,GAAG,MAAM,GAAG,MAAM,CAAC;IAC3D,eAAe,EAAE,MAAM,GAAG,MAAM,GAAG,MAAM,CAAC;IAC1C,QAAQ,EAAE,MAAM,GAAG,MAAM,CAAC;CAC7B;AAED,oEAAoE;AACpE,eAAO,MAAM,qBAAqB,gBAAgB,CAAC;AACnD,eAAO,MAAM,yBAAyB,oBAAoB,CAAC;AAC3D,eAAO,MAAM,oBAAoB,eAAe,CAAC;AACjD,eAAO,MAAM,qBAAqB,gBAAgB,CAAC;AACnD,eAAO,MAAM,qBAAqB,gBAAgB,CAAC;AAYnD;;;;GAIG;AACH,wBAAgB,kBAAkB,CAAC,MAAM,EAAE,SAAS,GAAG,SAAS,GAAG,IAAI,GAAG,mBAAmB,GAAG,IAAI,CAyBnG;AAED;;;;GAIG;AACH,wBAAgB,WAAW,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,GAAG,mBAAmB,GAAG,IAAI,CAOvF;AAED,qEAAqE;AACrE,wBAAgB,gBAAgB,CAAC,UAAU,EAAE,UAAU,GAAG,MAAM,CAG/D;AAED,mDAAmD;AACnD,wBAAgB,uBAAuB,CAAC,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,mBAAmB,GAAG,MAAM,GAAG,IAAI,CAEtG;AAED,uCAAuC;AACvC,wBAAgB,cAAc,CAAC,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,mBAAmB,GAAG,MAAM,GAAG,IAAI,CAE7F;AAED,uDAAuD;AACvD,wBAAgB,wBAAwB,CAAC,UAAU,EAAE,UAAU,EAAE,MAAM,EAAE,mBAAmB,GAAG,OAAO,CAGrG"}
@@ -0,0 +1,96 @@
1
+ "use strict";
2
+ /**
3
+ * SLA policy — pure logic.
4
+ *
5
+ * An assignment carries an optional `sla` policy describing its service-level
6
+ * contract: completion deadline (from accept), freshness TTL (from first
7
+ * enqueue), and rejection budget. Everything here is deliberately
8
+ * side-effect free: `AssignmentMatcher` owns the Redis writes, this module
9
+ * owns the decisions.
10
+ *
11
+ * The response/acceptance side is owned by `EscalationPolicy`; SLA starts
12
+ * where escalation stops.
13
+ */
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.rejectionBudgetExhausted = exports.slaExpiryScore = exports.completionDeadlineScore = exports.rejectionCountOf = exports.slaFromJson = exports.normalizeSlaPolicy = exports.SLA_ACCEPTED_BY_FIELD = exports.SLA_ACCEPTED_AT_FIELD = exports.SLA_MATCHED_AT_FIELD = exports.SLA_REJECTION_COUNT_FIELD = exports.SLA_ENQUEUED_AT_FIELD = void 0;
16
+ /** Internal markers the matcher persists on the assignment JSON. */
17
+ exports.SLA_ENQUEUED_AT_FIELD = '_enqueuedAt';
18
+ exports.SLA_REJECTION_COUNT_FIELD = '_rejectionCount';
19
+ exports.SLA_MATCHED_AT_FIELD = '_matchedAt';
20
+ exports.SLA_ACCEPTED_AT_FIELD = '_acceptedAt';
21
+ exports.SLA_ACCEPTED_BY_FIELD = '_acceptedBy';
22
+ function positiveMs(value) {
23
+ const n = Number(value);
24
+ return Number.isFinite(n) && n > 0 ? n : undefined;
25
+ }
26
+ function nonNegativeInt(value) {
27
+ const n = Number(value);
28
+ return Number.isFinite(n) && n >= 0 ? Math.floor(n) : undefined;
29
+ }
30
+ /**
31
+ * Resolve an assignment's SLA policy, or `null` when it has none (the
32
+ * overwhelming majority of assignments — callers use the null to stay on
33
+ * the untouched legacy path).
34
+ */
35
+ function normalizeSlaPolicy(policy) {
36
+ if (!policy || typeof policy !== 'object')
37
+ return null;
38
+ const completeWithinMs = positiveMs(policy.completeWithinMs);
39
+ const expireAfterMs = positiveMs(policy.expireAfterMs);
40
+ const maxRejections = nonNegativeInt(policy.maxRejections);
41
+ if (completeWithinMs === undefined && expireAfterMs === undefined && maxRejections === undefined) {
42
+ return null;
43
+ }
44
+ return {
45
+ completeWithinMs,
46
+ expireAfterMs,
47
+ maxRejections,
48
+ onCompletionBreach: policy.onCompletionBreach === 'requeue' ||
49
+ policy.onCompletionBreach === 'fail' ||
50
+ policy.onCompletionBreach === 'park'
51
+ ? policy.onCompletionBreach
52
+ : 'notify',
53
+ onMaxRejections: policy.onMaxRejections === 'fail' || policy.onMaxRejections === 'keep' ? policy.onMaxRejections : 'park',
54
+ onExpire: policy.onExpire === 'park' ? 'park' : 'drop',
55
+ };
56
+ }
57
+ exports.normalizeSlaPolicy = normalizeSlaPolicy;
58
+ /**
59
+ * Same question, answered from the stored JSON without paying for a parse on
60
+ * the claim/accept hot path. Assignments without an SLA — effectively all of
61
+ * them in a typical deployment — cost one `indexOf` and nothing else.
62
+ */
63
+ function slaFromJson(json) {
64
+ if (!json || json.indexOf('"sla"') === -1)
65
+ return null;
66
+ try {
67
+ return normalizeSlaPolicy(JSON.parse(json).sla);
68
+ }
69
+ catch {
70
+ return null;
71
+ }
72
+ }
73
+ exports.slaFromJson = slaFromJson;
74
+ /** Current rejection count of an assignment (0 = never rejected). */
75
+ function rejectionCountOf(assignment) {
76
+ const raw = Number(assignment[exports.SLA_REJECTION_COUNT_FIELD]);
77
+ return Number.isFinite(raw) && raw > 0 ? Math.floor(raw) : 0;
78
+ }
79
+ exports.rejectionCountOf = rejectionCountOf;
80
+ /** Deadline score for the accepted-expiry zset. */
81
+ function completionDeadlineScore(acceptedAt, policy) {
82
+ return policy.completeWithinMs === undefined ? null : acceptedAt + policy.completeWithinMs;
83
+ }
84
+ exports.completionDeadlineScore = completionDeadlineScore;
85
+ /** Deadline score for the TTL zset. */
86
+ function slaExpiryScore(enqueuedAt, policy) {
87
+ return policy.expireAfterMs === undefined ? null : enqueuedAt + policy.expireAfterMs;
88
+ }
89
+ exports.slaExpiryScore = slaExpiryScore;
90
+ /** Whether the rejection budget has been exhausted. */
91
+ function rejectionBudgetExhausted(assignment, policy) {
92
+ if (policy.maxRejections === undefined)
93
+ return false;
94
+ return rejectionCountOf(assignment) >= policy.maxRejections;
95
+ }
96
+ exports.rejectionBudgetExhausted = rejectionBudgetExhausted;
@@ -1 +1 @@
1
- {"version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AACH,wBAAgB,mBAAmB,CAAC,MAAM,EAAE;IACxC,SAAS,EAAE,cAAc,CAAC;IAC1B,OAAO,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC7B,IAAI,EAAE,iBAAiB,CAAC;IACxB,KAAK,EAAE,gBAAgB,EAAE,CAAC;IAC1B,aAAa,EAAE,MAAM,CAAC;IACtB,SAAS,EAAE,MAAM,CAAC;CACrB,GAAG,kBAAkB,EAAE,CAgDvB;AAED,oFAAoF;AACpF,wBAAgB,mBAAmB,CAC/B,MAAM,EAAE,KAAK,CAAC;IAAE,YAAY,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAA;CAAE,CAAC,EACzE,SAAS,EAAE,MAAM,GAClB,kBAAkB,EAAE,CAkBtB"}
@@ -64,9 +64,11 @@ function excludedCandidate(ctx, assignmentId, tags) {
64
64
  if (weights) {
65
65
  for (const [pattern, weight] of Object.entries(weights)) {
66
66
  if (weight === 0) {
67
+ const source = (0, match_score_1.vetoSource)(ctx.user, pattern);
67
68
  for (const tag of tags) {
68
- if ((0, match_score_1.matchesPattern)(pattern, tag))
69
- reasons.push({ kind: 'veto', tag, pattern });
69
+ if (!(0, match_score_1.matchesPattern)(pattern, tag))
70
+ continue;
71
+ reasons.push(source ? { kind: 'veto', tag, pattern, source } : { kind: 'veto', tag, pattern });
70
72
  }
71
73
  }
72
74
  }
@@ -9,6 +9,12 @@ export interface User {
9
9
  longitude?: number;
10
10
  maxTravelDistanceKm?: number;
11
11
  maxBacklogSize?: number;
12
+ /** Snapshot of routingWeights before the last learned sync; used by revertLearnedRoutingWeights(). */
13
+ routingWeightsSnapshot?: Record<string, number>;
14
+ /** Unix epoch ms of the last learned routing-weights sync for this user. */
15
+ learnedRoutingWeightsSyncedAt?: number;
16
+ /** The weights last applied by syncLearnedRoutingWeights(); for observability only. */
17
+ learnedRoutingWeights?: Record<string, number>;
12
18
  [key: string]: any;
13
19
  }
14
20
  export type Assignment = {
@@ -23,6 +29,7 @@ export type Assignment = {
23
29
  maxDistanceKm?: number;
24
30
  requireGeo?: boolean;
25
31
  escalation?: EscalationPolicy;
32
+ sla?: SlaPolicy;
26
33
  [key: string]: any;
27
34
  };
28
35
  /**
@@ -90,6 +97,105 @@ export interface EscalationPolicy {
90
97
  */
91
98
  onExhausted?: 'queue' | 'park';
92
99
  }
100
+ /**
101
+ * What service-level contract applies to an assignment once it is queued.
102
+ *
103
+ * EscalationPolicy owns the response/acceptance side (`respondWithinMs`);
104
+ * SlaPolicy owns everything after that: how long the accepting user has to
105
+ * finish, how many times the assignment may be rejected before it is pulled
106
+ * from rotation, and an absolute freshness cutoff after which the work is
107
+ * considered moot.
108
+ *
109
+ * All timers are swept by the maintenance tick (see `startMaintenance()` /
110
+ * `runMaintenanceOnce()`), so they fire with sweep granularity rather than
111
+ * at the exact deadline.
112
+ *
113
+ * @example
114
+ * ```typescript
115
+ * await matcher.addAssignment({
116
+ * id: 'order-42',
117
+ * tags: ['fulfillment'],
118
+ * sla: {
119
+ * completeWithinMs: 30 * 60_000,
120
+ * onCompletionBreach: 'requeue',
121
+ * maxRejections: 3,
122
+ * expireAfterMs: 24 * 3600_000,
123
+ * },
124
+ * });
125
+ * ```
126
+ */
127
+ export interface SlaPolicy {
128
+ /**
129
+ * Milliseconds the accepting user has to complete the assignment,
130
+ * measured from the moment `acceptAssignment()` succeeds. When the clock
131
+ * runs out the completion-deadline sweep applies `onCompletionBreach`.
132
+ */
133
+ completeWithinMs?: number;
134
+ /**
135
+ * Absolute freshness cutoff in milliseconds, measured from the first
136
+ * enqueue (survives requeues and applies in every state — queued,
137
+ * pending, accepted). When the cutoff elapses the TTL sweep applies
138
+ * `onExpire`. Use this for work that becomes moot after a while
139
+ * regardless of who holds it.
140
+ */
141
+ expireAfterMs?: number;
142
+ /**
143
+ * Maximum number of times the assignment may be refused before
144
+ * `onMaxRejections` fires. Both explicit `rejectAssignment()` calls and
145
+ * blocking no-response expiries (`escalation.onNoResponse: 'block'`)
146
+ * count; idle releases, operator releases, and non-blocking expiries
147
+ * do not.
148
+ */
149
+ maxRejections?: number;
150
+ /**
151
+ * What happens when the completion deadline (`completeWithinMs`) elapses.
152
+ * - `'notify'` — emit a `completionBreached` lifecycle event and record
153
+ * an `expire` learning outcome; the worker keeps the assignment.
154
+ * - `'requeue'` — take the assignment back, block the breaching user,
155
+ * and return it to the queue. The TTL (`expireAfterMs`) keeps ticking.
156
+ * - `'fail'` — close the assignment as failed in the completed store.
157
+ * - `'park'` — hold the assignment out of matching (see parked store).
158
+ * @default 'notify'
159
+ */
160
+ onCompletionBreach?: 'notify' | 'requeue' | 'fail' | 'park';
161
+ /**
162
+ * What happens when the rejection budget (`maxRejections`) is exhausted.
163
+ * - `'park'` — move to the parked store; retrievable via
164
+ * `getParkedAssignments()` / `unparkAssignment()`.
165
+ * - `'fail'` — close the assignment as failed in the completed store.
166
+ * - `'keep'` — keep requeueing (legacy behaviour; makes `maxRejections`
167
+ * a measurement-only knob).
168
+ * @default 'park'
169
+ */
170
+ onMaxRejections?: 'park' | 'fail' | 'keep';
171
+ /**
172
+ * What happens when the freshness cutoff (`expireAfterMs`) elapses.
173
+ * - `'drop'` — remove the assignment entirely from whichever store it
174
+ * occupies.
175
+ * - `'park'` — move it to the parked store for operator inspection.
176
+ * @default 'drop'
177
+ */
178
+ onExpire?: 'drop' | 'park';
179
+ }
180
+ /** Aggregate SLO attainment counters from `getSlaStats()`. */
181
+ export interface SlaStats {
182
+ /** Total assignments offered (pending) for the scope */
183
+ offers: number;
184
+ /** Assignments accepted before their response deadline */
185
+ acceptedInTime: number;
186
+ /** Pending assignments whose response deadline elapsed (all, not only SLA-bearing) */
187
+ acceptanceBreaches: number;
188
+ /** Accepted assignments whose completion deadline elapsed */
189
+ completionBreaches: number;
190
+ /** Assignments removed/parked by the freshness TTL */
191
+ ttlExpiries: number;
192
+ /** Assignments parked because their rejection budget ran out */
193
+ rejectionParked: number;
194
+ /** Mean accept latency in ms (acceptedAt - matchedAt), 0 when no data */
195
+ meanAcceptLatencyMs: number;
196
+ /** Mean completion latency in ms (completedAt - acceptedAt), 0 when no data */
197
+ meanCompleteLatencyMs: number;
198
+ }
93
199
  export type GeoMatchResult = {
94
200
  eligible: boolean;
95
201
  distanceKm?: number;
@@ -186,11 +292,16 @@ export type MatchTraceReason =
186
292
  kind: 'customScore';
187
293
  score: number;
188
294
  }
189
- /** A zero-weight routing entry hard-vetoed an assignment tag */
295
+ /**
296
+ * A zero-weight routing entry hard-vetoed an assignment tag. `source` is set
297
+ * only for users carrying `learnedRoutingWeights`, and distinguishes a veto
298
+ * the learning layer synthesized from one an operator configured.
299
+ */
190
300
  | {
191
301
  kind: 'veto';
192
302
  tag: string;
193
303
  pattern: string;
304
+ source?: 'manual' | 'learned';
194
305
  }
195
306
  /** The user is in the assignment's `vetoedUsers` list */
196
307
  | {
@@ -388,6 +499,45 @@ export type AssignmentLifecycleEvent = {
388
499
  level: number;
389
500
  parked: boolean;
390
501
  at: number;
502
+ }
503
+ /**
504
+ * An accepted assignment's completion deadline (`sla.completeWithinMs`)
505
+ * elapsed. `action` is what the policy did about it.
506
+ */
507
+ | {
508
+ kind: 'completionBreached';
509
+ taskId: string;
510
+ workerId: string | null;
511
+ action: 'notify' | 'requeue' | 'fail' | 'park';
512
+ /** The assignment as it stood when the deadline elapsed. See the note below. */
513
+ assignment: Assignment;
514
+ at: number;
515
+ }
516
+ /**
517
+ * The freshness TTL (`sla.expireAfterMs`) elapsed; the assignment was
518
+ * removed from whichever store it occupied.
519
+ */
520
+ | {
521
+ kind: 'slaExpired';
522
+ taskId: string;
523
+ ownerId: string | null;
524
+ action: 'drop' | 'park';
525
+ /** The assignment as it stood when the TTL elapsed. See the note below. */
526
+ assignment: Assignment;
527
+ at: number;
528
+ }
529
+ /**
530
+ * The rejection budget (`sla.maxRejections`) ran out; the assignment was
531
+ * pulled from rotation.
532
+ */
533
+ | {
534
+ kind: 'rejectionBudgetExhausted';
535
+ taskId: string;
536
+ rejections: number;
537
+ action: 'park' | 'fail';
538
+ /** The assignment as it stood when the budget ran out. See the note below. */
539
+ assignment: Assignment;
540
+ at: number;
391
541
  };
392
542
  /** Outcome of one `processResponseDeadlines()` sweep. */
393
543
  export type EscalationSweepResult = {
@@ -398,6 +548,16 @@ export type EscalationSweepResult = {
398
548
  /** How many exhausted their ladder and were parked */
399
549
  parked: number;
400
550
  };
551
+ /** Outcome of one `processCompletionDeadlines()` sweep. */
552
+ export type CompletionDeadlineSweepResult = {
553
+ /** Accepted assignments whose completion deadline elapsed */
554
+ breached: number;
555
+ };
556
+ /** Outcome of one `processSlaExpiries()` sweep. */
557
+ export type SlaExpirySweepResult = {
558
+ /** Assignments whose freshness TTL elapsed */
559
+ expired: number;
560
+ };
401
561
  /** One pass of `runMaintenanceOnce()`. Counts are per pass, not cumulative. */
402
562
  export type MaintenanceReport = {
403
563
  /** Pending assignments whose response deadline elapsed */
@@ -410,6 +570,10 @@ export type MaintenanceReport = {
410
570
  expiredSteps: number;
411
571
  /** Idle users removed from the pool (see `idleUserTimeoutMs`) */
412
572
  releasedIdleUsers: number;
573
+ /** Accepted assignments whose completion deadline elapsed (SLA) */
574
+ completionBreaches: number;
575
+ /** Assignments whose freshness TTL elapsed (SLA) */
576
+ slaExpiries: number;
413
577
  /** Wall-clock duration of the pass */
414
578
  tookMs: number;
415
579
  };
@@ -419,6 +583,10 @@ export type MaintenanceOptions = {
419
583
  intervalMs?: number;
420
584
  /** Response deadlines / escalation. @default true */
421
585
  responseDeadlines?: boolean;
586
+ /** Completion deadlines (SLA `completeWithinMs`). @default true */
587
+ completionDeadlines?: boolean;
588
+ /** Freshness TTL expiries (SLA `expireAfterMs`). @default true */
589
+ slaExpiries?: boolean;
422
590
  /** Workflow step timeouts. @default true when `enableWorkflows` */
423
591
  workflowStepTimeouts?: boolean;
424
592
  /** Idle-user release. @default true when `idleUserTimeoutMs` is set */
@@ -671,6 +839,13 @@ export type MatcherOptions = {
671
839
  learningRewards?: Partial<LearningRewards>;
672
840
  /** Custom feature extractor; defaults to tag/skill/overlap/embedding features */
673
841
  learningFeatureExtractor?: LearningFeatureExtractor;
842
+ /**
843
+ * Reference duration (ms) used to normalize the `sla:tightness` learning
844
+ * feature (default: 3600000 = 1 hour). An assignment with
845
+ * `sla.completeWithinMs` equal to this value gets tightness 0; shorter
846
+ * deadlines approach 1. Only used by the default feature extractor.
847
+ */
848
+ learningSlaTightnessReferenceMs?: number;
674
849
  /** TTL for stored decision contexts in ms (default: 604800000 = 7 days) */
675
850
  learningDecisionTtlMs?: number;
676
851
  /** Weights applied to named external feedback signals when computing rewards (default weight: 1) */
@@ -685,6 +860,13 @@ export type MatcherOptions = {
685
860
  enableAutoRoutingWeights?: boolean;
686
861
  /** Tuning for automatic routing-weight synthesis (UCB1 policy) */
687
862
  autoRoutingWeights?: AutoRoutingWeightsOptions;
863
+ /**
864
+ * Milliseconds between automatic learned routing-weight syncs for all
865
+ * tracked users. When unset (default), sync remains operator-driven.
866
+ * Set on at most one replica per deployment; a Redis lock prevents
867
+ * overlapping runs.
868
+ */
869
+ autoRoutingWeightsSyncIntervalMs?: number;
688
870
  };
689
871
  /** @deprecated Use MatcherOptions instead */
690
872
  export type options = MatcherOptions;
@@ -1047,7 +1229,17 @@ export interface LearningTagStat {
1047
1229
  rewardSum: number;
1048
1230
  /** rewardSum / count (0 when no observations) */
1049
1231
  meanReward: number;
1232
+ /** Sum of squared observed rewards (available when reward-squared tracking is enabled) */
1233
+ rewardSqSum?: number;
1234
+ /** Unix epoch ms of the most recent observation (used for time decay) */
1235
+ lastUpdatedAt?: number;
1236
+ /** Population variance of observed rewards (0 when absent or single observation) */
1237
+ variance?: number;
1238
+ /** Standard error of the mean (0 when absent or single observation) */
1239
+ standardError?: number;
1050
1240
  }
1241
+ /** Synthesis policy for automatic routing weights. */
1242
+ export type AutoRoutingWeightsPolicy = 'ucb1' | 'confidence' | 'thompson';
1051
1243
  /** Options controlling automatic routing-weight synthesis (UCB1 policy) */
1052
1244
  export interface AutoRoutingWeightsOptions {
1053
1245
  /** Minimum observations before a tag's stats are trusted (default: 5) */
@@ -1060,6 +1252,55 @@ export interface AutoRoutingWeightsOptions {
1060
1252
  explorationBonus?: number;
1061
1253
  /** Optimistic weight assigned to under-sampled or unobserved known tags (default: maxWeight / 2) */
1062
1254
  priorWeight?: number;
1255
+ /**
1256
+ * Synthesis policy.
1257
+ * - 'ucb1' (default): current mean + exploration-bonus mapping.
1258
+ * - 'confidence': upper-confidence-bound for weight, lower-confidence-bound for veto.
1259
+ * - 'thompson': sample from the per-tag posterior when mapping to a weight.
1260
+ */
1261
+ policy?: AutoRoutingWeightsPolicy;
1262
+ /**
1263
+ * Z-score used by the 'confidence' policy for UCB/LCB bounds (default: 1.96).
1264
+ * Also reused as the exploration multiplier by 'ucb1' when explorationBonus
1265
+ * is omitted and policy is 'confidence' for backward compatibility.
1266
+ */
1267
+ confidenceZ?: number;
1268
+ /**
1269
+ * Minimum total samples across all of a user's tags before sync will write
1270
+ * any learned weights (default: 0 = off).
1271
+ */
1272
+ minTotalSamples?: number;
1273
+ /**
1274
+ * Minimum samples required before a learned veto may override a tag that
1275
+ * already has a manual (non-learned) routing weight (defaults to
1276
+ * `minSamples`, i.e. 5, for backward compatibility). Raise it — 20 is a
1277
+ * reasonable production floor — to make learned vetoes of operator-set
1278
+ * weights harder to trigger.
1279
+ */
1280
+ minSamplesForVeto?: number;
1281
+ /**
1282
+ * Maximum absolute change allowed per sync on a single learned weight
1283
+ * (default: undefined = no clamping). Vetoes that pass the strict veto
1284
+ * gate may still jump to 0 despite the clamp.
1285
+ */
1286
+ maxDeltaPerSync?: number;
1287
+ /**
1288
+ * Reward-squared half-life in ms for tag statistics. When set, older
1289
+ * observations are decayed exponentially on read (default: undefined =
1290
+ * no decay).
1291
+ */
1292
+ decayHalfLifeMs?: number;
1293
+ /**
1294
+ * If true, only terminal outcomes (complete/reject/expire/fail plus manual
1295
+ * rewards/feedback) feed tag statistics; non-terminal 'accept' updates are
1296
+ * skipped (default: false).
1297
+ */
1298
+ terminalOnlyTagStats?: boolean;
1299
+ /**
1300
+ * Optional random source for Thompson sampling. Defaults to Math.random.
1301
+ * Must return values in [0, 1).
1302
+ */
1303
+ rng?: () => number;
1063
1304
  }
1064
1305
  /** Aggregate learning statistics */
1065
1306
  export interface LearningStats {